机器学习实验一: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)
相关推荐
外参财观15 分钟前
流量变现的边界:携程金融按下暂停键后的冷思考
大数据·人工智能·金融
人工智能AI技术29 分钟前
能用C#开发AI吗?
人工智能·c#
天赐学c语言32 分钟前
1.20 - x的平方根 && vector的扩容机制以及删除元素是否会释放内存
c++·算法·leecode
whitelbwwww1 小时前
车牌识别--obb识别车框
人工智能
果粒蹬i1 小时前
AI系统故障诊断:模型崩溃、算力瓶颈与数据漂移的识别与解决策略
人工智能
CCPC不拿奖不改名1 小时前
两种完整的 Git 分支协作流程
大数据·人工智能·git·python·elasticsearch·搜索引擎·自然语言处理
Coding茶水间1 小时前
基于深度学习的交通标志检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
开发语言·人工智能·深度学习·yolo·目标检测·机器学习
a努力。1 小时前
字节Java面试被问:TCP的BBR拥塞控制算法原理
java·开发语言·python·tcp/ip·elasticsearch·面试·职场和发展
亿信华辰软件1 小时前
构建智慧数据中台,赋能饮料集团全链路数字化转型新引擎
大数据·人工智能·云计算
费弗里1 小时前
一个小技巧轻松提升Dash应用debug效率
python·dash