ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[Pytorch]Tensor

2022-07-09 16:02:01  阅读:201  来源: 互联网

标签:Tensor torch 张量 Pytorch print data tensor


Tensors 张量

  • 张量是一种特殊的数据结构,与数组和矩阵非常相似。 在 PyTorch 中,我们使用张量来编码模型的输入和输出,以及模型的参数。

  • 张量类似于 NumPyndarray,张量可以在 GPU 或其他支持硬件加速器上运行。 事实上,张量和 NumPy 数组通常可以共享相同的底层内存,从而无需复制数据(参见 Bridge with NumPy)。 张量还针对自动微分进行了优化。

import torch 
import numpy as np 

1 初始化张量

1.1 直接从python数据

  • 数据类型会自行推断
data=[[1,2],[3,4]]
x_data=torch.tensor(data)
print(x_data)
print(x_data.type())
tensor([[1, 2],
        [3, 4]])
torch.LongTensor
  • 也可以指定类型
x_data=torch.tensor(data,dtype=torch.float)
x_data.type()
'torch.FloatTensor'

1.2 从numpy数组

np_array = np.array(data)
x_np = torch.from_numpy(np_array)
x_np
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)

1.3 从其他张量

x_ones = torch.ones_like(x_data) # 保留x_data的属性,类似于size、dtype等
print("Ones Tensor:\n{}\n".format(x_ones))
x_rand = torch.rand_like(x_data, dtype=torch.float) # 覆盖原有x_data的数据类型
print(f"Random Tensor: \n {x_rand} \n")
Ones Tensor:
tensor([[1., 1.],
        [1., 1.]])

Random Tensor: 
 tensor([[0.3120, 0.7532],
        [0.8578, 0.6995]]) 

1.4 从常量或者随机数

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}")
Random Tensor: 
 tensor([[0.8017, 0.0391, 0.3893],
        [0.6150, 0.4361, 0.8481]]) 

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

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

2 张量属性

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}")  # 使用存储张量的设备 CPU or GPU
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

3 张量操作

3.1 将张量存储(计算)至GPU

d=torch.ones(3)
print(d.device)
d=d.to("cuda")
print(d.device)
cpu
cuda:0

3.2 张量切片

tensor = torch.ones(4, 4) # 2维度的张量
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

3.3 张量连接

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

3.4 算术运算

# 矩阵相乘
tensor = torch.ones(4, 4) # 2维度的张量
y1 = tensor @ tensor.T # @矩阵相乘运算符
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(y1) # 先赋值,然后通过matmul计算相乘
torch.matmul(tensor, tensor.T, out=y3)
print(y3)

# 矩阵点乘
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor) # 先赋值,然后点乘输出
torch.mul(tensor, tensor, out=z3)
tensor([[4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.]])





tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])

可以用.sum()方法对张量求和,使用item()转化为python数值

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
16.0 <class 'float'>

In-place operations 将计算的值直接存储在变量中用对应_方法

print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]]) 

tensor([[6., 6., 6., 6.],
        [6., 6., 6., 6.],
        [6., 6., 6., 6.],
        [6., 6., 6., 6.]])

4 与numpy之间的转化

4.1 张量转化为numpy数组

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

在张量上的更改会直接改变numpy的值

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

4.2 numpy数组转化为Tensor

n = np.ones(5)
t = torch.from_numpy(n)

改变numpy的值会直接改变张量的值

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

标签:Tensor,torch,张量,Pytorch,print,data,tensor
来源: https://www.cnblogs.com/Vandaci/p/16461041.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有