pytorchDay33

发布于:2024-11-27 ⋅ 阅读:(24) ⋅ 点赞:(0)

创建tensor

import numpy as np
import torch


print(torch.__version__)

def creat_tensor():
    t1 = torch.tensor(7)#创建一个一阶张量
    print(t1)
    print(t1.shape)#形状
    print(t1.dtype)#它的类型(它指t1中的数据的类型)
    print(type(t1))
    
    
def creat_tensor2():
    data = np.array([10,20,30,40])
    t1 = torch.tensor(data)#创建一个一阶张量
    print(t1.shape)#形状
    print(t1.dtype)#它的类型(它指t1中的数据的类型)
    print(type(t1))
    
def creat_tensor3():
    data = [10,20,30,40]
    t1 = torch.tensor(data)#创建一个一阶张量
    print(t1.shape)#形状
    print(t1.dtype)#它的类型(它指t1中的数据的类型)
    print(type(t1))
    
def creat_tensor4():
    t = torch.Tensor(3,4)
    print(t)
    print(t.shape)#np阶段是(3,4)
    
def creat_tensor5():
    t = torch.Tensor([[10,20,30],[10,20,30]])
    print(t.shape)
    print(t.device)
    
def creat_tensor6():
    t = torch.IntTensor([10,20,30])
    # t = torch.FloatTensor([10,20,30])
    # t = torch.DoubleTensor([10,20,30])
    # t = torch.LongTensor([10,20,30])
    # t = torch.HalfTensor([10,20,30])
    # t = torch.BoolTensor([True,False])
    # t = torch.tensor([10,20,257],dtype=torch.int8,device='cuda')
    print(t)
    print(t.shape)
    print(t.dtype)
    print(t.device)
    
if __name__ == '__main__':
    creat_tensor4()
import torch
import numpy as np
data = np.array([[1,2,3],[12,34,56]])
data = torch.tensor(data)
x = torch.ones_like(data)
print(x)
import torch

# 创建一个 2x2 的浮点型张量
a = torch.Tensor([[1, 2], [3, 4]])
print(a)
print(a.dtype)  # 默认是 torch.float32

# 创建一个 2x2 的整型张量,需要指定数据类型
b = torch.tensor([[1, 2], [3, 4]]).type(torch.float64)
print(b)
print(b.dtype)  # torch.int32

x = torch.tensor([1,2,3],dtype=torch.float32)
print(x)
x = torch.Tensor([1,2,3]).type(torch.int32)
print(x)
x = torch.Tensor([1,2,3]).to('cuda')
print(x.device)

创建线性和随机张量

import torch


#关闭科学计数法的显示
#torch.set_printoptions(sci_mode=False)

#线性张量
def test01():
    x = torch.arange(1, 10, 2)  #从1开始到10结束(不包括10,[1,10)),步长为2,等差数列
    print(x)
    y = torch.linspace(1, 10, 5)  #也是等差数列,[1,10],取step个数,(end-start)/(step-1)
    print(y)
    z = torch.logspace(1, 10, 3, base=2)  #等比数列,base=2表示数列为2的指数,[2的1次方。。。。]step为等比数列个数
    print(z, z.dtype)


#随机张量 
def test02():
    #设置随机数种子
    torch.manual_seed(666)
    #获取当前随机数种子
    r = torch.initial_seed()
    print(r)
    #生成随机张量
    x = torch.rand(10,5)# np.random.rand(10,5)
    print(x)
    #生成标准正态分布随机张量
    y = torch.randn(3,3)
    print(y)
    #自己配置方差和均值
    z = torch.normal(2,1,(4,4))
    print(z)


if __name__ == '__main__':
    test01()

创建01张量

import numpy as np
import torch


def test01():
    x = torch.zeros(3, 3)
    print(x)
    y = torch.tensor([[10, 20, 30],
                      [22, 33, 44]])
    y = torch.rand(3, 2)
    # 传入的数据容器只能是tensor,不能列表或者数组
    # y = np.array([1,2,3])
    # y = [12,3,4]

    #解决方法:
    y = torch.tensor(np.array([1, 2, 3]))
    y = torch.zeros_like(y)
    print(y)

def test02():
    x = torch.ones(3,5)
    print(x)
    
    y = torch.tensor([1,2,3])
    y = torch.rand(3, 2)
    y = torch.ones_like(y)
    print(y)
    
def test03():
    x = torch.full((3,4),999)
    print(x)
    
    y = torch.full_like(x,2)
    print(y)
    
def test04():
    x = torch.eye(4)
    print(x)

if __name__ == '__main__':
    test04()

常见的属性和类型转换

import torch
from numpy import dtype


