pytorch中一些维度变换

pytorch中一些维度变换(小白自学笔记,大佬跳过)

主要是 torch.cat函数repeat函数

代码和运行结果

import random
import numpy as np
import torch
img=torch.ones(3,10,10)
print(img)
noise_level1 = torch.zeros(1).float()
print(noise_level1)
print(noise_level1.size()
#tensor([0.])
#torch.Size([1])
noise_level2 = torch.FloatTensor([np.random.uniform(0, 50)])/255.0
print(noise_level2)
print(noise_level2.size())
#tensor([0.1507])
#torch.Size([1])
noise = torch.randn(img.size()).mul_(noise_level2).float()
print(noise.size())
img.add_(noise)
print(img.size())
#torch.Size([3, 10, 10])
#torch.Size([3, 10, 10])
k_reduced=torch.ones(15)
M_vector = torch.cat((k_reduced, noise_level1), 0).unsqueeze(1).unsqueeze(1) 
print(k_reduced)
print(M_vector) 
print(M_vector.size())
M = M_vector.repeat(1, img.size()[-2], img.size()[-1])
print(M.size())
print(img.size()[-2])
print(img.size()[-1])
#tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
#tensor([[[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[1.]],

        [[0.]]])
#torch.Size([16, 1, 1])
#torch.Size([16, 10, 10])
#10
#10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
PyTorch,可以使用多种方法对张量的维度进行变换。其常用的方法有view()和squeeze()。view()方法可以用来改变张量的形状,而squeeze()方法可以去除维度值为1的尺寸。举例如下: 1. 使用view()方法进行维度变换。view()方法会返回一个改变了形状的新张量,但张量的元素数量必须保持不变。可以使用该方法实现维度的展平、增加或减少维度等操作。 2. 使用squeeze()方法进行维度变换。squeeze()方法可以去除张量维度值为1的尺寸,并返回一个新张量。可以指定具体的维度进行去除,也可以不指定维度,即默认去除所有为1的维度。 例如,假设有一个张量a的形状为(2, 1, 2, 1, 3),使用squeeze()方法可以去除其值为1的维度,得到一个形状为(2, 2, 3)的新张量。 在PyTorch,还可以使用unsqueeze()方法对张量进行维度扩展。unsqueeze()方法会在指定的维度上增加一个尺寸为1的维度,并返回一个新张量。 总结起来,PyTorch维度变换包括view()、squeeze()和unsqueeze()等方法,可以根据具体需求选择合适的方法进行张量的维度变换。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [PyTorchTensor的维度变换实现](https://download.csdn.net/download/weixin_38698174/13988496)[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: 50%"] - *2* *3* [Pytorch 基础之维度变化](https://blog.csdn.net/zxhandroid/article/details/129192950)[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: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值