数据处理

数据分离

``````def shuju(tr_path,ts_path,sep='t'):
#特征和结果分离
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')
``````

完整代码

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

def shuju(tr_path,ts_path,sep='t'):
#特征和结果分离
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:UserstwyPycharmProjects1train_images.csv",r"C:UserstwyPycharmProjects1test_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)
``````

THE END