Showing posts with label deep-learning. Show all posts
Showing posts with label deep-learning. 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

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

Saturday, August 4, 2018

Why is TensorFlow's `tf.data` package slowing down my code?

Leave a Comment

I'm just learning to use TensorFlow's tf.data API, and I've found that it is slowing my code down a lot, measured in time per epoch. This is the opposite of what it's supposed to do, I thought. I wrote a simple linear regression program to test it out.

Tl;Dr: With 100,000 training data, tf.data slows time per epoch down by about a factor of ten, if you're using full batch training. Worse if you use smaller batches. The opposite is true with 500 training data.

My question: What is going on? Is my implementation flawed? Other sources I've read have tf.data improving speeds by about 30%.

import tensorflow as tf  import numpy as np import timeit  import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' tf.logging.set_verbosity(tf.logging.ERROR)  n_epochs = 10 input_dimensions_list = [10]  def function_to_approximate(x):     return np.dot(x, random_covector).astype(np.float32) + np.float32(.01) * np.random.randn(1,1).astype(np.float32)  def regress_without_tfData(n_epochs, input_dimension, training_inputs, training_labels):     tf.reset_default_graph()     weights = tf.get_variable("weights", initializer=np.random.randn(input_dimension, 1).astype(np.float32))      X = tf.placeholder(tf.float32, shape=(None, input_dimension), name='X')     Y = tf.placeholder(tf.float32, shape=(None, 1), name='Y')     prediction = tf.matmul(X,weights)     loss = tf.reduce_mean(tf.square(tf.subtract(prediction, Y)))     loss_op = tf.train.AdamOptimizer(.01).minimize(loss)      init = tf.global_variables_initializer()      with tf.Session() as sess:         sess.run(init)         for _ in range(n_epochs):             sess.run(loss_op, feed_dict={X: training_inputs, Y:training_labels})  def regress_with_tfData(n_epochs, input_dimension, training_inputs, training_labels, batch_size):     tf.reset_default_graph()     weights = tf.get_variable("weights", initializer=np.random.randn(input_dimension, 1).astype(np.float32))      X,Y = data_set.make_one_shot_iterator().get_next()      prediction = tf.matmul(X, weights)     loss = tf.reduce_mean(tf.square(tf.subtract(prediction, Y)))     loss_op = tf.train.AdamOptimizer(.01).minimize(loss)      init = tf.global_variables_initializer()      with tf.Session() as sess:         sess.run(init)         while True:             try:                  sess.run(loss_op)             except tf.errors.OutOfRangeError:                 break  for input_dimension in input_dimensions_list:     for data_size in [500, 100000]:          training_inputs = np.random.randn(data_size, input_dimension).astype(np.float32)         random_covector = np.random.randint(-5, 5, size=(input_dimension, 1))         training_labels = function_to_approximate(training_inputs)          print("Not using tf.data, with data size "         "{}, input dimension {} and training with "         "a full batch, it took an average of "         "{} seconds to run {} epochs.\n".             format(                 data_size,                 input_dimension,                 timeit.timeit(                     lambda: regress_without_tfData(                         n_epochs, input_dimension,                          training_inputs, training_labels                     ),                      number=3                 ),                 n_epochs))  for input_dimension in input_dimensions_list:     for data_size, batch_size in [(500, 50), (500, 500), (100000, 50), (100000, 100000)]:          training_inputs = np.random.randn(data_size, input_dimension).astype(np.float32)         random_covector = np.random.randint(-5, 5, size=(input_dimension, 1))         training_labels = function_to_approximate(training_inputs)          data_set = tf.data.Dataset.from_tensor_slices((training_inputs, training_labels))         data_set = data_set.repeat(n_epochs)         data_set = data_set.batch(batch_size)          print("Using tf.data, with data size "         "{}, and input dimension {}, and training with "         "batch size {}, it took an average of {} seconds "         "to run {} epochs.\n".             format(                 data_size,                 input_dimension,                 batch_size,                 timeit.timeit(                     lambda: regress_with_tfData(                         n_epochs, input_dimension,                          training_inputs, training_labels,                          batch_size                     ),                     number=3                 )/3,                 n_epochs             )) 

This outputs for me:

Not using tf.data, with data size 500, input dimension 10 and training with a full batch, it took an average of 0.20243382899980134 seconds to run 10 epochs.

Not using tf.data, with data size 100000, input dimension 10 and training with a full batch, it took an average of 0.2431719040000644 seconds to run 10 epochs.

Using tf.data, with data size 500, and input dimension 10, and training with batch size 50, it took an average of 0.09512088866661846 seconds to run 10 epochs.

Using tf.data, with data size 500, and input dimension 10, and training with batch size 500, it took an average of 0.07286913600000844 seconds to run 10 epochs.

Using tf.data, with data size 100000, and input dimension 10, and training with batch size 50, it took an average of 4.421892363666605 seconds to run 10 epochs.

Using tf.data, with data size 100000, and input dimension 10, and training with batch size 100000, it took an average of 2.2555197536667038 seconds to run 10 epochs.

Edit: Fixed an important issue that Fred Guth pointed out. It didn't much affect the results, though.

1 Answers

Answers 1

First:

You are recreating the dataset unnecessarily.

data_set = tf.data.Dataset.from_tensor_slices((training_inputs, training_labels))

Create the dataset prior to the loop and change the regress_with_tfData input signature to use dataset instead of training_inputs and training_labels.

Second:

The problem here is that minibatches of size 50 or even 500 are too small to compensate the cost of td.data building latency. You should increase the minibatch size. Interestingly you did so with a minibatch of size 100000, but then maybe it is too big ( I am not certain of this, I think it would need more tests).

There are a couple of things you could try:

1) Increase the minibatch size to something like 10000 and see if you get an improvement 2) Change your pipeline to use an iterator, example:

    data_set = tf.data.Dataset.from_tensor_slices((training_inputs, training_labels))     data_set = data_set.repeat(n_epochs)     data_set = data_set.batch(batch_size)     iterator = data_set.make_one_shot_iterator()     ....     next_element = iterator.get_next() 
Read More

Saturday, May 5, 2018

Multi-output regression model always returns the same value for a batch in Tensorflow

Leave a Comment

I have a multi-layer perceptron for a multi-output regression problem which predicts 14 continuous values. The following is the code snippet for the same:

