!8554 Add expand_as function to tensor

From: @liangzhibo
Reviewed-by: @zh_qh,@chenfei52
Signed-off-by: @zh_qh
This commit is contained in:
mindspore-ci-bot 2020-11-13 15:19:01 +08:00 committed by Gitee
commit c11c79170e
3 changed files with 95 additions and 28 deletions

View File

@ -156,6 +156,12 @@ def enumerate_(x, start=0):
return ret
def expand_tensor_as(x, y):
"""Expand tensor"""
broadcast_to = P.BroadcastTo(shape_(y))
return broadcast_to(x)
def isinstance_(x, base_type):
"""Determine whether x is an instance of base_type."""
x_type = F.typeof(x)

View File

@ -166,6 +166,7 @@ BuiltInTypeMap &GetMethodMap() {
{"__gt__", std::string("gt")}, // C.gt
{"__le__", std::string("le")}, // C.le
{"__ge__", std::string("ge")}, // C.ge
{"expand_as", std::string("expand_tensor_as")}, // C.expand_as
{"__matmul__", prim::kPrimDot}, // P.dot,
{"__len__", prim::kPrimArrayLen}, // P.array_len,
{"__getitem__", prim::kPrimArrayGetItem}, // P.array_getitem,

View File

@ -0,0 +1,60 @@
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" test expand_as"""
import mindspore.nn as nn
from mindspore import Tensor
from mindspore import context
context.set_context(mode=context.GRAPH_MODE)
def test_expand_as():
class Net(nn.Cell):
def __init__(self):
super(Net, self).__init__()
self.t1 = Tensor([1, 2, 3])
self.t2 = Tensor([[1, 1, 1], [1, 1, 1]])
def construct(self):
return self.t1.expand_as(self.t2)
net = Net()
net()
def test_expand_as_parameter():
class Net(nn.Cell):
def __init__(self):
super(Net, self).__init__()
self.t1 = Tensor([1, 2, 3])
def construct(self, x):
return self.t1.expand_as(x)
net = Net()
net(Tensor([[1, 1, 1], [1, 1, 1]]))
def test_expand_tensor_as_parameter_1():
class Net(nn.Cell):
def __init__(self):
super(Net, self).__init__()
self.t2 = Tensor([[1, 1, 1], [1, 1, 1]])
def construct(self, x):
return x.expand_as(self.t2)
net = Net()
net(Tensor([1, 2, 3]))