波士顿房价预测

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

import matplotlib.pyplot as plt
%matplotlib inline

import sklearn.datasets as datasets

# 机器算法模型

# KNN:K最近邻
from sklearn.neighbors import KNeighborsRegressor
# 线形回归
from sklearn.linear_model import LinearRegression
# Ridge回归
from sklearn.linear_model import Ridge
# Lasso:
from sklearn.linear_model import Lasso
# 回归决策树
from sklearn.tree import DecisionTreeRegressor
# 支持向量回归模型
from sklearn.svm import SVR

# 切割训练数据和样本
from sklearn.model_selection import train_test_split

# 用于模型评分
from sklearn.metrics import r2_score


# 生成训练数据和测试数据
boston = datasets.load_boston()
train = boston.data
target = boston.target

# 切割数据样本集合 测试集
X_train,x_test,y_train,y_true = train_test_split(train,target,test_size=0.2)


# 创建学习模型
knn = KNeighborsRegressor()
linear = LinearRegression()
ridge = Ridge()
lasso = Lasso()
decision = DecisionTreeRegressor()
svr = SVR()



# 训练模型
knn.fit(X_train,y_train)
linear.fit(X_train,y_train)
ridge.fit(X_train,y_train)
lasso.fit(X_train,y_train)
decision.fit(X_train,y_train)
svr.fit(X_train,y_train)


# 预测数据
y_pre_knn = knn.predict(x_test)
y_pre_linear = linear.predict(x_test)
y_pre_ridge = ridge.predict(x_test)
y_pre_lasso = lasso.predict(x_test)
y_pre_decision = decision.predict(x_test)
y_pre_svr = svr.predict(x_test)


# 评分
knn_score = r2_score(y_true,y_pre_knn)
linear_score = r2_score(y_true,y_pre_linear)
ridge_score = r2_score(y_true,y_pre_ridge)
lasso_score = r2_score(y_true,y_pre_lasso)
svr_score = r2_score(y_true,y_pre_svr)
display(knn_score, linear_score, ridge_score, lasso_score, svr_score)


# 绘图
#KNN
plt.plot(y_true,label="true")
plt.plot(y_pre_knn,label='knn')
plt.legend()

#Linear
plt.plot(y_true,label="true")
plt.plot(y_pre_linear,label="linear")
plt.legend()

# Ridge
plt.plot(y_true,label="true")
plt.plot(y_pre_ridge,label="ridge")
plt.legend()

# lasso
plt.plot(y_true,label="true")
plt.plot(y_pre_lasso,label="lasso")
plt.legend()

# decision
plt.plot(y_true,label="true")
plt.plot(y_pre_decision,label="decision")
plt.legend()

# SVR
plt.plot(y_true,label="true")
plt.plot(y_pre_svr,label="svr")
plt.legend()
原文地址:https://www.cnblogs.com/li-code/p/10585423.html