# Parameters learning_rate = 0.001 training_epochs = 1000 batch_size = 500  # Network Parameters n_hidden_1 = 32  n_hidden_2 = 200  n_hidden_3 = 200 n_hidden_4 = 256 n_input = 14 n_classes = 14  # tf Graph input x = tf.placeholder("float", [None, n_input],name="x") y = tf.placeholder("float", [None, n_classes])  # Store layers weight & bias weights = {     'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1], 0, 0.1)),     'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], 0, 0.1)),     'h3': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3], 0, 0.1)),     'h4': tf.Variable(tf.random_normal([n_hidden_3, n_hidden_4], 0, 0.1)),     'out': tf.Variable(tf.random_normal([n_hidden_4, n_classes], 0, 0.1)) }  biases = {     'b1': tf.Variable(tf.random_normal([n_hidden_1], 0, 0.1)),     'b2': tf.Variable(tf.random_normal([n_hidden_2], 0, 0.1)),     'b3': tf.Variable(tf.random_normal([n_hidden_3], 0, 0.1)),     'b4': tf.Variable(tf.random_normal([n_hidden_4], 0, 0.1)),     'out': tf.Variable(tf.random_normal([n_classes], 0, 0.1)) }  # Create model def multilayer_perceptron(x):     # Hidden layer with RELU activation     layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])     layer_1 = tf.nn.relu(layer_1)      layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])     layer_2 = tf.nn.relu(layer_2)      layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])     layer_3 = tf.nn.relu(layer_3)      layer_4 = tf.add(tf.matmul(layer_3, weights['h4']), biases['b4'])     layer_4 = tf.nn.relu(layer_4)      out_layer = tf.matmul(layer_4, weights['out']) + biases['out']     return out_layer     # Construct model pred = multilayer_perceptron(x) cost = tf.reduce_mean(tf.square(pred-y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)  # Random batch generation     total_len = X_train.shape[0] INDEXES = list(range(total_len // batch_size)) random.shuffle(INDEXES) x_batch_data = tf.slice(X_train, [batch_size * ix, 0], [batch_size, -1]) y_batch_data = tf.slice(Y_train, [batch_size * ix, 0], [batch_size, -1])   # Run the graph in the session  init = tf.global_variables_initializer() with tf.Session() as sess:       for epoch in range(training_epochs):             avg_cost = 0.             total_batch = int(total_len/batch_size)             for i in INDEXES:                 x_batch, y_batch= sess.run([x_batch_data, y_batch_data], feed_dict={ix:i})                 c,o,p=sess.run([cost, optimizer, pred], feed_dict={x:x_batch, y:y_batch})                 print('pred: {}'.format(p))                 avg_cost += c / total_batch 

OUTPUT:

