Showing posts with label keras. Show all posts
Showing posts with label keras. Show all posts

Tuesday, October 16, 2018

Constant Validation Accuracy with a high loss in machine learning

Leave a Comment

I'm currently trying to do create an image classification model using Inception V3 with 2 classes. I have 1428 images which are balanced about 70/30. When I run my model I get a pretty high loss of as well as a constant validation accuracy. What might be causing this constant value?

data = np.array(data, dtype="float")/255.0 labels = np.array(labels,dtype ="uint8")  (trainX, testX, trainY, testY) = train_test_split(                             data,labels,                              test_size=0.2,                              random_state=42)   img_width, img_height = 320, 320 #InceptionV3 size  train_samples =  1145  validation_samples = 287 epochs = 20  batch_size = 32  base_model = keras.applications.InceptionV3(         weights ='imagenet',         include_top=False,          input_shape = (img_width,img_height,3))  model_top = keras.models.Sequential() model_top.add(keras.layers.GlobalAveragePooling2D(input_shape=base_model.output_shape[1:], data_format=None)), model_top.add(keras.layers.Dense(350,activation='relu')) model_top.add(keras.layers.Dropout(0.2)) model_top.add(keras.layers.Dense(1,activation = 'sigmoid')) model = keras.models.Model(inputs = base_model.input, outputs = model_top(base_model.output))   for layer in model.layers[:30]:   layer.trainable = False  model.compile(optimizer = keras.optimizers.Adam(                     lr=0.00001,                     beta_1=0.9,                     beta_2=0.999,                     epsilon=1e-08),                     loss='binary_crossentropy',                     metrics=['accuracy'])  #Image Processing and Augmentation  train_datagen = keras.preprocessing.image.ImageDataGenerator(           zoom_range = 0.05,           #width_shift_range = 0.05,            height_shift_range = 0.05,           horizontal_flip = True,           vertical_flip = True,           fill_mode ='nearest')   val_datagen = keras.preprocessing.image.ImageDataGenerator()   train_generator = train_datagen.flow(         trainX,          trainY,         batch_size=batch_size,         shuffle=True)  validation_generator = val_datagen.flow(                 testX,                 testY,                 batch_size=batch_size)  history = model.fit_generator(     train_generator,      steps_per_epoch = train_samples//batch_size,     epochs = epochs,      validation_data = validation_generator,      validation_steps = validation_samples//batch_size,     callbacks = [ModelCheckpoint]) 

This is my log when I run my model:

Epoch 1/20 35/35 [==============================]35/35[==============================] - 52s 1s/step - loss: 0.6347 - acc: 0.6830 - val_loss: 0.6237 - val_acc: 0.6875  Epoch 2/20 35/35 [==============================]35/35 [==============================] - 14s 411ms/step - loss: 0.6364 - acc: 0.6756 - val_loss: 0.6265 - val_acc: 0.6875  Epoch 3/20 35/35 [==============================]35/35 [==============================] - 14s 411ms/step - loss: 0.6420 - acc: 0.6743 - val_loss: 0.6254 - val_acc: 0.6875  Epoch 4/20 35/35 [==============================]35/35 [==============================] - 14s 414ms/step - loss: 0.6365 - acc: 0.6851 - val_loss: 0.6289 - val_acc: 0.6875  Epoch 5/20 35/35 [==============================]35/35 [==============================] - 14s 411ms/step - loss: 0.6359 - acc: 0.6727 - val_loss: 0.6244 - val_acc: 0.6875  Epoch 6/20 35/35 [==============================]35/35 [==============================] - 15s 415ms/step - loss: 0.6342 - acc: 0.6862 - val_loss: 0.6243 - val_acc: 0.6875 

2 Answers

Answers 1

I think you have too low learning rate and too few epochs. try with lr = 0.001 and epochs = 100.

Answers 2

Your accuracy is 68.25%. Given that your classes are split roughly 70/30 it is likely that your model is just predicting the same thing every time, ignoring the input. That would give the accuracy you are seeing. Your model has not yet learned from your data.

As Novak said, your learning rate seems very low, so maybe try increasing that first to see if that helps.

Read More

Wednesday, September 26, 2018

Keras: Accuracy Drops While Finetuning Inception

Leave a Comment

I am having trouble fine tuning an Inception model with Keras.

I have managed to use tutorials and documentation to generate a model of fully connected top layers that classifies my dataset into their proper categories with an accuracy over 99% using bottleneck features from Inception.

import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense from keras import applications   # dimensions of our images. img_width, img_height = 150, 150  #paths for saving weights and finding datasets top_model_weights_path = 'Inception_fc_model_v0.h5' train_data_dir = '../data/train2' validation_data_dir = '../data/train2'   #training related parameters? inclusive_images = 1424 nb_train_samples = 1424 nb_validation_samples = 1424 epochs = 50 batch_size = 16   def save_bottlebeck_features():     datagen = ImageDataGenerator(rescale=1. / 255)      # build bottleneck features     model = applications.inception_v3.InceptionV3(include_top=False, weights='imagenet', input_shape=(img_width,img_height,3))      generator = datagen.flow_from_directory(         train_data_dir,         target_size=(img_width, img_height),         batch_size=batch_size,         class_mode='categorical',         shuffle=False)      bottleneck_features_train = model.predict_generator(         generator, nb_train_samples // batch_size)      np.save('bottleneck_features_train', bottleneck_features_train)      generator = datagen.flow_from_directory(         validation_data_dir,         target_size=(img_width, img_height),         batch_size=batch_size,         class_mode='categorical',         shuffle=False)      bottleneck_features_validation = model.predict_generator(         generator, nb_validation_samples // batch_size)      np.save('bottleneck_features_validation', bottleneck_features_validation)  def train_top_model():     train_data = np.load('bottleneck_features_train.npy')     train_labels = np.array(range(inclusive_images))      validation_data = np.load('bottleneck_features_validation.npy')     validation_labels = np.array(range(inclusive_images))      print('base size ', train_data.shape[1:])      model = Sequential()     model.add(Flatten(input_shape=train_data.shape[1:]))     model.add(Dense(1000, activation='relu'))     model.add(Dense(inclusive_images, activation='softmax'))     model.compile(loss='sparse_categorical_crossentropy',              optimizer='Adam',              metrics=['accuracy'])      proceed = True      #model.load_weights(top_model_weights_path)      while proceed:         history = model.fit(train_data, train_labels,               epochs=epochs,               batch_size=batch_size)#,               #validation_data=(validation_data, validation_labels), verbose=1)         if history.history['acc'][-1] > .99:             proceed = False      model.save_weights(top_model_weights_path)   save_bottlebeck_features() train_top_model() 

Epoch 50/50 1424/1424 [==============================] - 17s 12ms/step - loss: 0.0398 - acc: 0.9909

I have also been able to stack this model on top of inception to create my full model and use that full model to successfully classify my training set.

from keras import Model from keras import optimizers from keras.callbacks import EarlyStopping  img_width, img_height = 150, 150  top_model_weights_path = 'Inception_fc_model_v0.h5' train_data_dir = '../data/train2' validation_data_dir = '../data/train2'   #how many inclusive examples do we have? inclusive_images = 1424 nb_train_samples = 1424 nb_validation_samples = 1424 epochs = 50 batch_size = 16  # build the complete network for evaluation base_model = applications.inception_v3.InceptionV3(weights='imagenet', include_top=False, input_shape=(img_width,img_height,3))  top_model = Sequential() top_model.add(Flatten(input_shape=base_model.output_shape[1:])) top_model.add(Dense(1000, activation='relu')) top_model.add(Dense(inclusive_images, activation='softmax'))  top_model.load_weights(top_model_weights_path)  #combine base and top model fullModel = Model(input= base_model.input, output= top_model(base_model.output))  #predict with the full training dataset results = fullModel.predict_generator(ImageDataGenerator(rescale=1. / 255).flow_from_directory(         train_data_dir,         target_size=(img_width, img_height),         batch_size=batch_size,         class_mode='categorical',         shuffle=False)) 

inspection of the results from processing on this full model match the accuracy of the bottleneck generated fully connected model.

import matplotlib.pyplot as plt import operator  #retrieve what the softmax based class assignments would be from results resultMaxClassIDs = [ max(enumerate(result), key=operator.itemgetter(1))[0] for result in results]  #resultMaxClassIDs should be equal to range(inclusive_images) so we subtract the two and plot the log of the absolute value  #looking for spikes that indicate the values aren't equal  plt.plot([np.log(np.abs(x)+10) for x in (np.array(resultMaxClassIDs) - np.array(range(inclusive_images)))]) 

results: spikes are misclassifications

Here is the problem: When I take this full model and attempt to train it, Accuracy drops to 0 even though validation remains above 99%.

model2 = fullModel  for layer in model2.layers[:-2]:     layer.trainable = False  # compile the model with a SGD/momentum optimizer # and a very slow learning rate. #model.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),  metrics=['accuracy'])  model2.compile(loss='categorical_crossentropy',              optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),               metrics=['accuracy'])  train_datagen = ImageDataGenerator(rescale=1. / 255)  test_datagen = ImageDataGenerator(rescale=1. / 255)  train_generator = train_datagen.flow_from_directory(     train_data_dir,     target_size=(img_height, img_width),     batch_size=batch_size,     class_mode='categorical')  validation_generator = test_datagen.flow_from_directory(     validation_data_dir,     target_size=(img_height, img_width),     batch_size=batch_size,     class_mode='categorical')  callback = [EarlyStopping(monitor='acc', min_delta=0, patience=3, verbose=0, mode='auto', baseline=None)] # fine-tune the model model2.fit_generator(     #train_generator,     validation_generator,     steps_per_epoch=nb_train_samples//batch_size,     validation_steps = nb_validation_samples//batch_size,     epochs=epochs,     validation_data=validation_generator) 

Epoch 1/50 89/89 [==============================] - 388s 4s/step - loss: 13.5787 - acc: 0.0000e+00 - val_loss: 0.0353 - val_acc: 0.9937

and it gets worse as things progress

Epoch 21/50 89/89 [==============================] - 372s 4s/step - loss: 7.3850 - acc: 0.0035 - val_loss: 0.5813 - val_acc: 0.8272

