热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

【深度学习】python矩阵乘积运算(multiply/maumul/*/@)

在训练数据时经常涉及到矩阵运算,有段时间没有练习过了,手便生疏了,今天重新测了一把,python中各类矩阵运算举例如下&#x

在训练数据时经常涉及到矩阵运算,有段时间没有练习过了,手便生疏了,今天重新测了一把,python中各类矩阵运算举例如下,可以清楚的看到tf.matmul(A,C)=np.dot(A,C)= A@C都属于叉乘,而tf.multiply(A,C)= A*C=A∙C属于点乘。

Python测试编码如下:

import tensorflow as tf
import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([5,6])
c = np.array([[5,6],[7,8]])
print(‘a:’+’\n’,a)
print(‘b:’+’\n’,b)
print(‘c:’+’\n’,c)
#叉乘
d1=a@c
d2=tf.matmul(a,c)
d3=np.dot(a,c)
#点乘
f1=a*c
f2=tf.multiply(a,c)

with tf.compat.v1.Session() as sess:
print(‘d1:叉乘a@c’ + ‘\n’, d1)
print(‘d2:叉乘matmul(a,c)’ + ‘\n’, sess.run(d2))
print(‘d3:叉乘dot(a,c)’ + ‘\n’, d3)
print(‘f1:点乘a*c’ + ‘\n’, f1)
print(‘f2:点乘multiply(a,c)’ + ‘\n’, sess.run(f2))

测试结果如下:

import torch
from torch import nnclass MyLinear(nn.Module):def __init__(self, in_features, out_features):super().__init__()self.weight = nn.Parameter(torch.randn(in_features, out_features))self.bias = nn.Parameter(torch.randn(out_features))def forward(self, input):return (input @ self.weight) + 2*self.bias # 其中的@,torch.matmul, torch.dot,numpy.dot.# torch.mul(), torch.multipy(), *, 是点乘积。m = MyLinear(4, 3)
sample_input = torch.randn(4)
k = m(sample_input)
print(k)

推荐阅读
author-avatar
大叔丶你好哇塞
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有