x_batch_data: [  1.77560000e+04   4.00000000e+00   4.00000000e+00 ...,   1.00000000e+00 5.61000000e+02   1.00000000e+00] [  1.34310000e+04   4.00000000e+00   4.00000000e+00 ...,   1.00000000e+00 5.61000000e+02   1.00000000e+00] [  2.98800000e+03   1.00000000e+00   0.00000000e+00 ...,   0.00000000e+00 0.00000000e+00   1.00000000e+00]  y_batch_data: [[  4.19700000e-01   1.04298450e+02   1.50000000e+02 ...,   2.75250000e-01 1.02000000e-01   7.28565000e+00] [  5.59600000e-01   1.39064600e+02   2.00000000e+02 ...,   3.67000000e-01 1.36000000e-01   9.71420000e+00] [  2.79800000e-01   6.95323000e+01   1.00000000e+02 ...,   1.83500000e-01 6.80000000e-02   4.85710000e+00]  Prediction:  [[   0.85085869   90.53585815  130.17015076 ...,    0.62335277  0.26637274    5.52062225] [   0.85085869   90.53585815  130.17015076 ...,    0.62335277  0.26637274    5.52062225] [   0.85085869   90.53585815  130.17015076 ...,    0.62335277  0.26637274    5.52062225] 

The predicted value is always same despite different input values. Can someone point out what could be the reason behind this?

P.S Similar questions referred to: tensorflow deep neural network for regression always predict same results in one batch

Approaches tried:
1. Gradually reduced the learning rate from 0.1 to 0.0001
2. Tried other optimizer algorithms
3. Changed the network architecture (number of hidden nodes and layers and activation functions)

Any help is appreciated.

0 Answers

Read More

Tuesday, April 3, 2018

Ways to combine two deep learning based classifiers

Leave a Comment

I want to have a primary CNN based classifier and a similar secondary classifier for image regions.

Both classifiers will be used on image regions. I need the first classifier to be used on a primary region while the secondary classifier to be used on assistive regions and will be used to support the decision made by the first classifier with further evidence.

Thus the primary image region and the assistive ones will be used to infer one class label at a time.

What other ways or architectures exist these days to perform such a task, instead of ROI Pooling?

Ideally, I would like to have a classifier scheme similar to the one of this paper but without the use of ROI Pooling.

https://arxiv.org/pdf/1505.01197.pdf

2 Answers

Answers 1

Yaw Lin's answer contains a good amount of information, I'll just build on what he said in his last paragraph. I think the essence of what you want to do is not so much to process the person and the background independently and compare the results (that's clearly what you said you're doing), but to process the background first and infer from it the kinds of expectations you have for the primary region. Once you have some expectations, you can compare the primary region to the most significant expectations.

For example, from Figure 1 (b) in your Arxiv link, if you can process the background and determine that it's outdoors in a highly populated region, then you can focus a lot of the probability density function of what the person is doing in social outdoor activities, making jogging much more likely as a guess before you even process the figure you're interested in. In contrast, for Figure 1 (a), if you can process the background and tell that it's indoors and contains computers, then you can focus probability on lone indoor computer-based activities, skyrocketing the probability of "working on a computer".

Answers 2

You can take a look at this https://arxiv.org/pdf/1611.10012.pdf which contains comprehensive survey of recent detection architectures. Basically there are 3 meta architectures and all models fall into one of those categories:

  1. Faster-RCNN: Similar to the paper you have referenced, this is the improved version of fast-rcnn which did not use selective search and directly integrate proposal generation into the network known as region proposal network(rpn).
  2. RFCN:similar in architecture to 1, except that roi pooling is performed differently, known as position sensitive roi pooling.
  3. SSD:Modifies the rpn in Faster-rcnn to directly output class probabilities, eliminating the need for per-roi computation as is done in roi pooling. This is the fastest architecture type. Yolo falls into this architecture.

I think based on my rough read through of the paper you have referenced, type 3 is the one you are looking for. However, in terms of implementation, it can be a little tricky to implement equation 3, i.e. you may need to stop backpropagating gradients to regions(or at least think about how it could effect the final results) that do not overlap with primary region as this architecture type computes probabilities for whole image.

I also note that there is in fact no primary/secondary "classifiers". The paper described primary/secondary "regions", the primary region is the region that contains the person(i.e use a person detector to find primary region first). And secondary regions are those that overlap with primary region. For activity classification there is only one classifier except that primary region carries more weight and secondary regions each contribute a little to the final prediction score.

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

Tuesday, March 6, 2018

TensorFlow memory use while running on GPU: why does it look like not all memory is used?

Leave a Comment

This is a follow-up to my question posted here: Memory error with larger images when running convolutional neural network using TensorFlow on AWS instance g2.2xlarge

I built a CNN model in Python using TensorFlow and run it on NVIDIA GRID K520 GPU. It runs fine with 64x64 images, but produces a memory error with 128x128 images (even when input consists of only 1 image).

The error says Ran out of memory trying to allocate 2.00GiB. 2GiB is the size of my first fully-connected layer (input: 128*128*2(channels) * output: 128*128 * 4 bytes = 2.14748 GB = 2.0 GiB).

From here, I can see that GRID K520 has 8GB = 7.45GiB memory. When I start running my code, I also see the output: Total memory: 3.94GiB, Free memory: 3.91GiB.

My question is, what is the relationship between all these numbers: if there are 7.45GiB of memory on GPU, why there are only 3.94GiB of total memory and most importantly, why GPU cannot allocate 2GiB memory, which is just above half of total memory? (I am not a computer scientist, so a detailed answer would be valuable.)

Some more specific information in case it is useful: I tried using allow_growth and per_process_gpu_memory_fraction. Still get the memory error, but also some memory stats (would really appreciate if someone could explain to me these numbers):

allow_growth = True Stats:  Limit:                  3878682624 InUse:                  2148557312 MaxInUse:               2148557312 NumAllocs:                      13 MaxAllocSize:           2147483648  allow_growth = False Stats:  Limit:                  3878682624 InUse:                  3878682624 MaxInUse:               3878682624 NumAllocs:                      13 MaxAllocSize:           3877822976  per_process_gpu_memory_fraction = 0.5 allow_growth = False Stats:  Limit:                  2116026368 InUse:                      859648 MaxInUse:                   859648 NumAllocs:                      12 MaxAllocSize:               409600  per_process_gpu_memory_fraction = 0.5 allow_growth = True Stats:  Limit:                  2116026368 InUse:                     1073664 MaxInUse:                  1073664 NumAllocs:                      12 MaxAllocSize:               623616 

--------
EDIT:
--------
Minimal working example: with dummy training set of the same size as the images I input and only one fully-connected layer (full model code is here). This example works with input of size

X_train = np.random.rand(1, 64, 64, 2) Y_train = np.random.rand(1, 64, 64) 

but doesn't work with input of size

X_train = np.random.rand(1, 128, 128, 2) Y_train = np.random.rand(1, 128, 128)  

Code:

import numpy as np import tensorflow as tf   # Dummy training set: X_train = np.random.rand(1, 128, 128, 2) Y_train = np.random.rand(1, 128, 128) print('X_train.shape at input = ', X_train.shape, ", Size = ",       X_train.shape[0] * X_train.shape[1] * X_train.shape[2]       * X_train.shape[3]) print('Y_train.shape at input = ', Y_train.shape, ", Size = ",       Y_train.shape[0] * Y_train.shape[1] * Y_train.shape[2])   def create_placeholders(n_H0, n_W0):      x = tf.placeholder(tf.float32, shape=[None, n_H0, n_W0, 2], name='x')     y = tf.placeholder(tf.float32, shape=[None, n_H0, n_W0], name='y')      return x, y   def forward_propagation(x):      x_temp = tf.contrib.layers.flatten(x)  # size (n_im, n_H0 * n_W0 * 2)     n_out = np.int(x.shape[1] * x.shape[2])  # size (n_im, n_H0 * n_W0)      # FC: input size (n_im, n_H0 * n_W0 * 2), output size (n_im, n_H0 * n_W0)     FC1 = tf.contrib.layers.fully_connected(         x_temp,         n_out,         activation_fn=tf.tanh,         normalizer_fn=None,         normalizer_params=None,         weights_initializer=tf.contrib.layers.xavier_initializer(),         weights_regularizer=None,         biases_initializer=None,         biases_regularizer=None,         reuse=True,         variables_collections=None,         outputs_collections=None,         trainable=True,         scope='fc1')      # Reshape output from FC layer into array of size (n_im, n_H0, n_W0, 1):     FC_M = tf.reshape(FC1, [tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2], 1])      return FC_M   def compute_cost(FC_M, Y):      cost = tf.square(FC_M - Y)      return cost   def model(X_train, Y_train, learning_rate=0.0001, num_epochs=100):      (m, n_H0, n_W0, _) = X_train.shape      # Create Placeholders     X, Y = create_placeholders(n_H0, n_W0)      # Build the forward propagation     DECONV = forward_propagation(X)      # Add cost function to tf graph     cost = compute_cost(DECONV, Y)      # Backpropagation     optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)      # Initialize all the variables globally     init = tf.global_variables_initializer()      # Memory config     config = tf.ConfigProto()     config.gpu_options.allow_growth = True      # Start the session to compute the tf graph     with tf.Session(config = config) as sess:          # Initialization         sess.run(init)          # Training loop         for epoch in range(num_epochs):              _, temp_cost = sess.run([optimizer, cost],                                     feed_dict={X: X_train, Y: Y_train})              print ('EPOCH = ', epoch, 'COST = ', np.mean(temp_cost))   # Finally run the model model(X_train, Y_train, learning_rate=0.00002, num_epochs=5) 

Full error:

W tensorflow/core/common_runtime/bfc_allocator.cc:274] **************************************************************************************************** W tensorflow/core/common_runtime/bfc_allocator.cc:275] Ran out of memory trying to allocate 2.00GiB.  See logs for memory state. W tensorflow/core/framework/op_kernel.cc:983] Internal: Dst tensor is not initialized. E tensorflow/core/common_runtime/executor.cc:594] Executor failed to create kernel. Internal: Dst tensor is not initialized.      [[Node: zeros = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [32768,16384] values: [0 0 0]...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]] Traceback (most recent call last):   File "myAutomap_MinExample.py", line 99, in <module>     num_epochs=5)   File "myAutomap_MinExample.py", line 85, in model     sess.run(init)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 767, in run     run_metadata_ptr)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 965, in _run     feed_dict_string, options, run_metadata)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1015, in _do_run     target_list, options, run_metadata)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1035, in _do_call     raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InternalError: Dst tensor is not initialized.      [[Node: zeros = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [32768,16384] values: [0 0 0]...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]  Caused by op u'zeros', defined at:   File "myAutomap_MinExample.py", line 99, in <module>     num_epochs=5)   File "myAutomap_MinExample.py", line 72, in model     optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 289, in minimize     name=name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 403, in apply_gradients     self._create_slots(var_list)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/rmsprop.py", line 103, in _create_slots     self._zeros_slot(v, "momentum", self._name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 647, in _zeros_slot     named_slots[var] = slot_creator.create_zeros_slot(var, op_name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/slot_creator.py", line 121, in create_zeros_slot     val = array_ops.zeros(primary.get_shape().as_list(), dtype=dtype)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py", line 1352, in zeros     output = constant(zero, shape=shape, dtype=dtype, name=name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 103, in constant     attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0]   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2327, in create_op     original_op=self._default_original_op, op_def=op_def)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1226, in __init__     self._traceback = _extract_stack()  InternalError (see above for traceback): Dst tensor is not initialized.      [[Node: zeros = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [32768,16384] values: [0 0 0]...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]] 

