Pytorch数据操作

import torch

# pytorch中的torch(张量)类似于numpy中的 ndarray
# torch 支持GUP  支持微分  更适合深度学习

# x = torch.arange(12);
# print(x.shape) #torch的形状
# print(x.numel())  #torch元素的数量
#
# x = x.reshape(3,4);   #将x从行向量转成矩阵
# x = x.reshape(-1,4)   #通过-1来调用此自动计算出维度的功能

#1.pytorch 的数学运算  元素计算
# x = torch.tensor([1.0, 2, 4, 8])
# y = torch.tensor([2, 2, 2, 2])
# print(torch.exp(x))

# 2.线性代数: 向量点积和矩阵乘法

# x = torch.tensor([1.0,2,4,8])

# 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]])
# print(torch.cat((x,y),dim=0))
# print(torch.cat((x,y),dim=1))

# print(x == y)

# print(torch.sum(x))

# 3.广播机制 两个张量的形状不同,通过调用广播机制,通过转换,使两个张量具有相同的形状
# a = torch.arange(3).reshape((3, 1))
# b = torch.arange(2).reshape((1, 2))
# print(a+b)  #先将两个矩阵扩成两个相同的矩阵进行加减

#4.索引和切片
# x = torch.arange(12,dtype = torch.float32).reshape((3,4));
# print(x[-1]);
# print(x[1:3]);
#
# x[1,2] =9;
# print(x)

#5.节省空间  Y = X + Y  取消引用Y指向的张量,指向了新分配的内存的内存处的张量
# x = torch.arange(12,dtype = torch.float32).reshape((3,4));
# y = torch.arange(12,dtype = torch.float32).reshape((3,4));
# z = torch.zeros_like(x)
# print(id(z))
#使用切片操作使空间地址保持不变
# z[:] = x + y;
# print(id(z))

# 使用 x += y 来操作

#6.转换成其他python对象
#将pytorch中的tensor转换成NumPy中的ndarray
# x = torch.arange(12,dtype = torch.float32).reshape((3,4));
# A = x.numpy();
# B = torch.tensor(A);
# print(type(A),type(B))

#7.将大小为1的张量转换成Python标量 可以调用item函数或者Python的内置函数
# a = torch.tensor([3.5])
# print(a.item());
# print(float(a));
# print(int(a))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值