背景:
在做吴恩达《机器学习》ex5作业时,出现ex5中的Figure 4图像与本人程序出的图像总是对不上的问题!如下:
![图1](https://i-blog.csdnimg.cn/blog_migrate/3368e74ca5c873ab16ad65f6f5f75e42.png)
图1 本人程序结果图
![图2](https://i-blog.csdnimg.cn/blog_migrate/dd3de1ee502bea0c2d604e50cfc6c1bb.png)
图2 exp5中Figure 4对应的结果图
把POWER改成6问题还是没解决。花了很多时间排查,发现是plot_fit函数(可视化上面图的函数)中出现了问题,具体排查出是:numpy.power()存在bug。
正文:
首先,看一下plot_fit函数:
def plot_poly_fit_line(theta, mu, sigma, power):
x = np.arange(-70, 50, step = 1)
x_ = np.column_stack((np.ones(len(x)), (poly_features(x, power) - mu) / sigma))
y = x_ @ theta
plt.plot(x, y, linestyle = '--')
这里的x = np.arange(-70, 50, step = 1)对应的类型是int型,而在多项式特征化函数poly_features()中里有np.power()函数,np.power函数存在以下bug:
从上图中可以看出,整型70的6次幂和浮点型70.的6次幂结果不同,而正确的答案是后者。经过验证np.power()6次幂以上存在这样的bug。我的numpy版本是:
综上,由于np.arange()默认为整型,导致x在进行多项式特征化时值不同,进而造成图像结果不同。
解决的方法:
将x定义为浮点型,如x = np.arange(-70, 50, step = 1, dtype = float)。