The only thing I could think of is that somehow the training labels are getting improperly assigned on this last train, but I've successfully done this with similar code using VGG16 before.

I have searched over the code trying to find a discrepancy to explain why a model making accurate predictions over 99% of the time drops its training accuracy while maintaining validation accuracy during fine tuning, but I can't figure it out. Any help would be appreciated.

Information about the code and environment:

Things that are going to stand out as weird, but are meant to be that way:

  • There is only 1 image per class. This NN is intended to classify objects whose environmental and orientation conditions are controlled. Their is only one acceptable image for each class corresponding to the correct environmental and rotational situation.
  • The test and validation set are the same. This NN is only ever designed to be used on the classes it is being trained on. The images it will process will be carbon copies of the class examples. It is my intent to overfit the model to these classes

I am using:

  • Windows 10
  • Python 3.5.6 under Anaconda client 1.6.14
  • Keras 2.2.2
  • Tensorflow 1.10.0 as the backend
  • CUDA 9.0
  • CuDNN 8.0

I have checked out:

  1. Keras accuracy discrepancy in fine-tuned model
  2. VGG16 Keras fine tuning: low accuracy
  3. Keras: model accuracy drops after reaching 99 percent accuracy and loss 0.01
  4. Keras inception v3 retraining and finetuning error
  5. How to find which version of TensorFlow is installed in my system?

but they appear unrelated.

2 Answers

Answers 1

Note: Since your problem is a bit strange and difficult to debug without having your trained model and dataset, this answer is just a (best) guess after considering many things that may have could go wrong. Please provide your feedback and I will delete this answer if it does not work.

Since the inception_V3 contains BatchNormalization layers, maybe the problem is due to (somehow ambiguous or unexpected) behavior of this layer when you set trainable parameter to False (1, 2, 3, 4).

Now, let's see if this is the root of the problem: as suggested by @fchollet, set the learning phase when defining the model for fine-tuning:

from keras import backend as K  K.set_learning_phase(0)  base_model = applications.inception_v3.InceptionV3(weights='imagenet', include_top=False, input_shape=(img_width,img_height,3))  for layer in base_model.layers:     layer.trainable = False  K.set_learning_phase(1)  top_model = Sequential() top_model.add(Flatten(input_shape=base_model.output_shape[1:])) top_model.add(Dense(1000, activation='relu')) top_model.add(Dense(inclusive_images, activation='softmax'))  top_model.load_weights(top_model_weights_path)  #combine base and top model fullModel = Model(input= base_model.input, output= top_model(base_model.output))  fullModel.compile(loss='categorical_crossentropy',              optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),               metrics=['accuracy'])   ##################################################################### # Here, define the generators and then fit the model same as before # ##################################################################### 

Side Note: This is not causing any problem in your case, but keep in mind that when you use top_model(base_model.output) the whole Sequential model (i.e. top_model) is stored as one layer of fullModel. You can verify this by either using fullModel.summary() or print(fullModel.layers[-1]). Hence when you used:

for layer in model2.layers[:-2]:     layer.trainable = False  

you are actually not freezing the last layer of base_model as well. However, since it is a Concatenate layer, and therefore does not have trainable parameters, no problem occurs and it would behave as you intended.

Answers 2

Like the previous reply, I'll try to share some thoughts to see whether it helps.

There are a couple of things that called my attention (and maybe are worth reviewing). Note: some of them should have given you issues with the separate models as well.

  • Correct if I'm wrong, but it seems you used sparse_categorical_crossentropy for the first training while you used categorical_crossentropy for the second one. Is it correct? Because I believe they assume labels differently (sparse assumes integers and the other assumes one-hot).
  • Have you tried to set the layers you added in the end as trainable = True? I know that you have already set the others to trainable = False, but maybe that's something worth checking too.
  • It seems the data generator is not making use of the default preprocessing function used in Inception v3, which uses a per-mean channel.
  • Have you tried any experiment using Functional instead of Sequential API?

I hope that helps.

Read More

Sunday, September 23, 2018

Tensorflow eager choose checkpoint max to keep

Leave a Comment

I'm writing a process-based implementation of a3c with tensorflow in eager mode. After every gradient update, my general model writes its parameters as checkpoints to a folder. The workers then update their parameters by loading the last checkpoints from this folder. However, there is a problem.

Often times, while the worker is reading the last available checkpoint from the folder, the master network will write new checkpoints to the folder and sometimes will erase the checkpoint that the worker is reading. A simple solution would be raising the maximum of checkpoints to keep. However, tfe.Checkpoint and tfe.Saver don't have a parameter to choose the max to keep.

Is there a way to achieve this?

2 Answers

Answers 1

For the tf.train.Saver you can specify max_to_keep:

tf.train.Saver(max_to_keep = 10) 

and max_to_keep seems to be present in the both fte.Saver and it's tf.training.Saver.

I haven't tried if it works though.

Answers 2

It seems the suggested way of doing checkpoint deletion is to use the CheckpointManager.

import tensorflow as tf checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) manager = tf.contrib.checkpoint.CheckpointManager(      checkpoint, directory="/tmp/model", max_to_keep=5) status = checkpoint.restore(manager.latest_checkpoint) while True: # train   manager.save() 
Read More

Sunday, September 16, 2018

Why does tensorflow/keras choke when I try to fit multiple models in parallel?

Leave a Comment

I'm trying to fit a finite mixture model, with the mixture models for each class being neural networks. It'd be super-useful for me to be able to be able to parallelize, because keras doesn't max out all of the available cores on my laptop, let alone a large cluster.

But when I try to set different learning rates for different models inside of a parallel foreach loop the whole thing chokes.

What is going on? I suspect that it has something to do with scope -- the workers aren't running on separate instantiations of tensorflow, maybe. But I really don't know. How can I make this work? And what do I need to understand to know why this doesn't work?

Here's a MWE. Set the foreach loop to %do% and it works fine. Set it to %dopar% and it chokes on the fitting stage.

library(foreach) library(doParallel) registerDoParallel(2) library(keras) library(tensorflow) mnist <- dataset_mnist() x_train <- mnist$train$x y_train <- mnist$train$y x_test <- mnist$test$x y_test <- mnist$test$y  x_train <- array_reshape(x_train, c(nrow(x_train), 784)) x_test <- array_reshape(x_test, c(nrow(x_test), 784)) # rescale x_train <- x_train / 255 x_test <- x_test / 255  y_train <- to_categorical(y_train, 10) y_test <- to_categorical(y_test, 10)  # make tensorflow run single-threaded session_conf <- tf$ConfigProto(intra_op_parallelism_threads = 1L,                                inter_op_parallelism_threads = 1L) # Create the session using the custom configuration sess <- tf$Session(config = session_conf) K <- backend() K$set_session(sess)   models <- foreach(i = 1:2) %dopar%{   model <- keras_model_sequential()    model %>%      layer_dense(units = 256/i, activation = 'relu', input_shape = c(784)) %>%      layer_dropout(rate = 0.4) %>%      layer_dense(units = 128/i, activation = 'relu') %>%     layer_dropout(rate = 0.3) %>%     layer_dense(units = 10, activation = 'softmax')    print("A")   model %>% compile(     loss = 'categorical_crossentropy',     optimizer = optimizer_rmsprop(),     metrics = c('accuracy')   )   print("B")   history <- model %>% fit(     x_train, y_train,      epochs = 3, batch_size = 128,      validation_split = 0.2, verbose = 0   )   print("done")   } 

Here's sessionInfo():

