python分析双十一销量
import numpy as np
import matplotlib.pyplot as plt
year = np.array([year for year in range(2009,2021)])
sales = np.array([0.5, 9.36, 52, 191, 352, 571, 912, 1207, 1682.69, 2135, 2684, 4982])
plt.plot(year, sales, 'ro')
z = np.polyfit(year, sales, 1)
z[0]
z[1]
yhat = z[0]* year + z[1]
plt.plot(year, yhat, 'g-')
plt.text(2010, 3000, "y={:0.2f}*year{:0.2f}".format(z[0], z[1]), size=18)
结果如下图:
当然还可以用二次项回归
z = np.polyfit(year, sales, 2)
z
z[0]
z[1]
z[2]
yhat = z[0]*year*year + z[1]*year+ z[2]
plt.plot(year, sales, 'ro')
plt.plot(year, yhat, 'b-')
plt.text(2010, 3000, "{:0.2f}*year^2 + {:0.2f}*year + {:0.2f}".format(z[0], z[1], z[2] ))
也可以用对数回归
lnsales = np.log(sales)
z = np.polyfit(year, lnsales, 1)
yhat = z[0]*year + z[1]
plt.plot(year, lnsales, 'ro')
plt.plot(year, yhat)
plt.text(2010, 1, "ln(sales)={:0.2f}*year+{:0.2f}".format(z[0], z[1]))
感觉多项式回归比较好一些:
###一元线性回归
from sklearn.linear_model import LinearRegression
model = LinearRegression()
X = year.reshape(-1, 1)
model.fit(X, sales)
model.intercept_
model.coef_
model.get_params()
model.score(X, sales)
############多项式回归
X
x2 = np.hstack([X, X**2])
x2
L2 = LinearRegression()
L2.fit(x2, sales)
L2.intercept_
L2.coef_
L2.score(x2,sales)
结果二次项回归R2 =0.94513, 一元线性回归,R2 = 0.7853
单纯做统计分析的话还是statsmodel库比较好一点。输出美观一些。
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd
df = pd.read_json('{"year ":{"0":2009,"1":2010,"2":2011,"3":2012,"4":2013,"5":2014,"6":2015,"7":2016,"8":2017,"9":2018,"10":2019,"11":2020}," sales":{"0":0.5,"1":9.36,"2":52.0,"3":191.0,"4":352.0,"5":571.0,"6":912.0,"7":1207.0,"8":1682.69,"9":2135.0,"10":2684.0,"11":4982.0}}')
df
results = smf.ols("sales ~ year ", data=df).fit()
results.summary()
results = smf.ols("sales ~ year + np.square(year) ", data=df).fit()
results = smf.ols("np.log(sales) ~ year", data=df).fit()
results.summary()