在Python中逐步实现线性回归

欢迎关注 “小白玩转Python”,发现更多 “有趣”

引言

最基本的机器学习算法必须是单变量线性回归算法。现如今有很多先进的机器学习算法,线性回归显得似乎并不重要。但夯实基础是为了更好的发展,这样你就能很清楚地理解概念。在本文中,我们将逐步实现线性回归算法。

思想和公式

线性回归使用了最基本的预测思想,这里有一个公式:

Y = C + BX

我们都学过这个公式,这是一条直线的方程。Y是因变量,B是斜率,C是截距。通常对于线性回归,它的公式如下:

在这里,h是假设或预测的因变量,x是输入特征,θ0和θ1是系数。首先随机初始化θ值。然后使用梯度下降法,我们将更新θ值,以最小化成本函数。下面是成本函数和梯度下降法的介绍。

成本函数和梯度下降法

成本函数决定了预测值与原始因变量之间的距离,下面是成本函数的公式:

任何机器学习算法的思想都是最小化成本函数,使预测值接近原始因变量。我们需要优化θ值来做到这一点。如果我们分别取基于θ0和θ1的偏导数,我们将得到梯度下降的值。为了更新θ值,我们需要从相应的θ值中减去梯度下降的值:

将成本函数代入可得:

例子

下面我们将在python中一步一步实现一个线性回归。

1. 导入库和数据集

import numpy as np
import pandas as pd
df = pd.read_csv('ex1data1.txt', header = None)
df.head()

在此数据集中,列0是输入特征,列1是输出变量或因变量。我们将使用上面的公式,用0列来预测1列。

2. 绘制

输入变量和输出变量之间的关系是线性的。当关系为线性时,线性回归效果最佳。

3. 初始化θ值

将θ值初始化为0,但其他的初始值也是可以的。

theta = [0,0]

4. 根据前面讨论的公式定义预测值和成本函数。

def hypothesis(theta, X):
    return theta[0] + theta[1]*Xdef cost_calc(theta, X, y):
    return (1/2*m) * np.sum((hypothesis(theta, X) - y)**2)

5. 定义梯度下降函数,更新θ值,直到成本函数为最小值。

m = len(df)
def gradient_descent(theta, X, y, epoch, alpha):
    cost = []
    i = 0
    while i < epoch:
        hx = hypothesis(theta, X)
        theta[0] -= alpha*(sum(hx-y)/m)
        theta[1] -= (alpha * np.sum((hx - y) * X))/m
        cost.append(cost_calc(theta, X, y))
        i += 1
    return theta, cost

6. 定义预测函数。它将从梯度下降函数中得到更新的θ,并对输出变量进行预测。

def predict(theta, X, y, epoch, alpha):
    theta, cost = gradient_descent(theta, X, y, epoch, alpha)
    return hypothesis(theta, X), cost, theta

7. 使用预测函数,得到预测值和更新的θ。

y_predict, cost, theta = predict(theta, df[0], df[1], 2000, 0.01)

最终θ的值为-3.79和1.18.

8. 在同一个图中画出原始的y和假设或者预测的y。

%matplotlib inline
import matplotlib.pyplot as plt
plt.figure()
plt.scatter(df[0], df[1], label = 'Original y')
plt.scatter(df[0], y_predict, label = 'predicted y')
plt.legend(loc = "upper left")
plt.xlabel("input feature")
plt.ylabel("Original and Predicted Output")
plt.show()

9. 记录每次迭代的成本函数,并绘制成本函数的变化图像。

plt.figure()
plt.scatter(range(0, len(cost)), cost)
plt.show()

正如上文提到的,我们的目的是优化θ值,使成本函数最小化。如上图所见,成本在开始时急剧下降,然后变得稳定。这意味着θ值正如我们预期的那样得到了正确的优化。

·  END  ·

HAPPY LIFE

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
逐步线性回归是一种常用的线性回归方法,它通过逐步选择最优的特征集合来建立模型。在该方法,模型的参数估计采用OLS(普通最小二乘)法,但是模型特征选择采用逐步回归的思想,它可以避免过拟合问题,并提高模型的预测精度。Python有很多库可以实现逐步线性回归,其比较常用的是statsmodels和sklearn。 在statsmodels,可以使用stepwise_selection函数实现逐步回归,代码如下: ``` import statsmodels.api as sm from sklearn.datasets import load_boston import pandas as pd data = load_boston() df = pd.DataFrame(data.data, columns=data.feature_names) target = pd.DataFrame(data.target, columns=["MEDV"]) # Forward stepwise selection def forward_selected(data, response): remaining = set(data.columns) selected = [] current_score, best_new_score = float('inf'), float('inf') while remaining and current_score == best_new_score: scores_with_candidates = [] for candidate in remaining: model = sm.OLS(response, sm.add_constant(pd.DataFrame(data[selected + [candidate]]))).fit() score = model.rsquared_adj scores_with_candidates.append((score, candidate)) scores_with_candidates.sort() best_new_score, best_candidate = scores_with_candidates.pop() if current_score > best_new_score: remaining.remove(best_candidate) selected.append(best_candidate) current_score = best_new_score return selected print(forward_selected(df, target)) ``` 在sklearn,可以使用sklearn.linear_model.LinearRegression类和sklearn.feature_selection.RFE类实现逐步回归,代码如下: ``` from sklearn.linear_model import LinearRegression from sklearn.feature_selection import RFE X = data.data y = data.target model = LinearRegression() # Recursive Feature Elimination rfe = RFE(model, 5) fit = rfe.fit(X, y) print("Selected Features: ", fit.support_) print("Feature Ranking: ", fit.ranking_) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值