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

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

相关推荐
财迅通Ai4 小时前
商业航天概念领涨A股,航天ETF华安(159267.SZ)收盘上涨1.2%
大数据·人工智能·区块链·中国卫星·航天电子
齐齐大魔王4 小时前
智能语音技术(八)
人工智能·语音识别
许彰午5 小时前
零成本搭建RAG智能客服:Ollama + Milvus + DeepSeek全程实战
人工智能·语音识别·llama·milvus
ZPC82105 小时前
自定义action server 接收arm_controller 指令
人工智能·机器人
迷茫的启明星5 小时前
各职业在当前发展阶段,使用AI的舒适区与盲区
大数据·人工智能·职场和发展
Liqiuyue6 小时前
Transformer:现代AI革命背后的核心模型
人工智能·算法·机器学习
桂花饼6 小时前
AI 视频生成:sora-2 模型快速对接指南
人工智能·音视频·sora2·nano banana 2·claude-opus-4-6·gemini 3.1
GreenTea7 小时前
AI Agent 评测的下半场:从方法论到落地实践
前端·人工智能·后端
冬奇Lab8 小时前
一天一个开源项目(第73篇):Multica - 把 AI 编程智能体变成真正的团队成员
人工智能·开源·资讯