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

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

相关推荐
蛋王派4 分钟前
本地部署DeepSeek-OCR:打造高效的PDF文字识别服务
人工智能·自然语言处理·pdf·ocr
Pocker_Spades_A7 分钟前
Answer企业社区实战:零成本搭建技术问答平台,远程协作效率提升300%!
人工智能
南方的狮子先生10 分钟前
【深度学习】卷积神经网络(CNN)入门:看图识物不再难!
人工智能·笔记·深度学习·神经网络·机器学习·cnn·1024程序员节
2501_9389639618 分钟前
基于音乐推荐数据的逻辑回归实验报告:曲风特征与用户收听意愿预测
算法·机器学习·逻辑回归
2501_9387912222 分钟前
逻辑回归正则化解释性实验报告:L2 正则对模型系数收缩的可视化分析
算法·机器学习·逻辑回归
2501_9387900723 分钟前
逻辑回归正则化参数选择实验报告:贝叶斯优化与网格搜索的效率对比
算法·机器学习·逻辑回归
2501_9387802826 分钟前
逻辑回归特征重要性排序实验报告:不同特征选择方法的排序一致性验证
算法·机器学习·逻辑回归
TOWE technology1 小时前
同为科技定制PDU赋能智联未来
人工智能·科技·物联网·数据中心·idc·智能pdu·定制pdu
小叮当⇔1 小时前
安信可(Ai-Thinker)WiFi系列模块全解析:选型指南与应用洞察
人工智能·物联网·wifi·乐鑫
极客BIM工作室1 小时前
变分自编码器(VAE):用概率解锁生成式AI的“基因密码”
人工智能