PyTorch 数据矩阵操作:实现 NumPy 相同功能 - 深度学习框架
PyTorch 数据矩阵操作:实现与 NumPy 相同的功能
本教程将演示如何在 PyTorch 中实现与 NumPy 相同的数据矩阵操作,包括数学函数、随机数组生成和矩阵形状修改。
1. 实现数学操作函数
首先,我们将实现一些基本的数学操作函数,例如平方、加法和绝对值,以及一个随机数组生成函数。
import torch
import numpy as np
# 数学操作函数
def square(x):
return torch.pow(x, 2)
# 加法操作函数
def add(x, y):
return torch.add(x, y)
# 绝对值操作函数
def abs(x):
return torch.abs(x)
# 随机生成数组函数
def random_array(shape):
return torch.randn(shape)
# 测试
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
print(square(x))
print(add(x, y))
print(abs(torch.tensor([-1, 2, -3])))
print(random_array((2, 3)))
输出:
tensor([1, 4, 9])
tensor([5, 7, 9])
tensor([1, 2, 3])
tensor([[-0.4763, -0.1333, -0.6454],
[ 0.5204, 0.3365, -0.8535]])
2. 利用 PyTorch 修改矩阵形状
接下来,我们将学习如何使用 PyTorch 修改矩阵的形状,而不会影响数据数量。
import torch
# 改变矩阵形状
def reshape(x, shape):
return torch.reshape(x, shape)
# 测试
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(reshape(x, (3, 2)))
print(x)
输出:
tensor([[1, 2],
[3, 4],
[5, 6]])
tensor([[1, 2, 3],
[4, 5, 6]])
可以看到,改变形状后的矩阵是新的,原来的矩阵并没有被修改。
原文地址: https://www.cveoy.top/t/topic/oNl5 著作权归作者所有。请勿转载和采集!