2 Answers

Answers 1

It would be good, if you can upload your code or at least a minimal example in order to see what is going on. Just looking at these numbers, it seems allow_growth is working as it should, that is, it is only allocating the amount of memory that it actually needs (the 2.148 GiB you calculated above).

Also can you provide the full console output of the error you are getting. My guess is, that you are confusing a non fatal warning message from the TF resource allocator for the actual error that's causing your program to fail.

Is this similar to the message that you are seeing? W tensorflow/core/common_runtime/bfc_allocator.cc:217] Allocator (GPU_1_bfc) ran out of memory trying to allocate 2.55GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.

Because this is just a warning that you may ignore unless you want to optimize the runtime performance of your code. It is not something that will cause your program to fail.

Answers 2

Looking the error log it looks like or you are running out of GPU memory or the tensor is not initiated at that point. You can try to insert Tensor::IsInitialized before the line that start the problem (99) to make sure it's the GPU, if it is, you may have some code still running in the GPU, from previous tries, make sure that is not happening. There is two discussions that I think may be relevant for your problem, here: https://github.com/tensorflow/tensorflow/issues/7025 and here: https://github.com/aymericdamien/TensorFlow-Examples/issues/38 Good luck

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

Thursday, December 28, 2017

TensorFlow Eager Mode: How to restore a model from a checkpoint?

Leave a Comment

I've trained a CNN model in TensorFlow eager mode. Now I'm trying to restore the trained model from a checkpoint file but haven't got any success.

All the examples (as shown below) I've found are talking about restoring checkpoint to a Session. But what I need is to restore the model into eager mode, i.e. without creating a session.

with tf.Session() as sess:   # Restore variables from disk.   saver.restore(sess, "/tmp/model.ckpt") 

Basically what I need is something like:

tfe.enable_eager_execution() model = tfe.restore('model.ckpt') model.predict(...) 

and then I can use the model to make predictions.

Can someone please help?

2 Answers

Answers 1

Eager Execution is still a new feature in TensorFlow, and was not included in the latest version, so not all features, are supported, but fortunately, loading a model from a saved checkpoint is.

You'll need to use the tfe.Saver class (which is a thin wrapper over the tf.train.Saver class), and your code should look something like this:

saver = tfe.Saver([x, y]) saver.restore('/tmp/ckpt') 

Where [x,y] represents the list of variables and/or models you wish to restore. This should precisely match the variables passed when the saver that created the checkpoint was initially created.

More details, including sample code, can be found here, and the API details of the saver can be found here.

Answers 2

I like to share TFLearn library which is Deep learning library featuring a higher-level API for TensorFlow. With the help of this library you can easily save and restore a model.

Saving a model

model = tflearn.DNN(net) #Here 'net' is your designed network model.  #This is a sample example for training the model model.fit(train_x, train_y, n_epoch=10, validation_set=(test_x, test_y), batch_size=10, show_metric=True) model.save("model_name.ckpt") 

Restore a model

model = tflearn.DNN(net) model.load("model_name.ckpt") 

For more example of tflearn you can check some site like...

Read More

Tuesday, October 17, 2017

How to Have Multiple Softmax Outputs in Tensorflow?

Leave a Comment

I am trying to create a network in tensor flow with multiple softmax outputs, each of a different size. The network architecture is: Input -> LSTM -> Dropout. Then I have 2 softmax layers: Softmax of 10 outputs and Softmax of 20 Outputs. The reason for this is because I want to generate two sets of outputs (10 and 20), and then combine them to produce a final output. I'm not sure how to do this in Tensorflow.

Previously, to make a network like described, but with one softmax, I think I can do something like this.

inputs = tf.placeholder(tf.float32, [batch_size, maxlength]) lengths = tf.placeholders(tf.int32, [batch_size]) lstm = {} lstm[0] = tf.contrib.rnn.LSTMCell(hidden_layer_size, state_is_tuple=True, initializer=tf.contrib.layers.xavier_initializer(seed=random_seed)) lstm[0] = tf.contrib.rnn.DropoutWrapper(lstm[0], output_keep_prob=0.5) lstm[0] = tf.contrib.rnn.MultiRNNCell(cells=[lstm[0]] * 1, state_is_tuple=True) output_layer = {} output_layer[0] = Layer.W(1 * hidden_layer_size, 20, 'OutputLayer') output_bias = {} output_bias[0] = Layer.b(20, 'OutputBias') outputs = {} fstate = {} with tf.variable_scope("lstm0"):     # create the rnn graph at run time   outputs[0], fstate[0] = tf.nn.dynamic_rnn(lstm[0], embeddings[0].lookup(inputs),                                       sequence_length=lengths,                                        dtype=tf.float32) logits = {} logits[0] = tf.matmul(tf.concat([f.h for f in fstate[0]], 1), output_layer[0]) + output_bias[0] loss = {} loss[0] = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits[0], labels=labels[0])) 

