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

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

相关推荐
IT猿手2 小时前
2025最新群智能优化算法:山羊优化算法(Goat Optimization Algorithm, GOA)求解23个经典函数测试集,MATLAB
人工智能·python·算法·数学建模·matlab·智能优化算法
Jet45053 小时前
玩转ChatGPT:GPT 深入研究功能
人工智能·gpt·chatgpt·deep research·深入研究
毕加锁3 小时前
chatgpt完成python提取PDF简历指定内容的案例
人工智能·chatgpt
Wis4e5 小时前
基于PyTorch的深度学习3——基于autograd的反向传播
人工智能·pytorch·深度学习
西猫雷婶5 小时前
神经网络|(十四)|霍普菲尔德神经网络-Hebbian训练
人工智能·深度学习·神经网络
梦丶晓羽6 小时前
自然语言处理:文本分类
人工智能·python·自然语言处理·文本分类·朴素贝叶斯·逻辑斯谛回归
SuperCreators6 小时前
DeepSeek与浏览器自动化AI Agent构建指南
人工智能·自动化
美狐美颜sdk6 小时前
什么是美颜SDK?从几何变换到深度学习驱动的美颜算法详解
人工智能·深度学习·算法·美颜sdk·第三方美颜sdk·视频美颜sdk·美颜api
訾博ZiBo6 小时前
AI日报 - 2025年3月10日
人工智能
waicsdn_haha6 小时前
Postman v11 安装与API测试入门教程(Windows平台)
人工智能·windows·测试工具·mysql·postman·dbeaver·rest