张量#
参考:ndarray
import numpy as np
from tvm.relax.frontend.nn import Tensor
# 生成1x10的随机矩阵,数值范围[0,1),默认dtype为float64
x = np.random.rand(1, 10)
assert x.dtype == np.float64 # 确保数据类型为float64
# 从numpy常量创建Tensor对象(预期自动转换为float32)
tensor_x = Tensor.from_const(x)
# 验证Tensor元数据(基于from_const的实现逻辑)
assert tensor_x.shape == [1, 10] # 保持原始维度
assert tensor_x.ndim == 2 # 二维张量
assert tensor_x.dtype == "float32" # 类型自动转换
assert repr(tensor_x) == 'Tensor([1, 10], "float32")' # 标准表示形式
# 显示Tensor对象(触发__repr__方法)
tensor_x
Tensor([1, 10], "float32")
x = 123.321
tensor_x = Tensor.from_scalar(x, dtype="float16")
assert tensor_x.shape == []
assert tensor_x.ndim == 0
assert tensor_x.dtype == "float16"
assert repr(tensor_x) == 'Tensor([], "float16")'
Tensor.from_scalar(np.random.rand(1, 10), dtype="float16")
Tensor([1, 10], "float16")