Theano 逻辑回归示例

数据挖掘 Python 逻辑回归 西阿诺
2021-10-07 01:17:37

我正在尝试使用 theano 来理解一些简单的神经网络案例。deeplearning.net 网站提供了以下简单代码,用于将逻辑回归应用程序实现到一个简单的案例:

import numpy
import theano
import theano.tensor as T
rng = numpy.random

N = 400
feats = 784
D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2))
training_steps = 10000

# Declare Theano symbolic variables
x = T.matrix("x")
y = T.vector("y")
w = theano.shared(rng.randn(feats), name="w")
b = theano.shared(0., name="b")
print("Initial model:")
print(w.get_value())
print(b.get_value())

# Construct Theano expression graph
p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b))   # Probability that target = 1
prediction = p_1 > 0.5                    # The prediction thresholded
xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function
cost = xent.mean() + 0.01 * (w ** 2).sum()# The cost to minimize
gw, gb = T.grad(cost, [w, b])             # Compute the gradient of the cost
                                          # (we shall return to this in a
                                          # following section of this tutorial)

# Compile
train = theano.function(
          inputs=[x,y],
          outputs=[prediction, xent],
          updates=((w, w - 0.1 * gw), (b, b - 0.1 * gb)))
predict = theano.function(inputs=[x], outputs=prediction)

# Train
for i in range(training_steps):
    pred, err = train(D[0], D[1])

print("Final model:")
print(w.get_value())
print(b.get_value())
print("target values for D:")
print(D[1])
print("prediction on D:")
print(predict(D[0]))

大部分我都懂,p_1是逻辑回归函数,预测的是值是在0类还是1类,xent是损失函数,即我们的预测离正确还有多远。我不明白下一行,成本。成本不应该等于xent,即损失吗?这里代表的成本函数是什么?另外,为什么偏差最初设置为 0 而不是像权重这样的随机数?

1个回答

我不明白下一行,成本。成本不应该等于xent,即损失吗?这里代表的成本函数是什么?

代价是误差 (xent.mean()) + 一些正则化 (0.01 * (w ** 2).sum())

为什么偏差最初设置为 0 而不是像权重这样的随机数?

将偏差初始化为零是可能且常见的,因为不对称破坏是由权重中的小随机数提供的。

更多细节在这里