numpy生成矩阵并转化为torch张量

例子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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值