机器学习实验一:KNN算法,手写数字数据集(使用汉明距离)(2)

KNN-手写数字数据集:

使用sklearn中的KNN 算法工具包( KNeighborsClassifier)替换实现分类器的构建,注意使用的是汉明距离

运行结果:(大概要运行4分钟左右)

代码:

python 复制代码
import pandas as pd
import os

def hamming(str1, str2):
    if len(str1) != len(str2):
        raise ValueError("两个字符串长度不相等")
    return sum(c1 != c2 for c1, c2 in zip(str1, str2))

def get_train():
    path = 'digits/trainingDigits'
    trainingFileList0 = os.listdir(path)
    trainingFileList = [file[2:] if file.startswith('._') else file for file in trainingFileList0]
    train = pd.DataFrame()
    img = []
    labels = []
    for i in range(len(trainingFileList)):
        filename = trainingFileList[i]
        with open(f'digits/trainingDigits/{filename}', 'r') as f:
            txt = f.read().replace('\n', '')
        img.append(txt)
        filelabel = filename.split('_')[0]
        labels.append(filelabel)
    train['img'] = img
    train['labels'] = labels
    return train

def get_test():
    path = 'digits/testDigits'
    testFileList0 = os.listdir(path)
    testFileList = [file[2:] if file.startswith('._') else file for file in testFileList0]
    test = pd.DataFrame()
    img = []
    labels = []
    for filename in testFileList:
        with open(f'digits/testDigits/{filename}', 'r') as f:
            txt = f.read().replace('\n', '')
        img.append(txt)
        filelabel = filename.split('_')[0]
        labels.append(filelabel)
    test['img'] = img
    test['labels'] = labels
    return test

def handwritingClass(train, test, k):
    n = train.shape[0]
    m = test.shape[0]
    result = []
    for i in range(m):
        dist = []
        for j in range(n):
            d = str(hamming(train.iloc[j, 0], test.iloc[i, 0]))
            dist.append(d)
        dist_l = pd.DataFrame({'dist': dist, 'labels': train.iloc[:, 1]})
        dr = dist_l.sort_values(by='dist')[:k]
        re = dr.loc[:, 'labels'].value_counts()
        result.append(re.index[0])
    result = pd.Series(result)
    test['predict'] = result
    acc = (test.iloc[:, -1] == test.iloc[:, -2]).mean()
    print(f'模型预测准确率为{acc:.5f}')
    return test

# 获取训练集和测试集
train = get_train()
test = get_test()

# 调用函数
handwritingClass(train, test, 3)
相关推荐
cnbestec36 分钟前
协作机器人UR7e与UR12e:轻量化设计与高负载能力助力“小而美”智造升级
人工智能·机器人·协作机器人·ur协作机器人·ur7e·ur12e
zskj_zhyl39 分钟前
毫米波雷达守护银发安全:七彩喜跌倒检测仪重构居家养老防线
人工智能·安全·重构
秋说2 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
gaosushexiangji2 小时前
利用sCMOS科学相机测量激光散射强度
大数据·人工智能·数码相机·计算机视觉
Maybyy2 小时前
力扣61.旋转链表
算法·leetcode·链表
ai小鬼头3 小时前
AIStarter新版重磅来袭!永久订阅限时福利抢先看
人工智能·开源·github
说私域3 小时前
从品牌附庸到自我表达:定制开发开源AI智能名片S2B2C商城小程序赋能下的营销变革
人工智能·小程序
卡卡卡卡罗特4 小时前
每日mysql
数据结构·算法
飞哥数智坊4 小时前
新版定价不够用,Cursor如何退回旧版定价
人工智能·cursor
12点一刻4 小时前
搭建自动化工作流:探寻解放双手的有效方案(2)
运维·人工智能·自动化·deepseek