python 作业(回归模型与房价预测)
1. 导入boston房价数据集
2. 一元线性回归模型,建立一个变量与房价之间的预测模型,并图形化显示。
3. 多元线性回归模型,建立13个变量与房价之间的预测模型,并检测模型好坏,并图形化显示检查结果。
4. 一元多项式回归模型,建立一个变量与房价之间的预测模型,并图形化显示。
from sklearn.datasets import load_boston import numpy as np boston = load_boston() boston.keys() boston.target import pandas as pd df = pd.DataFrame(boston.data) df x = boston.data[:, 5] # 变量 y = boston.target # 房价 from sklearn.linear_model import LinearRegression lineR = LinearRegression() lineR.fit(x.reshape(-1, 1), y) w = lineR.coef_ # x前的系数 b = lineR.intercept_ # 截距 print(w) print(b) from matplotlib import pyplot as plt plt.figure(figsize=(10, 6)) plt.scatter(x, y) plt.plot(x, 9.1 * x - 34.6, 'r') plt.show()
from sklearn.linear_model import LinearRegression lineR = LinearRegression() lineR.fit(boston.data,y) w = lineR.coef_ b = lineR.intercept_ print(w) print(b) from sklearn.linear_model import LinearRegression lineR = LinearRegression() lineR.fit(x, y) y_pred = lineR.predict(x) plt.plot(x, y_pred) print(lineR.coef_, lineR.intercept_) plt.show() from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=2) x_poly = poly.fit_transform(x) lrp = LinearRegression() lrp.fit(x_poly, y) y_poly_pred = lrp.predict(x_poly) plt.scatter(x, y) plt.scatter(x, y_pred) plt.scatter(x, y_poly_pred) plt.show()