from sklearn.datasets import load_boston # 导入boston房价数据集import numpyboston = load_boston()boston.keys()print(boston.data) #查看每一个key值print(boston.target)print(boston.feature_names)print(boston.DESCR)import pandas as pd #以(类似excel)表格形式表现boston.data数据集df = pd.DataFrame(boston.data)df#求出w,b之后可以画出x和y的直线与点图的关系。一元线性回归from sklearn.linear_model import LinearRegressionlr = LinearRegression()x = x.reshape(-1,1)lr.fit(x,y)w = lr.coef_ #y=wx+b,w为斜率,b为截距b = lr.intercept_print(w)print(b)from matplotlib import pyplot as pltx=boston.data[:,5]y=boston.targetplt.scatter(x,y) #点图plt.plot(x,9.1*x-34.7,'r') #直线plt.show()x.shape
data值
target值
feature_names值
DESCR值
w,b值
import matplotlib.pyplot as pltx = boston.data[:,12].reshape(-1,1)y = boston.targetplt.figure(figsize=(10,6))plt.scatter(x,y)from sklearn.linear_model import LinearRegressionlineR = LinearRegression()lineR.fit(x,y)y_pred = lineR.predict(x)plt.plot(x,y_pred,'g')print(lineR.coef_,lineR.intercept_)plt.show()#多元线性回归from sklearn.linear_model import LinearRegressionlr = LinearRegression()lr.fit(boston.data,y)w = lr.coef_print(w)b = lr.intercept_b
#一元多项式回归模型,建立一个变量与房价之间的预测模型,并图形化显示。from sklearn.preprocessing import PolynomialFeaturespoly = PolynomialFeatures(degree=2)x_poly = poly.fit_transform(x)lp = LinearRegression()lp.fit(x_poly,y)y_poly_pred = lp.predict(x_poly)plt.scatter(x,y)plt.plot(x,y_poly_pred,'r')plt.show()from sklearn.preprocessing import PolynomialFeaturespoly = PolynomialFeatures(degree=2)x_poly = poly.fit_transform(x)lrp = LinearRegression()lrp.fit(x_poly,y)plt.scatter(x,y)plt.scatter(x,y_pred)plt.scatter(x,y_poly_pred) #多项回归plt.show()