有沒有更有效的方法來用矩陣乘法替換這兩個 for 回圈?
def cost_func(x, y):
for i in range(24):
for j in range(24):
cost = np.sum(W[i][j]*(y[j] - x[i]))
return cost
W 是矩陣 (25,25),x,y 是具有 25 個元素的向量。
uj5u.com熱心網友回復:
不是 100% 確定您要在這里實作什么,因為正如 @Tim Roberts 指出的那樣,您并沒有節省成本。np.sum
假設并且是一維向量x
也是令人困惑的。y
但如果它們是一維向量,你可以這樣做:
import numpy as np
x = np.arange(24)
y = np.arange(24)
W = np.random.uniform(0, 1, (24, 24))
cost = (W * (y.reshape(1, -1) - x.reshape(-1, 1)))
# cost[i][j] = W[i][j]*(y[j] - x[i])
uj5u.com熱心網友回復:
numpy 支持矩陣乘法運算子@。我認為你可以通過以下方式得到你想要的:
C:\tmp>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> x = np.arange(3).reshape(1,3)
>>> y = np.arange(4)
>>> W = np.ones((3,4))
>>> (-x)@W@y
array([-18.])
>>>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470693.html
標籤:Python python-3.x python-2.7 for循环 矩阵
上一篇:Dart,for回圈中使用的int型別必須實作iterable
下一篇:你能把它合并成一個for回圈嗎?