Pytorch 学习第【2】天

张量是一种特殊的数据结构,它类似于数组与矩阵。在PyTorch中,主要使用张量来编码模块的输入和输出。张量类似于NumPy 的 nd array,但是张量(tensors) 可以在GUP或者其他硬件加速器上运行。

1.1 初始化张量


import torch
import numpy as np

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
print(x_data)

输出:

<class 'torch.Tensor'>

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

输出:

<class 'numpy.ndarray'>
[[1 2]
 [3 4]]
<class 'torch.Tensor'>
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
x_ones = torch.ones_like(x_data)
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float)
print(f"Random Tensor: \n {x_rand} \n")

输出:

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

Random Tensor:
 tensor([[0.8174, 0.9517],
        [0.5169, 0.0725]])

进程已结束,退出代码0

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}")

输出:

 tensor([[0.1193, 0.8213, 0.1462],
        [0.0224, 0.9084, 0.9621]])

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

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

进程已结束,退出代码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

这里全面描述了100多种张量运算,包括算术,线性代数,矩阵操作(转置,索引,切片),采样等。
在默认的情况下,张量是在CPU上创建的。我们需要使用方法(在检查 GPU 可用性之后)显式将张量移动到 GPU。请记住,在设备和内存方面,跨设备复制大张量可能很昂贵!.to

3.1. 判断是否存在GPU可用


if torch.cuda.is_available():
    print("存在GPU可用:")
    tensor = tensor.to("cuda")

输出:

存在GPU可用:

进程已结束,退出代码0

3.2. 标准类似 numpy 的索引和切片:

tensor = torch.ones(4, 4)
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.]])

进程已结束,退出代码0

3.3. cat 连接张量

tensor = torch.ones(4, 4)
tensor[:,1] = 0
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. 算术运算

它计算两个张量之间的矩阵乘法。Y1 y2 y3的值是一样的

tensor = torch.ones(4, 4)
tensor[:,1] = 0
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
print(y1)
print(y2)
print(y3)

输出:

tensor([[4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.]])
tensor([[4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.]])
tensor([[4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.],
        [4., 4., 4., 4.]])

这将计算元素的乘积。z1 z2 z3的值是一样的

tensor = torch.ones(4, 4)
tensor[:,1] = 0
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
print(z1)
print(z2)
print(z3)

输出:

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

进程已结束,退出代码0

单元素张量如果你有一个单元素张量,例如通过将一个张量的所有值聚合成一个值,你可以使用以下命令将其转换为Python数值:item()

agg = tensor.sum()
agg_item = agg.item()
print(agg, agg_item, type(agg_item))

输出:

tensor(12.) 12.0 <class 'float'>

. 3.3.4 add_

print(f"{tensor} \n")
tensor.add_(5)
print(tensor)

输出:

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

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

进程已结束,退出代码0

4.1. tensor 到NumPy数组

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

本文作者:九重!
本文链接:https://blog.csdn.net/weixin_43798572/article/details/123297754
关于博主:评论和私信会在第一时间回复。或者直接私信我。
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【点赞】【收藏】一下。您的鼓励是博主的最大动力!

Original: https://blog.csdn.net/weixin_43798572/article/details/123297754
Author: 九重!
Title: Pytorch 学习第【2】天

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/762737/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球