用SGD进行多项Logistic softmax回归

时间:2017-10-23 16:53:38

标签: python machine-learning neural-network logistic-regression gradient-descent

我正在尝试从头开始构建一个可以对MNIST图像(手写数字)进行分类的模型。模型需要输出表示输入图像是特定数字的可能性的概率列表。

这是我到目前为止的代码:

from sklearn.datasets import load_digits
import numpy as np


def softmax(x):
    return np.exp(x) / np.sum(np.exp(x), axis=0)


digits = load_digits()

features = digits.data
targets = digits.target

train_count = int(0.8 * len(features))
train_x = features[: train_count]
train_y = targets[: train_count]

test_x = features[train_count:]
test_y = targets[train_count:]

bias = np.random.rand()
weights = np.random.rand(len(features[0]))
rate = 0.02

for i in range(1000):
    for i, sample in enumerate(train_x):

        prod = np.dot(sample, weights) - bias
        soft = softmax(prod)
        predicted = np.argmax(soft) + 1

        error = predicted - train_y[i]
        weights -= error * rate * sample
        bias -= rate * error
        # print(error)

我正在尝试构建模型,以便它使用随机梯度下降但我对于传递给softmax函数的内容有点困惑。我理解它应该期望一个数字向量,但我习惯(构建一个小NN时)是模型应该产生一个数字,然后传递给激活函数,激活函数反过来产生预测。在这里,我觉得我错过了一步,我不知道它是什么。

1 个答案:

答案 0 :(得分:1)

在最简单的实现中,你的最后一层(就在softmax之前)确实应该输出一个10-dim向量,它将被softmax压缩到[0, 1]。这意味着weights应为形状矩阵[features, 10]bias应为[10]向量。

除此之外,您还应one-hot encode train_y[0, 0, ..., 1, ..., 0]标签,即将每个项目转换为train_y向量。因此[size, 10]的形状为TableName.find(id)

看一下logistic regression example - 它在张量流中,但模型很可能与你的相似:它们使用768个特征(所有像素),一个热标签用于标签和一个隐藏层。他们还使用小批量加速学习。