天天看點

不同行業工齡與薪水的線性回歸模型

import pandas as pd
import matplotlib.pyplot as plt
           
df = pd.read_excel('行業收入表.xlsx')
df.head()
           
不同行業工齡與薪水的線性回歸模型
X = df[['工齡']]
y = df['薪水']
           
# 繪制散點圖

plt.scatter(X, y)
plt.xlabel('工齡')
plt.ylabel('薪水')
plt.title('工齡與薪水散點圖')
plt.show()
           
不同行業工齡與薪水的線性回歸模型
# 模型搭建
from sklearn.linear_model import LinearRegression
regr = LinearRegression()
regr.fit(X, y)
           
# 模型可視化
plt.scatter(X, y)
plt.plot(X, regr.predict(X), color='r')
plt.xlabel('工齡')
plt.ylabel('薪水')
plt.title('工齡與薪水散點圖')
plt.show()
           
不同行業工齡與薪水的線性回歸模型
# 線性回歸方程構造
# 系數
regr.coef_[0]
           
# 截距
regr.intercept_
           
from sklearn.metrics import r2_score
r2 = r2_score(y, regr.predict(X))
r2
           
# 一進制二次線性回歸模型
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=2)
X_ = poly_reg.fit_transform(X)
           
regr = LinearRegression()
regr.fit(X_, y)
           
plt.scatter(X, y)
plt.plot(X, regr.predict(X_), color='r')
plt.show()
           
不同行業工齡與薪水的線性回歸模型
# 線性回歸模型評估
import statsmodels.api as sm
X2 = sm.add_constant(X)
est = sm.OLS(y, X2).fit()
est.summary()
           
不同行業工齡與薪水的線性回歸模型
X2 = sm.add_constant(X_)
est = sm.OLS(y, X2).fit()
est.summary()
           
不同行業工齡與薪水的線性回歸模型