[英]Python / Numpy: How can I avoid these for-loops?
我想重構這兩個函數以擺脫for
循環。 有什么想法可以使用 python / numpy 來完成嗎?
def hessian(self, theta, X):
matrix = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
for x in X:
g = self.gFunc(theta, x)
outer = np.outer(x, x)
matrix = matrix + g * (1.0 - g) * outer
return -matrix
def gradient(self, theta, X, Y):
gradient = np.array([0.0, 0.0, 0.0])
for x, y in zip(X, Y):
g = self.gFunc(theta, x)
gradient = gradient + (y - g) * x
return gradient
def gFunc(self, theta, x):
dot = np.dot(theta, x)
return 1.0 / (1.0 + np.exp(-dot))
或多或少,您可以將相同的運算符用於單一運算並將它們用於 numpy arrays,用於加法,乘法,...
def gradient2(self, theta, X: np.ndarray, Y: np.ndarray):
return np.multiply(Y - self.gFunc(theta, X), X).sum(axis=0)
對於hessian
,由於np.outer
我不知道如何簡化它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.