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()
