机器学习 - PyTorch 常见的操作

可以用PyTorch做加减乘除操作

python 复制代码
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.

做矩阵相乘的规则:

python 复制代码
(3,2) * (3,2) => 不符合条件

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

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

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

python 复制代码
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)
Operation Calculation Code
Element-wise multiplication [11, 22, 3*3] = [1, 4, 9] tensor * tensor
Matrix multiplication [11 + 22 + 3*3] = [14] tensor.matmul(tensor)

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

相关推荐
啦啦啦在冲冲冲3 分钟前
解释一下roberta,bert-chinese和bert-case有啥区别还有bert-large这些
人工智能·深度学习·bert
deepdata_cn4 分钟前
混合架构大型语言模型(Jamba)
人工智能·语言模型
居7然5 分钟前
从零开始学大模型之预训练语言模型
人工智能·语言模型·自然语言处理·大模型
2401_8979300627 分钟前
PyTorch 中训练语言模型过程
人工智能·pytorch·语言模型
Edward.W27 分钟前
别再和正则表达式死磕了!这套AI工具集让你的开发效率翻倍⚙️[特殊字符]
人工智能·正则表达式
爆改模型33 分钟前
【Trans2025】计算机视觉|即插即用|AFANet:炸裂!图像分割新SOTA,轻松碾压传统方法!
人工智能·计算机视觉
陈敬雷-充电了么-CEO兼CTO36 分钟前
具身智能多模态感知与场景理解:融合语言模型的多模态大模型
人工智能·python·gpt·语言模型·自然语言处理·chatgpt·多模态
荔枝吻36 分钟前
【AI总结】Python BERT 向量化入门指南
人工智能·python·bert
张子夜 iiii1 小时前
传统神经网络实现-----手写数字识别(MNIST)项目
人工智能·pytorch·python·深度学习·算法