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

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

相关推荐
视觉&物联智能1 分钟前
【杂谈】-人工智能蓬勃演进背后的隐性支撑体系
人工智能·ai·aigc·算力·agi·deepseek
IT WorryFree2 分钟前
openclaw飞书机器人权限管理
人工智能·机器人·飞书
吴佳浩5 分钟前
OpenClaw、Claude Code 等 Agent 为什么都选择 Node.js?
前端·人工智能·langchain
CoovallyAIHub7 分钟前
开源一周 6300+ Star!Andrew Ng 发布 Context Hub,专治 AI Agent 调用过时 API
人工智能·架构·github
witAI11 分钟前
**GLM5剧本拆解2025指南,解锁多模态创作新范式**
人工智能·python
badhope15 分钟前
C语言二级考点全解析与真题精讲
c语言·开发语言·c++·人工智能·python·microsoft·职场和发展
爱吃的小肥羊17 分钟前
Claude Code Skills 资源大盘点:导航站 + GitHub 精选仓库全整理
人工智能·ai编程
ai产品老杨19 分钟前
终结协议孤岛:基于GB28181/RTSP融合网关的多品牌设备统一接入与边缘推流方案
人工智能·docker·架构·kubernetes·音视频
Dr_哈哈22 分钟前
给 AI 装技能包:skills 生态科普
人工智能
沉沙丶27 分钟前
模型预测控制专题(九)—— 进一步优化的方向
人工智能·电机控制·永磁同步电机·模型预测·预测控制·pmsm·无模型预测控制