Pytorch 张量

在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。

张量初始化

import torch
import numpy as np
#初始化
#直接数据转张量
data=[[1,2],[3,4]]
x_data=torch.tensor(data)
#numpy数组转张量
np_array=np.array(data)
x_np=torch.from_numpy(np_array)
#从另一个张量中来
x_ones=torch.ones_like(x_data)#根据给定张量生成与其形状相同的全1张量,x_ones=tensor([[1, 1],[1, 1]])
print(f"Ones Tensor:\n{x_ones}\n")
x_rand=torch.rand_like(x_data,dtype=torch.float)#根据给定张量生成与其形状相同的随机张量,x_ones= tensor([[0.4621, 0.1440],[0.6105, 0.6398]])
print(f"Random Tensor:\n{x_rand}\n")
#使用随机或恒定值
shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
Ones Tensor:
tensor([[1, 1],
        [1, 1]])

Random Tensor:
tensor([[0.7534, 0.7931],
        [0.6865, 0.4835]])

Random Tensor: 
 tensor([[0.9617, 0.6932, 0.2289],
        [0.1303, 0.1489, 0.2075]]) 

Ones Tensor: 
 tensor([[1., 1., 1.],
        [1., 1., 1.]]) 

Zeros Tensor: 
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

Process finished with exit code 0

张量属性

#张量属性,包括形状,数据类型和存储设备
tensor = torch.rand(3, 4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

与numpy的连接

#torch与numpy的桥接,torch和numpy共享底层内存位置,改变一个会改变另一个
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
n = np.ones(5)
t = torch.from_numpy(n)
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值