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)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值