例子1:生成 n × n 随机矩阵并转为 torch.Tensor
import numpy as np
import torch
# 定义 n
n = 4 # 你可以改成任意整数
# 1️⃣ 生成一个 n x n 的随机矩阵 (元素范围 0~1)
matrix_np = np.random.rand(n, n)
# 2️⃣ 转换为 torch 张量
matrix_torch = torch.tensor(matrix_np, dtype=torch.float32)
print("Numpy矩阵:\n", matrix_np)
print("Torch张量:\n", matrix_torch)
如果想生成 n维张量(不仅仅是方阵)
比如生成形状 [n, n, n] 的三维张量:
tensor_3d = torch.rand(n, n, n) # 直接用 torch 生成随机张量
print(tensor_3d.shape) # -> torch.Size([n, n, n])
例子2:生成形状 [n, n, n] 的三维张量(通过numpy生成并转化)
import numpy as np
import torch
n = 4 # 你可以换成任意整数
# 1️⃣ 使用 numpy 生成三维随机数组
array_3d = np.random.rand(n, n, n) # 元素范围 [0, 1)
# 2️⃣ 转换为 torch 张量
tensor_3d = torch.tensor(array_3d, dtype=torch.float32)
print("Numpy 三维数组形状:", array_3d.shape) # (n, n, n)
print("Torch 张量形状:", tensor_3d.shape) # torch.Size([n, n, n])
其他生成方式
-
整数随机:
array_3d = np.random.randint(0, 10, size=(n, n, n)) # 元素为0~9的整数
-
全零/全一:
array_zeros = np.zeros((n, n, n))
array_ones = np.ones((n, n, n))

3万+

被折叠的 条评论
为什么被折叠?



