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

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

相关推荐
Coder个人博客2 分钟前
06_apollo_third_party子模块整体软件架构深入分析文档
linux·人工智能·架构
uzong3 分钟前
ClaudeCode 入门详细教程,手把手带你Vibe Coding
前端·人工智能
rebekk5 分钟前
PyTorch Dispatcher介绍
人工智能·pytorch·python
AI浩6 分钟前
第 11 章:多代理协作与编排 —— 从“单兵作战”到“集团军协同”
人工智能
一休哥※15 分钟前
ClawTeam 完整使用教程:用 AI 多智能体团队自动完成复杂任务
大数据·人工智能·elasticsearch
亦复何言??33 分钟前
BeyondMimic 论文解析
人工智能·算法·机器人
Lee川35 分钟前
🛠️ LangChain Tools 实战指南:让 AI 拥有“动手能力”
人工智能
gorgeous(๑>؂<๑)37 分钟前
【CVPR26-索尼】EW-DETR:通过增量低秩检测Transformer实现动态世界目标检测
人工智能·深度学习·目标检测·计算机视觉·transformer
xianluohuanxiang40 分钟前
新能源功率预测的“生死局”:从“能报曲线”到“能做收益”,中间差的不是一点算法
人工智能
码农垦荒笔记1 小时前
Claude Code 2026 年 3 月全面进化:Auto 模式、Computer Use 与云端持续执行重塑 AI 编程工作流
人工智能·ai 编程·claude code·agentic coding·computer use