微信扫一扫打赏支持

机器学习200725系列---1、线性回归实例

机器学习200725系列---1、线性回归实例

一、总结

一句话总结:

用的是sklearn库的linear_model,核心代码:linreg=LinearRegression()
#一、加载数据集 pd.read_csv("*****”)
#二、分割数据集 train_test_split()
#三、选择/建立模型 model=LinearRegression()
#四、训练模型 modeL.fit()I
#五、验证模型 model.predict()

#三、选择/建立模型 model=LinearRegression()
linreg=LinearRegression()
print(linreg)
model=linreg.fit(x_train,y_train)
#y_hat=theta1*X1 + theta2*X2 + theta3*X3+theat0
print(model)
print("权重系数(coef_)={}".format(linreg.coef_))
print("截距项(intercept)={}".format(linreg.intercept_)

结果
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
权重系数(coef_)=[ 0.04098751  0.20837822 -0.00213991]
截距项(intercept)=3.3343993230131055

 

 

1、本实例中sklearn库的应用?

数据分割【model_selection】:from sklearn.model_selection import train_test_split#分割数据集
线性模型【linear_model】:from sklearn.linear_model import LinearRegression#算法库

 

 

2、机器学习一般步骤?

加载数据集、分割数据集、选择/建立模型、训练模型、验证模型
#一、加载数据集 pd.read_csv("*****")
#二、分割数据集(分成train数据和test数据,分成x和f(x)) train_test_split()
#三、选择/建立模型 model=LinearRegression()
#四、训练模型 modeL.fit()I
#五、验证模型 model.predict()

 

 

3、matplotlib画图"ro"、"g^"、"mv"分别是什么意思?

红色的圆、绿色的上三角,紫色的下三角

|||-bgein

plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
plt.plot(data["TV"],y,"ro",label="TV")
plt.plot(data["radio"],y,"g^",label="Radio")
plt.plot(data["newspaper"],y,"mv",label="Newspaper")
plt.legend(loc="lower right")
plt.xlabel(u"广告花费",fontsize=16)
plt.ylabel(u"销售额度",fontsize=16)
plt.title(u"广告花费逾销售额度的线性数据分布",fontsize=20)
plt.grid()
plt.show()

|||-end

 

4、matplotlib画图 的网格?

plt.grid()

|||-bgein

plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
plt.plot(data["TV"],y,"ro",label="TV")
plt.plot(data["radio"],y,"g^",label="Radio")
plt.plot(data["newspaper"],y,"mv",label="Newspaper")
plt.legend(loc="lower right")
plt.xlabel(u"广告花费",fontsize=16)
plt.ylabel(u"销售额度",fontsize=16)
plt.title(u"广告花费逾销售额度的线性数据分布",fontsize=20)
plt.grid()
plt.show()

|||-end

 

5、matplotlib画子图?

1、plt.figure(facecolor="w",figsize=(9,10))
2、plt.subplot(311) # 三行 第一列 第一个子图
plt.figure(facecolor="w",figsize=(9,10))
# 三行 第一列 第一个子图
plt.subplot(311)
plt.plot(data["TV"],y,"ro")
plt.title("TV")
plt.grid()

plt.subplot(312)
plt.plot(data["radio"],y,"g^")
plt.title("Radio")
plt.grid()

plt.subplot(313)
plt.plot(data["newspaper"],y,"mv")
plt.title("Newspaper")
plt.grid()

 

 

6、sklearn.model_selection 分割数据集?

a、from sklearn.model_selection import train_test_split#分割数据集
b、x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,train_size=0.25)

 

 

7、sklearn.linear_model线性模型?

A、引入库:from sklearn.linear_model import LinearRegression
B、建立模型:linreg=LinearRegression()
C、训练模型:model=linreg.fit(x_train,y_train)
D、验证模型:y_hat=linreg.predict(np.array(x_train))

 

8、sklearn.linear_model线性模型中的w和b?

1、print("权重系数(coef_)={}".format(linreg.coef_))
2、print("截距项(intercept)={}".format(linreg.intercept_))
#三、选择/建立模型 model=LinearRegression()
linreg=LinearRegression()
print(linreg)
model=linreg.fit(x_train,y_train)
#y_hat=theta1*X1 + theta2*X2 + theta3*X3+theat0
print(model)
print("权重系数(coef_)={}".format(linreg.coef_))
print("截距项(intercept)={}".format(linreg.intercept_))

