经由过程运用python言语来完成线性回归是异常轻易的,由于它供应了多个现成的库,比方能够运用numpy.linalog.lstsq,pandas.ols以及
scipy.stats.linregress等,在本文中将运用sklearn库的linear_model.LinearRegression,它支撑恣意维度,异常好用。
【引荐教程:Python教程】
二维直线
例:线性方程y=a∗x+b;y=a∗x+b 示意平面一直线
鄙人面的例子中,我们将竖立线性回归模子,经由过程给出衡宇的面积来展望衡宇的价钱
import pandas as pd from io import StringIO from sklearn import linear_model import matplotlib.pyplot as plt # 衡宇面积与价钱历史数据(csv文件) csv_data = 'square_feet,price\n150,6450\n200,7450\n250,8450\n300,9450\n350,11450\n400,15450\n600,18450\n' # 读入dataframe df = pd.read_csv(StringIO(csv_data)) print(df) # 竖立线性回归模子 regr = linear_model.LinearRegression() # 拟合 regr.fit(df['square_feet'].reshape(-1, 1), df['price']) # 注重此处.reshape(-1, 1),由于X是一维的! # 不难获得直线的斜率、截距 a, b = regr.coef_, regr.intercept_ # 给出待展望面积 area = 238.5 # 体式格局1:依据直线方程盘算的价钱 print(a * area + b) # 体式格局2:依据predict要领展望的价钱 print(regr.predict(area)) # 绘图 # 1.实在的点 plt.scatter(df['square_feet'], df['price'], color='blue') # 2.拟合的直线 plt.plot(df['square_feet'], regr.predict(df['square_feet'].reshape(-1,1)), color='red', linewidth=4) plt.show()
结果图:
三维平面
线性方程z=a∗x+b∗y+c;z=a∗x+b∗y+c 示意空间一平面
import numpy as np from sklearn import linear_model from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt xx, yy = np.meshgrid(np.linspace(0,10,10), np.linspace(0,100,10)) zz = 1.0 * xx + 3.5 * yy + np.random.randint(0,100,(10,10)) # 构建成特性、值的情势 X, Z = np.column_stack((xx.flatten(),yy.flatten())), zz.flatten() # 竖立线性回归模子 regr = linear_model.LinearRegression() # 拟合 regr.fit(X, Z) # 不难获得平面的系数、截距 a, b = regr.coef_, regr.intercept_ # 给出待展望的一个特性 x = np.array([[5.8, 78.3]]) # 体式格局1:依据线性方程盘算待展望的特性x对应的值z(注重:np.sum) print(np.sum(a * x) + b) # 体式格局2:依据predict要领展望的值z print(regr.predict(x)) # 绘图 fig = plt.figure() ax = fig.gca(projection='3d') # 1.画出实在的点 ax.scatter(xx, yy, zz) # 2.画出拟合的平面 ax.plot_wireframe(xx, yy, regr.predict(X).reshape(10,10)) ax.plot_surface(xx, yy, regr.predict(X).reshape(10,10), alpha=0.3) plt.show()
结果图:
总结:以上就是本篇文章的全部内容了,愿望对人人有所协助
以上就是python怎样完成线性回归的细致内容,更多请关注ki4网别的相干文章!