R version 3.5.1 (2018-07-02) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.1 LTS  Matrix products: default BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1  locale:  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8     [6] LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C             [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C         attached base packages: [1] splines   parallel  stats     graphics  grDevices utils     datasets  methods   base       other attached packages:  [1] panelNNET_1.0       matrixStats_0.54.0  MASS_7.3-50         lfe_2.8-2           tensorflow_1.9      keras_2.1.6.9005     [7] mgcv_1.8-24         nlme_3.1-137        scales_1.0.0        forcats_0.3.0       stringr_1.3.1       purrr_0.2.5         [13] readr_1.1.1         tidyr_0.8.1         tibble_1.4.2        tidyverse_1.2.1     maptools_0.9-3      rgeos_0.3-28        [19] rgdal_1.3-4         sp_1.3-1            broom_0.5.0         ggplot2_3.0.0       randomForest_4.6-14 dplyr_0.7.6         [25] glmnet_2.0-16       Matrix_1.2-14       doBy_4.6-2          doParallel_1.0.11   iterators_1.0.10    foreach_1.4.4        loaded via a namespace (and not attached):  [1] httr_1.3.1          jsonlite_1.5        modelr_0.1.2        Formula_1.2-3       assertthat_0.2.0    cellranger_1.1.0     [7] yaml_2.2.0          pillar_1.3.0        backports_1.1.2     lattice_0.20-35     glue_1.3.0          reticulate_1.10     [13] digest_0.6.15       RcppEigen_0.3.3.4.0 rvest_0.3.2         colorspace_1.3-2    sandwich_2.5-0      plyr_1.8.4          [19] pkgconfig_2.0.1     haven_1.1.2         xtable_1.8-2        whisker_0.3-2       withr_2.1.2         lazyeval_0.2.1      [25] cli_1.0.0           magrittr_1.5        crayon_1.3.4        readxl_1.1.0        xml2_1.2.0          foreign_0.8-70      [31] tools_3.5.1         hms_0.4.2           munsell_0.5.0       bindrcpp_0.2.2      compiler_3.5.1      rlang_0.2.2         [37] grid_3.5.1          rstudioapi_0.7      base64enc_0.1-3     labeling_0.3        gtable_0.2.0        codetools_0.2-15    [43] R6_2.2.2            tfruns_1.3          zoo_1.8-3           lubridate_1.7.4     zeallot_0.1.0       bindr_0.1.1         [49] stringi_1.2.4       Rcpp_0.12.18        tidyselect_0.2.4 

1 Answers

Answers 1

Keras requires there is only one training in a given session. I would try to create a different session for each model.

I would insert this part of the code inside the %dopar%, to create a different session per model

sess <- tf$Session(config = session_conf) K <- backend() K$set_session(sess) 
Read More

Sunday, August 26, 2018

Opening Keras model with embedding layer in Tensorflow in Golang

Leave a Comment

I am trying to implement my Keras neural network in Go using the tfgo package. The model includes 2 regular inputs and two Keras embedding layers. It looks like this:

embedding_layer = Embedding(vocab_size,                             100,                             weights=[embedding_matrix],                             input_length=100,                             trainable=False)  sequence_input = Input(shape=(max_length,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) text_lstm = Bidirectional(LSTM(256))(embedded_sequences) text_lstm = Dropout(0.5)(text_lstm) text_lstm  = Dense(512, activation='relu')(text_lstm ) text_lstm = Dropout(0.5)(text_lstm) text_lstm  = Dense(256, activation='relu')(text_lstm) text_lstm = Dropout(0.5)(text_lstm) text_lstm  = Dense(128, activation='relu')(text_lstm) text_lstm = Dropout(0.5)(text_lstm)  title_input = Input(shape=(max_title_length,), dtype='int32') title_embed = Embedding(vocab_size, embedding_vector_length, input_length=max_title_length)(title_input) title_lstm = Bidirectional(LSTM(128))(title_embed) title_lstm = Dropout(0.5)(title_lstm) title_lstm  = Dense(512, activation='relu')(title_lstm ) title_lstm = Dropout(0.5)(title_lstm) title_lstm  = Dense(256, activation='relu')(title_lstm) title_lstm = Dropout(0.5)(title_lstm) title_lstm  = Dense(128, activation='relu')(title_lstm) title_lstm = Dropout(0.5)(title_lstm)   merged = concatenate([text_lstm, title_lstm])   merged_d1 = Dense(1024, activation='relu')(merged) merged_d1 = Dropout(0.5)(merged_d1) merged_d1 = Dense(512, activation='relu')(merged_d1) merged_d1 = Dropout(0.5)(merged_d1)   text_class = Dense(num_classes, activation='sigmoid')(merged_d1) model = Model([sequence_input, title_input], text_class) 

I'm trying to load the model in Go, so far I think I've been able to include the regular input layers like this:

s := make([]int32, 100) s1 := make([]int32, 15) model := tg.LoadModel("myModel3", []string{"myTag"}, nil) tensor1, _ := tf.NewTensor(s) tensor2, _ := tf.NewTensor(s1)  result := model.Exec([]tf.Output{     model.Op("dense_18/Sigmoid", 0), }, map[tf.Output]*tf.Tensor{     model.Op("input_1", 0): tensor1,     model.Op("input_3", 0): tensor2, }) 

But when I run the code, it reminds me that there are actually two more "inputs":

panic: You must feed a value for placeholder tensor 'input_4' with dtype int32 and shape [?,15]      [[Node: input_4 = Placeholder[_output_shapes=[[?,15]], dtype=DT_INT32, shape=[?,15], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] 

I would imagine that these would be "input2" and "input4" and that they would need to be initialized somehow with the embeddings from the model, but I have no idea how I could do this in Tensorflow in Go (I am new to Go).

I tried the following:

    s := make([]int32, 100) s1 := make([]int32, 15)  tensor1e, _ := tf.NewTensor([1][100][2]float32{}) tensor2e, _ := tf.NewTensor([1][15][2]float32{})  tensor1, _ := tf.NewTensor(s) tensor2, _ := tf.NewTensor(s1)  result := model.Exec([]tf.Output{     model.Op("dense_18/Sigmoid", 0), }, map[tf.Output]*tf.Tensor{     model.Op("input_3", 0):                tensor1,     model.Op("embedding_2/embeddings", 0): tensor2e,     model.Op("embedding_1/embeddings", 0): tensor1e,     model.Op("input_4", 0):                tensor2, })  But this  

produced the following, error:

2018-08-17 19:50:00.543771: W tensorflow/core/framework  /op_kernel.cc:1275] OP_REQUIRES failed at transpose_op.cc:157 : Invalid argument: transpose expects a vector of size 2. But input(1) is a vector of size 3 2018-08-17 19:50:00.543792: W tensorflow/core/framework/op_kernel.cc:1275] OP_REQUIRES failed at reduction_ops_common.h:155 : Invalid argument: Invalid reduction dimension (2 for input with 2 dimension(s) panic: Invalid reduction dimension (2 for input with 2 dimension(s)      [[Node: bidirectional_4/Sum = Sum[T=DT_FLOAT, Tidx=DT_INT32, _output_shapes=[[?]], keep_dims=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](bidirectional_4/zeros_like, bidirectional_3/Sum/reduction_indices)]] 

Can anyone point me in the right direction on how to complete this operation? Any help would be much appreciated!

1 Answers

Answers 1

So, it turns out that I did not need to specify the inputs for the embedding layers. I was actually structuring the input incorrectly. It should look like this:

tensor1, _ := tf.NewTensor([][]int32{tokes_text}) tensor2, _ := tf.NewTensor([][]int32{tokes_title})   result := model.Exec([]tf.Output{             model.Op("dense_18/Sigmoid", 0),         }, map[tf.Output]*tf.Tensor{             model.Op("input_3", 0): tensor1,             model.Op("input_4", 0): tensor2,         }) 
Read More

Wednesday, August 22, 2018

Keras: Masking and Flattening

Leave a Comment

I'm having difficulty building a straightforward model that deals with masked input values. My training data consists of variable-length lists of GPS traces, i.e. lists where each element contains Latitude and Longitude.

There are 70 training examples

enter image description here

Since they have variable lengths I am padding them with zeros, with the aim of then telling Keras to ignore these zero-values.

train_data = keras.preprocessing.sequence.pad_sequences(train_data, maxlen=max_sequence_len, dtype='float32',                                             padding='pre', truncating='pre', value=0) 

enter image description here

I then build a very basic model like so

model = Sequential() model.add(Dense(16, activation='relu',input_shape=(max_sequence_len, 2))) model.add(Flatten()) model.add(Dense(2, activation='sigmoid')) 

After some previous trial and error I realised that I need the Flatten layer or fitting the model would throw the error

ValueError: Error when checking target: expected dense_87 to have 3 dimensions, but got array with shape (70, 2) 

By including this Flatten layer, however, I can not use a Masking layer (to ignore the padded zeros) or Keras throws this error

TypeError: Layer flatten_31 does not support masking, but was passed an input_mask: Tensor("masking_9/Any_1:0", shape=(?, 48278), dtype=bool) 

I have searched extensively, reading GitHub issues and plenty of Q/A here but I can't figure it out.

2 Answers

Answers 1

Masking does seem bugged. But do not worry: the 0s are not going to make your model worse; at most less efficient.

I would recommend using a Convolutional approach instead of pure Dense or perhaps RNN. I think this will work really well for GPS data.

Please try the following code:

from keras.preprocessing.sequence import pad_sequences from keras import Sequential from keras.layers import Dense, Flatten, Masking, LSTM, GRU, Conv1D, Dropout, MaxPooling1D import numpy as np import random  max_sequence_len = 70  n_samples = 100 num_coordinates = 2 # lat/long  data = [[[random.random() for _ in range(num_coordinates)]          for y in range(min(x, max_sequence_len))]         for x in range(n_samples)]  train_y = np.random.random((n_samples, 2))  train_data = pad_sequences(data, maxlen=max_sequence_len, dtype='float32',                            padding='pre', truncating='pre', value=0)  model = Sequential() model.add(Conv1D(32, (5, ), input_shape=(max_sequence_len, num_coordinates))) model.add(Dropout(0.5)) model.add(MaxPooling1D()) model.add(Flatten()) model.add(Dense(2, activation='relu')) model.compile(loss='mean_squared_error', optimizer="adam") model.fit(train_data, train_y) 

Answers 2

Instead of using a Flatten layer, you could use a Global Pooling layer.

These are suited to collapse the length/time dimension without losing the capability of using variable lengths.

So, instead of Flatten(), you can try a GlobalAveragePooling1D or GlobalMaxPooling1D.

None of them use supports_masking in their code, so they must be used with care.

The average one will consider more inputs than the max (thus the values that should be masked).

The max will take only one from the length. With luck, if all your useful values are higher than the ones in the masked position, it will indirectly preserve the mask. It will probably need even more input neurons than the other.

That said, yes, try the Conv1D or RNN (LSTM) appoaches suggested.


Creating a custom pooling layer with mask

You can also create your own pooling layer (needs a functional API model where you pass both the model's inputs and the tensor which you want to pool)

Below, a working example with average pooling applying a mask based on the inputs:

def customPooling(maskVal):     def innerFunc(x):         inputs = x[0]         target = x[1]          #getting the mask by observing the model's inputs         mask = K.equal(inputs, maskVal)         mask = K.all(mask, axis=-1, keepdims=True)          #inverting the mask for getting the valid steps for each sample         mask = 1 - K.cast(mask, K.floatx())          #summing the valid steps for each sample         stepsPerSample = K.sum(mask, axis=1, keepdims=False)          #applying the mask to the target (to make sure you are summing zeros below)         target = target * mask          #calculating the mean of the steps (using our sum of valid steps as averager)         means = K.sum(target, axis=1, keepdims=False) / stepsPerSample          return means      return innerFunc   x = np.ones((2,5,3)) x[0,3:] = 0. x[1,1:] = 0.   print(x)  inputs = Input((5,3)) out = Lambda(lambda x: x*4)(inputs) out = Lambda(customPooling(0))([inputs,out])  model = Model(inputs,out) model.predict(x) 
Read More

Sunday, July 1, 2018

Evaluate a function in a sliding window with Keras

Leave a Comment

I'm trying to extend a matching matching algorithm across a sequence. My matches are 20 units long and have 4 channels at each timepoint. I have built a model that encapsulates the matching, I just can't figure out how to use that in a sliding window to apply it across a longer sequence to find the matches within the sequence.

I have 2 (20, 4) input tensors (query and target) that I concatenate, add, flatten, and then apply a simple dense layer. I have data at this stage to train with 100K query, target pairs.

def sum_seqs(seqs):     return K.sum(seqs, axis=3)  def pad_dims(seq):     return K.expand_dims(seq, axis=3)  def pad_outshape(in_shape):     return (in_shape[0], in_shape[1], in_shape[2], 1)   query = Input((20, 4)) query_pad = Lambda(pad_dims, output_shape=pad_outshape, name='gpad')(query)  target = Input((20,4)) target_pad = Lambda(pad_dims, output_shape=pad_outshape)(target)  matching = Concatenate(axis = 3)([query_pad, target_pad]) matching = Lambda(sum_seqs)(matching)  matching = Flatten()(matching) matching = Dropout(0.1)(matching) matching = Dense(1, activation = 'sigmoid')(matching)  match_model = Model([query, target], matching) 

This works perfectly. Now I want to use this pre-trained model to search a longer target sequence with varying query sequences.

It seems it should be something like:

long_target = Input((100, 4))  short_target = Input((20, 4)) choose_query = Input((20, 4))  spec_match = match_model([choose_query, short_target])  mdl = TimeDistributed(spec_match)(long_target) 

But TimeDistributed takes a Layer not a Tensor. Is there a wrapper I'm missing? Am I going about this the wrong way? Do I need to reformulate this as a convolution problem somehow?

Continued experimentation: After a day of beating my head against the keyboard it is clear that both TimeDistributed and backend.rnn only allow you to apply a model/layer to a single time-slice of the data. It doesn't seem like there is a way to do this. It looks like the only thing that can "walk" across multiple slices of the time dimension is a Conv1D.

So, I reframed my problem as a convolution but that doesn't work well either. I was able to building a Conv1D filter that it would match a specific query. This worked reasonably well and it did allow me to scan longer sequences and get matches. BUT each filter is unique to each query tensor and there doesn't seem to be a way to go from a novel query to the appropriate filter weights without training a whole new Conv1D layer. Since my goal is to find new querys which match the most targets this doesn't help much.

Since my "matching" requires the interaction of the target AND the query at each window there doesn't seem to be a way I can get an interaction of a 20-length query tensor at each window across a 100-length target tensor through Conv1D.

Is there any way to do this sliding window type evaluation in Keras/tensorflow? It seems like something so simple yet so far away. Is there a way I can do this that I'm not finding?

Responses and further experimentation.

The solutions from @today and @nuric work but they end up replicating the input target data in a tiling type fashion. So, for a query of length m there will be a little under m copies of the input data in the graph. I was hoping to find a solution that would actually "slide" the evaluation across the target without the duplication.

Here's a version of the Conv1D almost solution I came up with.

query_weights = []  for query, (targets, scores) in query_target_gen():     single_query_model = Sequential()     single_query_model.add(Conv1D(1, 20, input_shape = (20, 4)))     single_query_model.add(Flatten())      single_query_model.fit(targets, scores)      query_weights.append(single_query_model.layers[0].get_weights())  multi_query_model_long_targets = Sequential() multi_query_model_long_targets.add(Conv1D(len(query_weights), 20, input_shape = (100, 4)))  multi_query_model_long_targets.layers[0].set_weights(combine_weights(query_weights))  multi_query_model_long_targets.summary() 

The combine_weights function just does some unpacking and matrix rearrangement to stack the filters in the way Conv1D wants.

This solution fixes the data duplication issue but it screws me in other ways. One is data based ... my data contains many query, target pairs but it tends to be the same target many querys, since it is easier to generate the real-world data in that orientation. So, doing it this way makes the training difficult. Second, this assumes that each query works in an independent way, when in reality, I know that the query, target pairing is what is actually important. So it makes sense to use a model that can look at many examples of the pairs, and not individuals.

Is there a way to combine both methods? Is there a way to make it so Conv1D takes both the long target tensor combine it with the constant query as it walks along the sequence?

2 Answers

Answers 1

Just to provide an alternative solution using Keras backend functions.

You can also generate sliding windows with K.arange and K.map_fn:

def sliding_windows(inputs):     target, query = inputs     target_length = K.shape(target)[1]  # variable-length sequence, shape is a TF tensor     query_length = K.int_shape(query)[1]     num_windows = target_length - query_length + 1  # number of windows is also variable      # slice the target into consecutive windows     start_indices = K.arange(num_windows)     windows = K.map_fn(lambda t: target[:, t:(t + query_length), :],                        start_indices,                        dtype=K.floatx())      # `windows` is a tensor of shape (num_windows, batch_size, query_length, ...)     # so we need to change the batch axis back to axis 0     windows = K.permute_dimensions(windows, (1, 0, 2, 3))      # repeat query for `num_windows` times so that it could be merged with `windows` later     query = K.expand_dims(query, 1)     query = K.tile(query, [1, num_windows, 1, 1])      # just a hack to force the dimensions 2 to be known (required by Flatten layer)     windows = K.reshape(windows, shape=K.shape(query))     return [windows, query] 

To use it:

long_target = Input((None, 4)) choose_query = Input((20, 4)) windows, query = Lambda(sliding_windows)([long_target, choose_query]) 

Given your pretrained match_model, the problem with TimeDistributed is that it cannot wrap a Keras Model with multiple inputs.

However, since the logic matching target and query is implemented in the layers after Concatenate, you can collect these layers into a Model, and apply TimeDistributed to it:

submodel_input = Input((20, 4, 2)) x = submodel_input for layer in match_model.layers[-4:]:  # the `Lambda(sum_seqs)` layer     x = layer(x) submodel = Model(submodel_input, x) 

Now you just need to process and merge the outputs of sliding_windows in the same way as in match_model:

long_target = Input((None, 4)) choose_query = Input((20, 4)) windows, query = Lambda(sliding_windows)([long_target, choose_query])  windows_pad = Lambda(lambda x: K.expand_dims(x))(windows) query_pad = Lambda(lambda x: K.expand_dims(x))(query) merged = Concatenate()([windows_pad, query_pad])  match_scores = TimeDistributed(submodel)(merged) max_score = GlobalMaxPooling1D()(match_scores) model = Model([long_target, choose_query], max_score) 

model can then be used in an end-to-end fashion for matching long targets.

You can also verify that the output of model is indeed the maximum of the matching scores by applying match_model to sliding windows:

target_arr = np.random.rand(32, 100, 4) query_arr = np.random.rand(32, 20, 4)  match_model_scores = np.array([     match_model.predict([target_arr[:, t:t + 20, :], query_arr])     for t in range(81) ]) scores = model.predict([target_arr, query_arr])  print(np.allclose(scores, match_model_scores.max(axis=0))) True 

Answers 2

Note: look at @Yu-Yang's solution. It is much better.


Well, as I mentioned in my comment, you can use tf.exctract_image_patches() (if the documentation seems a bit vague read this answer on SO) to extract patches (Edit: I just added two variables win_len and feat_len and changed 100 to None and 81 to -1 to make it work with the target sequences of arbitrary length):

import tensorflow as tf from keras import layers, models import keras.backend as K  win_len = 20   # window length feat_len = 4   # features length  def extract_patches(data):     data = K.expand_dims(data, axis=3)     patches = tf.extract_image_patches(data, ksizes=[1, win_len, feat_len, 1], strides=[1, 1, 1, 1], rates=[1, 1, 1, 1], padding='VALID')     return patches  target = layers.Input((None, feat_len)) patches = layers.Lambda(extract_patches)(target) patches = layers.Reshape((-1, win_len, feat_len))(patches)  model = models.Model([target], [patches]) model.summary() 
Layer (type)                 Output Shape              Param #    ================================================================= input_2 (InputLayer)         (None, None, 4)           0          _________________________________________________________________ lambda_2 (Lambda)            (None, None, None, 80)    0          _________________________________________________________________ reshape_2 (Reshape)          (None, None, 20, 4)       0          ================================================================= Total params: 0 Trainable params: 0 Non-trainable params: 0 _________________________________________________________________ 

For example, if input target has a shape of (100, 4), the output shape is (81, 20, 4).

Here is a test:

import numpy as np  # an array consisting of numbers 0 to 399 with shape (100, 4) target = np.arange(1*100*4*1).reshape(1, 100, 4) print(model.predict(a)) 

Here is the output:

[[[[  0.   1.   2.   3.]    [  4.   5.   6.   7.]    [  8.   9.  10.  11.]    ...    [ 68.  69.  70.  71.]    [ 72.  73.  74.  75.]    [ 76.  77.  78.  79.]]    [[  4.   5.   6.   7.]    [  8.   9.  10.  11.]    [ 12.  13.  14.  15.]    ...    [ 72.  73.  74.  75.]    [ 76.  77.  78.  79.]    [ 80.  81.  82.  83.]]    [[  8.   9.  10.  11.]    [ 12.  13.  14.  15.]    [ 16.  17.  18.  19.]    ...    [ 76.  77.  78.  79.]    [ 80.  81.  82.  83.]    [ 84.  85.  86.  87.]]    ...    [[312. 313. 314. 315.]    [316. 317. 318. 319.]    [320. 321. 322. 323.]    ...    [380. 381. 382. 383.]    [384. 385. 386. 387.]    [388. 389. 390. 391.]]    [[316. 317. 318. 319.]    [320. 321. 322. 323.]    [324. 325. 326. 327.]    ...    [384. 385. 386. 387.]    [388. 389. 390. 391.]    [392. 393. 394. 395.]]    [[320. 321. 322. 323.]    [324. 325. 326. 327.]    [328. 329. 330. 331.]    ...    [388. 389. 390. 391.]    [392. 393. 394. 395.]    [396. 397. 398. 399.]]]] 
Read More

Wednesday, April 11, 2018

Convolution2D + LSTM versus ConvLSTM2D

Leave a Comment

Are 1 and 2 same?

  1. use Convolution2D layers and LSTM layers
  2. Use ConvLSTM2D

If there is something difference, can you explain for me?

1 Answers

Answers 1

  1. Use Convolution2D layers and LSTM layer

In this technique, you stack convolution and LSTM layers. The convolutoinal layers help you to learn the spatial features and the LSTM helps you learn the correlation in time.

2.Use ConvLSTM2D

ConvLSTM is a LSTM in which the gates (input to state and state to state transitions) are convolution operations.
Research paper- Convolutional LSTM Network: A Machine Learning Approach for Precipitation Nowcasting

More about ConvLSTM in this SO answer

Read More

Sunday, April 1, 2018

Memory error when using Keras ImageDataGenerator

Leave a Comment

I am attempting to predict features in imagery using keras with a TensorFlow backend. Specifically, I am attempting to use a keras ImageDataGenerator. The model is set to run for 4 epochs and runs fine until the 4th epoch where it fails with a MemoryError.

I am running this model on an AWS g2.2xlarge instance running Ubuntu Server 16.04 LTS (HVM), SSD Volume Type.

The training images are 256x256 RGB pixel tiles (8 bit unsigned) and the training mask is 256x256 single band (8 bit unsigned) tiled data where 255 == a feature of interest and 0 == everything else.

The following 3 functions are the ones pertinent to this error.

How can I resolve this MemoryError?


def train_model():         batch_size = 1         training_imgs = np.lib.format.open_memmap(filename=os.path.join(data_path, 'data.npy'),mode='r+')         training_masks = np.lib.format.open_memmap(filename=os.path.join(data_path, 'mask.npy'),mode='r+')         dl_model = create_model()         print(dl_model.summary())         model_checkpoint = ModelCheckpoint(os.path.join(data_path,'mod_weight.hdf5'), monitor='loss',verbose=1, save_best_only=True)         dl_model.fit_generator(generator(training_imgs, training_masks, batch_size), steps_per_epoch=(len(training_imgs)/batch_size), epochs=4,verbose=1,callbacks=[model_checkpoint])  def generator(train_imgs, train_masks=None, batch_size=None):  # Create empty arrays to contain batch of features and labels#          if train_masks is not None:                 train_imgs_batch = np.zeros((batch_size,y_to_res,x_to_res,bands))                 train_masks_batch = np.zeros((batch_size,y_to_res,x_to_res,1))                  while True:                         for i in range(batch_size):                                 # choose random index in features                                 index= random.choice(range(len(train_imgs)))                                 train_imgs_batch[i] = train_imgs[index]                                 train_masks_batch[i] = train_masks[index]                         yield train_imgs_batch, train_masks_batch         else:                 rec_imgs_batch = np.zeros((batch_size,y_to_res,x_to_res,bands))                 while True:                         for i in range(batch_size):                                 # choose random index in features                                 index= random.choice(range(len(train_imgs)))                                 rec_imgs_batch[i] = train_imgs[index]                         yield rec_imgs_batch  def train_generator(train_images,train_masks,batch_size):         data_gen_args=dict(rotation_range=90.,horizontal_flip=True,vertical_flip=True,rescale=1./255)         image_datagen = ImageDataGenerator()         mask_datagen = ImageDataGenerator() # # Provide the same seed and keyword arguments to the fit and flow methods         seed = 1         image_datagen.fit(train_images, augment=True, seed=seed)         mask_datagen.fit(train_masks, augment=True, seed=seed)         image_generator = image_datagen.flow(train_images,batch_size=batch_size)         mask_generator = mask_datagen.flow(train_masks,batch_size=batch_size)         return zip(image_generator, mask_generator) 

The following os the output from the model detailing the epochs and the error message:

Epoch 00001: loss improved from inf to 0.01683, saving model to /home/ubuntu/deep_learn/client_data/mod_weight.hdf5 Epoch 2/4 7569/7569 [==============================] - 3394s 448ms/step - loss: 0.0049 - binary_crossentropy: 0.0027 - jaccard_coef_int: 0.9983    Epoch 00002: loss improved from 0.01683 to 0.00492, saving model to /home/ubuntu/deep_learn/client_data/mod_weight.hdf5 Epoch 3/4 7569/7569 [==============================] - 3394s 448ms/step - loss: 0.0049 - binary_crossentropy: 0.0026 - jaccard_coef_int: 0.9982    Epoch 00003: loss improved from 0.00492 to 0.00488, saving model to /home/ubuntu/deep_learn/client_data/mod_weight.hdf5 Epoch 4/4 7569/7569 [==============================] - 3394s 448ms/step - loss: 0.0074 - binary_crossentropy: 0.0042 - jaccard_coef_int: 0.9975    Epoch 00004: loss did not improve Traceback (most recent call last):   File "image_rec.py", line 291, in <module>     train_model()   File "image_rec.py", line 208, in train_model     dl_model.fit_generator(train_generator(training_imgs,training_masks,batch_size),steps_per_epoch=1,epochs=1,workers=1)   File "image_rec.py", line 274, in train_generator     image_datagen.fit(train_images, augment=True, seed=seed)   File "/home/ubuntu/pyvirt_test/local/lib/python2.7/site-packages/keras/preprocessing/image.py", line 753, in fit     x = np.copy(x)   File "/home/ubuntu/pyvirt_test/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 1505, in copy     return array(a, order=order, copy=True) MemoryError 

5 Answers

Answers 1

it seems your problem is due to the data is too huge. I can see two solutions. The first one is run your code in a distributed system by means of spark, I guess you do not have this support, so let us move on to the other.

The second one is which I think is viable. I would slice the data and I would try feeding the model incrementally. We can do this with Dask. This library can slice the data and save in objects which then you can retrieve reading from disk, only in the part you want.

If you have a image which size is an matrix of 100x100, we can retrieve each array without the needed to load the 100 arrays in memory. We can load array by array in memory (releasing the previous one), which would be the input in your Neural Network.

To do this, you can to transform your np.array to dask array and assign the partitions. For example:

>>> k = np.random.randn(10,10) # Matrix 10x10 >>> import dask.array as da >>> k2 = da.from_array(k,chunks = 3) dask.array<array, shape=(10, 10), dtype=float64, chunksize=(3, 3)> >>> k2.to_delayed() array([[Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 0, 0)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 0, 1)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 0, 2)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 0, 3))],    [Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 1, 0)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 1, 1)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 1, 2)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 1, 3))],    [Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 2, 0)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 2, 1)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 2, 2)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 2, 3))],    [Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 3, 0)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 3, 1)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 3, 2)),     Delayed(('array-a08c1d25b900d497cdcd233a7c5aa108', 3, 3))]],   dtype=object) 

Here, you can see how the data is saved in objects, and then you can retrieve in parts to feed your model.

To implement this solution you must introduce a loop in your function which call each partition and feed the NN to get the incremental trainning.

For more information, see Dask documentation

Answers 2

Generally Keras/Tensorflow is very good with resource usage, but there is a known memory leak that has caused problems in the past. To make sure that's not the one causing your problems, try including these two lines of code to your training script:

# load the backend from keras import backend as K  # prevent Tensorflow memory leakage K.clear_session() 

Answers 3

You provided quite confusing code (in my opinion), ie. no call to the train_generator is visible. I am not sure that this is a problem of insufficient memore due to a big data, since you use memmap for that, but lets assume for now it is.

  • If the data is quite big and since you're loading the images from directory anyway, it might be worthy considering to use ImageDataGenerator's flow_from_directory method. It would require a slight change of design, tho, which might not be what you want.

You can load it in the following manner:

train_datagen = ImageDataGenerator() train_generator = train_datagen.flow_from_directory(         'data/train',         target_size=(256, 256),         batch_size=batch_size,         ...  # other configurations) 

More on that in the Keras documentation.

  • Also note that if you have 32bit, the memmap does not allow more than 2GB.

  • Do you use tensorflow-gpu, by any chance? Maybe your gpu is not sufficient, you could try this with the tensorflow package.

I would strongly suggest to try some memory profiling to see where bigger allocations of memory happen.


If it was not the case of insufficient memory, It might be wrong handling of the data in your model, since your loss function is not improving at all, it could be miswired for example.


Finally, the last note here .. it is good practice to load the memmap of training data as read-only, since you don't want to accidentaly mess the data.

UPDATE: I can see that you've updated the post and provided the code for the train_generator method, but there is still no call to that method in your call.

If I assume that you have a typo in the call - train_generator instead of the generator method in your d1_model.fit_generator method, it is possible that the fit_generator method is not working on a batch of data, but actually on the whole training_imgs and it copys over the whole set in the np.copy(x) call.

Also, as mentioned already, there indeed are (you can find some of them, fe. here is an open one) a few issues with Keras memory leak when using the fit and fit_generator methods.

Answers 4

This is common when running 32bit if the float precision is too high. Are you running 32bit? You may also consider casting or rounding the array.

Answers 5

In your code ,where ever your creating a numpy array of zeros,add the data type as float16

numpy.zeros(shape, dtype=float16) 

By default its float64,so we would be saving memory 4 folds.

Read More

Monday, March 12, 2018

Install keras and tensorflow using Rstudio

Leave a Comment

While trying to following the instructions of installing Keras and TensorFlow on Rstudio link https://keras.rstudio.com/index.html I get the following error. It is a work computer that is running Windows 7. I am not familiar with python, but I believe I have python 3.6 installed correctly (I am able to run simple python code in the Spyder IDE). Thanks in advance for any suggestions on how to get this working.

> install_keras() Creating r-tensorflow conda environment for TensorFlow installation... Solving environment: ...working... failed  CondaHTTPError: HTTP 000 CONNECTION FAILED for url  <https://repo.continuum.io/pkgs/main/noarch/repodata.json.bz2>  Elapsed: -  An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your  way. ConnectionError(MaxRetryError("HTTPSConnectionPool(host='repo.continuum.io', port=443): Max retries exceeded with url: /pkgs/main/noarch/repodata.json.bz2 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x000000000474D860>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',))",),)   Error: Error 1 occurred creating conda environment r-tensorflow In addition: Warning message: running command '"C:\Users\...\...\Local\CONTIN~1\ANACON~1\Scripts\conda.exe" "create" "--yes" "--name" "r-tensorflow" "python=3.6"' had status 1  

1 Answers

Answers 1

Installing Keras and TensorFlow using install_keras() isn't required to use the Keras R package. You can do a custom installation of Keras (and desired backend) as described on the Keras website and the Keras R package will find and use that version.

Source

So you can circumvent this issue with the firewall using a custom installation. The R package keras will then find that installation automatically. See the linked source for more information on how to do a custom installation.

edit: btw, there is a similar question that has been answered here. That poster goes into changing the proxy settings to cicrumvent the firewall. I cannot mark this question as a duplicate due to active bounty.

Read More

Monday, February 26, 2018

tf.keras.optimizers.Adam and other optimizers with minimization

Leave a Comment

I want to use the tf.contrib.keras to play around with it. However, there is something I don't understand. The classes from tf.train have a function minimize that you use for the optimization of your function. However, this minimize function does not exists for the classes in tf.contrib.keras.optimizers. Let's say we have the following code:

# tensorflow tf.train.AdamOptimizer(learning_rate=0.001) updateModel = trainer.minimize(loss)  # keras wrapper trainer=tf.contrib.keras.optimizers.Adam() updateModel = trainer.minimize(loss) # ERROR because minimize function does not exists 

The keras wrapper wont work because there is no minimize function. I'm trying to look for an example or workaround using tf.keras with tensorflow, but I don't find anything that helps me with that.

P.S. Here I'm using tf.contrib.keras.optimizers.Adam as a dummy example, but I would like to use other optimizers from the same package.

2 Answers

Answers 1

This caused because of differences between keras and tensorflow APIs. In keras optimizer is a function provided during model compilation which is used for a gradient descent optimization:

model.compile(optimizer='adam', ...) model.fit(..) <- optimiziation performed using Adam algorithm 

In tensorflow - you may use it in a custom manner as you presented.

Answers 2

Your confusion is caused by the fact that tf.contrib.keras API is not exactly tensorflow and isn't meant to be used like core tensorflow1.

If you look at the source code, the classes from tf.contrib.keras.optimizers are almost identical to ones from keras.optimizers. E.g., the first Optimizer and the second Optimizer, the first SGD and the second SGD, and so on. Keras is being gradually incorporated in tensorflow, but right now it's more like another project bundled together with tensorflow and can't be easily used with the arbitrary tensorflow graph. Instead, keras optimizers should be used with keras layers.

So you can either stick to the all-tensorflow API and use tf.train.AdamOptimizer (like you do right now) or to all-keras API and use Adam (see Marcin's answer). I don't see any value in mixing the two.


1 At least in TF 1.x. Keras might be integrated more with TF in the future versions.

Read More

Saturday, February 10, 2018

How to make keras in R use the tensorflow installed by Python

Leave a Comment

I have already performed the tensor flow installation with the following command:

pip install --ignore-installed https://github.com/mind/wheels/releases/download/tf1.5-gpu-cuda91-nomkl/tensorflow-1.5.0-cp27-cp27mu-linux_x86_64.whl 

This is the latest tensorflow wheel catered for CUDA 9.1. (3x faster than CUDA 8.0)

And I can call it successfully in my python code.

How can I make the keras in R to call the tensorflow installed by python above? The reason I asked that because I the default installation method

keras::install_keras(method="conda", tensorflow = "gpu") 

It failed to recognize the cuda-9.1 library.

> conv_base <- keras::application_vgg16( +   weights = "imagenet", +   include_top = FALSE, +   input_shape = c(150, 150, 3) + ) /home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.   from ._conv import register_converters as _register_converters Using TensorFlow backend. Error: ImportError: Traceback (most recent call last):   File "/home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>     from tensorflow.python.pywrap_tensorflow_internal import *   File "/home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>     _pywrap_tensorflow_internal = swig_import_helper()   File "/home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper     _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory 

This is because R installation method calling for tensorflow version 1.5.0 that is still not catered for CUDA 9.1.

2 Answers

Answers 1

Try to put this in your .bashrc:

export KERAS_BACKEND='tensorflow' 

Or based on this instruction, you can do:

tensorflow::install_tensorflow(version = "https://github.com/mind/wheels/releases/download/tf1.5-gpu-cuda91-nomkl/tensorflow-1.5.0-cp27-cp27mu-linux_x86_64.whl") 

Then keras will automatically identify the correct tensorflow

Answers 2

R is looking for the CUDA 9.0 version, rather than the latest 9.1. You should be able to symlink your system so it ends up at the 9.1 folder instead; something like:

ln -s [path to cuda 9.0 it's looking for] [cuda 9.1]

Alternatively you may be able to uninstall 9.1 and install 9.0. I believe you will also need cudnn version 7.

Read More

Wednesday, January 17, 2018

Run Identical model on multiple GPUs, but send different user data to each GPU

Leave a Comment

Any one have any success with efficient data-parallelism, where you send the identical model definition to multiple GPUs, but send different user data to each GPU?

It looks like dist-keras might be promising. but I would love to hear feedback on any approaches taken along these lines.

We have user behavioral data: 100k users, 200 fields (one-hot vectors), 30,000 records per user. We built an RNN, using Keras on top of Tensorflow, to predict the next action (out of 20+ possible actions) taken for only 1 user. It takes about 30min to train on 1 GPU. (My box has 8 GPUs). Now, We would like to build models for all 100k users.

We were able to perform data parallelism using Multi GPU approach for single user data.

But since the model takes 30 minutes per user, and there are 100k users, we want to partition the data by user and and run the same model for every user data in distributed way using a cluster and generate model output for that user.

I am currently using Keras 2.1.x with TensorFlow 1.4.

1 Answers

Answers 1

This is not exactly what you are describing, however, something that might work would be to take slices of each batch and train them on the different GPUs separately by taking the model and constructing a seperate one that does this automatically.

So say we want to make the model parallelized, and then split its batches during training among the hardware.

def make_parallel(model, gpu_count):     """     make a paralellized model from the input model on the     given gpu count that splits the input batch amongst the      hardware.      :param model: The model you want to make parallel     :param gpu_count: The gpu count     :return: The parellelized model     """     def get_slice(data, idx, parts): # take a slice of the batch         shape = tf.shape(data)         size = tf.concat([shape[:1] // parts, shape[1:]], axis=0)         stride = tf.concat([shape[:1] // parts, shape[1:] * 0], axis=0)         start = stride * idx         return tf.slice(data, start, size)      outputs_all = [[] for i in range(len(model.outputs))]      # Place a copy of the model on each GPU, each getting a slice of the batch     for i in range(gpu_count):         with tf.device('/gpu:%d' % i):             with tf.name_scope('tower_%d' % i) as scope:                 inputs = []                 for x in model.inputs:                     input_shape = tuple(x.get_shape().as_list())[1:]                     slice_n = Lambda(get_slice, output_shape=input_shape, arguments={'idx': i, 'parts': gpu_count})(x)                     inputs.append(slice_n)                  outputs = model(inputs)                  if not isinstance(outputs, list):                     outputs = [outputs]                  # Save all outputs to be joined at a later date                 for l in range(len(outputs)):                     outputs_all[l].append(outputs[l])      # merge outputs on CPU     with tf.device('/cpu:0'):         merged = [merge(output, mode='concat', concat_axis=0) for output in outputs_all]         return Model(input=model.inputs, output=merged) 

Can you report back speed results when training on this model?

Read More

Sunday, October 22, 2017

How to approximate the determinant with keras

Leave a Comment

As an experiment I am building a keras model to approximate the determinant of a matrix. However, when I run it the loss goes down at every epoch and the validation loss goes up! For example:

8s - loss: 7573.9168 - val_loss: 21831.5428 Epoch 21/50 8s - loss: 7345.0197 - val_loss: 23594.8540 Epoch 22/50 13s - loss: 7087.7454 - val_loss: 24718.3967 Epoch 23/50 7s - loss: 6851.8714 - val_loss: 25624.8609 Epoch 24/50 6s - loss: 6637.8168 - val_loss: 26616.7835 Epoch 25/50 7s - loss: 6446.8898 - val_loss: 28856.9654 Epoch 26/50 7s - loss: 6255.7414 - val_loss: 30122.7924 Epoch 27/50 7s - loss: 6054.5280 - val_loss: 32458.5306 Epoch 28/50 

Here is the complete code:

import numpy as np import sys from scipy.stats import pearsonr from scipy.linalg import det from sklearn.model_selection import train_test_split from tqdm import tqdm from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline import math import tensorflow as tf from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from keras import backend as K  def baseline_model(): # create model         model = Sequential()         model.add(Dense(200, input_dim=n**2, kernel_initializer='normal', activation='relu'))         model.add(Dense(1, input_dim=n**2))         #        model.add(Dense(1, kernel_initializer='normal'))         # Compile model         model.compile(loss='mean_squared_error', optimizer='adam')         return model   n = 15  print("Making the input data using seed 7", file=sys.stderr) np.random.seed(7) U = np.random.choice([0, 1], size=(n**2,n)) #U is a random orthogonal matrix X =[] Y =[] # print(U) for i in tqdm(range(100000)):         I = np.random.choice(n**2, size = n)         # Pick out the random rows and sort the rows of the matrix lexicographically.         A = U[I][np.lexsort(np.rot90(U[I]))]          X.append(A.ravel())         Y.append(det(A))  X = np.array(X) Y = np.array(Y)  print("Data created")  estimators = [] estimators.append(('standardize', StandardScaler())) estimators.append(('mlp', KerasRegressor(build_fn=baseline_model, epochs=50, batch_size=32, verbose=2))) pipeline = Pipeline(estimators) X_train, X_test, y_train, y_test = train_test_split(X, Y,                                                     train_size=0.75, test_size=0.25) pipeline.fit(X_train, y_train, mlp__validation_split=0.3) 

How can I stop it overfitting so badly?


Update 1

I tried adding more layers and L_2 regularization. However, it makes little or no difference.

def baseline_model(): # create model         model = Sequential()         model.add(Dense(n**2, input_dim=n**2, kernel_initializer='glorot_normal', activation='relu'))         model.add(Dense(int((n**2)/2.0), kernel_initializer='glorot_normal', activation='relu', kernel_regularizer=regularizers.l2(0.01)))         model.add(Dense(int((n**2)/2.0), kernel_initializer='glorot_normal', activation='relu', kernel_regularizer=regularizers.l2(0.01)))         model.add(Dense(int((n**2)/2.0), kernel_initializer='glorot_normal', activation='relu', kernel_regularizer=regularizers.l2(0.01)))         model.add(Dense(1, kernel_initializer='glorot_normal'))         # Compile model         model.compile(loss='mean_squared_error', optimizer='adam')         return model 

I increased the number of epochs to 100 and it finishes with:

19s - loss: 788.9504 - val_loss: 18423.2807 Epoch 97/100 24s - loss: 760.2046 - val_loss: 18305.9273 Epoch 98/100 20s - loss: 806.0941 - val_loss: 18174.8706 Epoch 99/100 24s - loss: 780.0487 - val_loss: 18356.7482 Epoch 100/100 27s - loss: 749.2595 - val_loss: 18331.5859 

Is it possible to approximate the determinant of a matrix using keras?

1 Answers

Answers 1

I tested your code and got the same result. But let's go into basic understanding of matrix determinant (DET). DET consists of n! products, so you cannot really approximate it with n*n weights in few layers of neural network. This requires number of weights that would not scale to n=15, since 15! is 1307674368000 terms for multiplication in the DET.

Read More

Keras Tensorflow - Exception while predicting from multiple threads

Leave a Comment

I am using keras 2.0.8 with tensorflow 1.3.0 backend.

I am loading a model in the class init and then use it to predict multithreaded.

import tensorflow as tf from keras import backend as K from keras.models import load_model   class CNN:     def __init__(self, model_path):         self.cnn_model = load_model(model_path)         self.session = K.get_session()         self.graph = tf.get_default_graph()      def query_cnn(self, data):         X = self.preproccesing(data)         with self.session.as_default():             with self.graph.as_default():                 return self.cnn_model.predict(X) 

I initialize the CNN once and the query_cnn method happens from multiple threads.

The exception i get in my log is:

  File "/home/*/Similarity/CNN.py", line 43, in query_cnn     return self.cnn_model.predict(X)   File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 913, in predict     return self.model.predict(x, batch_size=batch_size, verbose=verbose)   File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1713, in predict     verbose=verbose, steps=steps)   File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1269, in _predict_loop     batch_outs = f(ins_batch)   File "/usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py", line 2273, in __call__     **self.session_kwargs)   File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 895, in run     run_metadata_ptr)   File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1124, in _run     feed_dict_tensor, options, run_metadata)   File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1321, in _do_run     options, run_metadata)   File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1340, in _do_call     raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.NotFoundError: PruneForTargets: Some target nodes not found: group_deps  

The code works fine most of the times, its probably some problem with the multithreading.

How can i fix it?

1 Answers

Answers 1

Make sure you finish the graph creation before creating the other threads.

Calling finalize() on the graph may help you with that.

def __init__(self, model_path):         self.cnn_model = load_model(model_path)         self.session = K.get_session()         self.graph = tf.get_default_graph()         self.graph.finalize() 

Update 1: finalize() will make your graph read-only so it can be safely used in multiple threads. As a side effect, it will help you find unintentional behavior and sometimes memory leaks as it will throw an exception when you try to modify the graph.

Imagine that you have a thread that does for instance one hot encoding of your inputs. (bad example:)

def preprocessing(self, data):     one_hot_data = tf.one_hot(data, depth=self.num_classes)     return self.session.run(one_hot_data) 

If you print the amount of objects in the graph you will notice that it will increase over time

# amount of nodes in tf graph print(len(list(tf.get_default_graph().as_graph_def().node))) 

But if you define the graph first that won't be the case (slightly better code):

def preprocessing(self, data):     # run pre-created operation with self.input as placeholder     return self.session.run(self.one_hot_data, feed_dict={self.input: data}) 

Update 2: According to this thread you need to call model._make_predict_function() on a keras model before doing multithreading.

Keras builds the GPU function the first time you call predict(). That way, if you never call predict, you save some time and resources. However, the first time you call predict is slightly slower than every other time.

The updated code:

def __init__(self, model_path):     self.cnn_model = load_model(model_path)     self.cnn_model._make_predict_function() # have to initialize before threading     self.session = K.get_session()     self.graph = tf.get_default_graph()      self.graph.finalize() # make graph read-only 

Update 3: I did a proof of concept of a warming up, because _make_predict_function() doesn't seems to work as expected. First I created a dummy model:

import tensorflow as tf from keras.layers import * from keras.models import *  model = Sequential() model.add(Dense(256, input_shape=(2,))) model.add(Dense(1, activation='softmax'))  model.compile(loss='mean_squared_error', optimizer='adam')  model.save("dummymodel") 

Then in another script I loaded that model and made it run on multiple threads

import tensorflow as tf from keras import backend as K from keras.models import load_model import threading as t import numpy as np  K.clear_session()  class CNN:     def __init__(self, model_path):          self.cnn_model = load_model(model_path)         self.cnn_model.predict(np.array([[0,0]])) # warmup         self.session = K.get_session()         self.graph = tf.get_default_graph()         self.graph.finalize() # finalize      def preproccesing(self, data):         # dummy         return data      def query_cnn(self, data):         X = self.preproccesing(data)         with self.session.as_default():             with self.graph.as_default():                 prediction = self.cnn_model.predict(X)         print(prediction)         return prediction   cnn = CNN("dummymodel")  th = t.Thread(target=cnn.query_cnn, kwargs={"data": np.random.random((500, 2))}) th2 = t.Thread(target=cnn.query_cnn, kwargs={"data": np.random.random((500, 2))}) th3 = t.Thread(target=cnn.query_cnn, kwargs={"data": np.random.random((500, 2))}) th4 = t.Thread(target=cnn.query_cnn, kwargs={"data": np.random.random((500, 2))}) th5 = t.Thread(target=cnn.query_cnn, kwargs={"data": np.random.random((500, 2))}) th.start() th2.start() th3.start() th4.start() th5.start()  th2.join() th.join() th3.join() th5.join() th4.join() 

Commenting the lines for the warmingup and finalize I was able to reproduce your first issue

Read More

Friday, September 15, 2017

Load saved checkpoint and predict not producing same results as in training

Leave a Comment

I'm training based on a sample code I found on the Internet. The accuracy in testing is at 92% and the checkpoints are saved in a directory. In parallel (the training is running for 3 days now) I want to create my prediction code so I can learn more instead of just waiting.

This is my third day of deep learning so I probably don't know what I'm doing. Here's how I'm trying to predict:

  • Instantiate the model using the same code as in training
  • Load the last checkpoint
  • Try to predict

The code works but the results are nowhere near 90%.

Here's how I create the model:

INPUT_LAYERS = 2 OUTPUT_LAYERS = 2 AMOUNT_OF_DROPOUT = 0.3 HIDDEN_SIZE = 700 INITIALIZATION = "he_normal"  # : Gaussian initialization scaled by fan_in (He et al., 2014) CHARS = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .")  def generate_model(output_len, chars=None):     """Generate the model"""     print('Build model...')     chars = chars or CHARS     model = Sequential()     # "Encode" the input sequence using an RNN, producing an output of HIDDEN_SIZE     # note: in a situation where your input sequences have a variable length,     # use input_shape=(None, nb_feature).     for layer_number in range(INPUT_LAYERS):         model.add(recurrent.LSTM(HIDDEN_SIZE, input_shape=(None, len(chars)), init=INITIALIZATION,                          return_sequences=layer_number + 1 < INPUT_LAYERS))         model.add(Dropout(AMOUNT_OF_DROPOUT))     # For the decoder's input, we repeat the encoded input for each time step     model.add(RepeatVector(output_len))     # The decoder RNN could be multiple layers stacked or a single layer     for _ in range(OUTPUT_LAYERS):         model.add(recurrent.LSTM(HIDDEN_SIZE, return_sequences=True, init=INITIALIZATION))         model.add(Dropout(AMOUNT_OF_DROPOUT))      # For each of step of the output sequence, decide which character should be chosen     model.add(TimeDistributed(Dense(len(chars), init=INITIALIZATION)))     model.add(Activation('softmax'))      model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])     return model 

In a separate file predict.py I import this method to create my model and try to predict:

...import code model = generate_model(len(question), dataset['chars']) model.load_weights('models/weights.204-0.20.hdf5')  def decode(pred):     return character_table.decode(pred, calc_argmax=False)   x = np.zeros((1, len(question), len(dataset['chars']))) for t, char in enumerate(question):     x[0, t, character_table.char_indices[char]] = 1.  preds = model.predict_classes([x], verbose=0)[0]  print("======================================") print(decode(preds)) 

I don't know what the problem is. I have about 90 checkpoints in my directory and I'm loading the last one based on accuracy. All of them saved by a ModelCheckpoint:

checkpoint = ModelCheckpoint(MODEL_CHECKPOINT_DIRECTORYNAME + '/' + MODEL_CHECKPOINT_FILENAME,                          save_best_only=True) 

I'm stuck. What am I doing wrong?

3 Answers

Answers 1

In the repo you provided, the training and validation sentences are inverted before being fed into the model (as commonly done in seq2seq learning).

dataset = DataSet(DATASET_FILENAME) 

As you can see, the default value for inverted is True, and the questions are inverted.

class DataSet(object):     def __init__(self, dataset_filename, test_set_fraction=0.1, inverted=True):         self.inverted = inverted      ...          question = question[::-1] if self.inverted else question         questions.append(question) 

You can try to invert the sentences during prediction. Specifically,

x = np.zeros((1, len(question), len(dataset['chars']))) for t, char in enumerate(question):     x[0, len(question) - t - 1, character_table.char_indices[char]] = 1. 

Answers 2

When you generate model in your predict.py file:

model = generate_model(len(question), dataset['chars']) 

is your first parameter the same as in your training file? Or is the question length dynamic? If so, you are generating different model, thus your saved checkpoint doesn't work.

Answers 3

It can be the dimentionality of arrays/df passed not matching what is expected by the functions you call. When a single dimention is expected by the called method, try ravel on what you expect to be a single dimention

Read More

Tuesday, August 29, 2017

Saving tf.trainable_variables() using convert_variables_to_constants

Leave a Comment

I have a Keras model that I would like to convert to a Tensorflow protobuf (e.g. saved_model.pb).

This model comes from transfer learning on the vgg-19 network in which and the head was cut-off and trained with fully-connected+softmax layers while the rest of the vgg-19 network was frozen

I can load the model in Keras, and then use keras.backend.get_session() to run the model in tensorflow, generating the correct predictions:

frame = preprocess(cv2.imread("path/to/img.jpg") keras_model = keras.models.load_model("path/to/keras/model.h5")  keras_prediction = keras_model.predict(frame)  print(keras_prediction)  with keras.backend.get_session() as sess:      tvars = tf.trainable_variables()      output = sess.graph.get_tensor_by_name('Softmax:0')     input_tensor = sess.graph.get_tensor_by_name('input_1:0')      tf_prediction = sess.run(output, {input_tensor: frame})     print(tf_prediction) # this matches keras_prediction exactly 

If I don't include the line tvars = tf.trainable_variables(), then the tf_prediction variable is completely wrong and doesn't match the output from keras_prediction at all. In fact all the values in the output (single array with 4 probability values) are exactly the same (~0.25, all adding to 1). This made me suspect that weights for the head are just initialized to 0 if tf.trainable_variables() is not called first, which was confirmed after inspecting the model variables. In any case, calling tf.trainable_variables() causes the tensorflow prediction to be correct.

The problem is that when I try to save this model, the variables from tf.trainable_variables() don't actually get saved to the .pb file:

with keras.backend.get_session() as sess:     tvars = tf.trainable_variables()      constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), ['Softmax'])     graph_io.write_graph(constant_graph, './', 'saved_model.pb', as_text=False) 

What I am asking is, how can I save a Keras model as a Tensorflow protobuf with the tf.training_variables() intact?

Thanks so much!

1 Answers

Answers 1

So your approach of freezing the variables in the graph (converting to constants), should work, but isn't necessary and is trickier than the other approaches. (more on this below). If your want graph freezing for some reason (e.g. exporting to a mobile device), I'd need more details to help debug, as I'm not sure what implicit stuff Keras is doing behind the scenes with your graph. However, if you want to just save and load a graph later, I can explain how to do that, (though no guarantees that whatever Keras is doing won't screw it up..., happy to help debug that).

So there are actually two formats at play here. One is the GraphDef, which is used for Checkpointing, as it does not contain metadata about inputs and outputs. The other is a MetaGraphDef which contains metadata and a graph def, the metadata being useful for prediction and running a ModelServer (from tensorflow/serving).

In either case you need to do more than just call graph_io.write_graph because the variables are usually stored outside the graphdef.

There are wrapper libraries for both these use cases. tf.train.Saver is primarily used for saving and restoring checkpoints.

However, since you want prediction, I would suggest using a tf.saved_model.builder.SavedModelBuilder to build a SavedModel binary. I've provided some boiler plate for this below:

from tensorflow.python.saved_model.signature_constants import DEFAULT_SERVING_SIGNATURE_DEF_KEY as DEFAULT_SIG_DEF builder = tf.saved_model.builder.SavedModelBuilder('./mymodel') with keras.backend.get_session() as sess:   output = sess.graph.get_tensor_by_name('Softmax:0')   input_tensor = sess.graph.get_tensor_by_name('input_1:0')   sig_def = tf.saved_model.signature_def_utils.predict_signature_def(     {'input': input_tensor},     {'output': output}   )   builder.add_meta_graph_and_variables(       sess, tf.saved_model.tag_constants.SERVING,       signature_def_map={         DEFAULT_SIG_DEF: sig_def       }   ) builder.save() 

After running this code you should have a mymodel/saved_model.pb file as well as a directory mymodel/variables/ with protobufs corresponding to the variable values.

Then to load the model again, simply use tf.saved_model.loader:

# Does Keras give you the ability to start with a fresh graph? # If not you'll need to do this in a separate program to avoid # conflicts with the old default graph with tf.Session(graph=tf.Graph()):   meta_graph_def = tf.saved_model.loader.load(       sess,        tf.saved_model.tag_constants.SERVING,       './mymodel'   )   # From this point variables and graph structure are restored    sig_def = meta_graph_def.signature_def[DEFAULT_SIG_DEF]   print(sess.run(sig_def.outputs['output'], feed_dict={sig_def.inputs['input']: frame})) 

Obviously there's a more efficient prediction available with this code through tensorflow/serving, or Cloud ML Engine, but this should work. It's possible that Keras is doing something under the hood which will interfere with this process as well, and if so we'd like to hear about it (and I'd like to make sure that Keras users are able to freeze graphs as well, so if you want to send me a gist with your full code or something maybe I can find someone who knows Keras well to help me debug.)

