欢迎光临
我们一直在努力

python机器学习sklearn怎么实现识别数字

这篇文章主要介绍了python机器学习sklearn怎么实现识别数字的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python机器学习sklearn怎么实现识别数字文章都会有所收获,下面我们一起来看看吧。

数据处理

数据分离

因为我们打开我们的的学习数据集,最后一项是我们的真实数值,看过小唐上一篇的人都知道,老规矩先进行拆分,前面的特征放一块,后面的真实值放一块,同时由于数据没有列名,我们选择使用iloc[]来实现分离

def shuju(tr_path,ts_path,sep='\t'):
    train=pd.read_csv(tr_path,sep=sep)
    test=pd.read_csv(ts_path,sep=sep)
    #特征和结果分离
    train_features=train.iloc[:,:-1].values
    train_labels=train.iloc[:,-1].values
    test_features = test.iloc[:, :-1].values
    test_labels = test.iloc[:, -1].values
    return train_features,test_features,train_labels,test_labels

训练数据

我们在这里直接使用sklearn函数,通过选择模型,然后直接生成其识别规则

#训练数据
def train_tree(*data):
    x_train, x_test, y_train, y_test=data
    clf=DecisionTreeClassifier()
    clf.fit(x_train,y_train)
    print("学习模型预测成绩:{:.4f}".format(clf.score(x_train, y_train)))
    print("实际模型预测成绩:{:.4f}".format(clf.score(x_test, y_test)))
    #返回学习模型
    return clf

数据可视化

为了让我们的观察更加直观,我们还可以使用matplotlib来进行观测

def plot_imafe(test,test_labels,preds):
    plt.ion()
    plt.show()
    for i in range(50):
        label,pred=test_labels[i],preds[i]
        title='实际值:{},predict{}'.format(label,pred)
        img=test[i].reshape(28,28)
        plt.imshow(img,cmap="binary")
        plt.title(title)
        plt.show()
    print('done')

结果

完整代码

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt

def shuju(tr_path,ts_path,sep='\t'):
    train=pd.read_csv(tr_path,sep=sep)
    test=pd.read_csv(ts_path,sep=sep)
    #特征和结果分离
    train_features=train.iloc[:,:-1].values
    train_labels=train.iloc[:,-1].values
    test_features = test.iloc[:, :-1].values
    test_labels = test.iloc[:, -1].values
    return train_features,test_features,train_labels,test_labels
#训练数据
def train_tree(*data):
    x_train, x_test, y_train, y_test=data
    clf=DecisionTreeClassifier()
    clf.fit(x_train,y_train)
    print("学习模型预测成绩:{:.4f}".format(clf.score(x_train, y_train)))
    print("实际模型预测成绩:{:.4f}".format(clf.score(x_test, y_test)))
    #返回学习模型
    return clf

def plot_imafe(test,test_labels,preds):
    plt.ion()
    plt.show()
    for i in range(50):
        label,pred=test_labels[i],preds[i]
        title='实际值:{},predict{}'.format(label,pred)
        img=test[i].reshape(28,28)
        plt.imshow(img,cmap="binary")
        plt.title(title)
        plt.show()
    print('done')

train_features,test_features,train_labels,test_labels=shuju(r"C:\Users\twy\PycharmProjects\1\train_images.csv",r"C:\Users\twy\PycharmProjects\1\test_images.csv")
clf=train_tree(train_features,test_features,train_labels,test_labels)
preds=clf.predict(test_features)
plot_imafe(test_features,test_labels,preds)

关于“python机器学习sklearn怎么实现识别数字”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“python机器学习sklearn怎么实现识别数字”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注云搜网行业资讯频道。

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。