鱼C论坛

 找回密码
 立即注册
查看: 1450|回复: 0

[技术交流] 机器学习系列------二元分类器

[复制链接]
发表于 2018-6-12 09:23:25 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
        还是继续昨天的项目,把以前的代码复制过来:
  1. from sklearn.datasets import fetch_mldata



  2. mnist=fetch_mldata('MNIST original',data_home='.\datasets')


  3. X,y=mnist["data"],mnist["target"]
  4. %matplotlib inline
  5. import matplotlib
  6. import matplotlib.pyplot as plt

  7. X_train,X_test,y_train,y_test=X[:60000],X[60000:],y[:60000],y[60000:]

  8. import numpy as np
  9. shuffle_index=np.random.permutation(60000)
  10. X_train,y_train=X_train[shuffle_index],y_train[shuffle_index]
  11. some_digit=X[36000]
复制代码

        今天我换了个目录,不知为什么又出网上把数据自动下载下来了,看来官方的接口没关,只是网太卡了 。二元分类就是对与错两种状态,我从一大堆数据里找出我要的那种,我们先建两个变量:
  1. y_train_5=(y_train==5)
  2. y_test_5=(y_test==5)
复制代码

        这是两组布尔值的数组,如果等于5就是true,不等于5就是false,然后我们建个分类器:
  1. from sklearn.linear_model import SGDClassifier

  2. sgd_clf=SGDClassifier(random_state=42)
  3. sgd_clf.fit(X_train,y_train_5)
复制代码

        这种分类器叫做随机梯度下降分类器Stochastic Gradient Descent classifier,然后预测一下昨天我们找出来的那个5是不是5:
  1. sgd_clf.predict([some_digit])
复制代码

        输出结果为:array([ True], dtype=bool)
        看来预测正确了,我们再预测个别的试试:
  1. sgd_clf.predict([X[20000]])
复制代码

        输出:array([False], dtype=bool)
        这个肯定就不是5,然后我们用过去学过的方法测试准确率:
  1. from sklearn.model_selection import StratifiedKFold
  2. from sklearn.base import clone

  3. skfolds=StratifiedKFold(n_splits=3,random_state=42)
  4. for train_index,test_index in skfolds.split(X_train,y_train_5):
  5.     clone_clf=clone(sgd_clf)
  6.     X_train_folds=X_train[train_index]
  7.     y_train_folds=(y_train_5[train_index])
  8.     X_test_fold=X_train[test_index]
  9.     y_test_fold=(y_train_5[test_index])
  10.    
  11.     clone_clf.fit(X_train_folds,y_train_folds)
  12.     y_pred=clone_clf.predict(X_test_fold)
  13.     n_correct=sum(y_pred==y_test_fold)
  14.     print(n_correct/len(y_pred))
复制代码

        这个因为是分为3组数据n_splits=3所以for循环3次,准确率分别为:
0.9625
0.9655
0.9633

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 05:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表