结果
权重系数(coef_)=[ 0.04098751  0.20837822 -0.00213991]
截距项(intercept)=3.3343993230131055

 

 

9、拿权重系数验证模型?

1、公式计算:y_real = x_train.iloc[0,0]*linreg.coef_[0]+x_train.iloc[0,1]*linreg.coef_[1]+x_train.iloc[0,2]*linreg.coef_[2]+ linreg.intercept_
2、模型预测:y_hat_0 = linreg.predict(np.array([x_train.iloc[0]]))
# print(x_train)
print(x_train.iloc[0])
# 直接通过公式 y_hat=theta1*X1 + theta2*X2 + theta3*X3+theat0 算y_hat
y_real = x_train.iloc[0,0]*linreg.coef_[0]+ \
        x_train.iloc[0,1]*linreg.coef_[1]+ \
        x_train.iloc[0,2]*linreg.coef_[2]+ linreg.intercept_
print("直接通过公式 y_hat=theta1*X1 + theta2*X2 + theta3*X3+theat0 算y_hat:",y_real)
# 通过预测方法  linreg.predict 来算 y_hat
# 结果是一样的
y_hat_0=linreg.predict(np.array([x_train.iloc[0]]))
print("通过预测方法  linreg.predict 来算 y_hat:",y_hat_0)
# print(y_train)
print("真实数据:",y_train.iloc[0])

结果
TV           216.4
radio         41.7
newspaper     39.6
Name: 52, dtype: float64
直接通过公式 y_hat=theta1*X1 + theta2*X2 + theta3*X3+theat0 算y_hat: 20.80872883130116
通过预测方法  linreg.predict 来算 y_hat: [20.80872883]
真实数据: 22.6

 

 

 

10、本例中最小二乘法计算误差?

MSE=np.average((y_hat-np.array(y_train))**2)
# 最小二乘法计算误差
y_hat=linreg.predict(np.array(x_train))
MSE=np.average((y_hat-np.array(y_train))**2)
RMSE =np.sqrt(MSE)
print("残差平方根(MSE)={}".format(MSE))
print("开平方(RMSE)={}".format(RMSE))

结果
残差平方根(MSE)=2.2149498499353983
开平方(RMSE)=1.4882707582746488

 

11、matplotlib画真实结果和预测结果?

将x的数据换成连续数据(t=np.arange(len(x_train))),放上实际y和预测y
t=np.arange(len(x_train))
plt.title(u"模型于测试Y值的数据对比",fontsize=20)
plt.plot(t,y_hat,"r-",linewidth=2,label="Train")
plt.plot(t,y_train,"g-",linewidth=2,label="Predict")
plt.legend(loc ="upper right")
plt.show()

 

 

 

二、线性回归实例

博客对应课程的视频位置:

import csv
import numpy as np#科学统计库
import matplotlib.pyplot as plt#绘图工具
import matplotlib as mpl#绘图库
import pandas as pd#数据分析库
from sklearn.model_selection import train_test_split#分割数据集
from sklearn.linear_model import LinearRegression#算法库
#一、加载数据集 pd.read_csv("*****”)
#二、分割数据集 train_test_split()
#三、选择/建立模型 model=LinearRegression()
#四、训练模型 modeL.fit()I
#五、验证模型 model.predict()