However, now, I want my RNN output (after the dropout) to flow into 2 softmax layers, one of size 10 and another of size 20. Does anyone have an idea of how to do this?

Thanks

Edit: Ideally I would like to use a version of softmax such as what is defined here in this Knet Julia library. Does Tensorflow have an equivalent? https://github.com/denizyuret/Knet.jl/blob/1ef934cc58f9671f2d85063f88a3d6959a49d088/deprecated/src7/op/actf.jl#L103

2 Answers

Answers 1

You aren't defining your logits for the size 10 softmax layer in your code, and you would have to do that explicitly.

Once that was done, you could use tf.nn.softmax, applying it separately to both of your logit tensors.

For example, for your 20-class softmax tensor:

softmax20 = tf.nn.softmax(logits[0]) 

For the other layer, you could do:

output_layer[1] = Layer.W(1 * hidden_layer_size, 10, 'OutputLayer10') output_bias[1] = Layer.b(10, 'OutputBias10')  logits[1] = tf.matmul(tf.concat([f.h for f in fstate[0]], 1),  output_layer[1]) + output_bias[1]  softmax10 = tf.nn.softmax(logits[1]) 

There is also a tf.contrib.layers.softmax which allows you to apply the softmax on the final axis of a tensor with greater than 2 dimensions, but it doesn't look like you need anything like that. tf.nn.softmax should work here.

Side note: output_layer is not the greatest name for that list - should be something involving weights. These weights and biases (output_layer, output_bias) also do not represent the output layer of your network (as that will come from whatever you do to your softmax outputs, right?). [Sorry, couldn't help myself.]

Answers 2

You can do the following on the output of dynamic_rnn that you called output[0] in order to compute the two softmax and the corresponding losses:

with tf.variable_scope("softmax_0"):     # Transform you RNN output to the right output size = 10     W = tf.get_variable("kernel_0", [output[0].get_shape()[1], 10])     logits_0 = tf.matmul(inputs, W)     # Apply the softmax function to the logits (of size 10)     output_0 = tf.nn.softmax(logits_0, name = "softmax_0")     # Compute the loss (as you did in your question) with softmax_cross_entropy_with_logits directly applied on logits     loss_0 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits_0, labels=labels[0]))  with tf.variable_scope("softmax_1"):       # Transform you RNN output to the right output size = 20     W = tf.get_variable("kernel_1", [output[0].get_shape()[1], 20])     logits_1 = tf.matmul(inputs, W)     # Apply the softmax function to the logits (of size 20)     output_1 = tf.nn.softmax(logits_1, name = "softmax_1")     # Compute the loss (as you did in your question) with softmax_cross_entropy_with_logits directly applied on logits     loss_1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits_1, labels=labels[1])) 

You can then combine the two losses if it is relevant to your application:

total_loss = loss_0 + loss_1 

EDIT To answer your question in comment about what you specifically need to do with the two softmax outputs: you can do the following approximately:

with tf.variable_scope("second_part"):     W1 = tf.get_variable("W_1", [output_1.get_shape()[1], n])     W2 = tf.get_variable("W_2", [output_2.get_shape()[1], n])     prediction = tf.matmul(output_1, W1) + tf.matmul(output_2, W2) with tf.variable_scope("optimization_part"):     loss = tf.reduce_mean(tf.squared_difference(prediction, label)) 

You just need to defined n, the number of columns of W1 and W2.

Read More

Friday, September 29, 2017

How to improve accuracy of Tensorflow camera demo on iOS for retrained graph

Leave a Comment

I have an Android app that was modeled after the Tensorflow Android demo for classifying images,

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android

The original app uses a tensorflow graph (.pb) file to classify a generic set of images from Inception v3 (I think)

I then trained my own graph for my own images following the instruction in Tensorflow for Poets blog,

https://petewarden.com/2016/02/28/tensorflow-for-poets/

and this worked in the Android app very well, after changing the settings in,

ClassifierActivity

private static final int INPUT_SIZE = 299; private static final int IMAGE_MEAN = 128; private static final float IMAGE_STD = 128.0f; private static final String INPUT_NAME = "Mul"; private static final String OUTPUT_NAME = "final_result"; private static final String MODEL_FILE = "file:///android_asset/optimized_graph.pb"; private static final String LABEL_FILE =  "file:///android_asset/retrained_labels.txt"; 

To port the app to iOS, I then used the iOS camera demo, https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/ios/camera

and used the same graph file and changed the settings in,

CameraExampleViewController.mm

// If you have your own model, modify this to the file name, and make sure // you've added the file to your app resources too. static NSString* model_file_name = @"tensorflow_inception_graph"; static NSString* model_file_type = @"pb"; // This controls whether we'll be loading a plain GraphDef proto, or a // file created by the convert_graphdef_memmapped_format utility that wraps a // GraphDef and parameter file that can be mapped into memory from file to // reduce overall memory usage. const bool model_uses_memory_mapping = false; // If you have your own model, point this to the labels file. static NSString* labels_file_name = @"imagenet_comp_graph_label_strings"; static NSString* labels_file_type = @"txt"; // These dimensions need to match those the model was trained with. const int wanted_input_width = 299; const int wanted_input_height = 299; const int wanted_input_channels = 3; const float input_mean = 128f; const float input_std = 128.0f; const std::string input_layer_name = "Mul"; const std::string output_layer_name = "final_result"; 

After this the app is working on iOS, however...

The app on Android performs much better than iOS in detecting classified images. If I fill the camera's view port with the image, both perform similar. But normally the image to detect is only part of the camera view port, on Android this doesn't seem to impact much, but on iOS it impacts a lot, so iOS cannot classify the image.

My guess is that Android is cropping if camera view port to the central 299x299 area, where as iOS is scaling its camera view port to the central 299x299 area.

Can anyone confirm this? and does anyone know how to fix the iOS demo to better detect focused images? (make it crop)

In the demo Android class,

ClassifierActivity.onPreviewSizeChosen()

rgbFrameBitmap = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);     croppedBitmap = Bitmap.createBitmap(INPUT_SIZE, INPUT_SIZE, Config.ARGB_8888);  frameToCropTransform =         ImageUtils.getTransformationMatrix(             previewWidth, previewHeight,             INPUT_SIZE, INPUT_SIZE,             sensorOrientation, MAINTAIN_ASPECT);  cropToFrameTransform = new Matrix(); frameToCropTransform.invert(cropToFrameTransform); 

