我编写了代码来绘制给定数据集上线性函数的平均平方误差,以可视化最佳回归线的梯度下降训练期间的进度。
相关位如下:
def compute_error(f, X, Y):
e = lambda x, y : (y - f(x))**2
return sum(e(x, y) for (x, y) in zip(X, Y))/len(X)
mn, bn, density = abs(target_slope)*1.5, abs(target_intercept)*1.5, 20
M, B = map(list, zip(*[(m, b) for m in np.linspace(-mn, +mn, density)
for b in np.linspace(-bn, +bn, density)]))
E = [compute_error(lambda x : m*x+b, X, Y) for m, b in zip(M,B)]
这可行,但非常困惑。我怀疑可能有一种非常简洁的方法可以用 numpy 完成同样的事情。到目前为止我已经得到了这个:
M, B = map(np.ndarray.flatten, np.mgrid[-mn:+mn:1/density, -bn:+bn:1/density])
我仍然不知道如何改进 E
的实例化,并且由于某种原因,现在它比困惑的版本慢很多。
那么,用 numpy 映射像 M
XB
这样的平面的好方法是什么?
如果你想运行上面的代码,你可以像这样构建X
和Y
:
import numpy as np
from numpy.random import normal
target_slope = 3
target_intercept = 15
def generate_random_data(slope=1, minx=0, maxx=100, n=200, intercept=0):
f = lambda x : normal(slope*x, maxx/5)+intercept
X = np.linspace(minx, maxx, n)
Y = [f(x) for x in X]
return X, Y
X, Y = generate_random_data(slope=target_slope, intercept=target_intercept)
最佳答案
def compute_error(f, X, Y):
return np.mean( (Y - f(X))**2 )
MB = np.mgrid[-mn:+mn:2*mn/density, -bn:+bn:2*bn/density]
MB = MB.reshape((2, -1)).T
E = [compute_error(lambda x : m*x+b, X, Y) for m, b in MB]
可以编写完整的 numpy 解决方案:
Y = np.array(Y)
M, B = np.mgrid[-mn:+mn:2*mn/density, -bn:+bn:2*bn/density]
mx = M.reshape((-1,1))*X
b = B.reshape((-1,1))*np.ones_like(X)
E = np.mean( (mx+b - Y)**2, axis=1 )
也可以编写一个解决方案,而不需要展平数组并以 2D 数组的形式获取错误......
关于python - 如何使用 numpy 简洁地映射平面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51507156/