# 网络内构造常量

mindspore.ops.constexpr中提供了一个@constexpr的Python 装饰器，该装饰器可以用于修饰一个函数，该函数在编译阶段将会通过Python解释器执行，最终在MindSpore的类型推导阶段被常量折叠成为ANF图的一个常量节点(ValueNode)。

[1]:

import numpy as np
from mindspore.ops import constexpr
import mindspore.ops as ops
import mindspore.nn as nn
from mindspore import Tensor
import mindspore

@constexpr
def construct_tensor(x):
if x is None:
raise ValueError("input is an unknown value")
return Tensor(np.array(x), dtype=mindspore.float32)

class Net(nn.Cell):
def __init__(self):
super(Net, self).__init__()
self.relu = ops.ReLU()

def construct(self, x):
return self.relu(construct_tensor(ops.shape(x)))

net = Net()
x = Tensor(np.random.random([7, 6, 3]))
out = net(x)
print(out)

[7. 6. 3.]


@constexpr
def construct_tensor(x):
if x is None:
raise ValueError("input is an unknown value")
return Tensor(np.array(x), dtype=mindspore.float32)

class Net(nn.Cell):
def __init__(self):
super(Net, self).__init__()
self.relu = ops.ReLU()

def construct(self, x):
return self.relu(construct_tensor(self.relu(x)))

net = Net()
x = Tensor(np.random.random([7, 6, 3]))
out = net(x)
print(out)


ValueError: input is an unknown value