Scikit-learn 学习心得(线性回归)

一开始学习线性回归的时候,是在MATLAB里写的,现在学习用python来做。

Scikit-learn 的线性回归怎么用呢?

开始参考的是这个:https://blog.csdn.net/u010900574/article/details/52666291

官方参考为:http://scikit-learn.org/stable/modules/linear_model.html

 

其实很简单,主要有如下几步:

1,各种import

import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression

2,构造样本

#这里尝试做一个直线10 + 2x的回归

NUM = 10
x = np.linspace(1,10,NUM)
y = 10 + 2*x + np.random.randn(NUM)
x_train = np.array([[tmp] for tmp in x]) #sklearn线性回归函数的入参要整成这种,不能用前两行的x,(这个在一开始把我整的晕乎乎的,还不太熟悉python的数据类型)
y_train = np.array([[tmp] for tmp in y])

3,训练

model_linear = LinearRegression()  #设置线性回归模块
model_linear.fit(x_train, y_train) #训练数据,得出参数

4,得到特征参数:

print(model_linear.coef_)        #coef_ 用于存放系数
print(model_linear.intercept_)   #intercept_ 用于存放截距 (偏置项)

其他参数请查阅相关资料,例如:https://www.cnblogs.com/magle/p/5881170.html

5,模型应用:

y_predict = model_linear.predict(x_train)

6,绘图

label = ['sample', 'predict']
plt.plot(x_train, y_train, 'o')
plt.plot(x_train, y_predict)
plt.legend(label)
plt.show()

完成。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值