我想刷新我在Theano中编译的MLP模型,因为我想用不同的超参数重复使用该模型。
我知道我可以重新定义所有函数,但是每个函数的编译时间都很长。
我想定义一个函数来刷新模型的参数。
以下代码仅用于演示。
# 构建MLP类 classifier = MLP( rng=rng, input=x, n_in= n_input, n_hidden=n_hidden, n_out= n_output) cost = (classifier.negative_log_likelihood(y) + self.l1 * classifier.L1 + self.l2 * classifier.L2_sqr) gparams = [T.grad(cost, param) for param in classifier.params] updates = [(param, param - self.lr * gparam) \ for param, gparam in zip(classifier.params, gparams)] train_model = theano.function( inputs=[index], outputs=cost, updates=updates, givens={x: self.xTrain[index * self.batchSize: (index + 1) * self.batchSize], y: self.yTrain[index * self.batchSize: (index + 1) * self.batchSize]})
我的直觉告诉我,我可以简单地重新定义MLP()
类,而不会对其他已编译的函数产生影响。
这是正确的吗?
我在想,如果这是真的,我可以定义一个MLP.refresh()
函数,该函数重新实例化MLP()
类的每个组件的参数。
回答:
虽然MLP
类的工作原理尚不清楚,但只要共享变量的维数不变,您就可以重用之前编译的计算。
在下面的示例中,compile_model
函数创建了一个具有随机初始化参数的简单神经网络。在用这些参数训练后,共享变量被重新初始化为新的随机值,但这次网络的隐藏层大小增加了。尽管大小发生了变化,但仍重用了原始的训练函数。
import numpyimport theanoimport theano.tensor as ttdef compile_model(input_size, hidden_size, output_size, learning_rate): w_h = theano.shared(numpy.random.randn(input_size, hidden_size).astype(theano.config.floatX)) b_h = theano.shared(numpy.zeros(hidden_size, dtype=theano.config.floatX)) w_y = theano.shared(numpy.random.randn(hidden_size, output_size).astype(theano.config.floatX)) b_y = theano.shared(numpy.zeros(output_size, dtype=theano.config.floatX)) parameters = (w_h, b_h, w_y, b_y) x = tt.matrix() z = tt.lvector() h = tt.tanh(theano.dot(x, w_h) + b_h) y = tt.nnet.softmax(theano.dot(h, w_y) + b_y) c = tt.nnet.categorical_crossentropy(y, z).mean() u = [(p, p - learning_rate * theano.grad(c, p)) for p in parameters] trainer = theano.function([x, z], outputs=[c], updates=u) tester = theano.function([x], outputs=[y]) return trainer, tester, parametersdef refresh_model(parameters, input_size, hidden_size, output_size): w_h, b_h, w_y, b_y = parameters w_h.set_value(numpy.random.randn(input_size, hidden_size).astype(theano.config.floatX)) b_h.set_value(numpy.zeros(hidden_size, dtype=theano.config.floatX)) w_y.set_value(numpy.random.randn(hidden_size, output_size).astype(theano.config.floatX)) b_y.set_value(numpy.zeros(output_size, dtype=theano.config.floatX))def main(): input_size = 30 hidden_size = 10 output_size = 20 learning_rate = 0.01 batch_size = 40 epoch_count = 50 trainer, tester, parameters = compile_model(input_size, hidden_size, output_size, learning_rate) x = numpy.random.randn(batch_size, input_size) z = numpy.random.randint(output_size, size=(batch_size,)) print 'Training model with hidden size', hidden_size for _ in xrange(epoch_count): print trainer(x, z) hidden_size = 15 refresh_model(parameters, input_size, hidden_size, output_size) print 'Training model with hidden size', hidden_size for _ in xrange(epoch_count): print trainer(x, z)main()