benym的知识笔记 benym的知识笔记
🦮首页
  • Java

    • Java-基础
    • Java-集合
    • Java-多线程与并发
    • Java-JVM
    • Java-IO
  • Python

    • Python-基础
    • Python-机器学习
  • Kafka
  • Redis
  • MySQL
  • 分布式事务
  • Spring

    • SpringIOC
    • SpringAOP
🦌设计模式
  • 剑指Offer
  • LeetCode
  • 排序算法
🐧实践
  • Rpamis

    • Utils
    • Exception
    • Security
  • 归档
  • 标签
  • 目录
🦉里程碑
🐷关于
GitHub (opens new window)

benym

惟其艰难,才更显勇毅🍂惟其笃行,才弥足珍贵
🦮首页
  • Java

    • Java-基础
    • Java-集合
    • Java-多线程与并发
    • Java-JVM
    • Java-IO
  • Python

    • Python-基础
    • Python-机器学习
  • Kafka
  • Redis
  • MySQL
  • 分布式事务
  • Spring

    • SpringIOC
    • SpringAOP
🦌设计模式
  • 剑指Offer
  • LeetCode
  • 排序算法
🐧实践
  • Rpamis

    • Utils
    • Exception
    • Security
  • 归档
  • 标签
  • 目录
🦉里程碑
🐷关于
GitHub (opens new window)
  • Python-基础

    • assert语句的运用
    • list(列表)、tuple(元组)、dict(字典)的回顾
    • Python中的Docstring
    • Python中的多态
    • Python中的集合
    • Python中的列表
    • Python中的序列以及切片的解释
    • Python中的引用和切片
    • Python中的元组
    • Python中对列表和元组的切片操作
    • Python中完整for循环的实际运用
    • Python中字典(key-value)
    • Python中字符串的一些方法回顾(拆分与合并)
    • Python中字符串的一些方法回顾(切片回顾)
    • Python中字符串的一些方法回顾(文本对齐、去除空白)
    • Python中字符串的一些方法回顾
    • Python中字符串的一些基本操作
    • 多种方法快速交换两个变量的值
    • 利用Python进行文件的自动备份
    • 利用Python进行文件的自动备份(第二版)
    • 利用Python进行文件的自动备份(第三版和第四版)
    • 列表推导
    • 在函数中接受元组与字典
    • 装饰器
    • finally异常处理
    • Python的__name__ = '__main__' 的作用
    • Python的pickle模块
    • Python对象的实例化
    • Python日志模块
    • Python中的__new__方法的重写
    • Python中的lambda函数
    • Python中的静态方法、实例方法、类方法的区别
    • Python中的正则表达式
    • Python中的正则表达式match和search
    • Python中面向对象比较简单的内部函数
    • with open异常处理
    • 单例设计模式
    • 继承的运用
    • 简单的异常处理
    • 类变量与对象变量
    • 输入输出——简单的回文判断
    • 输入输出——回文字串的判断(加强版)
    • 文件操作
    • 用户自己引发的异常处理
    • 正则表达式检索与替换
    • 正则表达式中的compile函数
    • 正则表达式中的compile函数(二)
  • Python-机器学习

    • Numpy库的首次使用
    • kNN(k-近邻算法)
    • kNN识别手写图像
      • 代码
      • 运行结果
    • LogisticRegression(逻辑回归)
    • Ndarray对象
    • Numpy中的数组维度
    • Numpy中花式索引和shape用法
    • turtle绘图库
    • 第一个使用Tensorflow的程序
    • 将下载下来的MNIST手写数字数据集转化成为图片
    • Tensorflow交互式使用
    • 使用k-近邻算法改进约会网站的配对效果
    • Numpy数据类型和arange方法、astype方法的使用
    • 一些TensorFlow的基本操作
  • Python
  • Python-机器学习
benym
2018-08-16
目录

kNN识别手写图像