一、加载数据集 pd.read_csv("*”)

In [2]:
#一、加载数据集 pd.read_csv("*****”)
data = pd.read_csv('dataset/Advertising.csv')
data
Out[2]:
 Unnamed: 0TVradionewspapersales
0 1 230.1 37.8 69.2 22.1
1 2 44.5 39.3 45.1 10.4
2 3 17.2 45.9 69.3 9.3
3 4 151.5 41.3 58.5 18.5
4 5 180.8 10.8 58.4 12.9
... ... ... ... ... ...
195 196 38.2 3.7 13.8 7.6
196 197 94.2 4.9 8.1 9.7
197 198 177.0 9.3 6.4 12.8
198 199 283.6 42.0 66.2 25.5
199 200 232.1 8.6 8.7 13.4

200 rows × 5 columns

In [3]:
x = data.iloc[:,1:-1]
y = data.iloc[:,-1]
x
Out[3]:
 TVradionewspaper
0 230.1 37.8 69.2
1 44.5 39.3 45.1
2 17.2 45.9 69.3
3 151.5 41.3 58.5
4 180.8 10.8 58.4
... ... ... ...
195 38.2 3.7 13.8
196 94.2 4.9 8.1
197 177.0 9.3 6.4
198 283.6 42.0 66.2
199 232.1 8.6 8.7

200 rows × 3 columns

In [4]:
y
Out[4]:
0      22.1
1      10.4
2       9.3
3      18.5
4      12.9
       ... 
195     7.6
196     9.7
197    12.8
198    25.5
199    13.4
Name: sales, Length: 200, dtype: float64
In [5]:
x["TV"]
Out[5]:
0      230.1
1       44.5
2       17.2
3      151.5
4      180.8
       ...  
195     38.2
196     94.2
197    177.0
198    283.6
199    232.1
Name: TV, Length: 200, dtype: float64
In [6]:
data["TV"]
Out[6]:
0      230.1
1       44.5
2       17.2
3      151.5
4      180.8
       ...  
195     38.2
196     94.2
197    177.0
198    283.6
199    232.1
Name: TV, Length: 200, dtype: float64
In [7]:
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
In [8]:
plt.plot(data["TV"],y,"ro",label="TV")
plt.plot(data["radio"],y,"g^",label="Radio")
plt.plot(data["newspaper"],y,"mv",label="Newspaper")
plt.legend(loc="lower right")
plt.xlabel(u"广告花费",fontsize=16)
plt.ylabel(u"销售额度",fontsize=16)
plt.title(u"广告花费逾销售额度的线性数据分布",fontsize=20)
plt.grid()
plt.show()
In [9]:
plt.figure(facecolor="w",figsize=(9,10))
# 三行 第一列 第一个子图
plt.subplot(311)
plt.plot(data["TV"],y,"ro")
plt.title("TV")
plt.grid()

plt.subplot(312)
plt.plot(data["radio"],y,"g^")
plt.title("Radio")
plt.grid()

plt.subplot(313)
plt.plot(data["newspaper"],y,"mv")
plt.title("Newspaper")
plt.grid()

二、分割数据集 train_test_split()

In [10]:
#二、分割数据集 train_test_split()
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,train_size=0.25)
print(x_train)
print(x_test)
        TV  radio  newspaper
52   216.4   41.7       39.6
26   142.9   29.3       12.6
76    27.5    1.6       20.7
43   206.9    8.4       26.4
24    62.3   12.6       18.3
3    151.5   41.3       58.5
169  284.3   10.6        6.4
49    66.9   11.7       36.8
149   44.7   25.8       20.6
131  265.2    2.9       43.0
190   39.5   41.1        5.8
30   292.9   28.3       43.2
121   18.8   21.7       50.4
115   75.1   35.0       52.7
175  276.9   48.9       41.8
8      8.6    2.1        1.0
60    53.5    2.0       21.4
128  220.3   49.0        3.2
1     44.5   39.3       45.1
57   136.2   19.2       16.6
22    13.2   15.9       49.6
61   261.3   42.7       54.7
63   102.7   29.6        8.4
7    120.2   19.6       11.6
196   94.2    4.9        8.1
141  193.7   35.4       75.6
86    76.3   27.5       16.0
96   197.6    3.5        5.9
68   237.4   27.5       11.0
50   199.8    3.1       34.6
142  220.5   33.2       37.9
157  149.8    1.3       24.3
156   93.9   43.5       50.5
139  184.9   43.9        1.7
146  240.1    7.3        8.7
101  296.4   36.3      100.9
20   218.4   27.7       53.4
178  276.7    2.3       23.7
25   262.9    3.5       19.5
134   36.9   38.6       65.6
71   109.8   14.3       31.7
129   59.6   12.0       43.1
144   96.2   14.8       38.9
192   17.2    4.1       31.6
79   116.0    7.7       23.1
133  219.8   33.5       45.1
137  273.7   28.9       59.7
72    26.8   33.0       19.3
140   73.4   17.0       12.9
37    74.7   49.4       45.7
        TV  radio  newspaper