and on iOS is has,

CameraExampleViewController.runCNNOnFrame()

const int sourceRowBytes = (int)CVPixelBufferGetBytesPerRow(pixelBuffer);   const int image_width = (int)CVPixelBufferGetWidth(pixelBuffer);   const int fullHeight = (int)CVPixelBufferGetHeight(pixelBuffer);    CVPixelBufferLockFlags unlockFlags = kNilOptions;   CVPixelBufferLockBaseAddress(pixelBuffer, unlockFlags);    unsigned char *sourceBaseAddr =       (unsigned char *)(CVPixelBufferGetBaseAddress(pixelBuffer));   int image_height;   unsigned char *sourceStartAddr;   if (fullHeight <= image_width) {     image_height = fullHeight;     sourceStartAddr = sourceBaseAddr;   } else {     image_height = image_width;     const int marginY = ((fullHeight - image_width) / 2);     sourceStartAddr = (sourceBaseAddr + (marginY * sourceRowBytes));   }   const int image_channels = 4;    assert(image_channels >= wanted_input_channels);   tensorflow::Tensor image_tensor(       tensorflow::DT_FLOAT,       tensorflow::TensorShape(           {1, wanted_input_height, wanted_input_width, wanted_input_channels}));   auto image_tensor_mapped = image_tensor.tensor<float, 4>();   tensorflow::uint8 *in = sourceStartAddr;   float *out = image_tensor_mapped.data();   for (int y = 0; y < wanted_input_height; ++y) {     float *out_row = out + (y * wanted_input_width * wanted_input_channels);     for (int x = 0; x < wanted_input_width; ++x) {       const int in_x = (y * image_width) / wanted_input_width;       const int in_y = (x * image_height) / wanted_input_height;       tensorflow::uint8 *in_pixel =           in + (in_y * image_width * image_channels) + (in_x * image_channels);       float *out_pixel = out_row + (x * wanted_input_channels);       for (int c = 0; c < wanted_input_channels; ++c) {         out_pixel[c] = (in_pixel[c] - input_mean) / input_std;       }     }   }    CVPixelBufferUnlockBaseAddress(pixelBuffer, unlockFlags); 

1 Answers

Answers 1

Since you are not using YOLO Detector the MAINTAIN_ASPECT flag is set to false. Hence the image on Android app is not getting cropped, but it's scaled. However, in the code snippet provided I don't see the actual initialisation of the flag. Confirm that the value of the flag is actually false in your app.

I know this isn't a complete solution but hope this helps you in debugging the 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

Friday, June 9, 2017

Pre-process data with multiple instances against 1 label for neural network tensorflow

Leave a Comment

I'm training a neural network to predict the number of fan growth of a Facebook page based on the no of posts, the category of post(video, link,status etc) and number of shares ,like & comments for each post. So, there is a single label against multiple instances as label(fan_growth) is being calculated for each day(not for each post): enter image description here

So If i use one hot encoding for categorical data: enter image description here

here date,day,link,video,status,reactions,comments and shares are features, while fan_growth is label. How can I use single label against more than 1 instance? As using '100' again all 1st 3 instances would not be correct.

2 Answers

Answers 1

If I understand correctly, basically you have a variable number of events that can occur in a given day (posted a video, link, or status zero or more times each), and for each of these you have the associated reactions, comments, and shares. Then you want to predict the fan growth per day based on this variable number of actions taken in a single day. Please correct me if I am wrong.

What you can do is train a recurrent neural network on variable-length sequences of data. You would structure your input data as:

x_ij = [category, reactions, comments, shares]_i for day j i = 1, 2, ..., n_j (number of posts in day "j") j = 1, 2, ..., N (number of days in dataset) 

You can think of each x_ij as a time step in day j. Then the full input sequence for a single day would look like:

X_j = [x_1j, x_2j, ..., x_nj] 

And your output vector would be Y = [y_1, y_2, ..., y_N] where each y_j is the fan growth for day j. Basically the training process then involves setting up your recurrent neural network using tf.nn.dynamic_rnn and using the sequence_length to specify how long each input sequence is. It would look something like this (there are going to be a lot of implementation details that I will skip here):

cell = tf.contrib.rnn.GRUCell(num_hidden) # Any additional things like tf.contrib.rnn.DropoutWrapper you want here cell = tf.contrib.rnn.OutputProjectionWrapper(cell, 1)  # only one output number, right? output, _ = tf.nn.dynamic_rnn(cell, data, sequence_length=sequence_length) 

Note that I use GRU cells here (TF docs) instead of LSTM (TF docs). This is partly preference, but basically GRU can do everything LSTM can but is more efficient. You will run your training process then, passing batches of data of size [batch_size, num_steps_per_day, num_features], and a sequence_length tensor of size [batch_size, 1] that gives the number of steps per day. Something like:

with tf.Session() as sess:   for epoch in range(num_epochs):     shuffle_training_set()     for batch in range(num_batches):       d = get_next_batch()       t = get_next_target_batch()       s = # length of each data sample in your batch       sess.run(optimize, feed_dict={data: d, targets: t, sequence_length: s})       # periodically validate and stop when you stop improving 

Here, optimize might be defined something like:

cost = # your cost function here... optimizer = tf.train.AdamOptimizer()  # I usually have luck with this optimizer optimize = optimizer.minimize(cost) 

Check out this excellent example (not my content) to get you started on some of the implementation details. This example is showing sequence labeling, but it should be fairly simple to modify it to predict fan growth instead.

Answers 2

I don't think that RNN should be apply per day in that case.

You could simply sum all the information on 1 day?

For example: enter image description here

you could have:

