栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pytorch 入门

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pytorch 入门

Pytorch 基本元素的操作

创建一个矩阵的操作

import torch



x = torch.empty(5,3)

if __name__ == '__main__':
    print(x)

 

创建一个有初始化的矩阵: 

y = torch.rand(2,4)

y_1 = torch.randn(2,4)

if __name__ == '__main__':

    print(y)
    print(y_1)

对比有初始化和无初始化的矩阵时,当声明一个未初始化的矩阵的时候,它本身不包活任何确切的值。

 创建一个全0的矩阵,指定数据的类型为long

x: Tensor = torch.zeros(5,7,dtype =torch.long )

if __name__ == '__main__':
    print(x)

 通过数据来创建张量 

y: Tensor = torch.tensor([2.5,3.5])

通过已有的一个张量来创建一个相同尺寸的新张量,创建一个与已有张量尺寸相同的张量但是其中的值不同的张量

x: Tensor = torch.zeros(5, 7, dtype=torch.long)

'''use new_methods to construct a new tensor which own the same size of the 
ole ones '''
x = x.new_ones(5, 7, dtype=torch.double)

'''use rand_like method to construct a new tensor which own the same size of 
the old one but the values of the new tensor are random also the type of the 
 values are redefine'''
y: Tensor = torch.rand_like(x, dtype=torch.double)

double类型显示的所有张量都带有.

 得出张量的尺寸 

    print(x.size())

注意:x.size()函数本质返回的是一个tuple,因此它支持元组的所有操作。

基本运算操作

加法操作

第一种

    print(x+y)

第二种

z = torch.add(x,y)

第三种

'''define a new empty tensor, use the parameter of the add method to give the
 value of the method's result through " out " '''
result = torch.empty(5,7)
torch.add(x,y,out=result)

第四种(原地置换)

y.add_(x)

注意:所有的原地置换(in-place)都是存在小下划线的_,并且会改变原来的对象

利用Numpy切片的方式访问张量

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/581289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号