Python 之 numpy 和 tensorflow 中的各种乘法(点乘和矩阵乘)

点乘和矩阵乘的区别:

1)点乘(即“ * ”) ---- 各个矩阵对应元素做乘法

若 w 为 m*1 的矩阵,x 为 m*n 的矩阵,那么通过点乘结果就会得到一个 m*n 的矩阵。

 

 

若 w 为 m*n 的矩阵,x 为 m*n 的矩阵,那么通过点乘结果就会得到一个 m*n 的矩阵。

 

 

w的列数只能为 1 与x的列数相等(即n),w的行数与x的行数相等 才能进行乘法运算。

2)矩阵乘 ---- 按照矩阵乘法规则做运算

若 w 为 m*p 的矩阵,x 为 p*n 的矩阵,那么通过矩阵相乘结果就会得到一个 m*n 的矩阵。

只有 w 的列数 == x的行数 时,才能进行乘法运算

 

1. numpy

1)点乘

1 import numpy as np
2 
3 w = np.array([[0.4], [1.2]])
4 x = np.array([range(1,6), range(5,10)])
5 
6 print w
7 print x
8 print w*x

运行结果如下图:

 2)矩阵乘

1 import numpy as np
2 
3 w = np.array([[0.4, 1.2]])
4 x = np.array([range(1,6), range(5,10)])
5 
6 print w
7 print x
8 print np.dot(w,x)

运行结果如下:

 

2. tensorflow

 1)点乘

复制代码
 1 import tensorflow as tf
 2 
 3 w = tf.Variable([[0.4], [1.2]], dtype=tf.float32) # w.shape: [2, 1]
 4 x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5]
 5 y = w * x     # 等同于 y = tf.multiply(w, x)   y.shape: [2, 5]
 6 
 7 sess = tf.Session()
 8 init = tf.global_variables_initializer()
 9 sess.run(init)
10 
11 print sess.run(w)
12 print sess.run(x)
13 print sess.run(y)
复制代码

 运行结果如下:

 

 2)矩阵乘

复制代码
 1 # coding:utf-8
 2 import tensorflow as tf
 3 
 4 w = tf.Variable([[0.4, 1.2]], dtype=tf.float32) # w.shape: [1, 2]
 5 x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5]
 6 y = tf.matmul(w, x) # y.shape: [1, 5]
 7 
 8 sess = tf.Session()
 9 init = tf.global_variables_initializer()
10 sess.run(init)
11 
12 print sess.run(w)
13 print sess.run(x)
14 print sess.run(y)
复制代码

 运行结果如下:

 

posted on   刘[小]倩  阅读(73017)  评论(4编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示