对于分类任务,用到的数据集是MNIST。该数据集由7w张手写数字图片构成。
from sklearn.datasets import fetch_openml
mnist=fetch_openml('mnist_784', version=1)
mnist.keys()
如果报错cannot import name 'fetch_openml',可能是scikit-learn版本过低,需要升级到0.2版本以上。
方法1:
在Anaconda Prompt中:
conda update scikit-learn
方法2:
下载scikit-learn包:
https://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn
我的Python版本是3.6.1,因此选择cp36m的。
然后在Anaconda Prompt中:
pip install D:\python机器学习\scikit_learn-0.24.0-cp36-cp36m-win_amd64.whl
sklearn加载的数据集通常包括data键和target键。
查看这两个数组:
X,y=mnist['data'], mnist['target']
X.shape
y.shape
其中X表示data键,y表示target键(即标签)。
随机查看一个实例:
import matplotlib as mpl
import matplotlib.pyplot as plt
some_digit=X[0]
some_digit_image=some_digit.reshape(28,28)
plt.imshow(some_digit_image, cmap='binary')
plt.axis('off')
plt.show()
查看其标签:
y[0]
标签是字符型,可以将其转换成整数型:
y=y.astype(np.uint8)
在MNIST数据集中,前6w张图片是训练集,后1w张图片是测试集。因此:
X_train, X_test, y_train, y_test=X[:60000], X[60000:], y[:60000], y[60000:]
由于并非时间序列数据,因此可以将训练集的数据进行混洗。
先训练一个二元分类器,目标是识别数字5,即将数字分为“5”和“非5”两个类别。
创建目标变量:
y_train_5=(y_train==5)
y_test_5=(y_test==5)
使用SGD分类器进行训练:
from sklearn.linear_model import SGDClassifier
sgd_clf=SGDClassifier(random_state=42)
sgd_clf.fit(X_train, y_train_5)
SGD即随机梯度下降,适合处理大型数据集。
进行预测:
sgd_clf.predict([some_digit])