tersor创建与操作

import torch
import numpy as np
import torch

#torch随机数种子
torch.manual_seed(42)

'''
torch.Tensor与torch.tensor区别

| 特性                   | `torch.Tensor()`            | `torch.tensor()`                       |
| :--------------------- | :------------------------- | :------------------------------------- |
| 数据类型推断       | 强制转为 `torch.float32`   | 根据输入数据自动推断(如整数→`int64`) |
| 显式指定 `dtype`  | 不支持                     | 支持(如 `dtype=torch.float64`)   |
| 设备指定          | 不支持                     | 支持(如 `device='cuda'`)         |
| 输入为张量时的行为  | 创建新副本(不继承原属性)     | 默认共享数据(除非 `copy=True`)     |
| 推荐使用场景       | 需要快速创建浮点张量          | 需要精确控制数据类型或设备            |
'''

def test01():
    #通过标量创建tensor
    t1 = torch.tensor(2025)
    print(t1)
    #device:tensor运行的设备,可以是CPU可以是cuda
    print(t1.shape, t1.dtype, t1.device)

    t2 = torch.tensor([1,2,3])
    print(t2.shape, t2.dtype, t2.device)

    t3 = torch.tensor([[1,2,3],[4,5,6]])
    print(t3.shape, t3.dtype, t3.device)

#Tensor创建
def test02():
    #根据形状创建tensor
    t1 = torch.Tensor(2,3)
    print(t1)

    #根据数据生成tensor
    t2 = torch.Tensor([1,2,3])
    print(t2,t2.shape, t2.dtype, t2.device)


def test03():
    #生成[0,1)的随机张量,符合均匀分布
    #生成2行3列的张量(也叫2个样本,每个样本3个特征)
    t1 = torch.rand(2,3)
    print(t1)

    #根据正态分布创建随机张量
    t2 = torch.randn(2,3)
    print(t2)

    #randint(start,end,size):根据start,end,size,创建随机整数
    t3 = torch.randint(0,10,(2,3))
    print(t3)

    #创建单位矩阵张量
    t4 = torch.eye(3) #表示生成(3,3)的单位矩阵
    print(t4)

#tensor切换设备
def test04():
    #1.创建tensor时设置device属性(切换到GPU上)(默认在CPU上)
    t1 = torch.tensor([[1,2,3],[4,5,6]],device='cuda')
    print(t1)

    #2.to():切换设备
    t2 = torch.tensor([[1,2,3],[4,5,6]])
    t2 = t2.to('cuda')
    print(t2,t2.device)

    #3.cuda():切换到cuda
    t3 = torch.tensor([[1,2,3],[4,5,6]])
    t3 = t3.cuda()
    #对应着有.cpu() 表示切换到cpu
    print(t3,t3.device)

#张量转numpy
def test05():
    t1 = torch.tensor([[1,2,3],[4,5,6]])
    #浅拷贝,结果是原对象的视图(即修改拷贝对象,原对象也会被修改)
    q1 = t1.numpy()
    print(q1,type(q1))

    #深拷贝,结果是对象的副本
    s1 = t1.numpy().copy()
    s1[0] = 9
    print(s1,type(s1),t1)

#numpy转换为tensor
def test06():
    t1 = np.array([[1,2,3],[4,5,6]])
    #.from_numpy():该方法是浅拷贝
    t1 = torch.from_numpy(t1)
    print(t1)

    #深拷贝
    t2 = torch.tensor(t1)
    print(t2)
    t2[0] = 9
    print(t1)

if __name__ == '__main__':
    test06()



import torch
from PIL import Image
from torchvision import transforms
import os

torch.manual_seed(42)
#图片转tensor
def test01():
    #获取指定图片的相对路径
    path = os.path.join(os.path.dirname(__file__), 'img', '1.jpg')
    path = os.path.realpath(path)
    print(path)

    #根据路径打开图片
    img = Image.open(path)
    print(img.size)

    #图片转tensor
    #ToTensor():将PIL图像或Numpy数组转换为PyTorch张量
    #同时将0-255的数值归一化为0-1之间的值
    #转置,将(HWC)转换为(CHW)
    transform = transforms.ToTensor()
    t_img = transform(img)
    print(t_img.shape)
    print(t_img)

#tensor转图片
#ToPILImage():将tensor转化为pillow图片
def test02():
    # 1. 随机一个数据表示图片
    img_tensor = torch.randn(3, 224, 224)
    # 2. 创建一个transforms
    transform = transforms.ToPILImage()
    # 3. 转换为图片
    img = transform(img_tensor)
    img.show()
    # # 4. 保存图片
    # img.save("./test.jpg")

#获取单个原数值
#item():获取单个元素,和数组维度无关,只要是单个元素就可以获取,多个元素会报错
def test03():
    t = torch.tensor([5])
    print(t.item())

#阿达玛积:两个数组对应位置的数值相乘
#运算符号:*或者mul()
#注意:与矩阵相乘不一样,矩阵相乘用@或者.matmul()方法
def test04():
    t1 = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    t2 = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    t3 = t1*t2
    print(t3)
    #矩阵相乘
    print(t1 @ t2)
    print(t1.matmul(t2))

#拼接:cat([tensor1,tensor2]):在现有维度上拼接,不会增加新维度
#
# stack([tensor1,tensor2]):在新维度上堆叠,会增加一个维度。
#
def test05():
    t1 = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    t2 = torch.tensor([[10, 11, 12], [13, 14, 15], [16, 17, 18]])
    # 在指定的维度上进行拼接:dim : 0,按垂直方向,张量列数要一致,1,按水平方向
    print(torch.cat([t1, t2],dim=0))

#数据变形
#view():修改数组形状  前提是数据是连续的即按C(按行)
#is_contiguous():判断数据是否连续
def test06():
    t1 = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    print(t1.is_contiguous())
    #.t():做转置
    t2 = t1.t()
    print(t2.is_contiguous())

    t2 = t2.view(2,-1)
    print(t2)

#维度交换
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(t,(1,2,0))
    print(t2)

#切割数组
def test08():
    #chunk(tensor, chunks, dim(默认为0)):切割数组,按分数切割,每块大小相同,最后一块可能比较小(余数)
    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,100))

    #split(tensor, split_size_or_sections, dim(默认为0)):按照每个子张量的大小切割
    #参数 split_size_or_sections:如果是一个整数,表示每个子张量的大小(沿指定维度)。如果是一个列表,表示每个子张量的具体长度。
    print(torch.split(x,3))
    print(torch.split(x,[2,1,2],dim=0))
    #这句会报错,分段大小之和必须等于该维度长度
    # print(torch.split(x, [2, 1, 3], dim=0))

#保存和加载
def test09():
    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__':
    test09()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值