tensor创建:
import torch
import numpy as np
# 检验torch库是否正常
# print(torch.cuda.is_available())
# print(torch.__version__)
# 设置随机数种子
# 作用:固定随机出来的运行结果
torch.manual_seed(42)
# tensor():创建张量
def test01():
# 通过标量创建tensor
t1 = torch.tensor(1)
print(t1)
# device:tensor运行的设备,可以是cpu、cuda
print(t1.dtype, t1.shape, t1.device)
# 通过一维数组创建tensor
t2 = torch.tensor([1, 2, 3])
print(t2)
# 二维数组
t3 = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(t3, t3.dtype, t3.shape, t3.device)
# Tensor创建
# Tensor默认数据类型为float32
# tensor()的数据类型会根据输入数据自动推断
# Tensor不支持dtype和device,tensor()支持dtype和device
# 大部分场景使用tensor()创建对象
def test02():
# 根据形状创建tensor
t1 = torch.Tensor(2, 3)
print(t1)
# 根据数据生成tensor
t2 = torch.Tensor([1, 2, 3])
print(t2, t2.dtype, t2.shape, t2.device)
# 随机张量
def test03():
# 生成[0,1)的随机张量
# 生成两行三列的张量(即拥有三个特征的两个样本)
t1 = torch.rand(2, 3)
print(t1)
# 根据标准正态分布创建随机张量
t2 = torch.randn(2, 3)
print(t2)
# 通过randint(起始值,终止值(不包含),形状)创建随机整数
t3 = torch.randint(0, 10, (2, 3))
print(t3)
# 创建单位矩阵张量
# eye(n):创建一个n*n的单位矩阵
t4 = torch.eye(4)
print(t4)
# tensor切换设备
def test04():
# 1.创建tensor时设置device属性
t1 = torch.tensor([1, 2, 3], device="cuda")
print(t1)
# 2.使用to()切换设备
t2 = torch.tensor([1, 2, 3])
t2 = t2.to("cuda")
print(t2)
# 3.使用cuda()切换到cuda
t3 = torch.tensor([1, 2, 3])
t3 = t3.cuda()
print(t3)
# 张量转numpy
def test05():
t1 = torch.tensor([1, 2, 3])
# 浅拷贝,结果是原对象的视图
# (即更改拷贝对象会影响原对象)
a1 = t1.numpy()
print(type(a1))
a1[0] = 100
print(t1)
# 深拷贝,结果是原对象的副本
# (即更改拷贝对象不会影响原对象)
a2 = t1.numpy().copy()
a2[0] = 100
print(t1)
# numpy转tensor
def test06():
a1 = np.array([1, 2, 3])
# from_numpy():浅拷贝
t1 = torch.from_numpy(a1)
print(t1)
t1[0] = 100
print(a1)
# tensor():深拷贝
t2 = torch.tensor(a1)
print(t2)
t2[0] = 200
print(a1)
if __name__ == '__main__':
# test01()
# test02()
# test03()
# test04()
# test05()
test06()
tensor操作:
import torch
from PIL import Image
from torchvision import transforms
import os
# 图片转tensor
def test01():
# 获取指定图片的相对路径
# path = "./img/1.jpg"
path = os.path.join(os.path.dirname(__file__), "img", "1.jpg")
path = os.path.relpath(path)
print(path)
# 根据路径打开图片
img = Image.open(path)
print(img.size)
# 图片转tensor
# ToTensor():将 PIL 图像或 NumPy 数组转换为 PyTorch 张量
# transforms.ToTensor():自动进行数值归一化和维度调整
# 数值归一化:化为0~1之间的值
# 转置:将(HWC)转置为(CHW)
transform = transforms.ToTensor()
t_img = transform(img)
print(t_img.shape)
print(t_img)
# tensor转图片
# ToPILImage():将tensor转换为pillow图片
def test02():
t_img = torch.randn(3, 224, 224)
transform = transforms.ToPILImage()
img = transform(t_img)
img.show()
# 获取单个元素
# item():获取单个元素,不受数组维度影响,只要是单个元素就可获取
def test03():
t = torch.tensor([5])
print(t.item())
# 阿达玛积:两个数组对应位置的数值相乘
# 运算符号:*或mul()
# 要注意阿达玛积和矩阵相乘的区别
def test04():
t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
t2 = torch.tensor([[1, 2, 3], [4, 5, 6]])
t3 = t1 * t2
print(t3)
def test05():
t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
t2 = torch.tensor([[7, 8, 9], [10, 11, 12]])
print(torch.stack([t1, t2], dim=0))
print(torch.stack([t1, t2], dim=1))
print(torch.stack([t1, t2], dim=2))
# 数据变形
# view():修改数组形状
# 前提:数组形状需连续,不连续则报错
# 优势:不重新分配内存,效率更高
def test06():
t = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(t.is_contiguous())
t1 = t.t()
print(t1.is_contiguous())
t2 = t.view(2, -1)
print(t2)
# 维度交换
# 1.transpose():交换数组中任意两个维度
def test07():
t = torch.randint(0, 10, (3, 4, 5))
print(t)
# transpose()
t1 = torch.transpose(t, 0, 2)
print(t1)
# permute():交换数组中的任意维度
t2 = torch.permute(t1, (1, 2, 0))
print(t2)
# chunk():按份数切割数组,每一块的大小相同
# 最后一块可能出现较小的情况(类似于整除后的余数)
def test08():
x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]])
print(torch.chunk(x, 3))
print(torch.chunk(x, 3, dim=1))
# 如果切割份数大于数组的行或列,则按最多的行或列切割,不会报错
print(torch.chunk(x, 10, dim=1))
# split():切割函数,按照每个子张量的大小切割
# 参数:
# split_size_or_sections:
# 如果是整数,表示每个子张量的大小
# 如果是数组,表示的每个子张量要切割的长度
def test09():
x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9],
[10, 11, 12], [13, 14, 15], [16, 17, 18]])
print(torch.split(x, 2))
print(torch.split(x, [1, 2, 3], dim=0))
# 要切割的每个子张量长度之和要与原张量的长度一致,否则会报错
print(torch.split(x, [1, 2, 4], dim=1))
# 保存和加载
def test10():
t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
torch.save(t, "t.pt")
x = torch.load("t.pt")
print(x)
if __name__ == '__main__':
# test01()
# test02()
# test03()
# test04()
# test05()
# test06()
# test07()
# test08()
# test09()
test10()
2479

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



