随机树ExtraTreeRegressor(): 分列点随机选取、不考虑信息增益,减少过拟合
获取一个对象所属的类名称: model.class.name
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# 导入人脸数据集
from sklearn.datasets import fetch_olivetti_faces,fetch_lfw_people
faces = fetch_olivetti_faces()
images = faces.images
data = faces.data
target = faces.target
# 训练集和测试集拆分
# 训练集由每个人提供九张照片
# 测试集每个人呢提供2张照片
# 样本特征和照片
# 每张照片扁平处理,前半部分2048之前,为样本特征X
# 每张照片扁平处理,前半部分2048之后,为样本标签X
def precess_faces(images):
# 正常图像处理步骤:1.图像定位(opencv)2.图像大小规范 3.灰度处理 4.扁平化
X_train = []
X_test = []
Y_train = []
Y_test = []
idx = 0
for i in range(40):
for j in range(10):
img_data = images[idx].ravel()
upper_data = img_data[:2048]
bottom_data = img_data[2048:]
idx += 1
if j < 9:
X_train.append(upper_data)
Y_train.append(bottom_data)
else:
X_test.append(upper_data)
Y_test.append(bottom_data)
return np.array(X_train),np.array(X_test),np.array(Y_train),np.array(Y_test)
# 拆分
X_train,X_test,Y_train,Y_test = precess_faces(images)
# 建模预测回归
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression,Ridge,Lasso
from sklearn.tree import DecisionTreeRegressor,ExtraTreeRegressor
knn = KNeighborsRegressor()
liner = LinearRegression()
ridge = Ridge()
ls = Lasso()
et = ExtraTreeRegressor()
dt = DecisionTreeRegressor()
# 得到预测结果
result = {}
for model in [knn,liner,ridge,ls,et,dt]:
model.fit(X_train,Y_train)
Y_ = model.predict(X_test)
result[model.__class__.__name__] = Y_
# 将真实值添加进结果
result['True'] = Y_test
# 展示预测结果
plt.figure(figsize=(24,30))
ax_loc = 1
for idx in range(5):
upper_face_data = X_test[idx]
for key,Y_ in result.items():
bottom_face_data = Y_[idx]
plt.subplot(5,7,ax_loc)
ax_loc +=1
plt.imshow(np.concatenate((upper_face_data,bottom_face_data)).reshape(64,64),plt.cm.gray)
plt.title(key,fontsize=15,color='red')