gpt4 book ai didi

python - 如何对此代码执行 Numpy 优化?

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:36 25 4
gpt4 key购买 nike

我有以下代码片段:

def func1(self, X, y):
#X.shape = (455,13)
#y.shape = (455)

num_examples, num_features = np.shape(X)
self.weights = np.random.uniform(-1 / (2 * num_examples), 1 / (2 * num_examples), num_features)

while condition:
new_weights = np.zeros(num_features)
K = (np.dot(X, self.weights) - y)

for j in range(num_features):
summ = 0

for i in range(num_examples):
summ += K[i] * X[i][j]

new_weights[j] = self.weights[j] - ((self.alpha / num_examples) * summ)

self.weights = new_weights

此代码运行速度太慢。有什么我可以做的优化吗?

最佳答案

您可以高效地使用 np.einsum()。请参阅下面的测试版本:

def func2(X, y):
num_examples, num_features = np.shape(X)
weights = np.random.uniform(-1./(2*num_examples), 1./(2*num_examples), num_features)

K = (np.dot(X, weights) - y)

return weights - alpha/num_examples*np.einsum('i,ij->j', K, X)

关于python - 如何对此代码执行 Numpy 优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com