【发布时间】:2017-05-20 04:30:31
【问题描述】:
我正在尝试实现一个神经网络,将图像分类为两个离散类别之一。然而,问题是它目前总是预测任何输入为 0,我不太确定为什么。
这是我的特征提取方法:
def extract(file):
# Resize and subtract mean pixel
img = cv2.resize(cv2.imread(file), (224, 224)).astype(np.float32)
img[:, :, 0] -= 103.939
img[:, :, 1] -= 116.779
img[:, :, 2] -= 123.68
# Normalize features
img = (img.flatten() - np.mean(img)) / np.std(img)
return np.array([img])
这是我的梯度下降例程:
def fit(x, y, t1, t2):
"""Training routine"""
ils = x.shape[1] if len(x.shape) > 1 else 1
labels = len(set(y))
if t1 is None or t2 is None:
t1 = randweights(ils, 10)
t2 = randweights(10, labels)
params = np.concatenate([t1.reshape(-1), t2.reshape(-1)])
res = grad(params, ils, 10, labels, x, y)
params -= 0.1 * res
return unpack(params, ils, 10, labels)
这是我的前向和后向(梯度)传播:
def forward(x, theta1, theta2):
"""Forward propagation"""
m = x.shape[0]
# Forward prop
a1 = np.vstack((np.ones([1, m]), x.T))
z2 = np.dot(theta1, a1)
a2 = np.vstack((np.ones([1, m]), sigmoid(z2)))
a3 = sigmoid(np.dot(theta2, a2))
return (a1, a2, a3, z2, m)
def grad(params, ils, hls, labels, x, Y, lmbda=0.01):
"""Compute gradient for hypothesis Theta"""
theta1, theta2 = unpack(params, ils, hls, labels)
a1, a2, a3, z2, m = forward(x, theta1, theta2)
d3 = a3 - Y.T
print('Current error: {}'.format(np.mean(np.abs(d3))))
d2 = np.dot(theta2.T, d3) * (np.vstack([np.ones([1, m]), sigmoid_prime(z2)]))
d3 = d3.T
d2 = d2[1:, :].T
t1_grad = np.dot(d2.T, a1.T)
t2_grad = np.dot(d3.T, a2.T)
theta1[0] = np.zeros([1, theta1.shape[1]])
theta2[0] = np.zeros([1, theta2.shape[1]])
t1_grad = t1_grad + (lmbda / m) * theta1
t2_grad = t2_grad + (lmbda / m) * theta2
return np.concatenate([t1_grad.reshape(-1), t2_grad.reshape(-1)])
这是我的预测函数:
def predict(theta1, theta2, x):
"""Predict output using learned weights"""
m = x.shape[0]
h1 = sigmoid(np.hstack((np.ones([m, 1]), x)).dot(theta1.T))
h2 = sigmoid(np.hstack((np.ones([m, 1]), h1)).dot(theta2.T))
return h2.argmax(axis=1)
我可以看到错误率随着每次迭代而逐渐降低,一般在 1.26e-05 左右收敛。
到目前为止我已经尝试过:
- 主成分分析
- 不同的数据集(来自 sklearn 的虹膜和来自 Coursera ML 课程的手写数字,两者的准确率都达到了 95% 左右)。但是,这两个都是批量处理的,所以我可以假设我的一般实现是正确的,但是我提取特征的方式或训练分类器的方式有问题。
- 尝试了 sklearn 的 SGDClassifier,但它的性能并没有好多少,准确率约为 50%。那么这些功能有问题吗?
编辑: h2 的平均输出如下所示:
[0.5004899 0.45264441]
[0.50048522 0.47439413]
[0.50049019 0.46557124]
[0.50049261 0.45297816]
因此,所有验证示例的 sigmoid 输出都非常相似。
【问题讨论】:
-
想一想,你是在随机化你的训练集吗?如果第一批中有一堆
0类,它可能很早就开始关注它们。 -
数据是有序的,即:10000个0,然后10000个1。
-
刚刚意识到您说的是“批处理”。我想我对“小批量”感到困惑,这是一个常见问题。我需要再考虑一下。
-
仅供参考:我尝试随机化输入数据,结果仍然相同。
-
尝试从最终的
predict调用中返回原始的h2值。它们也都一样吗?
标签: python-3.x numpy neural-network deep-learning gradient-descent