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

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

相关推荐
Vane12 分钟前
从零开发一个AI插件,经历了什么?
人工智能·后端
70asunflower3 分钟前
2026年前沿人工智能语言模型评估:基于任务驱动的最佳模型选择路径
人工智能·语言模型·自然语言处理
geneculture9 分钟前
《智能通信速分多次传输技术(VDMT)》专利文件的全文汉英双语对照版本
服务器·网络·人工智能·融智学的重要应用·哲学与科学统一性·融智时代(杂志)·人机间性
湘-枫叶情缘12 分钟前
AI 编程时代 DDD 的理论重估:一种面向复杂业务与生成式智能的建模语言
人工智能·设计规范
DogDaoDao12 分钟前
【GitHub】andrej-karpathy-skills:让 AI 编程助手告别三大通病
人工智能·深度学习·程序员·大模型·github·ai编程·andrej-karpathy
Cosolar14 分钟前
一文吃透 LangChain&LangGraph:设计理念、框架结构与内部组件全拆解
人工智能·面试·架构
Joseph Cooper26 分钟前
RAG 与 AI Agent:智能体真的需要检索增强生成吗?
数据库·人工智能·ai·agent·rag·上下文工程
phoenix@Capricornus33 分钟前
卷积表示的错误
机器学习
LaughingZhu37 分钟前
Product Hunt 每日热榜 | 2026-04-29
人工智能·经验分享·深度学习·神经网络·产品运营
FindYou.1 小时前
机器学习day01(机器学习概述 + KNN算法)
人工智能·机器学习