作者:mobiledu2502863807 | 来源:互联网 | 2023-10-14 16:52
前提#认为天猫销量和年份之间存在一定函数关系导包importnumpyasnpimportmatplotlib.pyplotasplt%matplotlibinline对年份
前提 #认为天猫销量和年份之间存在一定函数关系 导包
import numpy as np import matplotlib.pyplot as plt %matplotlib inline
对年份进行处理
years = np.arange(2009,2020) years
sales = np. array( [ 0.5 , 9.36 , 52 , 191 , 352 , 571 , 912 , 1207 , 1682.69 , 2135 , 2684 ] ) sales
plt. scatter( years, sales, c = 'red' , marker = '*' , s = 20 )
X = ( years - 2008 ) . reshape( - 1 , 1 ) X
y = sales y
from sklearn. linear_model import LinearRegression lr = LinearRegression( fit_intercept = True ) lr. fit( X, y) w = lr. coef_[ 0 ] b = lr. intercept_ display( w, b)
plt. scatter( ( years- 2008 ) , sales, c = 'red' , marker = '*' , s = 80 ) x = np. linspace( 1 , 12 , 50 ) plt. plot( x, w* x + b, c = 'green' )
from sklearn. linear_model import LinearRegression lr = LinearRegression( fit_intercept = True ) X2 = np. concatenate( [ X** 2 , X] , axis = 1 ) lr. fit( X2, y) w1, w2 = lr. coef_ b = lr. intercept_ display( w1, w2, b)
plt. scatter( ( years- 2008 ) , sales, c = 'red' , marker = '*' , s = 80 ) x = np. linspace( 1 , 12 , 50 ) plt. plot( x, w1* x** 2 + w2* x + b, c = 'green' )
f = lambda x: w1* x** 2 + w2* x + bprint ( '2020年销量预测' , f( 12 ) )