sklearn机器学习实战-简单线性回归

记录下学习使用sklearn,将使用sklearn实现机器学习大部分内容

基于scikit-learn机器学习(第2版)这本书,和scikit-learn中文社区

简单线性回归

首先,最简单的线性回归也有几个地方要注意

  1. fit的时候,对于X,要求是n*m的类型,y要是n*1的类型
  2. sklearn会将得到的系数存储起来,分别在coef_中和intercept_中,intercept_是偏移,也就是b,coef_是k,或者向量中的W

来看具体例子

from sklearn.linear_model import LinearRegression
model = LinearRegression()
import numpy as np
# 线性模型为y = kx + b
X = np.array([1,2,3,4,5,6]).reshape(-1,1)
y = [1,2.1,2.9,4.1,5.2,6.1]
# y = np.array([1,2.1,2.9,4.1,5.2,6.1]) 这样写也是可以的
# y = np.array([1,2.1,2.9,4.1,5.2,6.1]).reshape(-1,1) 这样写也是可以的
# y = np.array([1,2.1,2.9,4.1,5.2,6.1]).reshape(1,-1) 这样写就不行了
model.fit(X,y)
print(model.coef_)
print(model.intercept_)

/*
[[1.02857143]]
[-0.03333333]
*/

上面y的长度总是要和X保持一致的

y = [1,2.1,2.9,4.1,5.2,6.1]
print("y:")
print(y)
y = np.array([1,2.1,2.9,4.1,5.2,6.1]) # 这样写也是可以的
print("y:")
print(y)
print(y.shape)
y = np.array([1,2.1,2.9,4.1,5.2,6.1]).reshape(-1,1) # 这样写也是可以的
print("y:")
print(y)
print(y.shape)
y = np.array([1,2.1,2.9,4.1,5.2,6.1]).reshape(1,-1) # 这样写就不行了
print("y:")
print(y)
print(y.shape)

/*
y:
[1, 2.1, 2.9, 4.1, 5.2, 6.1]
y:
[1.  2.1 2.9 4.1 5.2 6.1]
(6,)
y:
[[1. ]
 [2.1]
 [2.9]
 [4.1]
 [5.2]
 [6.1]]
(6, 1)
y:
[[1.  2.1 2.9 4.1 5.2 6.1]]
(1, 6)
*/

再来看这个例子

# 最小二乘法用于sklearn中的线性回归,引入它。
from sklearn import linear_model
reg = linear_model.LinearRegression()

def foo(x1,x2): # w0 = 5, w1 = 2, w2 = 3
    return 2 * x1 + 3 * x2 + 5

"""生成测试数据 X,y
X 10行2列
y 10行1列
"""
X = [[i,(i+1)/2] for i in range(10)]
y = [foo(i,(i+1)/2) for i in range(10)]

# 根据参数拟合直线
reg.fit(X,y)

# 输出 w1,w2 = [2.8, 1.4]
print(reg.coef_)

# 输出 w0 = 5.8
print(reg.intercept_)

"""
    拟合直线: y = 2.8 * x1 + 1.4 * x2 + 5.8
"""

#  用生成的直线进行预测
print(reg.predict(X))
[2.8 1.4]
5.799999999999997
X:
[[0, 0.5], [1, 1.0], [2, 1.5], [3, 2.0], [4, 2.5], [5, 3.0], [6, 3.5], [7, 4.0], [8, 4.5], [9, 5.0]]
y:
[6.5, 10.0, 13.5, 17.0, 20.5, 24.0, 27.5, 31.0, 34.5, 38.0]
predict:
[ 6.5 10.  13.5 17.  20.5 24.  27.5 31.  34.5 38. ]

这个例子来源:https://blog.csdn.net/weixin_43899202/article/details/104155313

看完之后第一反应是,明明 y = 2 * x1 + 3 * x2 + 5,怎么就变成 y = 2.8 * x1 + 1.4 * x2 + 5.8

这是因为我们对X赋值的时候都是等比例缩放,我们现在再用两个测试集去验证一下就知道了

# 验证集1
X_test = np.array([[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]])
y_test1 = np.array([5,10,15,20,25,30])
score1 = reg.score(X_test,y_test1)
print("score1:")
print(score1)
# 验证集2
X_test = np.array([[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]])
y_test2 = np.array([5.8,10,14.2,18.4,22.6,26.8])
score2 = reg.score(X_test,y_test2)
print("score2")
print(score2)
score1:
0.9546514285714286
score2
1.0

最后,再使用predict方法

X_predict = np.array([[0,0],[0,1],[1,1],[1,2],[2,2]])
print(reg.predict(X))
[ 6.5 10.  13.5 17.  20.5 24.  27.5 31.  34.5 38. ]

这样,学习使用了线性模型、fit方法、predict方法、score方法,以及线性模型的参数coef_intercept_

posted on 2021-12-09 11:34  lpzju  阅读(182)  评论(0)    收藏  举报

导航