示例 :使用k-近邻算法的手写识别系统 (1) 收集数据:提供文本文件。 (2) 准备数据:编写函数classify0(), 将图像格式转换为分类器使用的list格式。 (3) 分析数据:检查数据,确保它符合要求。 (4) 训练算法:此步驟不适用于k-近邻算法。 (5) 测试算法:编写函数使用提供的部分数据集作为测试样本,测试样本与非测试样本的区别在于测试样本是已经完成分类的数据,如果预测分类与实际类别不同,则标记为一个错误。 (6) 使用算法:本例没有完成此步骤,若你感兴趣可以构建完整的应用程序,从图像中提取数字,并完成数字识别,美国的邮件分拣系统就是一个实际运行的类似系统。

提示

注:由于原本数据集已经在0和1之间,所以不需要转化数字特征值。数据集 (opens new window)

# 代码

from numpy import *
from os import listdir
import operator


def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    # 距离计算
    '''
     tile(A,rep) 
        功能:重复A的各个维度 
        参数类型: 
        A: Array类的都可以 
        rep:A沿着各个维度重复的次数
    '''
    diffMat = tile(inX, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    # numpy中的 axis=0表示列,向下,axis=1表示行,向右
    # 在平时使用的sun默认的是axis=0就是普通的相加,当加入axis=1以后就是将一个矩阵的每一行向量相加
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    # argsort函数返回的是数组值从小到大的索引值
    sortedDistIndicies = distances.argsort()
    classCount = {}
    # 选择距离最小的k个点
    for i in range(k):
        votellabel = labels[sortedDistIndicies[i]]
        classCount[votellabel] = classCount.get(votellabel, 0) + 1
    # 排序
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


def img2vector(filename):
    # 将图像矩阵转化为1x1024的向量
    returnVect = zeros((1, 1024))
    fr = open(filename)
    # 循环读出文件的前32行
    for i in range(32):
        lineStr = fr.readline()
        # 将每行的头32个字符值存储在Numpy数组中
        for j in range(32):
            returnVect[0, 32 * i + j] = int(lineStr[j])
        # 返回数组
    return returnVect


def handwritingClassTest():
    hwLabels = []
    # 获取训练数据集下目录的所有文件名的列表
    trainingFileList = listdir('trainingDigits')
    # 得到文件数量
    m = len(trainingFileList)
    # 创建m行1024列的训练矩阵
    trainingMat = zeros((m, 1024))
    for i in range(m):
        # 从文件名解析分类数字
        # 解析出0_10.txt
        fileNameStr = trainingFileList[i]
        # 获得0_10
        fileStr = fileNameStr.split('.')[0]
        # 获得0
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i, :] = img2vector('trainingDigits/%s' % fileNameStr)
    # 获得测试数据集下目录的所有文件名的列表
    testFileList = listdir('testDigits')
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
        print("the classifier came back with:%d,the real answer is:%d" % (classifierResult, classNumStr))
        if (classifierResult != classNumStr):
            errorCount += 1.0
    print("\nthe total number of errors is:%d" % errorCount)
    print("\nthe total error rate is :%f" % (errorCount / float(mTest)))


testVector = img2vector('testDigits/0_13.txt')
# X[:,  m:n],即取二维数组中的第m到n-1列的所有数据
print("测试输出:\n", testVector[0, 0:31])
handwritingClassTest()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

# 运行结果

the classifier came back with:1,the real answer is:1
the classifier came back with:1,the real answer is:1

.....

the classifier came back with:5,the real answer is:5
the classifier came back with:5,the real answer is:5
the classifier came back with:6,the real answer is:6
the classifier came back with:6,the real answer is:6

....

the classifier came back with:9,the real answer is:9
the classifier came back with:9,the real answer is:9
the classifier came back with:9,the real answer is:9

the total number of errors is:11
# 错误率为1.2%
the total error rate is :0.011628
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
编辑 (opens new window)
#k-近邻算法#Python#机器学习#Numpy
上次更新: 2022/12/31, 16:52:27
kNN(k-近邻算法)
LogisticRegression(逻辑回归)

← kNN(k-近邻算法) LogisticRegression(逻辑回归)→

最近更新
01
SpringCache基本配置类
05-16
02
DSTransactional与Transactional事务混用死锁场景分析
03-04
03
Rpamis-security-原理解析
12-13
更多文章>
Theme by Vdoing | Copyright © 2018-2024 benym | MIT License
 |   |   | 
渝ICP备18012574号 | 渝公网安备50010902502537号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式