文章目录
引言
在 Python 编程中,有一些常用技巧和最佳实践可以帮助你编写更优雅、更高效的代码。本文将介绍的是 Python 中使用 Scikit-Learn
下载 MNIST
数据,并训练模型,序列化模型、MLPClassifier
模型的参数查看、MLPClassifier 的激活函数
及其实现、从 pandas.core.frame.DataFrame
中获取数据等。
Scikit-Learn 下载 MNIST 数据、训练模型、序列化模型
下面是使用 Scikit-Learn
下载 MNIST
数据集并训练一个具有 3 层(2 个隐层,其中第 1 层有 50 个神经元,第 2 层有 100 个神经元)的神经网络模型的示例。
安装依赖库
确保已经安装 scikit-learn
和 numpy
。可以使用以下命令安装:
pip install scikit-learn numpy
训练模型
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report, accuracy_score
# 下载 MNIST 数据集
mnist = fetch_openml('mnist_784', version=1)
X, y = mnist.data, mnist.target
# 将目标标签转换为整数
y = y.astype(int)
# 拆分数据集为训练和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 初始化并训练神经网络模型
model = MLPClassifier(hidden_layer_sizes=(50, 100), max_iter=20, random_state=42)
model.fit(X_train, y_train)
# 进行预测
y_pred = model.predict(X_test)
# 输出结果
print(f"准确率: {
accuracy_score(y_test, y_pred)}")
print(classification_report(y_test, y_pred))
运行上述代码后,程序将训练一个 3 层的神经网络模型,并输出测试集的准确率和分类报告,从而给出模型的性能评估。
准确率: 0.9499
precision recall f1-score support
0 0.97 0.99 0.98 980
1 0.98 0.98 0.98 1135
2 0.95 0.95 0.95 1032
3 0.93 0.93 0.93 1010
4 0.97 0.92 0.94 982
5 0.95 0.93 0.94 892
6 0.97 0.96 0.96 958
7 0.97 0.94 0.96 1028
8 0.91 0.95 0.93 974
9 0.91 0.95 0.93