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

Pytorch 张量

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

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.]

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

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

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