regression - Softmax 回归梯度
问题描述
从Ufldl softmax regression , 我尝试在 Python 中实现成本函数的梯度,但我的损失几乎没有改变:
def update_theta(x, y, theta, learning_rate):
# 4 classes, 3 features
theta_gradients = np.zeros((4, 3)).astype(np.float)
for j in range(4):
for i in range(len(x)):
# p: softmax P(y = j|x, theta)
p = softmax(sm_input(x[i], theta))[y[i]]
# target function {y = j}
p -= 1 if y[i] == j else 0
x[i] = p * x[i]
# sum gradients
theta_gradients[j] += x[i]
theta_gradients[j] = theta_gradients[j] / len(x)
theta = theta.T - learning_rate * theta_gradients
return theta.T
我的前 10 个 epoch 损失和累积:
1.3863767797767788
train acc cnt 3
1.386293406734411
train acc cnt 255
1.3862943723056675
train acc cnt 3
1.3862943609888068
train acc cnt 255
1.386294361121427
train acc cnt 3
1.3862943611198806
train acc cnt 254
1.386294361119894
train acc cnt 4
1.3862943611198937
train acc cnt 125
1.3862943611198937
train acc cnt 125
1.3862943611198937
train acc cnt 125
我不知道我是否误解了方程式,任何建议将不胜感激!
解决方案
难道你总是在你的 update_theta 函数中初始化你的 theta_gradients 吗?
通常梯度的每一步都应该从前一个 theta 中学习。
举个例子:
def step_gradient(theta_current, X, y, learning_rate):
preds = predict_abs(theta_current, X)
theta_gradient = -(2 / len(y)) * np.dot(X.T, (y - preds))
theta = theta_current - learning_rate * theta_gradient
return theta
推荐阅读
- linkedin - LinkedIn:通过 URN 获取潜在客户的 API?
- java - 基于多个属性对对象进行分组
- git - 如何撤消另一个分支的 git pull 并解决合并冲突?
- python - Pycharm CE 没有在我的 Django 项目中遇到断点
- scala - 如何在 scala 中加载加权图?
- javascript - 使用 styled-components 将容器中的内容居中
- ios - iOS 移动设备上 React App 的静音功能
- javascript - 有没有办法在没有文本框的情况下在 Javascript/Html 中获取文本输入?
- python - 如何对文件中的交替行进行操作
- javascript - 如何访问 SectionList 的数据?