python機器學習sklearn實現(xiàn)識別數(shù)字
簡介
本文主要簡述如何通過sklearn模塊來進行預測和學習,最后再以圖表這種更加直觀的方式展現(xiàn)出來
數(shù)據(jù)集
數(shù)據(jù)處理
數(shù)據(jù)分離
因為我們打開我們的的學習數(shù)據(jù)集,最后一項是我們的真實數(shù)值,看過小唐上一篇的人都知道,老規(guī)矩先進行拆分,前面的特征放一塊,后面的真實值放一塊,同時由于數(shù)據(jù)沒有列名,我們選擇使用iloc[]來實現(xiàn)分離
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
訓練數(shù)據(jù)
我們在這里直接使用sklearn函數(shù),通過選擇模型,然后直接生成其識別規(guī)則
#訓練數(shù)據(jù) 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
數(shù)據(jù)可視化
為了讓我們的觀察更加直觀,我們還可以使用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 #訓練數(shù)據(jù) 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實現(xiàn)識別數(shù)字的文章就介紹到這了,更多相關python sklearn識別數(shù)字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Pycharm Terminal 與Project interpreter 安裝
本文主要介紹了Pycharm Terminal 與Project interpreter 安裝包不同步問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02結合Python的SimpleHTTPServer源碼來解析socket通信
SimpleHTTPServer是Python中一個現(xiàn)成的HTTP服務器例子,本文我們將結合Python的SimpleHTTPServer源碼來解析socket通信,我們先來看一下socket的基本概念:2016-06-06