深度学习笔记-2. 数据操作

  1. 基本操作
import torch
# 创建一个向量
x = torch.arange(12)
# 形状
x.shape
# 大小(元素的个数)
x.numel()
# 改变形状
x.reshape(3,4) #指定为-1的维度会自动计算
# 全0矩阵
torch.zeros((3,4))
#全1矩阵
torch.ones((3,4))
#高斯分布矩阵
torch.randn(3,4)
# 从列表创建张量
torch.tensor([[1,2,3],[4,5,6],[5,6,2]])
  1. 数据运算
# 基本运算
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y # **运算符是求幂运算
torch.exp(x)
# 形状拼接
# dim=0,按行拼接,dim=1,按列拼接
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
# 逻辑运算
X == Y #元素相等位置为1,否则为0
# 求和
X.sum()
# 广播,沿着数组中长度为1的轴进行广播
# a会被扩展成3*2张量,b会被扩展为3*2张量,进而计算
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
  1. 索引和切片
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
X[-1]
X[1:3]
X[1:2] = 9
X[0:2,:]=1
# 使用切片赋值不会分配新的内存,提高性能
Z = torch.zeros_like(Y)
print('id(Z):', id(Z))
Z[:] = X + Y
print('id(Z):', id(Z))
  1. 与numpy的转换
A = X.numpy()
B = torch.tensor(A)
type(A), type(B) #(numpy.ndarray, torch.Tensor)
# 将大小为1的张量转换为标量
a = torch.tensor([3.5])
a, a.item(), float(a), int(a) #(tensor([3.5000]), 3.5, 3.5, 3)
  1. 与pandas转换
# inputs为pd.DataFrame
X = torch.tensor(inputs.to_numpy(dtype=float))

posted on   朝朝暮Mu  阅读(15)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示