聚类(K-means)实现手写数字识别

其他实现手写数字识别的方法:
1.KNN实现手写数字识别
2. 卷积神经网络(CNN)实现手写数字识别
3. 全连接神经网络实现手写数字识别
4. 聚类(K-means)实现手写数字识别-2

  1. 实验数据是老师收集了所有人的手写数字图片,且经过处理将图像生成了.txt文件,如何生成点击这,如下图
    在这里插入图片描述

  2. 代码实现
    代码修改自sklearn官方给出的代码,在读取数据时发生了改变,增加了几个函数,因为用的是自己的数据,而且sklearn是自带很多数据集的

import numpy as np
from sklearn.cluster import KMeans
from sklearn import metrics
from os import listdir

# 因为你的数据是自己的数据,所以才会有前三个方法:img2vector(), getLabel(), 
# getData()用来获取数据,数据标签和处理数据。如果你用的是mnist数据集
# 或者是sklearn中自带的数据集,则直接加载即可

"""
函数说明:将32x32的二进制图像转换为1x1024向量
"""
def img2vector(filename):
    # 创建1x1024零向量
    returnVect = np.zeros((1, 1024))
    # 打开文件
    fr = open(filename)
    # 按行读取
    for i in range(32):
        # 读一行数据
        lineStr = fr.readline()
        # 每一行的前32个元素依次添加到returnVect中
        for j in range(32):
            returnVect[0, 32 * i + j] = float(lineStr[j])
    # 返回转换后的1x1024向量
    return returnVect

'''
函数说明:获取标签
'''
def getLabel(Datapath):
    # 训练集的Labels
    hwLabels = []
    # 返回Datapath目录下的文件名
    trainingFileList = listdir(Datapath)
    # 返回文件夹下文件的个数
    m = len(trainingFileList)
    # 从文件名中解析出训练集的类别
    for i in range(m):
        # 获得文件的名字
        fileNameStr = trainingFileList[i]
        # 获得分类的数字
        classNumber = int(fileNameStr.split('_')[0])
        # 将获得的类别添加到hwLabels中
        hwLabels.append(classNumber)
    return hwLabels

'''
函数说明:获取数据
'''
def getData(Datapath):
    # 返回train目录下的文件名
    trainingFileList = listdir(Datapath)
    # 返回文件夹下文件的个数
    m = len(trainingFileList)
    # 初始化训练的Mat矩阵,训练集
    trainingMat = np.zeros((m, 1024))
    for i in range(m):
        # 获得文件的名字
        fileNameStr = trainingFileList[i]
        # 将每一个文件的1x1024数据存储到trainingMat矩阵中
        trainingMat[i, :] = img2vector(Datapath+'/%s' % (fileNameStr))
    return trainingMat

# -------------load data
# 加载数据
train_images = getData('train')
test_images = getData('testless')
train_labels = getLabel('train')
test_labels = getLabel('testless')


# -------------training
# initialize,and set cluster nums
kmeans = KMeans(n_clusters=10)
kmeans.fit(train_images)
y_pred = kmeans.predict(test_images)

# -------------performance measure by ARI(Adjusted Rand Index)
print(metrics.adjusted_rand_score(test_labels, y_pred))
  1. 还有一个K-means实现手写数字识别的代码,我过段时间再分享
  • 3
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
K-means聚类分析手写数字识别的步骤如下: 1.读取手写数字数据集,将每个数字图像转换为向量形式。 2.将所有向量随机分为K个簇。 3.计算每个向量与每个簇中心的距离,并将向量分配到距离最近的簇中心。 4.重新计算每个簇的中心。 5.重复步骤3和4,直到簇中心不再改变或达到最大迭代次数。 6.将每个簇中的向量标记为该簇的类别。 7.使用标记的数据集训练分类器。 以下是K-means聚类分析手写数字识别的Python代码示例: ```python from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # 加载手写数字数据集 digits = load_digits() # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=42) # 使用K-means聚类算法将训练集分为10个簇 kmeans = KMeans(n_clusters=10, random_state=42) kmeans.fit(X_train) # 将训练集和测试集中的每个向量分配到最近的簇中心 X_train_clusters = kmeans.predict(X_train) X_test_clusters = kmeans.predict(X_test) # 将每个簇中的向量标记为该簇的类别 train_cluster_labels = [list(kmeans.cluster_centers_).index(kmeans.cluster_centers_[i]) for i in X_train_clusters] test_cluster_labels = [list(kmeans.cluster_centers_).index(kmeans.cluster_centers_[i]) for i in X_test_clusters] # 使用标记的数据集训练分类器 from sklearn.linear_model import LogisticRegression clf = LogisticRegression(max_iter=10000) clf.fit(X_train, train_cluster_labels) # 在测试集上评估分类器的性能 y_pred = clf.predict(X_test) accuracy = accuracy_score(test_cluster_labels, y_pred) print("Accuracy:", accuracy) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值