{1st row: {day:1,         link: 2,         video: 1,         status: 0,         reactions: 489+964+964,         comments: 0,         shares: 0},  2nd row: {day: 3,         link:1,         video: 1,         status: 0,         reactions: 685,         comments: 0,         shares: 0}} 

What is possible with RNN would be to see each day as a sequence and see how things evolve through time.

Read More

Wednesday, May 24, 2017

Tensorflow Training and Validation Input Queue Separation

Leave a Comment

I tried to replicate the Fully Convolutional Network results using TensorFlow. I used Marvin Teichmann's implementation from github. I only need to write the training wrapper. I create two graphs that share variables and two input queues, one for training and one for validation. To test my training wrapper, I used two short lists of training and validation files and I do a validation immediately after every training epoch. I also printed out the shape of every image from the input queue to check whether I get the correct input. However, after I started the training, it seems that only the images from the training queue is being dequeued. So both the training and validation graphs take input from the training queue and the validation queue is never accessed. Can anyone help explain and solve this problem?

Here's part of the relevant code:

def get_data(image_name_list, num_epochs, scope_name, num_class = NUM_CLASS):     with tf.variable_scope(scope_name) as scope:         images_path = [os.path.join(DATASET_DIR, i+'.jpg') for i in image_name_list]         gts_path = [os.path.join(GT_DIR, i+'.png') for i in image_name_list]         seed = random.randint(0, 2147483647)         image_name_queue = tf.train.string_input_producer(images_path, num_epochs=num_epochs, shuffle=False, seed = seed)         gt_name_queue = tf.train.string_input_producer(gts_path, num_epochs=num_epochs, shuffle=False, seed = seed)         reader = tf.WholeFileReader()         image_key, image_value = reader.read(image_name_queue)         my_image = tf.image.decode_jpeg(image_value)         my_image = tf.cast(my_image, tf.float32)         my_image = tf.expand_dims(my_image, 0)         gt_key, gt_value = reader.read(gt_name_queue)         # gt stands for ground truth         my_gt = tf.cast(tf.image.decode_png(gt_value, channels = 1), tf.float32)         my_gt = tf.one_hot(tf.cast(my_gt, tf.int32), NUM_CLASS)         return my_image, my_gt  train_image, train_gt = get_data(train_files, NUM_EPOCH, 'training') val_image, val_gt = get_data(val_files, NUM_EPOCH, 'validation') with tf.variable_scope('FCN16') as scope:         train_vgg16_fcn = fcn16_vgg.FCN16VGG()         train_vgg16_fcn.build(train_image, train=True, num_classes=NUM_CLASS, keep_prob = KEEP_PROB)         scope.reuse_variables()         val_vgg16_fcn = fcn16_vgg.FCN16VGG()         val_vgg16_fcn.build(val_image, train=False, num_classes=NUM_CLASS, keep_prob = 1) """ Define the loss, evaluation metric, summary, saver in the computation graph. Initialize variables and start a session. """ for epoch in range(starting_epoch, NUM_EPOCH):     for i in range(train_num):         _, loss_value, shape = sess.run([train_op, train_entropy_loss, tf.shape(train_image)])         print shape     for i in range(val_num):         loss_value, shape = sess.run([val_entropy_loss, tf.shape(val_image)])         print shape 

1 Answers

Answers 1

To make sure you are reading different images you could run:

[train_image_np, val_image_np] = sess.run([train_image, val_image]) 

To reuse variables this is better and safer:

with tf.variable_scope('FCN16') as scope:    train_vgg16_fcn = fcn16_vgg.FCN16VGG()      train_vgg16_fcn.build(train_image, train=True, num_classes=NUM_CLASS, keep_prob = KEEP_PROB) with tf.variable_scope(scope, reuse=True):    val_vgg16_fcn = fcn16_vgg.FCN16VGG()    val_vgg16_fcn.build(val_image, train=False, num_classes=NUM_CLASS, keep_prob = 1) 
Read More

Monday, January 9, 2017

Retraining the last layer of Inception-ResNet-v2

Leave a Comment

I am trying to retrain the last layer of inception-resnet-v2. Here's what I came up with:

  1. Get names of variables in the final layer
  2. Create a train_op to minimise only these variables wrt loss
  3. Restore the whole graph except the final layer while initialising only the last layer randomly.

And I implemented that as follows:

with slim.arg_scope(arg_scope):     logits = model(images_ph, is_training=True, reuse=None) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels_ph)) accuracy = tf.contrib.metrics.accuracy(tf.argmax(logits, 1), labels_ph)  train_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'InceptionResnetV2/Logits') optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)  train_op = optimizer.minimize(loss, var_list=train_list)  # restore all variables whose names doesn't contain 'logits' restore_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='^((?!Logits).)*$')  saver = tf.train.Saver(restore_list, write_version=tf.train.SaverDef.V2)  with tf.Session() as session:       init_op = tf.group(tf.local_variables_initializer(), tf.global_variables_initializer())      session.run(init_op)     saver.restore(session, '../models/inception_resnet_v2_2016_08_30.ckpt')   # followed by code for running train_op 

This doesn't seem to work (training loss, error don't improve much from initial values). Is there a better/elegant way to do this? It would be good learning for me if you can also tell me what's going wrong here.

1 Answers

Answers 1

There are several things:

  • how is the learning rate? a too high value can mess with everything (probably not the reason)
  • try to use stochastic gradient descent, you should have less problems
  • is the scope correctly set? if you don't use L2 regularization and batch normalization of the gradients you might fall into a local minimum very soon and the network is unable to learn

    from nets import inception_resnet_v2 as net with net.inception_resnet_v2_arg_scope():     logits, end_points = net.inception_resnet_v2(images_ph, num_classes=num_classes,                                                  is_training=True) 
  • you should add the regularization variables to the loss (or at least the ones of the last layer):

    regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) all_losses = [loss] + regularization_losses total_loss = tf.add_n(all_losses, name='total_loss') 
  • training only the full connected layer might not be a good idea, I would train all the network as the features you need for your class aren't necessarily defined in the last layer but few layers before and you need to change them.

  • double check the train_op runs after the loss:

    with ops.name_scope('train_op'):     train_op = control_flow_ops.with_dependencies([train_op], total_loss) 
Read More

Tuesday, August 2, 2016

In Torch / Lua, how to implement a probabilistic neural network?

Leave a Comment

