-#!/usr/bin/env python

-# # # -- coding: utf-8 --

-# # # @Time : 2019.5.22 14:09

-# # # @Author : AndrewCHH

-# # # @File : after_class.py

1. 获取数据

  • 使用MNIST数据集练习分类任务
  1. from __future__ import print_function
  2. import pandas as pd
  3. # 导入后加入以下列,再显示时显示完全。
  4. pd.set_option('display.max_rows', 500)
  5. pd.set_option('display.max_columns', 500)
  6. pd.set_option('display.width', 1000)
  7. from sklearn.datasets import fetch_mldata
  8. from scipy.io import loadmat
  9. mnist = fetch_mldata('MNIST original', transpose_data=True, data_home='files')
  10. print("mnist",mnist)
  11. # *DESCR为description,即数据集的描述
  12. # *CLO_NAMES为列名
  13. # *target键,带有标记的数组
  14. # *data键,每个实例为一行,每个特征为1列
  15. # 共七万张图片,每张图片784个特征点
  16. X, y = mnist["data"], mnist["target"]
  17. print(X.shape, y.shape)
  18. print(type(X))
  19. # 显示图片
  20. import matplotlib
  21. import matplotlib.pyplot as plt
  22. some_digit = X[36001]
  23. some_digit_image = some_digit.reshape(28, 28) # 将一维数组转化为28*28的数组
  24. # cmap->颜色图谱(colormap)
  25. # interpolation: 图像插值参数,图像插值就是利用已知邻近像素点的灰度值(或rgb图像中的三色值)来产生未知像素点的灰度值,以便由原始图像再生出具有更高分辨率的图像。
  26. # * If interpolation is None, it defaults to the image.interpolation rc parameter.
  27. # If the interpolation is 'none', then no interpolation is performed for the Agg, ps and pdf backends. Other backends will default to 'nearest'.
  28. # For the Agg, ps and pdf backends, interpolation = 'none' works well when a big image is scaled down,
  29. # while interpolation = 'nearest' works well when a small image is scaled up.
  30. plt.imshow(some_digit_image, cmap=matplotlib.cm.binary,
  31. interpolation="nearest")
  32. plt.axis("off")
  33. plt.show()
  34. print(y[36001])
  1. D:\Anaconda3\lib\site-packages\sklearn\utils\deprecation.py:77: DeprecationWarning: Function fetch_mldata is deprecated; fetch_mldata was deprecated in version 0.20 and will be removed in version 0.22
  2. warnings.warn(msg, category=DeprecationWarning)
  3. D:\Anaconda3\lib\site-packages\sklearn\utils\deprecation.py:77: DeprecationWarning: Function mldata_filename is deprecated; mldata_filename was deprecated in version 0.20 and will be removed in version 0.22
  4. warnings.warn(msg, category=DeprecationWarning)
  5. mnist {'DESCR': 'mldata.org dataset: mnist-original', 'COL_NAMES': ['label', 'data'], 'target': array([0., 0., 0., ..., 9., 9., 9.]), 'data': array([[0, 0, 0, ..., 0, 0, 0],
  6. [0, 0, 0, ..., 0, 0, 0],
  7. [0, 0, 0, ..., 0, 0, 0],
  8. ...,
  9. [0, 0, 0, ..., 0, 0, 0],
  10. [0, 0, 0, ..., 0, 0, 0],
  11. [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)}
  12. (70000, 784) (70000,)
  13. <class 'numpy.ndarray'>
  14. <Figure size 640x480 with 1 Axes>
  15. 5.0

2. 创建测试集训练集

  1. x_train, x_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]

2.1 数据洗牌(注意数据的顺序敏感性)

  1. import numpy as np
  2. # Randomly permute a sequence, or return a permuted range.
  3. shuffle_index = np.random.permutation(60000)
  4. x_train, y_train = x_train[shuffle_index], y_train[shuffle_index]
  5. # # Q1:
  6. # ## 1.1 创建KNN分类器
  7. y_train_5 =(y_train==5)
  8. from sklearn.neighbors import KNeighborsClassifier
  9. # knn_clf = KNeighborsClassifier()
  10. # knn_clf = KNeighborsClassifier(n_jobs=-1, weights='distance', n_neighbors=4)
  11. # knn_clf.fit(x_train, y_train)
  12. # array = knn_clf.predict(x_test)
  13. # print("knnResult",array)
  14. # # ## 1.2 对knn执行网格搜索
  15. # from sklearn.model_selection import GridSearchCV
  16. # para_grid = [
  17. # {'n_neighbors':[3,4,5,6],'weights':["uniform","distance",]}
  18. # ]
  19. # knn_clf = KNeighborsClassifier()
  20. # grid_search = GridSearchCV(knn_clf,para_grid,cv=5,verbose=3,n_jobs=-1,scoring="neg_mean_squared_error")
  21. # grid_search.fit(x_train,y_train)
  22. # print(grid_search.best_params_)
  23. # print(grid_search.best_estimator_)
  24. # from sklearn.model_selection import GridSearchCV
  25. #
  26. # param_grid = [{'weights': ["uniform", "distance"], 'n_neighbors': [3, 4, 5]}]
  27. #
  28. # knn_clf = KNeighborsClassifier()
  29. # grid_search = GridSearchCV(knn_clf, param_grid, cv=5, verbose=3, n_jobs=-1)
  30. # grid_search.fit(x_train, y_train)
  31. # print(grid_search.best_params_)
  32. # print(grid_search.best_estimator_)
  33. # ## 1.2 评估准确性
  34. # y_knn_pred = knn_clf.predict(x_test)
  35. # from sklearn.metrics import accuracy_score
  36. # a = accuracy_score(y_test,y_knn_pred)
  37. # print(a)
  38. # # Q2:
  39. # 使用shaift方法移动图片中的像素,注意,self传进来的X[1]是一维数组,要使用reshape变成28*28的数组。
  40. # cval参数指的是移动图片后填补的像素值
  41. from scipy.ndimage.interpolation import shift
  42. def movePiexOfImage(self,dx,dy,new=0):
  43. return shift(self.reshape(28,28),[dx,dy],cval=new)
  44. # 图片显示维度错误检测
  45. def valid_imshow_data(data):
  46. data = np.asarray(data)
  47. if data.ndim == 2:
  48. return True
  49. elif data.ndim == 3:
  50. if 3 <= data.shape[2] <= 4:
  51. return True
  52. else:
  53. print('The "data" has 3 dimensions but the last dimension '
  54. 'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
  55. ''.format(data.shape[2]))
  56. return False
  57. else:
  58. print('To visualize an image the data must be 2 dimensional or '
  59. '3 dimensional, not "{}".'
  60. ''.format(data.ndim))
  61. return False
  62. print("image:",X[1])
  63. imageShift=movePiexOfImage(X[1],5,1,new=100)
  64. imageShift = imageShift.reshape(28,28)
  65. plt.imshow(imageShift,cmap=matplotlib.cm.binary)
  66. plt.show()
  67. print(len(x_train))
  68. for i in range(len(x_train)):
  69. moveLeft = movePiexOfImage(x_train[i],1,0,new=100)
  70. # moveDown = movePiexOfImage(x_train[i],0,1,new=100)
  71. # moveRight = movePiexOfImage(x_train[i],-1,0,new=100)
  72. # moveUp = movePiexOfImage(x_train[i],0,-1,new=100)
  73. # moveDown = moveDown.reshape(1,784)
  74. moveLeft = moveLeft.reshape(1,784)
  75. # moveRight = moveRight.reshape(1,784)
  76. # moveUp = moveUp.reshape(1,784)
  77. x_train = np.concatenate((x_train,moveLeft),axis=0)
  78. print(len(x_train))
  1. image: [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  2. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  3. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  4. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  5. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  6. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  7. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  8. 0 0 0 64 253 255 63 0 0 0 0 0 0 0 0 0 0 0
  9. 0 0 0 0 0 0 0 0 0 0 0 0 96 205 251 253 205 111
  10. 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  11. 0 0 0 96 189 251 251 253 251 251 31 0 0 0 0 0 0 0
  12. 0 0 0 0 0 0 0 0 0 0 16 64 223 244 251 251 211 213
  13. 251 251 31 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  14. 0 80 181 251 253 251 251 251 94 96 251 251 31 0 0 0 0 0
  15. 0 0 0 0 0 0 0 0 0 0 92 253 253 253 255 253 253 253
  16. 95 96 253 253 31 0 0 0 0 0 0 0 0 0 0 0 0 0
  17. 0 92 236 251 243 220 233 251 251 243 82 96 251 251 31 0 0 0
  18. 0 0 0 0 0 0 0 0 0 0 80 253 251 251 188 0 96 251
  19. 251 109 0 96 251 251 31 0 0 0 0 0 0 0 0 0 0 0
  20. 0 96 240 253 243 188 42 0 96 204 109 4 0 12 197 251 31 0
  21. 0 0 0 0 0 0 0 0 0 0 0 221 251 253 121 0 0 0
  22. 36 23 0 0 0 0 190 251 31 0 0 0 0 0 0 0 0 0
  23. 0 0 48 234 253 0 0 0 0 0 0 0 0 0 0 0 191 253
  24. 31 0 0 0 0 0 0 0 0 0 0 44 221 251 251 0 0 0
  25. 0 0 0 0 0 0 0 12 197 251 31 0 0 0 0 0 0 0
  26. 0 0 0 190 251 251 251 0 0 0 0 0 0 0 0 0 0 96
  27. 251 251 31 0 0 0 0 0 0 0 0 0 0 190 251 251 113 0
  28. 0 0 0 0 0 0 0 0 40 234 251 219 23 0 0 0 0 0
  29. 0 0 0 0 0 190 251 251 94 0 0 0 0 0 0 0 0 40
  30. 217 253 231 47 0 0 0 0 0 0 0 0 0 0 0 191 253 253
  31. 253 0 0 0 0 0 0 12 174 253 253 219 39 0 0 0 0 0
  32. 0 0 0 0 0 0 0 67 236 251 251 191 190 111 72 190 191 197
  33. 251 243 121 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  34. 63 236 251 253 251 251 251 251 253 251 188 94 0 0 0 0 0 0
  35. 0 0 0 0 0 0 0 0 0 0 0 27 129 253 251 251 251 251
  36. 229 168 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  37. 0 0 0 0 0 95 212 251 211 94 59 0 0 0 0 0 0 0
  38. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  39. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  40. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  41. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  42. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  43. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  44. 0 0 0 0 0 0 0 0 0 0]

  1. 60000

Hand on Machine Learning第三章课后作业(2):其余小练习的更多相关文章

  1. Hand on Machine Learning第三章课后作业(1):垃圾邮件分类

    import os import email import email.policy 1. 读取邮件数据 SPAM_PATH = os.path.join( "E:\\3.Study\\机器 ...

  2. C++第三章课后作业答案及解析---指针的使用

    今天继续完成上周没有完成的习题---C++第三章课后作业,本章题涉及指针的使用,有指向对象的指针做函数参数,对象的引用以及友元类的使用方法等 它们具体的使用方法在下面的题目中会有具体的解析(解析标注在 ...

  3. Hand on Machine Learning 第三章:分类器

    1. 获取数据 使用MNIST数据集练习分类任务 from sklearn.datasets import fetch_mldata from scipy.io import loadmat mnis ...

  4. CSAPP深入理解计算机系统(第二版)第三章家庭作业答案

    <深入理解计算机系统(第二版)>CSAPP 第三章 家庭作业 这一章介绍了AT&T的汇编指令 比较重要 本人完成了<深入理解计算机系统(第二版)>(以下简称CSAPP) ...

  5. 機器學習基石(Machine Learning Foundations) 机器学习基石 课后习题链接汇总

    大家好,我是Mac Jiang,非常高兴您能在百忙之中阅读我的博客!这个专题我主要讲的是Coursera-台湾大学-機器學習基石(Machine Learning Foundations)的课后习题解 ...

  6. JAVA第三周课后作业

    JAVA课后作业 一.枚举类型 代码: enum Size{SMALL,MEDIUM,LARGE}; public cl ass EnumTest { public static void main( ...

  7. 中级Perl 第三章课后习题

    3. 10. 1. 练习1 [25 分钟] 读当前目录的文件列表并转换成全路径.不能用shell 命令或外部程序读当前目 录.Perl 的File::Spec 和Cwd 两个模块对这个程序有帮助.每个 ...

  8. Python核心编程2第三章课后练习

    1. 标识符.为什么Python 中不需要变量名和变量类型声明? Python中的变量不需要声明,变量的赋值操作既是变量声明和定义的过程.每个变量在内存中创建,都包括变量的标识,名称和数据这些信息.每 ...

  9. Machine Learning 第三周

    ML week3 逻辑回归 Logistic Function h_\theta(x)=g(\theta^Tx) g(t)=\frac{1}{1+e^{-z}} 当t大于0, 即下面公式成立时,y=1 ...

随机推荐

  1. threading.local作用及原理

    先看下应用: import threading from threading import local import time obj = local() def task(i): obj.xxxxx ...

  2. centos7 远程桌面连接到xfce桌面

    1 安装xfce $ sudo yum install -y epel-release $ sudo yum groupinstall -y "Xfce" $ sudo reboo ...

  3. outlook 使用临时邮箱 使用旧数据

    控制面板-->邮件32位 显示配置文件 删除再添加 具体可参考 https://blog.csdn.net/liuyukuan/article/details/80043840 偷懒,图片从网上 ...

  4. MyBatis主配置文件(转载)

    原文地址:http://limingnihao.iteye.com/blog/1060764 其中高亮字体是我的理解. 在定义sqlSessionFactory时需要指定MyBatis主配置文件: X ...

  5. Docker(1)--概述

    Docker概述 Docker是一个用于开发,交付和运行应用程序的开放平台.Docker使您能够将应用程序与基础架构分开,从而可以快速交付软件.借助Docker,您可以以与管理应用程序相同的方式来管理 ...

  6. python接口自动化七(重定向-禁止重定向Location)

    前言 某屌丝男A鼓起勇气向女神B打电话表白,女神B是个心机婊觉得屌丝男A是好人,不想直接拒绝于是设置呼叫转移给闺蜜C了,最终屌丝男A和女神闺蜜C表白成功了,这种场景其实就是重定向了. 一.重定向 1. ...

  7. HDU 1097 快速幂

    #include<iostream> using namespace std; long long quick(long long a,long long b,int c) { ; a=a ...

  8. 01-scrapy框架

    1.Scrapy图例: Scrapy Engine(引擎): 负责Spider.ItemPipeline.Downloader.Scheduler中间的通讯,信号.数据传递等. Scheduler(调 ...

  9. 字符串处理工具StringUtils

    package yqw.java.util; import java.io.File;import java.text.ParseException;import java.text.SimpleDa ...

  10. java list去重方式,以及效率问题

    之前面试被问到关于java如何去重的问题,当时没怎么留意,今天刚好项目中用到了,所以记录一下. 实体类: /** * 用户类 */ class User{ private String usernam ...