14-3-NN-recognise-images.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from sklearn.neural_network import MLPClassifier
  2. from sklearn.datasets import fetch_openml
  3. import matplotlib.pyplot as plt
  4. def main():
  5. mnist_data = fetch_openml("mnist_784")
  6. x, y = mnist_data.data / 255., mnist_data.target
  7. x_train, x_test = x[:60000], x[60000:]
  8. y_train, y_test = y[:60000], y[60000:]
  9. mlp = MLPClassifier(hidden_layer_sizes=(50,), max_iter=10, alpha=1e-4, solver='sgd', tol=1e-4, random_state=1,
  10. learning_rate_init=.1)
  11. # hidden_layer_sizes:第i个元素表示第i个隐藏层中的神经元数量。
  12. # slover:{‘lbfgs’,‘sgd’,‘adam’},默认’adam’。权重优化的求解器:'lbfgs’是准牛顿方法族的优化器;'sgd’指的是随机梯度下降。'adam’是指由Kingma
  13. # alpha:L2惩罚(正则化项)参数
  14. # random_state:默认无随机数生成器的状态或种子
  15. # max_iter:最大迭代次数
  16. # verbose:是否将进度消息打印到stdout
  17. # 优化的容忍度,容差优化
  18. # learning_rate_init:初始学习率
  19. mlp.fit(x_train, y_train)
  20. print(mlp.score(x_train, y_train)) # 0.9868
  21. print(mlp.score(x_test, y_test)) # 0.97
  22. fig, axes = plt.subplots(4, 4)
  23. # 使用“全局最小值/最大值”确保以相同的比例显示所有权重
  24. vmin, vmax = mlp.coefs_[0].min(), mlp.coefs_[0].max()
  25. for coef, ax in zip(mlp.coefs_[0].T, axes.ravel()):
  26. ax.matshow(coef.reshape(28, 28), cmap=plt.cm.gray, vmin=.5 * vmin, vmax=.5 * vmax)
  27. ax.set_xticks(())
  28. ax.set_yticks(())
  29. plt.show()
  30. if __name__ == "__main__":
  31. main()