神经网络入门之Logistic回归(分类问题)
来源:互联网 发布:淘宝一天最多几个好评 编辑:程序博客网 时间:2024/05/16 05:19
Logistic回归(分类问题)
这部分教程将介绍一部分:
- Logistic分类模型
我们在上次的教程中给出了一个很简单的模型,只有一个输入和一个输出。在这篇教程中,我们将构建一个二分类模型,输入参数是两个变量。这个模型在统计上被称为Logistic回归模型,网络结构可以被描述如下:
我们先导入教程需要使用的软件包。
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import colorConverter, ListedColormapfrom matplotlib import cm
定义类分布
在教程中,目标分类t
将从两个独立分布中产生,当t=1
时,用蓝色表示。当t=0
时,用红色表示。输入参数X
是一个N*2
的矩阵,目标分类t
是一个N * 1
的向量。更直观的表现,见下图。
# Define and generate the samplesnb_of_samples_per_class = 20 # The number of sample in each classred_mean = [-1,0] # The mean of the red classblue_mean = [1,0] # The mean of the blue classstd_dev = 1.2 # standard deviation of both classes# Generate samples from both classesx_red = np.random.randn(nb_of_samples_per_class, 2) * std_dev + red_meanx_blue = np.random.randn(nb_of_samples_per_class, 2) * std_dev + blue_mean# Merge samples in set of input variables x, and corresponding set of output variables tX = np.vstack((x_red, x_blue))t = np.vstack((np.zeros((nb_of_samples_per_class,1)), np.ones((nb_of_samples_per_class,1))))
# Plot both classes on the x1, x2 planeplt.plot(x_red[:,0], x_red[:,1], 'ro', label='class red')plt.plot(x_blue[:,0], x_blue[:,1], 'bo', label='class blue')plt.grid()plt.legend(loc=2)plt.xlabel('$x_1$', fontsize=15)plt.ylabel('$x_2$', fontsize=15)plt.axis([-4, 4, -4, 4])plt.title('red vs. blue classes in the input space')plt.show()
Logistic函数和交叉熵损失函数
Logistic函数
我们设计的网络的目的是从输入的x
去预测目标t
。假设,输入x = [x1, x2]
,权重w = [w1, w2]
,预测目标t = 1
。那么,概率P(t = 1|x, w)
将是神经网络输出的y
,即y = σ(x∗wT)
。其中,σ
表示Logistic函数
,定义如下:
如果,对于Logistic函数和它的导数还不是很清楚的,可以查看这个教程,里面进行了详细描述。
交叉熵损失函数
对于这个分类问题的损失函数优化,我们使用交叉熵误差函数来解决,对于每个训练样本i
,交叉熵误差函数定义如下:
如果我们要计算整个训练样本的交叉熵误差,那么只需要把每一个样本的值进行累加就可以了,即:
关于交叉熵误差函数更加详细的介绍可以看这个教程。
logistic(z)
函数实现了Logistic
函数,cost(y, t)
函数实现了损失函数,nn(x, w)
实现了神经网络的输出结果,nn_predict(x, w)
实现了神经网络的预测结果。
# Define the logistic functiondef logistic(z): return 1 / (1 + np.exp(-z))# Define the neural network function y = 1 / (1 + numpy.exp(-x*w))def nn(x, w): return logistic(x.dot(w.T))# Define the neural network prediction function that only returns# 1 or 0 depending on the predicted classdef nn_predict(x,w): return np.around(nn(x,w))# Define the cost functiondef cost(y, t): return - np.sum(np.multiply(t, np.log(y)) + np.multiply((1-t), np.log(1-y)))
# Plot the cost in function of the weights# Define a vector of weights for which we want to plot the costnb_of_ws = 100 # compute the cost nb_of_ws times in each dimensionws1 = np.linspace(-5, 5, num=nb_of_ws) # weight 1ws2 = np.linspace(-5, 5, num=nb_of_ws) # weight 2ws_x, ws_y = np.meshgrid(ws1, ws2) # generate gridcost_ws = np.zeros((nb_of_ws, nb_of_ws)) # initialize cost matrix# Fill the cost matrix for each combination of weightsfor i in range(nb_of_ws): for j in range(nb_of_ws): cost_ws[i,j] = cost(nn(X, np.asmatrix([ws_x[i,j], ws_y[i,j]])) , t)# Plot the cost function surfaceplt.contourf(ws_x, ws_y, cost_ws, 20, cmap=cm.pink)cbar = plt.colorbar()cbar.ax.set_ylabel('$\\xi$', fontsize=15)plt.xlabel('$w_1$', fontsize=15)plt.ylabel('$w_2$', fontsize=15)plt.title('Cost function surface')plt.grid()plt.show()
梯度下降优化损失函数
梯度下降算法的工作原理是损失函数ξ
对于每一个参数的求导,然后沿着负梯度方向进行参数更新。
参数w
按照一定的学习率沿着负梯度方向更新,即w(k+1)=w(k)−Δw(k+1)
,其中Δw
可以表示为:
对于每个训练样本i
,∂ξi/∂w
计算如下:
其中,yi=σ(zi)
是神经元的Logistic
输出,zi=xi∗wT
是神经元的输入。
在详细推导损失函数对于权重的导数之前,我们先这个教程中摘取几个推导。
参考上面的分步推导,我们可以得到下面的详细推导:
因此,对于每个权重的更新Δwj
可以表示为:
在批处理中,我们需要将N
个样本的梯度都进行累加,即:
在开始梯度下降算法之前,你需要对参数都进行一个随机数赋值过程,然后采用梯度下降算法更新参数,直至收敛。
gradient(w, x, t)
函数实现了梯度∂ξ/∂w
,delta_w(w_k, x, t, learning_rate)
函数实现了Δw
。
# define the gradient function.def gradient(w, x, t): return (nn(x, w) - t).T * x# define the update function delta w which returns the # delta w for each weight in a vectordef delta_w(w_k, x, t, learning_rate): return learning_rate * gradient(w_k, x, t)
梯度下降更新
我们在训练集X
上面运行10
次去做预测,下图中画出了前三次的结果,图中蓝色的点表示在第k
次,w(k)
的值。
# Set the initial weight parameterw = np.asmatrix([-4, -2])# Set the learning ratelearning_rate = 0.05# Start the gradient descent updates and plot the iterationsnb_of_iterations = 10 # Number of gradient descent updatesw_iter = [w] # List to store the weight values over the iterationsfor i in range(nb_of_iterations): dw = delta_w(w, X, t, learning_rate) # Get the delta w update w = w-dw # Update the weights w_iter.append(w) # Store the weights for plotting
# Plot the first weight updates on the error surface# Plot the error surfaceplt.contourf(ws_x, ws_y, cost_ws, 20, alpha=0.9, cmap=cm.pink)cbar = plt.colorbar()cbar.ax.set_ylabel('cost')# Plot the updatesfor i in range(1, 4): w1 = w_iter[i-1] w2 = w_iter[i] # Plot the weight-cost value and the line that represents the update plt.plot(w1[0,0], w1[0,1], 'bo') # Plot the weight cost value plt.plot([w1[0,0], w2[0,0]], [w1[0,1], w2[0,1]], 'b-') plt.text(w1[0,0]-0.2, w1[0,1]+0.4, '$w({})$'.format(i), color='b')w1 = w_iter[3] # Plot the last weightplt.plot(w1[0,0], w1[0,1], 'bo')plt.text(w1[0,0]-0.2, w1[0,1]+0.4, '$w({})$'.format(4), color='b') # Show figureplt.xlabel('$w_1$', fontsize=15)plt.ylabel('$w_2$', fontsize=15)plt.title('Gradient descent updates on cost surface')plt.grid()plt.show()
训练结果可视化
下列代码,我们将训练的结果进行可视化。
# Plot the resulting decision boundary# Generate a grid over the input space to plot the color of the# classification at that grid pointnb_of_xs = 200xs1 = np.linspace(-4, 4, num=nb_of_xs)xs2 = np.linspace(-4, 4, num=nb_of_xs)xx, yy = np.meshgrid(xs1, xs2) # create the grid# Initialize and fill the classification planeclassification_plane = np.zeros((nb_of_xs, nb_of_xs))for i in range(nb_of_xs): for j in range(nb_of_xs): classification_plane[i,j] = nn_predict(np.asmatrix([xx[i,j], yy[i,j]]) , w)# Create a color map to show the classification colors of each grid pointcmap = ListedColormap([ colorConverter.to_rgba('r', alpha=0.30), colorConverter.to_rgba('b', alpha=0.30)])# Plot the classification plane with decision boundary and input samplesplt.contourf(xx, yy, classification_plane, cmap=cmap)plt.plot(x_red[:,0], x_red[:,1], 'ro', label='target red')plt.plot(x_blue[:,0], x_blue[:,1], 'bo', label='target blue')plt.grid()plt.legend(loc=2)plt.xlabel('$x_1$', fontsize=15)plt.ylabel('$x_2$', fontsize=15)plt.title('red vs. blue classification boundary')plt.show()
- 神经网络入门之Logistic回归(分类问题)
- 分类数据之logistic回归
- logistic分类(logistic回归 LR)
- Logistic回归(一)分类
- 逻辑回归之从Logistic回归到sigmoid与softmax的分类问题
- 分类算法之logistic 回归模型
- Logistic回归多分类之鸢尾花
- 机器学习之logistic回归与分类
- Spark2.0机器学习系列之2:Logistic回归及Binary分类(二分问题)结果评估
- Logistic回归(LR)分类器
- Logistic回归分类
- logistic回归分类
- logistic回归分类
- Python Logistic 回归分类
- 分类和Logistic回归
- 分类算法:Logistic回归
- 神经网络入门之线性回归
- 《机器学习实战》学习笔记(四)之Logistic(下)Logistic回归实战之预测病马死亡率及使用Sklearn构建Logistic回归分类器
- 分享一个仿微信多选图cordova插件(相册内带相机功能)
- 二分查找法
- SSD卡驱动中trim命令的实现原理
- Scrollview嵌套Recyclerview出现的显示不全 不显示问题的解决方法
- 数据库个人总结
- 神经网络入门之Logistic回归(分类问题)
- 写作建议
- 剑指offer--面试题7:重建二叉树
- css笔记:包含块(Containing Block)
- Java还要再学一遍基础(十五)
- 第一节 scala 变量的定义和使用
- 04_Qt的画笔、作画和自定义控件
- 76. Minimum Window Substring 10-line template that can solve most 'substring' problems
- <java EE 项目:petstore> 从一个简单项目看 java web 如何在本jsp页面上对用户输入的格式进行限制与验证