机器学习实验一: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)
相关推荐
TF男孩2 分钟前
老AI人面对MCP、Skills等新名词
人工智能·程序员
AI Coder 码农王5 分钟前
AgentScope Java v2 第2课,ReActAgent 的循环引擎
人工智能
qq_364682159 分钟前
Android APP会议记录工具生成图文内容
人工智能·powerpoint
guhunyihan12 分钟前
零代码快速搭建平台典型应用场景,恐象 AI 落地能力分析
大数据·人工智能
最强小杰13 分钟前
Claude Opus 4.8 调用报 529 怎么办?并发限制触发过载——退避策略与降级方案完整指南
运维·网络·python·ai
血小溅17 分钟前
什么是 A2A?从协议原理到 AgentScope Java 最小实践
人工智能
wshzd25 分钟前
LLM之Agent(114)|DeepSeek-Harness(二十一)内置工具全解析
人工智能
databook27 分钟前
MinMax vs Standard vs Robust:三种特征缩放怎么选
python·机器学习·数据分析
木圭的AI时代指南28 分钟前
MiniCPM-V 4.7 35B-A3B 本地部署实录:RTX 3070 8GB 显存跑多模态,36 token/s
人工智能·ai·本地部署·openbmb·端侧大模型·minicpm-v 4.7