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

pytorch---关于tensor的一些常规知识点

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

pytorch---关于tensor的一些常规知识点

1、创建一个服从均匀分布或者随机分布的张量,其大小可变,可一维,二维

tensor.rand(均匀) :区间(0,1)
与tensor.randn(正太分布):标准差为0,方差为1
参数:
size (int…) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.

y = torch.rand(4)
y1 = torch.rand(2,3)
print(y)
print(y1)

x = torch.randn(4)
x1 = torch.randn(2,3)
print(x)
print(x1)

输出结果:

tensor([0.4162, 0.4271, 0.0685, 0.1288])
tensor([[0.9016, 0.5871, 0.0199],
        [0.4834, 0.1247, 0.3603]])
        
tensor([ 0.8691,  1.4418,  1.5524, -0.8321])
tensor([[-1.2848,  0.1464,  0.6162],
        [-0.2246,  1.0506, -0.2157]])

2、torch.range:返回一个一维张量,左开右闭,可带步长
torch.arange:返回一个一维张量,左开右闭,可带步长
参数:
start (Number) – the starting value for the set of points. Default: 0.
end (Number) – the ending value for the set of points
step (Number) – the gap between each pair of adjacent points. Default: 1.

z = torch.arange(1,6)
print(z)

结果如下:

tensor([1, 2, 3, 4, 5])

小技巧:
返回一维张量的有:linspace,logspace,arange,range
形状可变的有:ones,zeros,rand, randn

二、numpy 与tensor之间的转换

  1. 由Numpy array数组转为张量
import numpy as np
import torch

numpy_data = np.array([1,4,5])
numpy_to_tensor = torch.from_numpy(numpy_data)

print(numpy_to_tensor)

结果如下:

2、 由张量变换为Numpy array数组

tensor_data = torch.randn(2, 4)
tensor_to_numpy = tensor_data.numpy()
print(tensor_data)
print(tensor_to_numpy)

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

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

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