日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python機器學習sklearn實現識別數字_python

作者:小唐同學大呆子 ? 更新時間: 2022-06-01 編程語言

簡介

本文主要簡述如何通過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)

原文鏈接:https://blog.csdn.net/weixin_52521533/article/details/123802259

欄目分類
最近更新