可以用PyTorch做加减乘除操作

import torch

tensor_operation = torch.tensor([1,2,3])
print(tensor_operation)

print(tensor_operation + 10)
print(torch.add(tensor_operation, 10))

print(tensor_operation * 10) 
print(torch.multiply(tensor_operation, 10))

print(tensor_operation - 10)
print(tensor_operation / 10)

print(tensor_operation * tensor_operation)

# 输出

0s
tensor_operation = torch.tensor([1,2,3])
print(tensor_operation)

print(tensor_operation + 10)
print(torch.add(tensor_operation, 10))

print(tensor_operation * 10) 
print(torch.multiply(tensor_operation, 10))

print(tensor_operation - 10)

tensor([1, 2, 3])
tensor([11, 12, 13])
tensor([11, 12, 13])
tensor([10, 20, 30])
tensor([10, 20, 30])
tensor([-9, -8, -7])
tensor([0.1000, 0.2000, 0.3000])
tensor([1, 4, 9])


矩阵相乘

One of the most common operations in machine learning and deep learning algorithms (like neural networks) is matrix multiplication.

做矩阵相乘的规则:

(3,2) * (3,2) => 不符合条件

(2,3) * (3,2) = (2,2)

(3,2) * (2,3) = (3,3)

在 PyTorch 里,可以使用 torch.matmul() 方法。

tensor_matrix = torch.tensor([1,2,3])
print(tensor_matrix * tensor_matrix)
print(torch.matmul(tensor_matrix, tensor_matrix))
print(tensor_matrix.matmul(tensor_matrix))

# 结果
tensor([1, 4, 9])
tensor(14)
tensor(14)

都看到这里了,给个赞咯~

03-20 21:54