numpy和tensorflow中的各種乘法(點乘和矩陣乘)
點乘和矩陣乘的區(qū)別:
1)點乘(即“ * ”) ---- 各個矩陣對應元素做乘法
若 w 為 m*1 的矩陣,x 為 m*n 的矩陣,那么通過點乘結(jié)果就會得到一個 m*n 的矩陣。

若 w 為 m*n 的矩陣,x 為 m*n 的矩陣,那么通過點乘結(jié)果就會得到一個 m*n 的矩陣。

w的列數(shù)只能為 1 或 與x的列數(shù)相等(即n),w的行數(shù)與x的行數(shù)相等 才能進行乘法運算。
2)矩陣乘 ---- 按照矩陣乘法規(guī)則做運算
若 w 為 m*p 的矩陣,x 為 p*n 的矩陣,那么通過矩陣相乘結(jié)果就會得到一個 m*n 的矩陣。
只有 w 的列數(shù) == x的行數(shù) 時,才能進行乘法運算

1. numpy
1)點乘
import numpy as np w = np.array([[0.4], [1.2]]) x = np.array([range(1,6), range(5,10)]) print w print x print w*x
運行結(jié)果如下圖:

2)矩陣乘
import numpy as np w = np.array([[0.4, 1.2]]) x = np.array([range(1,6), range(5,10)]) print w print x print np.dot(w,x)
運行結(jié)果如下:

2. tensorflow
1)點乘
import tensorflow as tf w = tf.Variable([[0.4], [1.2]], dtype=tf.float32) # w.shape: [2, 1] x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5] y = w * x # 等同于 y = tf.multiply(w, x) y.shape: [2, 5] sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) print sess.run(w) print sess.run(x) print sess.run(y)
運行結(jié)果如下:

2)矩陣乘
# coding:utf-8 import tensorflow as tf w = tf.Variable([[0.4, 1.2]], dtype=tf.float32) # w.shape: [1, 2] x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5] y = tf.matmul(w, x) # y.shape: [1, 5] sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) print sess.run(w) print sess.run(x) print sess.run(y)
運行結(jié)果如下:

到此這篇關于numpy和tensorflow中的各種乘法(點乘和矩陣乘)的文章就介紹到這了,更多相關numpy和tensorflow 乘法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
利用Chatgpt開發(fā)一款加減乘除計算器(Python代碼實現(xiàn))
這篇文章主要為大家詳細介紹了如何利用Chatgpt開發(fā)一款加減乘除計算器(用Python代碼實現(xiàn)),文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-02-02
Python實現(xiàn)爬取網(wǎng)頁中動態(tài)加載的數(shù)據(jù)
這篇文章主要介紹了Python實現(xiàn)爬取網(wǎng)頁中動態(tài)加載的數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08
Python基于jieba庫進行簡單分詞及詞云功能實現(xiàn)方法
這篇文章主要介紹了Python基于jieba庫進行簡單分詞及詞云功能實現(xiàn)方法,結(jié)合實例形式分析了Python分詞庫jieba以及wordcloud庫進行詞云繪制相關步驟與操作技巧,需要的朋友可以參考下2018-06-06

