首页 > 编程知识 正文

一元线性回归Linear Regression,一元线性回归

时间:2023-05-05 10:22:25 阅读:222507 作者:2986

简介

在这节练习中,建立一个一元线性回归模型,以预测食品配送的利润。假设你是一家连锁餐厅的老板,正在考虑在不同的城市开设一家新的餐厅。这个连锁店在各个城市都可以配送,并且你有这个城市的利润和人口数据。

ex1data1.txt文件包含了线性回归问题的数据集。第一列是城市的人口数据,第二列是食品配送的利润,负值表示亏损。

绘制数据

对于这个数据集,可以使用散点图来可视化数据,因为它只有两个属性要绘制(利润和人口)。

# PLOTDATA Plots the data points x and y into a new figure # PLOTDATA(x,y) plots the data points and gives the figure axes labels of# population and profit.from matplotlib import pyplot as pltimport numpy as npdef plotData(x, y): plt.title("Training data") plt.xlim(4, 24) plt.ylim(-5, 25) plt.xticks(np.arange(4, 25, 2)) plt.yticks(np.arange(-5, 26, 5)) plt.xlabel("Population of City in 10,000s") plt.ylabel("Profit in $10,000s") plt.scatter(x, y, s=100, c='r', marker='x') plt.show()

如图:

若要加上线性回归拟合直线,加上预测值y_即可:

def plotLinearFit(x, y, y_): plt.title("Linear Regression") plt.xlim(4, 24) plt.ylim(-5, 25) plt.xticks(np.arange(4, 25, 2)) plt.yticks(np.arange(-5, 26, 5)) plt.xlabel("Population of City in 10,000s") plt.ylabel("Profit in $10,000s") plt.scatter(x, y, s=100, c='r', marker='x') plt.plot(x, y_, linestyle='-') plt.legend(scatterpoints=1, labels=['Linear regression', 'Training data'], loc=4) plt.show() 梯度下降

这一部分使用梯度下降将线性回归参数θ拟合到数据集。

1.更新公式

线性回归的目标是最小化代价函数J(θ):

其中假设函数由线性模型给出:

模型的参数是,调整它来最小化代价函数J(θ),一种方法是采用批梯度下降算法,在批梯度下降中,每次迭代执行更新:

(同时更新所有的)

随着梯度下降的每一次迭代,参数会更接近最优值,达到最低代价J(θ)。

2.初始化

将初始参数初始化为0,学习速率alpha初始化为0.01。

3.计算代价函数J(θ)

在执行梯度下降以学习最小化代价函数J(θ)时,通过计算代价来监控收敛性是很有帮助的。这一部分实现一个计算J(θ)的函数,以便检查梯度下降实现的收敛性。

# COMPUTECOST Compute cost for linear regression# J = COMPUTECOST(X, y, theta) computes the cost of using theta as the# parameter for linear regression to fit the data points in X and ydef computeCost(X, y, theta): m = len(y) J = 0 for i in range(m): J += (float(X[i].dot(theta)) - y[i])**2 return J/(2*m)

4.梯度下降

# GRADIENTDESCENT Performs gradient descent to learn theta# theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta by# taking num_iters gradient steps with learning rate alphafrom computeCost import computeCostimport numpy as npdef gradientDescent(X, y, theta, alpha, num_iters): m = len(y) # number of training examples J_history = np.zeros(shape=(num_iters, 1)) for i in range(num_iters): deriv_0 = 0 deriv_1 = 0 for j in range(m): deriv_0 += float(X[j].dot(theta))-y[j] deriv_1 += (float(X[j].dot(theta))-y[j])*X[j][1] theta[0] -= deriv_0*alpha/m theta[1] -= deriv_1*alpha/m # Save the cost J in every iteration J_history[i] = computeCost(X, y, theta) if i % 300 == 0: print("After %d steps, the cost function:" % i, J_history[i]) print("the gradient:", theta) return theta

线性回归拟合数据得到的结果如图:

可视化代价函数J(θ)

为了更好地理解代价函数J(θ),在和值的二维网格上绘制三维代价函数曲线图。

具体代码参考:https://github.com/hanmy1021/MachineLearning

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。