机器学习实验一: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)
相关推荐
一路向北North1 分钟前
Spring AI(11) :ChatPDF-向量数据库、PDF处理、向量写入和向量搜索
数据库·人工智能·spring
Wang's Blog5 分钟前
AI Agent白手起家44: LangChain 文档切分实战 — 长度、文本架构与语义切片
人工智能·langchain
GrowthDiary0077 分钟前
Python 常用函数总结
开发语言·python
only-qi8 分钟前
大模型微调流程深度解析:从面试题到工程实践
人工智能·机器学习·ai·llm
热心网友俣先生20 分钟前
2026年华数杯C 题 超详细解题思路
c语言·开发语言·人工智能
RSTJ_162523 分钟前
PYTHON+AI LLM DAY ONE HUNDRED AND THIRTY
人工智能
火山引擎开发者社区31 分钟前
Seed-Evolving再升级:检索准、幻觉少!
人工智能
2601_9578838434 分钟前
2026年8月:外星人笔记本维修服务揭秘
python·电脑
math_hongfan36 分钟前
鸿蒙多模态AI交互高级:图文+语音+手势融合交互/多模态大模型端侧适配/跨模态检索高阶实战
人工智能·学习·华为·交互·语音识别·harmonyos·鸿蒙
fthux37 分钟前
MCP协议开发实战:从零搭建AI Agent工具链
前端·人工智能·ai·开源·github