300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 一元线性回归(Linear Regression)

一元线性回归(Linear Regression)

时间:2023-10-06 18:10:52

相关推荐

一元线性回归(Linear Regression)

简介

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

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 = 0for i in range(m):J += (float(X[i].dot(theta)) - y[i])**2return 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 examplesJ_history = np.zeros(shape=(num_iters, 1))for i in range(num_iters):deriv_0 = 0deriv_1 = 0for 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/mtheta[1] -= deriv_1*alpha/m# Save the cost J in every iterationJ_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(θ),在和值的二维网格上绘制三维代价函数曲线图。

具体代码参考:/hanmy1021/MachineLearning

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。