I've been studying this artificial neural network model called probabilistic neural network. I think I understood the general idea, but I cannot understand how to implement it in Torch.

Does anyone know how to implement a probabilistic neural network in Torch?

0 Answers

Read More

Friday, May 6, 2016

Appropriate Deep Learning Structure for multi-class classification

Leave a Comment

I have the following data

         feat_1    feat_2 ... feat_n   label gene_1   100.33     10.2  ... 90.23    great gene_2   13.32      87.9  ... 77.18    soso .... gene_m   213.32     63.2  ... 12.23    quitegood 

The size of M is large ~30K rows, and N is much smaller ~10 columns. My question is what is the appropriate Deep Learning structure to learn and test the data like above.

At the end of the day, the user will give a vector of genes with expression.

gene_1   989.00 gene_2   77.10 ... gene_N   100.10 

And the system will label which label does each gene apply e.g. great or soso, etc...

By structure I mean one of these:

  • Convolutional Neural Network (CNN)
  • Autoencoder
  • Deep Belief Network (DBN)
  • Restricted Boltzman Machine

3 Answers

Answers 1

To expand a little on @sung-kim 's comment:

  • CNN's are used primarily for problems in computer imaging, such as classifying images. They are modelled on animals visual cortex, they basically have a connection network such that there are tiles of features which have some overlap. Typically they require a lot of data, more than 30k examples.
  • Autoencoder's are used for feature generation and dimensionality reduction. They start with lots of neurons on each layer, then this number is reduced, and then increased again. Each object is trained on itself. This results in the middle layers (low number of neurons) providing a meaningful projection of the feature space in a low dimension.
  • While I don't know much about DBN's they appear to be a supervised extension of the Autoencoder. Lots of parameters to train.
  • Again I don't know much about Boltzmann machines, but they aren't widely used for this sort of problem (to my knowledge)

As with all modelling problems though, I would suggest starting from the most basic model to look for signal. Perhaps a good place to start is Logistic Regression before you worry about deep learning.

If you have got to the point where you want to try deep learning, for whatever reasons. Then for this type of data a basic feed-forward network is the best place to start. In terms of deep-learning, 30k data points is not a large number, so always best start out with a small network (1-3 hidden layers, 5-10 neurons) and then get bigger. Make sure you have a decent validation set when performing parameter optimisation though. If your a fan of the scikit-learn API, I suggest that Keras is a good place to start

One further comment, you will want to use a OneHotEncoder on your class labels before you do any training.

EDIT

I see from the bounty and the comments that you want to see a bit more about how these networks work. Please see the example of how to build a feed-forward model and do some simple parameter optisation

import numpy as np from sklearn import preprocessing from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout  # Create some random data np.random.seed(42) X = np.random.random((10, 50))  # Similar labels labels = ['good', 'bad', 'soso', 'amazeballs', 'good'] labels += labels labels = np.array(labels) np.random.shuffle(labels)  # Change the labels to the required format numericalLabels = preprocessing.LabelEncoder().fit_transform(labels) numericalLabels = numericalLabels.reshape(-1, 1) y = preprocessing.OneHotEncoder(sparse=False).fit_transform(numericalLabels)  # Simple Keras model builder def buildModel(nFeatures, nClasses, nLayers=3, nNeurons=10, dropout=0.2):     model = Sequential()     model.add(Dense(nNeurons, input_dim=nFeatures))     model.add(Activation('sigmoid'))     model.add(Dropout(dropout))     for i in xrange(nLayers-1):         model.add(Dense(nNeurons))         model.add(Activation('sigmoid'))         model.add(Dropout(dropout))     model.add(Dense(nClasses))     model.add(Activation('softmax'))      model.compile(loss='categorical_crossentropy', optimizer='sgd')      return model  # Do an exhaustive search over a given parameter space for nLayers in xrange(2, 4):     for nNeurons in xrange(5, 8):         model = buildModel(X.shape[1], y.shape[1], nLayers, nNeurons)         modelHist = model.fit(X, y, batch_size=32, nb_epoch=10,                               validation_split=0.3, shuffle=True, verbose=0)         minLoss = min(modelHist.history['val_loss'])         epochNum = modelHist.history['val_loss'].index(minLoss)         print '{0} layers, {1} neurons best validation at'.format(nLayers, nNeurons),         print 'epoch {0} loss = {1:.2f}'.format(epochNum, minLoss) 

Which outputs

2 layers, 5 neurons best validation at epoch 0 loss = 1.18 2 layers, 6 neurons best validation at epoch 0 loss = 1.21 2 layers, 7 neurons best validation at epoch 8 loss = 1.49 3 layers, 5 neurons best validation at epoch 9 loss = 1.83 3 layers, 6 neurons best validation at epoch 9 loss = 1.91 3 layers, 7 neurons best validation at epoch 9 loss = 1.65 

Answers 2

Deep learning structure would be recommended if you were dealing with raw data and wanted to find features, that work towards your classification goal, automatically. But based on the names of your columns and their number (only 10) it seems that you have your features already engineered.

For this reason you could just go with a standard multi-layer neural network and use supervised learning (back propagation). Such network would have the number of inputs matching the number of your columns (10), followed by a number of hidden layers, and then followed by an output layer with the number of neurons matching the number of your labels. You could experiment with using different number of hidden layers, neurons, different neuron types (sigmoid, tanh, rectified linear etc.) and so on.

Alternatively you could use the raw data (if it's available) and then go with DBNs (they're known to be robust and achieve good results across different problems) or auto-encoders.

Answers 3

If you expect the output to be thought of like scores for a label (as I understood from your question), try a supervised multi-class logistic regression classifier. (the highest score takes the label).

If you're bound to use deep-learning.

A simple feed-forward ANN should do, supervise learning through back propagation. Input layer with N neurons, and one or two hidden layers can be added, not more than that. There is no need to go 'deep' and add more layers for this data, there is risk to overfit the data easily with more layers, if you do so it can be tricky to figure out what the problem is, and the test accuracy will be affected greatly.

Simply plotting or visualizing the data i.e with t-sne can be a good start, if you need to figure out which features are important (or any correlation that may exist).

you can then play with higher powers of those feature dimensions/ or add increased weight to their score.

For problems like this, deep-learning probably isn't very well suited. but a simpler ANN architecture like this should work well depending on the data.

Read More