机器学习 - 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)

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

相关推荐
AI人工智能+9 分钟前
应用俄文OCR技术,为跨语言交流与数字化管理提供更强大的支持
人工智能·ocr·文字识别
UQI-LIUWJ21 分钟前
李宏毅LLM笔记: AI Agent
人工智能·笔记
百度Geek说33 分钟前
百度阮瑜:百度大模型应用赋能产业智变|2025全球数字经济大会
人工智能
大明哥_37 分钟前
最新 Coze 教程:40+ 条视频涨粉 10W+,利用 Coze 工作流 + 视频组件,一键制作爆款小人国微景动画视频
人工智能·agent
SugarPPig1 小时前
ReAct (Reason and Act) OR 强化学习(Reinforcement Learning, RL)
人工智能
孤狼warrior1 小时前
灰色预测模型
人工智能·python·算法·数学建模
AI生存日记1 小时前
AI 行业早报:微软发布诊断工具,上海聚焦四大应用场景
人工智能·microsoft·机器学习·open ai大模型
求职小程序华东同舟求职1 小时前
龙旗科技社招校招入职测评25年北森笔试测评题库答题攻略
大数据·人工智能·科技
李元豪1 小时前
【行云流水ai笔记】粗粒度控制:推荐CTRL、GeDi 细粒度/多属性控制:推荐TOLE、GPT-4RL
人工智能·笔记
机器学习之心1 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络