我试图使用MLPRegressor来拟合一个预定义的三维函数。问题是我无法打印出正确的结果,因此当我绘制图表时,拟合效果看起来非常糟糕。
函数如下所示:
def threeDFunc(xin,yin): z = np.zeros((40,40)) for xIndex in range(0,40,1): for yIndex in range(0,40,1): z[xIndex,yIndex]=(np.exp(-(xin[xIndex]**2+yin[yIndex]**2)/0.1)) return zxThD = np.arange(-1,1,0.05)yThD = np.arange(-1,1,0.05)zThD = threeDFunc(xThD, yThD)
上图是它应该近似的结果。
红色部分是实际拟合的结果。
代码如下:
classifier = neural_network.MLPRegressor(hidden_layer_sizes=(200, 200), activation='logistic', learning_rate='adaptive')xy = np.array((xThD.flatten(),yThD.flatten()))classifier.fit(np.transpose(xy), zThD)pre = classifier.predict(np.transpose(xy))import pylabfrom mpl_toolkits.mplot3d import Axes3Dfig = pylab.figure()ax = Axes3D(fig)X, Y = np.meshgrid(xThD, yThD)ax.plot_wireframe(X, Y, zThD)ax.plot_wireframe(X, Y, pre, color='red')print(np.shape(zThD))print(np.shape(pre))plt.show()
回答:
将激活函数改为双曲正切函数,使用activation='tanh'
,并将求解器改为lbfgs,使用solver='lbfgs'
。
如果你的分类器实例化如下所示,红色和蓝色的图表应该几乎相同:
classifier = neural_network.MLPRegressor(hidden_layer_sizes=(200, 200), solver='lbfgs', activation='tanh', learning_rate='adaptive')