梯度下降:代码
2017-07-02 17:13
155 查看
梯度下降:代码
之前我们看到一个权重的计算是:Δwi=ηδxi
这里 error term δ 是指
δ=(y−y^)f′(h)=(y−y^)f′(∑wixi)
记住,上面公式中 (y−y^) 是输出误差,f′(h) 是激活函数 f(h) 的导函数,我们把这个导函数称做输出的梯度。
现在假设只有一个输出,我来把这个写成代码。我们还是用 sigmoid 来作为激活函数 f(h)。import numpy as np
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1/(1+np.exp(-x))
def sigmoid_prime(x):
"""
# Derivative of the sigmoid function
"""
return sigmoid(x) * (1 - sigmoid(x))
learnrate = 0.5
x = np.array([1, 2, 3, 4])
y = np.array(0.5)
# Initial weights
w = np.array([0.5, -0.5, 0.3, 0.1])
### Calculate one gradient descent step for each weight
### Note: Some steps have been consilated, so there are
### fewer variable names than in the above sample code
# TODO: Calculate the node's linear combination of inputs and weights
h = np.dot(x, w)
# TODO: Calculate output of neural network
nn_output = sigmoid(h)
# TODO: Calculate error of neural network
error = y - nn_output
# TODO: Calculate the error term
# Remember, this requires the output gradient, which we haven't
# specifically added a variable for.
error_term = error * sigmoid_prime(h)
# TODO: Calculate change in weights
del_w = learnrate * error_term * x
print('Neural Network output:')
print(nn_output)
print('Amount of Error:')
print(error)
print('Change in Weights:')
print(del_w)
相关文章推荐
- 梯度下降详解(包含代码例子)
- 机器学习入门:线性回归及梯度下降(附matlab代码)
- 最优化问题-梯度下降(Gradient Descent)算法&样例代码以及相关扩展
- 斯坦福大学机器学习笔记——单变量的线性回归以及损失函数和梯度下降法(包含代码)
- 理解梯度下降,随机梯度下降,附电影推荐系统的简单代码小样 2
- 线性回归之梯度下降法(附代码)
- [吴恩达 DL] CLass2 Week2 Mini-batch梯度下降 课程总结+代码实现
- LR 逻辑回归代码 (梯度下降)
- Java应用梯度下降求解线性SVM模型参考代码
- Python神经网络代码实现流程(三):反向传播与梯度下降
- 线性回归的正规方程解法与梯度下降解法的代码
- 梯度下降(Gradient Descent),一句代码,一个式子
- 1、梯度下降c代码
- 梯度下降法,牛顿法,高斯-牛顿迭代法,附代码实现
- 线性回归之梯度下降(附代码)
- 最小二乘参数估计---梯度下降法求解参数的sas代码实现
- 梯度下降实现案例(含python代码)
- 梯度下降法Python代码
- 随机梯度下降法,批量梯度下降法和小批量梯度下降法以及代码实现
- 梯度下降求解逻辑回归(代码)