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

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

相关推荐
Li emily1 小时前
成功接入A股实时行情API获取实时市场数据
人工智能·python·金融·fastapi
China_Yanhy2 小时前
转型AI运维工程师·Day 7:构建“数据飞轮” —— 每一句对话都是资产
运维·人工智能·状态模式
苍何2 小时前
爆肝 2 天,用 GLM5 开发了 OpenClaw 接入微信 bot,已开源!
人工智能
kuankeTech2 小时前
“数改智转”加速跑:外贸ERP助力钢铁智能工厂“提质增效”
大数据·人工智能·经验分享·软件开发·erp
澳鹏Appen2 小时前
澳鹏无锡成功获评国家高新技术企业
人工智能
threerocks2 小时前
前端将死,Agent 永生
前端·人工智能·ai编程
苍何2 小时前
偶然间发现一款逆天的 AI PPT 工具!免费生成!
人工智能
苍何2 小时前
Openclaw + OpenCode 才是 vibe coding 的最棒组合!
人工智能
AI360labs_atyun3 小时前
字节AI双王炸来了!Seedance 2.0 + Seedream 5.0
人工智能·科技·学习·百度·ai
AIMarketing3 小时前
2026 年 GEO 综合实力服务商推荐 行业研究与实践分析
人工智能