EDIT: You can find an end to end example of this here: https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/keras/trainer/model.py#L85

Read More

Sunday, July 9, 2017

How can I use the Keras OCR example?

Leave a Comment

I found examples/image_ocr.py which seems to for OCR. Hence it should be possible to give the model an image and receive text. However, I have no idea how to do so. How do I feed the model with a new image? Which kind of preprocessing is necessary?

What I did

Installing the depencencies:

  • Install cairocffi: sudo apt-get install python-cairocffi
  • Install editdistance: sudo -H pip install editdistance
  • Change train to return the model and save the trained model.
  • Run the script to train the model.

Now I have a model.h5. What's next?

See https://github.com/MartinThoma/algorithms/tree/master/ML/ocr/keras for my current code. I know how to load the model (see below) and this seems to work. The problem is that I don't know how to feed new scans of images with text to the model.

Related side questions

  • What is CTC? Connectionist Temporal Classification?
  • Are there algorithms which reliably detect the rotation of a document?
  • Are there algorithms which reliably detect lines / text blocks / tables / images (hence make a reasonable segmentation)? I guess edge detection with smoothing and line-wise histograms already works reasonably well for that?

What I tried

#!/usr/bin/env python  from keras import backend as K import keras from keras.models import load_model import os  from image_ocr import ctc_lambda_func, create_model, TextImageGenerator from keras.layers import Lambda from keras.utils.data_utils import get_file import scipy.ndimage import numpy  img_h = 64 img_w = 512 pool_size = 2 words_per_epoch = 16000 val_split = 0.2 val_words = int(words_per_epoch * (val_split)) if K.image_data_format() == 'channels_first':     input_shape = (1, img_w, img_h) else:     input_shape = (img_w, img_h, 1)  fdir = os.path.dirname(get_file('wordlists.tgz',                                 origin='http://www.mythic-ai.com/datasets/wordlists.tgz', untar=True))  img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),                              bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),                              minibatch_size=32,                              img_w=img_w,                              img_h=img_h,                              downsample_factor=(pool_size ** 2),                              val_split=words_per_epoch - val_words                              ) print("Input shape: {}".format(input_shape)) model, _, _ = create_model(input_shape, img_gen, pool_size, img_w, img_h)  model.load_weights("my_model.h5")  x = scipy.ndimage.imread('example.png', mode='L').transpose() x = x.reshape(x.shape + (1,))  # Does not work print(model.predict(x)) 

