机器学习实验一: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)
相关推荐
生而为虫4 分钟前
31.Python语言进阶
python·scrapy·django·flask·fastapi·pygame·tornado
言之。10 分钟前
Claude Code 实用开发手册
python
2501_9181269118 分钟前
如何用ai把特定领域的生活成本归零
人工智能·生活·个人开发
计算机毕设小月哥20 分钟前
【Hadoop+Spark+python毕设】中国租房信息可视化分析系统、计算机毕业设计、包括数据爬取、Spark、数据分析、数据可视化、Hadoop
后端·python·mysql
Brianna Home26 分钟前
[鸿蒙2025领航者闯关] 鸿蒙 6.0 星盾安全架构 + AI 防窥:金融级支付安全实战与深度踩坑实录
人工智能·安全·harmonyos·安全架构
2***c43530 分钟前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
CoderYanger1 小时前
递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:12.全排列
java·算法·leetcode·机器学习·深度优先·剪枝·1024程序员节
憨憨崽&1 小时前
进击大厂:程序员必须修炼的算法“内功”与思维体系
开发语言·数据结构·算法·链表·贪心算法·线性回归·动态规划
飞哥数智坊1 小时前
V4/R4 没来,但 DeepSeek-V3.2 好像又便宜又好用?
人工智能·deepseek
CareyWYR1 小时前
AI:比我更懂我的旁观者
人工智能