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

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

相关推荐
NAGNIP2 小时前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
moshuying4 小时前
别让AI焦虑,偷走你本该有的底气
前端·人工智能
董董灿是个攻城狮4 小时前
零基础带你用 AI 搞定命令行
人工智能
喝拿铁写前端7 小时前
Dify 构建 FE 工作流:前端团队可复用 AI 工作流实战
前端·人工智能
阿里云大数据AI技术7 小时前
阿里云 EMR Serverless Spark + DataWorks 技术实践:引领企业 Data+AI 一体化转型
人工智能
billhan20167 小时前
MCP 深入理解:协议原理与自定义开发
人工智能
Jahzo7 小时前
openclaw桌面端体验--ClawX
人工智能·github
billhan20168 小时前
Agent 开发全流程:从概念到生产
人工智能
threerocks8 小时前
过了个年,AI 圈变天了?但没人告诉你为什么
人工智能