Demonstrate stochastic gradient descent optimization of a log-linear model This is demonstrated on MNIST. :type learning_rate: float :param learning_rate: learning rate used (factor for the stochastic gradient) :type n_epochs: int :param n_ep
(learning_rate=0.13, n_epochs=1000,
dataset='mnist.pkl.gz',
batch_size=600)
| 254 | |
| 255 | |
| 256 | def sgd_optimization_mnist(learning_rate=0.13, n_epochs=1000, |
| 257 | dataset='mnist.pkl.gz', |
| 258 | batch_size=600): |
| 259 | """ |
| 260 | Demonstrate stochastic gradient descent optimization of a log-linear |
| 261 | model |
| 262 | |
| 263 | This is demonstrated on MNIST. |
| 264 | |
| 265 | :type learning_rate: float |
| 266 | :param learning_rate: learning rate used (factor for the stochastic |
| 267 | gradient) |
| 268 | |
| 269 | :type n_epochs: int |
| 270 | :param n_epochs: maximal number of epochs to run the optimizer |
| 271 | |
| 272 | :type dataset: string |
| 273 | :param dataset: the path of the MNIST dataset file from |
| 274 | http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz |
| 275 | |
| 276 | """ |
| 277 | datasets = load_data(dataset) |
| 278 | |
| 279 | train_set_x, train_set_y = datasets[0] |
| 280 | valid_set_x, valid_set_y = datasets[1] |
| 281 | test_set_x, test_set_y = datasets[2] |
| 282 | |
| 283 | # compute number of minibatches for training, validation and testing |
| 284 | n_train_batches = train_set_x.get_value(borrow=True).shape[0] // batch_size |
| 285 | n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] // batch_size |
| 286 | n_test_batches = test_set_x.get_value(borrow=True).shape[0] // batch_size |
| 287 | |
| 288 | ###################### |
| 289 | # BUILD ACTUAL MODEL # |
| 290 | ###################### |
| 291 | print('... building the model') |
| 292 | |
| 293 | # allocate symbolic variables for the data |
| 294 | index = T.lscalar() # index to a [mini]batch |
| 295 | |
| 296 | # generate symbolic variables for input (x and y represent a |
| 297 | # minibatch) |
| 298 | x = T.matrix('x') # data, presented as rasterized images |
| 299 | y = T.ivector('y') # labels, presented as 1D vector of [int] labels |
| 300 | |
| 301 | # construct the logistic regression class |
| 302 | # Each MNIST image has size 28*28 |
| 303 | classifier = LogisticRegression(input=x, n_in=28 * 28, n_out=10) |
| 304 | |
| 305 | # the cost we minimize during training is the negative log likelihood of |
| 306 | # the model in symbolic format |
| 307 | cost = classifier.negative_log_likelihood(y) |
| 308 | |
| 309 | # compiling a Theano function that computes the mistakes that are made by |
| 310 | # the model on a minibatch |
| 311 | test_model = theano.function( |
| 312 | inputs=[index], |
| 313 | outputs=classifier.errors(y), |
no test coverage detected