deep_thoughts

1.tensor

tensor就是一个n维的数组。

import torch
import  numpy as np
data = [[1, 2],[3, 4]]
print(type(data))#<class 'list'>
x_data = torch.tensor(data)
print(type(x_data))#<class 'torch.Tensor'>
print(x_data.dtype)#torch.int64
np_array = np.array(data)
x_np = torch.from_numpy(np_array)#将np数组转换成为tensor张量
x_ones = torch.ones_like(x_data)#张量结构和x_data相同,但是里面的元素全部变成了0
x_rand = torch.rand_like(x_data, dtype=torch.float)#张量结构和x_data相同,但是里面的元素全部变成了随机数
rand_tensor = torch.rand((3,3))#()表示的是元组 (tuple),元组是一个不可变的有序数据集合,可以使用索引来访问元素,但不能修改元素。
print(rand_tensor)
rand_tensor = torch.rand([4,4])#[]表示的是列表 (list),列表是一个有序的数据集合,可以使用索引来访问元素,并且可以修改列表中的元素。
print(rand_tensor)
#但是torch.rand函数中不可以使用{}集合来表示shape传递参数.集合 (set) 是一个无序的不重复数据集合,不能使用索引来访问元素,并且可以进行集合运算(并集,交集等)


tensor = torch.rand(3,4)
print(f"Shape of tensor: {tensor.shape}")#Shape of tensor: torch.Size([3, 4])
print(f"Datatype of tensor: {tensor.dtype}")#Datatype of tensor: torch.float32
print(f"Device tensor is stored on: {tensor.device}")#Device tensor is stored on: cpu.看张量是在哪个设备上创建的
if torch.cuda.is_available():
    tensor = tensor.to("cuda")#如果安装了cuda环境,将张量移动到gpu上去执行。
torch.set_default_dtype(torch.float64)#将张量的元素类型设置为64为浮点型
torch.arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) 
torch.arange(1, 2.5, 0.5)#tensor([ 1.0000,  1.5000,  2.0000])#区间是左闭右开
torch.range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
torch.range(1, 4)#tensor([ 1.,  2.,  3.,  4.])去见识左闭右闭
torch.eye(3)#创建2维的张量并且对角线是1
#tensor([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]])
torch.full(size, fill_value)#Creates a tensor of size size filled with fill_value.
torch.full((2, 3), 3.141592)
#tensor([[ 3.1416,  3.1416,  3.1416],
        [ 3.1416,  3.1416,  3.1416]])
torch.cat(tensors, dim=0, *, out=None)#张量的拼接
Example:
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 0)
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 1)
tensor([[ 0.6580, -1.0969, -0.4614,  0.6580, -1.0969, -0.4614,  0.6580,
         -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497, -0.1034, -0.5790,  0.1497, -0.1034,
         -0.5790,  0.1497]])
torch.chunk(input, chunks, dim=0) → List of Tensors#从dim维度将张量input分成chunks份

从dim=0维度来进行splite

从dim=1维度来进行splite

torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor
torch.reshape(input, shape) #shape中m和n的乘积要等于input的元素个数
>>> a = torch.arange(4.)
>>> torch.reshape(a, (2, 2))
tensor([[ 0.,  1.],
        [ 2.,  3.]])
>>> b = torch.tensor([[0, 1], [2, 3]])
>>> torch.reshape(b, (-1,))#如果reshape成为一维的,但不知道具体形状,也就是元素的个数,就用-1去代替。 
tensor([ 0,  1,  2,  3])

torch.split(tensor, split_size_or_sections, dim=0)
>>> a = torch.arange(10).reshape(5, 2)
>>> a
tensor([[0, 1],
        [2, 3],
        [4, 5],
        [6, 7],
        [8, 9]])
>>> torch.split(a, 2)//将a从dim=0的维度每2个划分一次
(tensor([[0, 1],
         [2, 3]]),
 tensor([[4, 5],
         [6, 7]]),
 tensor([[8, 9]]))
>>> torch.split(a, [1, 4])//将a从dim=0的维度按照列表进行划分成两个块,分别是1行和4行。
(tensor([[0, 1]]),
 tensor([[2, 3],
         [4, 5],
         [6, 7],
         [8, 9]]))
torch.squeeze(input, dim=None) → Tensor

将大小为1的维度直接移除掉,毕竟当某个维度的大小是1时,并没有新增额外的元素。

torch.stack(tensors, dim=0, *, out=None) → Tensor

cat是直接连起来,但是stack是堆叠起来,维度肯定是会扩充的。

 2.Dataset和DataLoader

自定义的dataset必须实现__init__, __len__, and __getitem__三个函数

import os
import pandas as pd
from torchvision.io import read_image

class CustomImageDataset(Dataset):
    def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):#transform是对image进行预处理,而target_transform是对标签进行预处理
        self.img_labels = pd.read_csv(annotations_file)
        self.img_dir = img_dir
        self.transform = transform
        self.target_transform = target_transform

    def __len__(self):
        return len(self.img_labels)

    def __getitem__(self, idx):#基于一个索引idx返回一个训练对 
        img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
        image = read_image(img_path)
        label = self.img_labels.iloc[idx, 1]
        if self.transform:
            image = self.transform(image)
        if self.target_transform:
            label = self.target_transform(label)
        return image, label
from torch.utils.data import DataLoader

train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)

 

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在PyTorch中,算子融合是指将多个操作合并为一个操作以提高计算效率。根据引用中的参数维度输出结果,我们可以看到融合算子的形状和尺寸。具体来说,融合操作主要包括改造和融合两个步骤。 首先,改造步骤涉及修改卷积层的权重和偏置。根据引用中的参数维度,改造步骤会将3x3的卷积权重改变为2x2x3x3的形状,并且将3x3的卷积偏置改变为2x1x1的形状。这个改造过程通常是为了适应融合操作的需求。 接下来,融合步骤是将多个操作合并为一个操作。具体来说,我们需要使用torch.isclose方法比较两个浮点矩阵result1和result2,因为直接使用torch.equal方法无法比较浮点矩阵。然后,我们可以使用torch.all函数对这些比较结果进行统一判断。根据引用的输出结果,如果所有的比较结果都为True,那么我们可以得出算子融合为True。 关于算子融合的更多信息,可以参考PyTorch官方文档中的torch.nn.functional.pad函数。该函数提供了关于算子融合的详细说明和示例。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【deep_thoughts】16_PyTorch中进行卷积残差模块算子融合](https://blog.csdn.net/qq_45670134/article/details/129883225)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值