机器学习 - 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 1*1, 2*2, 3\*3 = 1, 4, 9 tensor * tensor
Matrix multiplication 1*1 + 2*2 + 3\*3 = 14 tensor.matmul(tensor)

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

相关推荐
雨落Re1 小时前
如何设计一个高质量Skill
人工智能
Token炼金师1 小时前
大模型权重文件全指南:从格式选择到优化实战
人工智能
阿牛哥_GX1 小时前
CDP 浏览器操控原理:让脚本接管你的浏览器
人工智能
ThreeS1 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
米小虾2 小时前
Loop Engineering —— 循环的设计与自主执行
人工智能·agent
米小虾3 小时前
Harness Engineering —— 系统的安全护栏
人工智能·agent
火山引擎开发者社区3 小时前
积分当钱花,火山引擎开发者激励计划首月消费双倍回馈
人工智能
aqi003 小时前
15天学会AI应用开发(十)把文本嵌入模型换成国产模型
人工智能·python·ai编程
MobotStone4 小时前
为什么在AI时代,“好奇心”成了最值钱的能力?
人工智能