this gives

2017-07-05 22:07:58.695665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:996] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN Black, pci bus id: 0000:01:00.0) Traceback (most recent call last):   File "eval_example.py", line 45, in <module>     print(model.predict(x))   File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1567, in predict     check_batch_axis=False)   File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 106, in _standardize_input_data     'Found: array with shape ' + str(data.shape)) ValueError: The model expects 4 arrays, but only received one array. Found: array with shape (512, 64, 1) 

2 Answers

Answers 1

Here, you created a model that needs 4 inputs:

model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out) 

Your predict attempt, on the other hand, is loading just an image.
Hence the message: The model expects 4 arrays, but only received one array

From your code, the necessary inputs are:

input_data = Input(name='the_input', shape=input_shape, dtype='float32') labels = Input(name='the_labels', shape=[img_gen.absolute_max_string_len],dtype='float32') input_length = Input(name='input_length', shape=[1], dtype='int64') label_length = Input(name='label_length', shape=[1], dtype='int64') 

The original code and your training work because they're using the TextImageGenerator. This generator cares to give you the four necessary inputs for the model.

So, what you have to do is to predict using the generator. As you have the fit_generator() method for training with the generator, you also have the predict_generator() method for predicting with the generator.


Now, for a complete answer and solution, I'd have to study your generator and see how it works (which would take me some time). But now you know what is to be done, you can probably figure it out.

