|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
还是继续昨天的项目,把以前的代码复制过来:
- from sklearn.datasets import fetch_mldata
- mnist=fetch_mldata('MNIST original',data_home='.\datasets')
- X,y=mnist["data"],mnist["target"]
- %matplotlib inline
- import matplotlib
- import matplotlib.pyplot as plt
- X_train,X_test,y_train,y_test=X[:60000],X[60000:],y[:60000],y[60000:]
- import numpy as np
- shuffle_index=np.random.permutation(60000)
- X_train,y_train=X_train[shuffle_index],y_train[shuffle_index]
- some_digit=X[36000]
复制代码
今天我换了个目录,不知为什么又出网上把数据自动下载下来了,看来官方的接口没关,只是网太卡了 。二元分类就是对与错两种状态,我从一大堆数据里找出我要的那种,我们先建两个变量:
- y_train_5=(y_train==5)
- y_test_5=(y_test==5)
复制代码
这是两组布尔值的数组,如果等于5就是true,不等于5就是false,然后我们建个分类器:
- from sklearn.linear_model import SGDClassifier
- sgd_clf=SGDClassifier(random_state=42)
- sgd_clf.fit(X_train,y_train_5)
复制代码
这种分类器叫做随机梯度下降分类器Stochastic Gradient Descent classifier,然后预测一下昨天我们找出来的那个5是不是5:
- sgd_clf.predict([some_digit])
复制代码
输出结果为:array([ True], dtype=bool)
看来预测正确了,我们再预测个别的试试:
- sgd_clf.predict([X[20000]])
复制代码
输出:array([False], dtype=bool)
这个肯定就不是5,然后我们用过去学过的方法测试准确率:
- from sklearn.model_selection import StratifiedKFold
- from sklearn.base import clone
- skfolds=StratifiedKFold(n_splits=3,random_state=42)
- for train_index,test_index in skfolds.split(X_train,y_train_5):
- clone_clf=clone(sgd_clf)
- X_train_folds=X_train[train_index]
- y_train_folds=(y_train_5[train_index])
- X_test_fold=X_train[test_index]
- y_test_fold=(y_train_5[test_index])
-
- clone_clf.fit(X_train_folds,y_train_folds)
- y_pred=clone_clf.predict(X_test_fold)
- n_correct=sum(y_pred==y_test_fold)
- print(n_correct/len(y_pred))
复制代码
这个因为是分为3组数据n_splits=3所以for循环3次,准确率分别为:
0.9625
0.9655
0.9633 |
|