我用theano编写了一个非常简单而紧凑的逻辑回归程序。我正在随机初始化我的数据,并且我已经将训练步骤的数量限制在1,所以由于权重也是随机的,我应该期望结果遵循标准的分布。我有10个类和10个最初的例子,所以我期望我的准确性接近10,大多数时候,但是我经常(经常)得到非常远的结果(比如0或49)。我希望有时能得到这样的结果,但不会经常这样。我的代码有什么问题吗?
import theano
import theano.tensor as T
import numpy as np
rng = np.random
#rng = np.random.RandomState(0)
ninputs = 100
nfeatures = 784
noutputs = 10
nhiddens = 50
#training rate
tr_rate = 0.1
training_steps = 1
D = (rng.randn(ninputs, nfeatures), rng.randint(size=ninputs, low=0, high=noutputs))
# Feed-forward
x = T.dmatrix('x')
t = T.ivector('t')
w = theano.shared(rng.randn(nfeatures, noutputs), name="w")
b = theano.shared(np.full(noutputs, 0.01), name="b")
sigma = T.nnet.softmax(T.dot(x,w) + b)
prediction = T.argmax(sigma, axis=1)
parameters = [w, b]
xent = -T.mean(T.log(sigma)[T.arange(t.shape[0]), t]) # Cost function
cost = xent.mean() + 0.01 * (w ** 2).sum() # Regularisation
gparameters = [T.grad(cost, param) for param in parameters] # Compute the gradient of the cost
pars = zip(parameters, gparameters)
train = theano.function(
inputs=[x,t],
outputs=[xent],
updates = [(param, param - tr_rate * gparam) for param, gparam in zip(parameters, gparameters)],
allow_input_downcast = True )
predict = theano.function(inputs=[x], outputs=prediction)
# Train
for i in range(training_steps):
train(D[0], D[1])
result = predict(D[0]) - D[1]
N = ninputs
error = 0
for index in result:
if result[index] != 0:
error += 1
correct_guesses = N - error
accuracy = (N - error)*100/N
print
print "correct predictions = %f over %i examples" % (correct_guesses, N)
print "accuracy = %i%%" % accuracy发布于 2015-12-16 14:41:34
如果您随机初始化权重并立即进行预测,您可能会期望1/num_classes的准确性。
但你得先训练。数据可能是随机的,但仍有可能对其进行过度拟合。通过一个小而宽的样本,您可以偶然地想象类的某种程度的可分性。在这种情况下,您的网络可以学习比随机更好的权重(在一次迭代中远非完美)。
通过使用更多的数据或保留/使用新的随机数据来测试准确性,这种影响可能会减少。
发布于 2015-12-17 07:07:04
在我的代码中发现了一个简单的错误。我写道:
for index in result:
if result[index] != 0:
error += 1虽然应该是这样的:
for index in range(N):
if result[index] != 0:
error += 1https://datascience.stackexchange.com/questions/9407
复制相似问题