1. model
这里待求解的是一个 binary logistic regression,它是一个分类模型,参数是权值矩阵
当然最终的目标是求解在整个样本集
- 这里的取均值是为了解耦后续的正则化系数,以及 SGD 时的步长的选择;
当然也可对
2. theano 的使用
实现 theano 下的最小化问题的求解,涉及如下的四个流程:
(1)声明符号变量;
import numpy import theano.tensor as T from theano import shared, function x = T.matrix() y = T.lvector() w = shared(numpy.random.randn(100)) b = shared(numpy.zeros(())) print 'step 1, initial mode: ' print w.get_value(), b.get_value()
(2)使用这些变量构建符号表达式图(symbolic expression graph)
# hypothesis p_1 = 1/(1+T.exp(-T.dot(x, w)-b)) xent = -y*T.log(p_1)-(1-y)*T.log(1-p_1) cost = xent.mean() + 0.01*(w**2).sum() gw, gb = T.grad(cost, [w, b]); prediction = p_1 > .5
(3)编译 Theano functions;
train = function(inputs=[x, y], outputs=[predication, xent], updates={w:w-0.1*gw, b:b-0.1*gb}) predict = function(inputs=[x], outputs=predication)
(4)调用编译好的函数来执行数值计算;
N = 4 feats = 100 D = (numpy.random.randn(N, feats), numpy.random.randi(low=0, high=2, size=(N,))) training_epochs = 10 for _ in range(training_epochs): pred, err = train(D[0], D[1]) print 'final model: ' print 'target values for D', D[1] print 'predication on D', predict(D[0])