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

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

相关推荐
袁庭新14 分钟前
使用扣子+飞书+DeepSeek搭建批量提取公众号文章内容并改写的智能体
人工智能·aigc·coze
黑心萝卜三条杠27 分钟前
解码微生物适应性的关键:基因组序列与栖息地预测的深度关联
人工智能
黑心萝卜三条杠1 小时前
Everywhere Attack:通过多目标植入提升对抗样本的目标迁移性
人工智能
carpell1 小时前
【语义分割专栏】3:Segnet原理篇
人工智能·python·深度学习·计算机视觉·语义分割
ahead~1 小时前
【大模型原理与技术-毛玉仁】第五章 模型编辑
人工智能·深度学习·机器学习
迪娜学姐1 小时前
GenSpark vs Manus实测对比:文献综述与学术PPT,哪家强?
论文阅读·人工智能·prompt·powerpoint·论文笔记
TDengine (老段)2 小时前
TDengine 在电力行业如何使用 AI ?
大数据·数据库·人工智能·时序数据库·tdengine·涛思数据
猎板PCB厚铜专家大族2 小时前
高频 PCB 技术发展趋势与应用解析
人工智能·算法·设计规范
l0sgAi2 小时前
SpringBoot整合LangChain4j实现RAG (检索增强生成)
人工智能
祐言QAQ2 小时前
浅谈边缘计算
人工智能·边缘计算