58   210.8   49.6       37.7
40   202.5   22.3       31.6
34    95.7    1.4        7.4
102  280.2   10.1       21.4
184  253.8   21.3       30.0
..     ...    ...        ...
15   195.4   47.7       52.9
41   177.0   33.4       38.7
163  163.5   36.8        7.4
109  255.4   26.9        5.5
80    76.4   26.7       22.3

[150 rows x 3 columns]
In [11]:
# x_train 表示训练数据中的x,y_train表示训练数据中的y
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
print(y_train)
print(y_test)
(50, 3)
(50,)
(150, 3)
(150,)
52     22.6
26     15.0
76      6.9
43     12.9
24      9.7
3      18.5
169    15.0
49      9.7
149    10.1
131    12.7
190    10.8
30     21.4
121     7.0
115    12.6
175    27.0
8       4.8
60      8.1
128    24.7
1      10.4
57     13.2
22      5.6
61     24.2
63     14.0
7      13.2
196     9.7
141    19.2
86     12.0
96     11.7
68     18.9
50     11.4
142    20.1
157    10.1
156    15.3
139    20.7
146    13.2
101    23.8
20     18.0
178    11.8
25     12.0
134    10.8
71     12.4
129     9.7
144    11.4
192     5.9
79     11.0
133    19.6
137    20.8
72      8.8
140    10.9
37     14.7
Name: sales, dtype: float64
58     23.8
40     16.6
34      9.5
102    14.8
184    17.6
       ... 
15     22.4
41     17.1
163    18.0
109    19.8
80     11.8
Name: sales, Length: 150, dtype: float64
In [12]:
LinearRegression
Out[12]:
sklearn.linear_model._base.LinearRegression

三、选择/建立模型 model=LinearRegression()

四、训练模型 modeL.fit()I

In [13]:
#三、选择/建立模型 model=LinearRegression()
linreg=LinearRegression()
print(linreg)
model=linreg.fit(x_train,y_train)
#y_hat=theta1*X1 + theta2*X2 + theta3*X3+theat0
print(model)
print("权重系数(coef_)={}".format(linreg.coef_))
print("截距项(intercept)={}".format(linreg.intercept_))
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
权重系数(coef_)=[ 0.04098751  0.20837822 -0.00213991]
截距项(intercept)=3.3343993230131055

五、验证模型 model.predict()

train数据的误差

In [14]:
# 最小二乘法计算误差
y_hat=linreg.predict(np.array(x_train))
MSE=np.average((y_hat-np.array(y_train))**2)
RMSE =np.sqrt(MSE)
print("残差平方根(MSE)={}".format(MSE))
print("开平方(RMSE)={}".format(RMSE))
残差平方根(MSE)=2.2149498499353983
开平方(RMSE)=1.4882707582746488
In [15]:
t=np.arange(len(x_train))
plt.title(u"模型于测试Y值的数据对比",fontsize=20)
plt.plot(t,y_hat,"r-",linewidth=2,label="Train")
plt.plot(t,y_train,"g-",linewidth=2,label="Predict")
plt.legend(loc ="upper right")
plt.show()

test数据的误差

In [16]:
# 最小二乘法计算误差
y_hat=linreg.predict(np.array(x_test))
MSE=np.average((y_hat-np.array(y_test))**2)
RMSE =np.sqrt(MSE)
print("残差平方根(MSE)={}".format(MSE))
print("开平方(RMSE)={}".format(RMSE))
残差平方根(MSE)=3.3098041082919782
开平方(RMSE)=1.8192867031592295
In [17]:
t=np.arange(len(x_test))
plt.title(u"模型于测试Y值的数据对比",fontsize=20)
plt.plot(t,y_hat,"r-",linewidth=2,label="Test")
plt.plot(t,y_test,"g-",linewidth=2,label="Predict")
plt.legend(loc ="upper right")
plt.show()
In [ ]:
 

 

 

 
posted @ 2020-07-26 22:54  范仁义  阅读(360)  评论(0)    收藏  举报