def test01():
    # torch.Tensor()
    x = torch.tensor([1, 2, 3], device='cuda')  #可以指定创建设备,CUDA或者cpu
    print(x, x.dtype)  #tensor中的数据类型
    print(x.device)  #tensor在哪个设备上运行,默认在cpu上
    #[]0介张量标量
    #[3]1阶张量,有3个数据
    #[3,4]2介张量,有3行4列
    #[4,2,512,512]4介张量,第1层有4个,每个中有2个512*512的矩阵
    print(x.shape)  #获取tensor形状
 

def test02():
    #不同的设备上的tensor是不能参与运算的
    # x = torch.tensor([1, 20, 30], device='cuda')
    # x2 = torch.tensor([2, 33, 44], device='cpu')
    # print(x)
    # print(x2)
    # c = x + x2
    # print(c)

    #设备切换方法1
    x = torch.tensor([1, 2, 3], device='cuda')
    print(1, x)

    #设备切换方法2
    y = torch.tensor([4, 5, 6])
    z = y.to('cuda:0')  #会返回一个新的z,这个新的y在cuda上,原y在cpu上
    print(2, z.device)
    #可以通过API获取当前设备中是否有cuda
    res = torch.cuda.is_available()
    print(res)  #设备上有显卡返回True否则返回False
    c = 1 if 100 > 10 else 0
    print(c)
    x.to('cuda' if torch.cuda.is_available() else 'cpu')
    print(x.device)

    #设备切换方法3
    #把创建的tensor移动到cuda上
    x = torch.tensor([123, 123])
    print(x.device)
    x = x.cuda()  #返回一个新的x,这个新的x在cuda上,原变量的值依然在cpu上
    print(x.device)
    x = x.cuda() if torch.cuda.is_available() else x

def test03():
    #类型转换1
    x = torch.tensor([10,20,30,40],dtype=torch.float16)
    print(x)
    
    #类型转换2
    x = x.type(torch.int8)#type函数不会修改原数据,会返回一个新数据
    print(x.dtype)
    
    #类型转换3
    x = x.half()
    print(x.dtype)
    x = x.double()
    print(x.dtype)
    x = x.float()
    print(x.dtype)    
    x = x.long()
    print(x.dtype)
    x = x.int()
    print(x.dtype)
    
if __name__ == '__main__':
    test03()

数据转换

import numpy as np
import torch


def test01():
    x = torch.tensor([1, 2, 3])
    print(x)
    #把tensor转换成numpy
    x2 = x.numpy()
    print(x2)
    print(type(x2))
    #x和x2是两个不同的对象,但他们的数据是共享的
    x2[0] = 100
    print('x2',x2)
    print('x',x)


def test02():
    print('--------------')
    x = torch.tensor([1, 2, 3])
    x3 = x.numpy()
    x2 = x3.copy()  # numpy的copy方法 numpy还有一个方法view
    print(x2)
    x2[0] = 100
    print(x)
    print(x2)
    print(x3)
    
    
def test03():
    print('-----------------')
    #numpy转tensor  1
    x = np.array([1,2,3])
    x2 = torch.tensor(x)#numpy转tensor,不共用内存
    x[0]=122
    x2[1]=999
    print(x)
    print(x2)
    
    #numpy转tensor  2
    x3 = np.array([2,3,4])
    x4 = torch.from_numpy(x3)#numpy转tensor,共用内存
    x3[0] = 111
    x4[1] =7678
    print(x3)
    print(x4)
    

if __name__ == '__main__':
    test01()
    test02()
    test03()

图像转张量

import cv2
import torch
from PIL import Image
from torchvision import transforms


def test01():    
    img = cv2.imread('data/1.png')
    print(img)
    print(type(img))
    img = torch.from_numpy(img)
    print(img)
    
    
def test02():
    #图像的PIL转换为tensor对象
    path = r'./data/1.png'
    img = Image.open(path)
    print(img)
    transfer = transforms.ToTensor()
    img_tensor = transfer(img)
    print(img_tensor)
    print(img_tensor.shape)
    '''
    [[[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]],
     [[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]],
     [[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]],
     [[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]]]
    
    4,5,6
    '''
    print(img_tensor[0])
    

def test03():
    # r = torch.rand(315,315)
    # g = torch.rand(315,315)
    # b = torch.rand(315,315)
    # a = torch.rand(315,315)
    # img_tensor = ([r,g,b,a])
    img_tensor = torch.rand(4,315,315)
    print(img_tensor)
    print(img_tensor.shape)
    #tensor转PIL
    trans = transforms.ToPILImage()
    img_pil = trans(img_tensor)
    img_pil.show()
    
    
def test04():
    path = r'./data/1.png'
    img = Image.open(path)
    print(img)
    transfer = transforms.ToTensor()
    img_tensor = transfer(img)
    img_tensor[:,10,10]=255
    tensor2pil = transforms.ToPILImage()
    img_pil = tensor2pil(img_tensor)
    img_pil.show()
    
    
if __name__ == '__main__':
    test03()