You can either use the generator as it is, and predict probably a huge lot of data, or you can try to replicate a generator that will yield just one or a few images with the necessary labels, length and label length.

Or maybe, if possible, just create the 3 remaining arrays manually, but making sure they have the same shapes (except for the first, which is the batch size) as the generator outputs.

The one thing you must assert, though, is: have 4 arrays with the same shapes as the generator outputs, except for the first dimension.

Answers 2

Now I have a model.h5. What's next?

First I should comment that the model.h5 contains the weights of your network, if you wish to save the architecture of your network as well you should save it as a json like this example:

model_json = model_json = model.to_json() with open("model_arch.json", "w") as json_file:     json_file.write(model_json) 

Now, once you have your model and its weights you can load them on demand by doing the following:

json_file = open('model_arch.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model # if you already have a loaded model and dont need to save start from here loaded_model.load_weights("model.h5")     # compile loaded model with certain specifications sgd = SGD(lr=0.01) loaded_model.compile(loss="binary_crossentropy", optimizer=sgd, metrics=["accuracy"]) 

Then, with that loaded_module you can proceed to predict the classification of certain input like this:

prediction = loaded_model.predict(some_input, batch_size=20, verbose=0) 

Which will return the classification of that input.

About the Side Questions:

  1. CTC seems to be a term they are defining in the paper you refered, extracting from it says:

In what follows, we refer to the task of labelling un- segmented data sequences as temporal classification (Kadous, 2002), and to our use of RNNs for this pur- pose as connectionist temporal classification (CTC).

  1. To compensate the rotation of a document, images, or similar you could either generate more data from your current one by applying such transformations (take a look at this blog post that explains a way to do that ), or you could use a Convolutional Neural Network approach, which also is actually what that Keras example you are using does, as we can see from that git:

This example uses a convolutional stack followed by a recurrent stack and a CTC logloss function to perform optical character recognition of generated text images.

You can check this tutorial that is related to what you are doing and where they also explain more about Convolutional Neural Networks.

  1. Well this one is a broad question but to detect lines you could use the Hough Line Transform, or also Canny Edge Detection could be good options.

Edit: The error you are getting is because it is expected more parameters instead of 1, from the keras docs we can see:

predict(self, x, batch_size=32, verbose=0) 

Raises ValueError: In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.

Read More