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

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

相关推荐
风象南37 分钟前
OpenClaw Token 太贵顶不住?试试 Coding Plan
人工智能
万少8 小时前
小龙虾(openclaw),轻松玩转自动发帖
前端·人工智能·后端
飞哥数智坊9 小时前
openclaw 重大更新,真的懂我啊
人工智能
KaneLogger9 小时前
AI 时代编程范式迁移的思考
人工智能·程序员·代码规范
飞哥数智坊9 小时前
养虾记第2期:从“人工智障”到“赛博分身”,你的龙虾还缺这两个灵魂
人工智能
飞哥数智坊9 小时前
龙虾虽香,小心扎手!官方点名后,我们该怎么“养虾”?
人工智能
yiyu071610 小时前
3分钟搞懂深度学习AI:实操篇:卷积层
人工智能·深度学习
字节架构前端11 小时前
Skill再回首—深度解读Anthropic官方最新Skill白皮书
人工智能·agent·ai编程
冬奇Lab12 小时前
OpenClaw 深度解析(八):Skill 系统——让 LLM 按需学习工作流
人工智能·开源·源码阅读