用pytorch创建tensor,tensor的操作

import torch
import numpy as np
print(torch.cuda.is_available())
print(torch.__version__)

# 1. 用标量创建张量
def test001():
    tensor = torch.tensor(5)
    print(tensor.shape)
# 2. 根据形状创建张量
def test002():
    tensor1 = torch.Tensor(2, 3)
    print(tensor1)

#随机张量
def test03():
    #生成[0,1)的随机张量
    #生成3行2列的张量,或者2个样本,每个样本3个特征
    t1 = torch.randn(2, 3)
    print(t1)
    #根据标准正太分布,创建随机张量
    t2 = torch.randn(2, 3)
    print(t2)
    #randint(start,end,size):根据开始值,形状,创建随机整数
    t3 = torch.randint(0, 10, (2, 3))
    print(t3)
    #创建单位矩阵张量
    t4=torch.eye(3)
    print(t4)

#tensor切换设备
def test04():
    #创建tensor时设置device属性
    t1 = torch.randn([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)

#创建单位矩张量
def test05():
    data = torch.eye(4)
    print(data)

#numpy转tensor
def test06():
    a1=np.array([1,2,3])
    #from_numpy():numpy转tensor,浅拷贝结果是原对象试图
    t1=torch.from_numpy(a1)
    print(t1)
    t1[0]=100
    print(t1)

import torch
from PIL import Image
from torchvision import transforms
import os
import numpy as np

# 图片转tensor
def test_01():
    """
    此函数用于将指定图片转换为 PyTorch 张量。
    它会打开指定路径下的图片,并将其转换为张量,同时打印相关信息。
    """
    try:
        # 获取指定图片的相对路径
        path = os.path.join(os.getcwd(), 'images', '1.jpg')
        path = os.path.realpath(path)
        print(f"图片路径: {path}")

        # 根据路径打开图片
        img = Image.open(path)
        print(f"图片尺寸: {img.size}")

        # 图片转tensor
        # ToTensor():将 PIL 图像或 NumPy 数组转换为 PyTorch 张量
        # 同时将0-255的数值归一化为0-1之间的值
        # 转置,将(HWC)转换为(CHW)
        transform = transforms.ToTensor()
        t_img = transform(img)
        print(f"张量形状: {t_img.shape}")
        print(f"张量内容: {t_img}")
    except FileNotFoundError:
        print("错误: 未找到图片文件。")
    except Exception as e:
        print(f"发生未知错误: {e}")


# tensor转图片
# ToPILImage():将tensor转换为pillow图片
def test_02():
    """
    此函数用于将随机生成的 PyTorch 张量转换为 PIL 图片并显示。
    """
    t_img = torch.randn(3, 224, 224)
    transform = transforms.ToPILImage()
    img = transform(t_img)
    img.show()


# 获取单个元素值
# item():获取单个元素,和数组维度没有关系,只要是单个元素就可以获取
# tensor中有多个元素时会报错
def test_03():
    """
    此函数用于演示如何使用 item() 方法获取张量中的单个元素。
    """
    t = torch.tensor([[5]])
    print(t.item())


# 阿达玛积:两个数组对应位置的数值相乘
# 运算符号:*或者mul
def test_04():
    """
    此函数用于演示两个张量的阿达玛积运算。
    """
    t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
    t2 = torch.tensor([[1, 2, 3], [4, 5, 6]])
    t3 = t1 * t2
    print(t3)


# 数据拼接
def test_05():
    """
    此函数用于演示如何使用 torch.stack() 方法对两个张量进行不同维度的拼接。
    """
    t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
    t2 = torch.tensor([[7, 8, 9], [10, 11, 12]])

    print(f"dim=0 拼接结果:\n{torch.stack(tensors=[t1, t2], dim=0)}")
    print(f"dim=1 拼接结果:\n{torch.stack(tensors=[t1, t2], dim=1)}")
    print(f"dim=2 拼接结果:\n{torch.stack(tensors=[t1, t2], dim=2)}")


# 数据变形
# view():修改数组形状
# 前提: 数组存储是连续的: C-按行
# is_contiguous():判断数组是否为连续的
def test_06():
    """
    此函数用于演示如何使用 view() 方法对张量进行形状变换,
    同时展示如何判断张量是否连续存储。
    """
    t = torch.tensor([[1, 2, 3], [4, 5, 6]])
    print(f"原始张量是否连续: {t.is_contiguous()}")

    t1 = t.t()
    print(f"转置后张量是否连续: {t1.is_contiguous()}")

    t2 = t.view(2, -1)
    print(f"变形后的张量:\n{t2}")


def test_07():
    """
    此函数用于演示如何使用 view() 方法对张量进行不同方式的形状变换,
    包括指定维度和自动推断维度。
    """
    tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
    # 将 2x3 的张量转换为 3x2
    reshaped_tensor = tensor.view(3, 2)
    print(f"转换为 3x2 的张量:\n{reshaped_tensor}")
    # 自动推断一个维度
    reshaped_tensor = tensor.view(-1, 2)
    print(f"自动推断维度后的张量:\n{reshaped_tensor}")


# 参数:
# split size_or sections:如果是整数,表示每个子张量的大小
# 如果是数组,表示的每个子张量要切割的长度
def test_08():
    """
    此函数用于演示如何使用 transpose() 方法对张量进行形状变换。
    """
    data = torch.randint(0, 10, (3, 4, 5))
    print(f"原始张量:\n{data},形状: {data.shape}")
    # 使用 transpose 进行形状变换
    transpose_data = torch.transpose(data, 0, 1)
    # transpose_data = data.transpose(0, 1)
    print(f"转置后的张量:\n{transpose_data},形状: {transpose_data.shape}")


def test_09():
    """
    此函数用于演示如何使用 torch.split() 方法对张量进行分割。
    """
    x = torch.tensor([[10, 11, 12], [13, 14, 15], [16, 17, 18]])
    print(f"按固定大小分割结果: {torch.split(x, split_size_or_sections=2)}")
    # 修正分割长度
    print(f"按指定长度分割结果: {torch.split(x, split_size_or_sections=[1, 2], dim=0)}")

你可能感兴趣的:(pytorch,人工智能,python)