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

Thursday, September 13, 2018

“ValueError: Trying to share variable $var, but specified dtype float32 and found dtype float64_ref” when trying to use get_variable

Leave a Comment

I am trying to build a custom variational autoencoder network, where in I'm initializing the decoder weights using the transpose of the weights from the encoder layer, I couldn't find something native to tf.contrib.layers.fully_connected so I used tf.assign instead, here's my code for the layers:

def inference_network(inputs, hidden_units, n_outputs):     """Layer definition for the encoder layer."""     net = inputs     with tf.variable_scope('inference_network', reuse=tf.AUTO_REUSE):         for layer_idx, hidden_dim in enumerate(hidden_units):             net = layers.fully_connected(                 net,                 num_outputs=hidden_dim,                 weights_regularizer=layers.l2_regularizer(training_params.weight_decay),                 scope='inf_layer_{}'.format(layer_idx))             add_layer_summary(net)         z_mean = layers.fully_connected(net, num_outputs=n_outputs, activation_fn=None)         z_log_sigma = layers.fully_connected(             net, num_outputs=n_outputs, activation_fn=None)      return z_mean, z_log_sigma   def generation_network(inputs, decoder_units, n_x):     """Define the decoder network."""     net = inputs  # inputs here is the latent representation.     with tf.variable_scope("generation_network", reuse=tf.AUTO_REUSE):         assert(len(decoder_units) >= 2)         # First layer does not have a regularizer         net = layers.fully_connected(             net,             decoder_units[0],             scope="gen_layer_0",         )         for idx, decoder_unit in enumerate([decoder_units[1], n_x], 1):             net = layers.fully_connected(                 net,                 decoder_unit,                 scope="gen_layer_{}".format(idx),                 weights_regularizer=layers.l2_regularizer(training_params.weight_decay)             )     # Assign the transpose of weights to the respective layers     tf.assign(tf.get_variable("generation_network/gen_layer_1/weights"),               tf.transpose(tf.get_variable("inference_network/inf_layer_1/weights")))     tf.assign(tf.get_variable("generation_network/gen_layer_1/bias"),               tf.get_variable("generation_network/inf_layer_0/bias"))     tf.assign(tf.get_variable("generation_network/gen_layer_2/weights"),               tf.transpose(tf.get_variable("inference_network/inf_layer_0/weights")))     return net # x_recon 

It is wrapped using this tf.slim arg_scope:

def _autoencoder_arg_scope(activation_fn):     """Create an argument scope for the network based on its parameters."""      with slim.arg_scope([layers.fully_connected],                         weights_initializer=layers.xavier_initializer(),                         biases_initializer=tf.initializers.constant(0.0),                         activation_fn=activation_fn) as arg_sc:         return arg_sc 

However I'm getting the error: ValueError: Trying to share variable VarAutoEnc/generation_network/gen_layer_1/weights, but specified dtype float32 and found dtype float64_ref. I have narrowed this down to the get_variablecall, but I don't know why it's failing.

If there is a way where you can initialize a tf.contrib.layers.fully_connected from another fully connected layer without a tf.assign operation, that solution is fine with me.

1 Answers

Answers 1

I can't reproduce your error. Here is a minimalistic runnable example that does the same as your code:

import tensorflow as tf  with tf.contrib.slim.arg_scope([tf.contrib.layers.fully_connected],                                weights_initializer=tf.contrib.layers.xavier_initializer(),                                biases_initializer=tf.initializers.constant(0.0)):    i = tf.placeholder(tf.float32, [1, 30])    with tf.variable_scope("inference_network", reuse=tf.AUTO_REUSE):     tf.contrib.layers.fully_connected(i, 30, scope="gen_layer_0")    with tf.variable_scope("generation_network", reuse=tf.AUTO_REUSE):     tf.contrib.layers.fully_connected(i, 30, scope="gen_layer_0",       weights_regularizer=tf.contrib.layers.l2_regularizer(0.01))    with tf.variable_scope("", reuse=tf.AUTO_REUSE):     tf.assign(tf.get_variable("generation_network/gen_layer_0/weights"),               tf.transpose(tf.get_variable("inference_network/gen_layer_0/weights"))) 

The code runs without a ValueError. If you get a ValueError running this, then it is probably a bug that has been fixed in a later tensorflow version (I tested on 1.9). Otherwise the error is part of your code that you don't show in the question.

By the way, assign will return an op that will perform the assignment once the returned op is run in a session. So you will want to return the output of all assign calls in the generation_network function. You can bundle all assign ops into one using tf.group.

Read More

Tuesday, September 11, 2018

Tensorflow Estimator: Cache bottlenecks

Leave a Comment

When following the tensorflow image classification tutorial, at first it caches the bottleneck of each image:

def: cache_bottlenecks())

I have rewritten the training using tensorflow's Estimator. This really simplified all the code. However I want to cache the bottleneck features here.

Here is my model_fn. I want to cache the results of the dense layer so I can make changes to the actual training without having to compute the bottlenecks each time.

How can I accomplish that?

def model_fn(features, labels, mode, params):     is_training = mode == tf.estimator.ModeKeys.TRAIN      num_classes = len(params['label_vocab'])      module = hub.Module(params['module_spec'], trainable=is_training and params['train_module'])     bottleneck_tensor = module(features['image'])      with tf.name_scope('final_retrain_ops'):         logits = tf.layers.dense(bottleneck_tensor, units=num_classes, trainable=is_training)  # save this?      def train_op_fn(loss):         optimizer = tf.train.AdamOptimizer()         return optimizer.minimize(loss, global_step=tf.train.get_global_step())      head = tf.contrib.estimator.multi_class_head(n_classes=num_classes, label_vocabulary=params['label_vocab'])      return head.create_estimator_spec(         features, mode, logits, labels, train_op_fn=train_op_fn     ) 

0 Answers

Read More

Friday, September 7, 2018

LabelPropagation - How to avoid division by zero?

Leave a Comment

When using LabelPropagation, I often run into this warning (imho it should be an error because it completely fails the propagation):

/usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:279: RuntimeWarning: invalid value encountered in true_divide self.label_distributions_ /= normalizer

So after few tries with the RBF kernel, I discovered the paramater gamma has an influence.

EDIT:

The problem comes from these lines:

        if self._variant == 'propagation':             normalizer = np.sum(                 self.label_distributions_, axis=1)[:, np.newaxis]             self.label_distributions_ /= normalizer 

I don't get how label_distributions_ can be all zeros, especially when its definition is:

self.label_distributions_ = safe_sparse_dot( graph_matrix, self.label_distributions_) 

Gamma has an influence on the graph_matrix (because graph_matrix is the result of _build_graph() that call the kernel function). OK. But still. Something's wrong

OLD POST (before edit)

I remind you how graph weights are computed for the propagation: W = exp(-gamma * D), D the pairwise distance matrix between all points of the dataset.

The problem is: np.exp(x) returns 0.0 if x very small.
Let's imagine we have two points i and j such that dist(i, j) = 10.

>>> np.exp(np.asarray(-10*40, dtype=float)) # gamma = 40 => OKAY 1.9151695967140057e-174 >>> np.exp(np.asarray(-10*120, dtype=float)) # gamma = 120 => NOT OKAY 0.0 

In practice, I'm not setting gamma manually but I'm using the method described in this paper (section 2.4).

So, how would one avoid this division by zero to get a proper propagation ?

The only way I can think of is to normalize the dataset in every dimension, but we lose some geometric/topologic property of the dataset (a 2x10 rectangle becoming a 1x1 square for example)


Reproductible example:

In this example, it's worst: even with gamma = 20 it fails.

In [11]: from sklearn.semi_supervised.label_propagation import LabelPropagation  In [12]: import numpy as np  In [13]: X = np.array([[0, 0], [0, 10]])  In [14]: Y = [0, -1]  In [15]: LabelPropagation(kernel='rbf', tol=0.01, gamma=20).fit(X, Y) /usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:279: RuntimeWarning: invalid value encountered in true_divide   self.label_distributions_ /= normalizer /usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:290: ConvergenceWarning: max_iter=1000 was reached without convergence.   category=ConvergenceWarning Out[15]:  LabelPropagation(alpha=None, gamma=20, kernel='rbf', max_iter=1000, n_jobs=1,          n_neighbors=7, tol=0.01)  In [16]: LabelPropagation(kernel='rbf', tol=0.01, gamma=2).fit(X, Y) Out[16]:  LabelPropagation(alpha=None, gamma=2, kernel='rbf', max_iter=1000, n_jobs=1,          n_neighbors=7, tol=0.01)  In [17]:  

1 Answers

Answers 1

Basically you're doing a softmax function, right?

The general way to prevent softmax from over/underflowing is (from here)

# Instead of this . . .  def softmax(x, axis = 0):     return np.exp(x) / np.sum(np.exp(x), axis = axis, keepdims = True)  # Do this def softmax(x, axis = 0):     e_x = np.exp(x - np.max(x, axis = axis, keepdims = True))     return e_x / e_x.sum(axis, keepdims = True) 

This bounds e_x between 0 and 1, and assures one value of e_x will always be 1 (namely the element np.argmax(x)). This prevents overflow and underflow (when np.exp(x.max()) is either bigger or smaller than float64 can handle).

In this case, as you can't change the algorithm, I would take the input D and make D_ = D - D.min() as this should be numerically equivalent to the above, as W.max() should be -gamma * D.min() (as you're just flipping the sign). The do your algorithm with regards to D_

EDIT:

As recommended by @PaulBrodersen below, you can build a "safe" rbf kernel based on the sklearn implementation here:

def rbf_kernel_safe(X, Y=None, gamma=None):         X, Y = sklearn.metrics.pairwise.check_pairwise_arrays(X, Y)        if gamma is None:            gamma = 1.0 / X.shape[1]         K = sklearn.metrics.pairwise.euclidean_distances(X, Y, squared=True)        K *= -gamma        K -= K.max()       np.exp(K, K)    # exponentiate K in-place        return K  

And then use it in your propagation

LabelPropagation(kernel = rbf_kernel_safe, tol = 0.01, gamma = 20).fit(X, Y) 

Unfortunately I only have v0.18, which doesn't accept user-defined kernel functions for LabelPropagation, so I can't test it.

EDIT2:

Checking your source for why you have such large gamma values makes me wonder if you are using gamma = D.min()/3, which would be incorrect. The definition is sigma = D.min()/3 while the definition of sigma in w is

w = exp(-d**2/sigma**2)  # Equation (1) 

which would make the correct gamma value 1/sigma**2 or 9/D.min()**2

Read More

Monday, September 3, 2018

Python OCR: ignore signatures in documents

Leave a Comment

I'm trying to do OCR of a scanned document which has handwritten signatures in it. See the image below.

enter image description here

My question is simple, is there a way to still extract the names of the people using OCR while ignoring the signatures? When I run Tesseract OCR it fails to retrieve the names. I tried grayscaling/blurring/thresholding, using the code below, but without luck. Any suggestions?

image = cv2.imread(file_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.GaussianBlur(image, (5, 5), 0) image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] 

4 Answers

Answers 1

You can use scikit-image's Gaussian filter to blur thin lines first (with an appropriate sigma), followed by binarization of image (e.g., with some thresholding function), then by morphological operations (such as remove_small_objects or opening with some appropriate structure), to remove the signatures mostly and then try classification of the digits with sliding window (assuming that one is already trained with some blurred characters as in the test image). The following shows an example.

from skimage.morphology import binary_opening, square from skimage.filters import threshold_minimum from skimage.io import imread from skimage.color import rgb2gray from skimage.filters import gaussian  im = gaussian(rgb2gray(imread('lettersig.jpg')), sigma=2) thresh = threshold_minimum(im) im = im > thresh im = im.astype(np.bool) plt.figure(figsize=(20,20)) im1 = binary_opening(im, square(3)) plt.imshow(im1) plt.axis('off') plt.show()     

enter image description here

[EDIT]: Use Deep Learning Models

Another option is to pose the problem as an object detection problem where the alphabets are objects. We can use deep learning: CNN/RNN/Fast RNN models (with tensorflow/keras) for object detection or Yolo model (refer to the this article for car detection with yolo model).

Answers 2

I suppose the input pictures are grayscale, otherwise maybe the different color of the ink could have a distinctive power.

The problem here is that, your training set - I guess - contains almost only 'normal' letters, without the disturbance of the signature - so naturally the classifier won't work on letters with the ink of signature on them. One way to go could be to extend the training set with letters of this type. Of course it is quite a job to extract and label these letters one-by-one.

You can use real letters with different signatures on them, but it might be also possible to artificially generate similar letters. You just need different letters with different snippets of signatures moved above them. This process might be automated.

Answers 3

You may try to preprocess the image with morphologic operations.

You can try opening to remove the thin lines of the signature. The problem is that it may remove the punctuation as well.

image = cv2.imread(file_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) 

You may have to alter the kernel size or shape. Just try different sets.

Answers 4

You can try other OCR providers for the same task. For example, https://cloud.google.com/vision/ try this. You can upload an image and check for free.

You will get a response from API from where you can extract the text which you need. Documentation for extracting that text is also given on the same webpage.

Check out this. this will help you in fetching that text. this is my own answer when I faced the same problem. Convert Google Vision API response to JSON

enter image description here

Read More

Thursday, August 9, 2018

Distributed Tensorflow: who applies the parameter update?

Leave a Comment

I've used TensorFlow but am new to distributed TensorFlow for training models. My understanding is that current best practices favor the data parallel model with asynchronous updates:

A paper published by the Google Brain team in April 2016 benchmarked various approaches and found that data parallelism with synchronous updates using a few spare replicas was the most efficient, not only converging faster but also producing a better model. -- Chapter 12 of Hands-On Machine Learning with Scikit-Learn and Tensorflow.

Now, my confusion from reading further about this architecture is figuring out which component applies the parameter updates: the workers or the parameter server?

In my illustration below, it's clear to me that the workers compute the gradients dJ/dw (the gradient of the loss J with respect to the parameter weights w). But who applies the gradient descent update rule?

enter image description here

What's a bit confusing is that this O'Reilly article on Distributed TensorFlow states the following:

In the more centralized architecture, the devices send their output in the form of gradients to the parameter servers. These servers collect and aggregate the gradients. In synchronous training, the parameter servers compute the latest up-to-date version of the model, and send it back to devices. In asynchronous training, parameter servers send gradients to devices that locally compute the new model. In both architectures, the loop repeats until training terminates.

The above paragraph suggests that in asynchronous training:

  1. The workers compute gradients and send it to the parameter server.
  2. The parameter server broadcasts the gradients to the workers.
  3. Each worker receives the broadcasted gradients and applies the update rule.

Is my understanding correct? If it is, then that doesn't seem very asynchronous to me because the workers have to wait for the parameter server to broadcast the gradients. Any explanation would be appreciated.

1 Answers

Answers 1

Usually the parameter servers only store the global parameters and the workers directly apply their gradients to the global parameters (which are stored on the parameter servers). In asynchronous training no broadcasting takes place! The workers do the following in a loop:

  1. Get current global parameters from PS
  2. Calculate gradient
  3. Apply gradient to global parameters (after applying the gradients to variables stored on the parameter servers, tensorflow will send the gradients to the parameter servers and apply them there)

In between of the steps 1 and 3 the global parameters change because other workers apply their gradients. The applying of the gradients is usually hogwild.

In asynchronous training, parameter servers send gradients to devices

I don't think this happens in any asynchronous implementations. Don't know what the author tried to say here.

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

Friday, July 27, 2018

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); 

I think the issue is here,

tensorflow::uint8 *in_pixel =           in + (in_y * image_width * image_channels) + (in_x * image_channels);       float *out_pixel = out_row + (x * wanted_input_channels); 

My understanding is this is just scaling to the 299 size by pick every xth pixel instead of scaling the original image to the 299 size. So this leads to poor scaling and poor image recognition.

The solution is to first scale to pixelBuffer to size 299. I tried this,

UIImage *uiImage = [self uiImageFromPixelBuffer: pixelBuffer]; float scaleFactor = (float)wanted_input_height / (float)fullHeight; float newWidth = image_width * scaleFactor; NSLog(@"width: %d, height: %d, scale: %f, height: %f", image_width, fullHeight, scaleFactor, newWidth); CGSize size = CGSizeMake(wanted_input_width, wanted_input_height); UIGraphicsBeginImageContext(size); [uiImage drawInRect:CGRectMake(0, 0, newWidth, size.height)]; UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); pixelBuffer = [self pixelBufferFromCGImage: destImage.CGImage]; 

and to convert image to pixle buffer,

- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image {     NSDictionary *options = @{                               (NSString*)kCVPixelBufferCGImageCompatibilityKey : @YES,                               (NSString*)kCVPixelBufferCGBitmapContextCompatibilityKey : @YES,                               };      CVPixelBufferRef pxbuffer = NULL;     CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, CGImageGetWidth(image),                                           CGImageGetHeight(image), kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef) options,                                           &pxbuffer);     if (status!=kCVReturnSuccess) {         NSLog(@"Operation failed");     }     NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);      CVPixelBufferLockBaseAddress(pxbuffer, 0);     void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);      CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();     CGContextRef context = CGBitmapContextCreate(pxdata, CGImageGetWidth(image),                                                  CGImageGetHeight(image), 8, 4*CGImageGetWidth(image), rgbColorSpace,                                                  kCGImageAlphaNoneSkipFirst);     NSParameterAssert(context);      CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));     CGAffineTransform flipVertical = CGAffineTransformMake( 1, 0, 0, -1, 0, CGImageGetHeight(image) );     CGContextConcatCTM(context, flipVertical);     CGAffineTransform flipHorizontal = CGAffineTransformMake( -1.0, 0.0, 0.0, 1.0, CGImageGetWidth(image), 0.0 );     CGContextConcatCTM(context, flipHorizontal);      CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),                                            CGImageGetHeight(image)), image);     CGColorSpaceRelease(rgbColorSpace);     CGContextRelease(context);      CVPixelBufferUnlockBaseAddress(pxbuffer, 0);     return pxbuffer; }  - (UIImage*) uiImageFromPixelBuffer: (CVPixelBufferRef) pixelBuffer {     CIImage *ciImage = [CIImage imageWithCVPixelBuffer: pixelBuffer];      CIContext *temporaryContext = [CIContext contextWithOptions:nil];     CGImageRef videoImage = [temporaryContext                              createCGImage:ciImage                              fromRect:CGRectMake(0, 0,                                                  CVPixelBufferGetWidth(pixelBuffer),                                                  CVPixelBufferGetHeight(pixelBuffer))];      UIImage *uiImage = [UIImage imageWithCGImage:videoImage];     CGImageRelease(videoImage);     return uiImage; } 

Not sure if this is the best way to resize, but this worked. But it seemed to make image classification even worse, not better...

Any ideas, or issues with the image conversion/resize?

3 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.

Answers 2

Please change at this code:

// 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 = 1.0f; const std::string input_layer_name = "Mul"; const std::string output_layer_name = "final_result"; 

Here change : const float input_std = 1.0f;

Answers 3

Tensorflow Object detection have default and standard configurations, below is the list of settings,

Important things you need to check based on your input ML model,

-> model_file_name - This according to your .pb file name,

-> model_uses_memory_mapping - It's up to you to reduce overall memory usage.

-> labels_file_name - This varies based on our label file name,

-> input_layer_name/output_layer_name - Make sure you are using your own layer input/output names which you are using during graph(.pb) file creation.

snippet:

// 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 = @"graph";//@"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 = true; // If you have your own model, point this to the labels file. static NSString* labels_file_name = @"labels";//@"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 = 224; const int wanted_input_height = 224; const int wanted_input_channels = 3; const float input_mean = 117.0f; const float input_std = 1.0f; const std::string input_layer_name = "input"; const std::string output_layer_name = "final_result"; 

Custom Image Tensorflow detection, you can use below working snippet:

-> For this process you just need to pass the UIImage.CGImage object,

NSString* RunInferenceOnImageResult(CGImageRef image) {     tensorflow::SessionOptions options;      tensorflow::Session* session_pointer = nullptr;     tensorflow::Status session_status = tensorflow::NewSession(options, &session_pointer);     if (!session_status.ok()) {         std::string status_string = session_status.ToString();         return [NSString stringWithFormat: @"Session create failed - %s",                 status_string.c_str()];     }     std::unique_ptr<tensorflow::Session> session(session_pointer);     LOG(INFO) << "Session created.";      tensorflow::GraphDef tensorflow_graph;     LOG(INFO) << "Graph created.";      NSString* network_path = FilePathForResourceNames(@"tensorflow_inception_graph", @"pb");     PortableReadFileToProtol([network_path UTF8String], &tensorflow_graph);      LOG(INFO) << "Creating session.";     tensorflow::Status s = session->Create(tensorflow_graph);     if (!s.ok()) {         LOG(ERROR) << "Could not create TensorFlow Graph: " << s;         return @"";     }      // Read the label list     NSString* labels_path = FilePathForResourceNames(@"imagenet_comp_graph_label_strings", @"txt");     std::vector<std::string> label_strings;     std::ifstream t;     t.open([labels_path UTF8String]);     std::string line;     while(t){         std::getline(t, line);         label_strings.push_back(line);     }     t.close();      // Read the Grace Hopper image.     //NSString* image_path = FilePathForResourceNames(@"grace_hopper", @"jpg");     int image_width;     int image_height;     int image_channels; //    std::vector<tensorflow::uint8> image_data = LoadImageFromFile( //                                                                  [image_path UTF8String], &image_width, &image_height, &image_channels);     std::vector<tensorflow::uint8> image_data = LoadImageFromImage(image,&image_width, &image_height, &image_channels);     const int wanted_width = 224;     const int wanted_height = 224;     const int wanted_channels = 3;     const float input_mean = 117.0f;     const float input_std = 1.0f;     assert(image_channels >= wanted_channels);     tensorflow::Tensor image_tensor(                                     tensorflow::DT_FLOAT,                                     tensorflow::TensorShape({         1, wanted_height, wanted_width, wanted_channels}));     auto image_tensor_mapped = image_tensor.tensor<float, 4>();     tensorflow::uint8* in = image_data.data();     // tensorflow::uint8* in_end = (in + (image_height * image_width * image_channels));     float* out = image_tensor_mapped.data();     for (int y = 0; y < wanted_height; ++y) {         const int in_y = (y * image_height) / wanted_height;         tensorflow::uint8* in_row = in + (in_y * image_width * image_channels);         float* out_row = out + (y * wanted_width * wanted_channels);         for (int x = 0; x < wanted_width; ++x) {             const int in_x = (x * image_width) / wanted_width;             tensorflow::uint8* in_pixel = in_row + (in_x * image_channels);             float* out_pixel = out_row + (x * wanted_channels);             for (int c = 0; c < wanted_channels; ++c) {                 out_pixel[c] = (in_pixel[c] - input_mean) / input_std;             }         }     }      NSString* result; //    result = [NSString stringWithFormat: @"%@ - %lu, %s - %dx%d", result, //              label_strings.size(), label_strings[0].c_str(), image_width, image_height];      std::string input_layer = "input";     std::string output_layer = "output";     std::vector<tensorflow::Tensor> outputs;     tensorflow::Status run_status = session->Run({{input_layer, image_tensor}},                                                  {output_layer}, {}, &outputs);     if (!run_status.ok()) {         LOG(ERROR) << "Running model failed: " << run_status;         tensorflow::LogAllRegisteredKernels();         result = @"Error running model";         return result;     }     tensorflow::string status_string = run_status.ToString();     result = [NSString stringWithFormat: @"Status :%s\n",               status_string.c_str()];      tensorflow::Tensor* output = &outputs[0];     const int kNumResults = 5;     const float kThreshold = 0.1f;     std::vector<std::pair<float, int> > top_results;     GetTopN(output->flat<float>(), kNumResults, kThreshold, &top_results);      std::stringstream ss;     ss.precision(3);     for (const auto& result : top_results) {         const float confidence = result.first;         const int index = result.second;          ss << index << " " << confidence << "  ";          // Write out the result as a string         if (index < label_strings.size()) {             // just for safety: theoretically, the output is under 1000 unless there             // is some numerical issues leading to a wrong prediction.             ss << label_strings[index];         } else {             ss << "Prediction: " << index;         }          ss << "\n";     }      LOG(INFO) << "Predictions: " << ss.str();      tensorflow::string predictions = ss.str();     result = [NSString stringWithFormat: @"%@ - %s", result,               predictions.c_str()];      return result; } 

Scaling Image for custom width and height - C++ code snippet,

std::vector<uint8> LoadImageFromImage(CGImageRef image,                                      int* out_width, int* out_height,                                      int* out_channels) {      const int width = (int)CGImageGetWidth(image);     const int height = (int)CGImageGetHeight(image);     const int channels = 4;     CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();     const int bytes_per_row = (width * channels);     const int bytes_in_image = (bytes_per_row * height);     std::vector<uint8> result(bytes_in_image);     const int bits_per_component = 8;     CGContextRef context = CGBitmapContextCreate(result.data(), width, height,                                                  bits_per_component, bytes_per_row, color_space,                                                  kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);     CGColorSpaceRelease(color_space);     CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);     CGContextRelease(context);     CFRelease(image);      *out_width = width;     *out_height = height;     *out_channels = channels;     return result; } 

Above function helps you to load the image data based on your custom ratio. High accurate image pixel ratio for both Width and height during tensorflow classification is 224 x 224.

You need to call above LoadImage function from RunInferenceOnImageResult, with actual custom width and height arguments along with Image reference.

Read More

Saturday, June 16, 2018

How to identify the normalized feature

Leave a Comment

I have been trying to solve a problem stated in an exam of coursera. I am not seeking the solution but I need to get the steps and concepts to resolve this. Can any one share the concept and steps to help me find the solution. enter image description here

UPDATE: I was expecting a down-vote and its not unusual, as its the most easiest thing people can do. I am seeking the direction to solve the problem as I wasn't able to get the idea to solve it after watching the videos on Coursera. I hope someone sensible out there can share a direction and step to achieve the mentioned goal.

3 Answers

Answers 1

The first step of solving this question is to identify what is x_1^3, from the content of the lecture, it refers to the first feature of the third training case. Which is the unsquared version of the midterm score in the third row of the table.

Secondly, you need to understand the concept of normalization. The reason why we need normalization is that the value of some features among all training examples may much larger than the value of other features, which may make the cost function have pretty bad shape and this will make it harder gradient descent to find the minimum. In order to solve this, we want to make all features have nearly the same scale, and make the range of the feature to be centered at zero.

In this question, we want to scale every feature to a scale of 1, in order to do this, you need to find the max and min value of the feature among all training cases. Then squeeze the range of the feature to 0 and 1. The second step is to find the center value of the feature (average value in this case) and move the center value of the feature to 0.

I think this is pretty much all hints I can give you, you will totally be able to calculate the answer to this question by yourself from this point.

Answers 2

Your course would have covered on the mean normaliazation and min-max scaling as:xn = xt -μ /(xmax - xmin) .

Applying it on the above table would lead to:

enter image description here

Now the tricky part of the question is: you need to figure out whether the 3rd value of mindterm exam square is either (0.530184) or is it the square of (0.52): the midterm value.

Note: Look at the function you want to fit.

Answers 3

Mean Normalization

Mean normalization, also known as 'standardization', is one of the most popular techniques of feature scaling.

enter image description here

Andrew Ng describes it in the 12a slide of lecture 4: enter image description here

How to resolve the problem

The problem asks you to standardize the first feature in the third example: midterm = 94;
well, we have just to resolve the equation!


Just for clarity, the notation:

μ (mu) = "avg value of x in training set", in other words: the mean of the x1 column.

σ (sigma) = "range (max-min)", literaly σ = max-min (of the x1 column).


So:

μ = ( 89 + 72 + 94 +69 )/4 = 81

σ = ( 94 - 69 ) = 25

x_std = (94 - 81)/25 = 0.52

Result: 0.52


Best regards, Marco.

Read More

Sunday, May 13, 2018

Using Boosting tree to generate feature in sklearn

Leave a Comment

I am referring to this link to Feature Transformation using tree ensembles for the context.

Specifically for below part of code, in the sample of the link, the method of (1) using Boosting tree to generate feature, then using LR to train, outperforms (2) using Boosting tree itself. Questions,

  1. Wondering if it is true in general case using Boosting tree to generate feature (and using another classifier to classify) is better than using Boosting tree to do classification itself?
  2. And also wondering why using Boosting tree to generate feature, then using LR to train, outperforms using Boosting tree itself?

    grd = GradientBoostingClassifier(n_estimators=n_estimator) grd_enc = OneHotEncoder() grd_lm = LogisticRegression() grd.fit(X_train, y_train) grd_enc.fit(grd.apply(X_train)[:, :, 0]) grd_lm.fit(grd_enc.transform(grd.apply(X_train_lr)[:, :, 0]), y_train_lr) 

1 Answers

Answers 1

Interesting sources are paper_1 and paper_2 and additional references in them.

So to answer your questions:

  1. Very general statement, looking at some experimental results in the above papers there seem to be some exceptions. However, most of the time it does improve the score.
  2. The main idea behind doing so is to map features into a space where samples are linearly separable. If it really is the case, then linear classifiers shine.
Read More

Thursday, April 26, 2018

Is there a better way to guess possible unknown variables without brute force than I am doing? Machine learning?

Leave a Comment

I have a game with the following rules:

  • User is given fruit prices and has a chance to buy or sell items in their fruit basket every turn.

  • The user cannot make more than a 10% total change in their basket on a single turn.

  • Fruit prices change everyday and when multiplied by the quantities of items in the fruit basket, the total value of the basket changes relative to the fruit price changes everyday as well.
  • The program is only given the current price of all the fruits and the current value of the basket (current price of fruit * quantities for all items in the basket).
  • Based on these 2 inputs(all fruit prices and basket total value), the program tries to guess what items are in the basket.
  • Basket cannot hold more than 100 items but slots can be empty
  • The play can play several turns.

My goal is to accurately guess as computationally inexpensively as possible (read: no brute force) and scale if there are thousands of new fruits.

I am struggling to find an answer but in my mind it’s not hard. If I have the below table. I could study day 1 and get the following data:

Apple   1 Pears   2 Oranges 3  Basket Value = 217 

I can do a back of napkin calculation and assume, the weights in the basket are: 0 apple, 83 pears, and 17 Oranges equaling a basket value of 217.

The next day, the values of the fruits and basket changes. To (apple = 2, Pear 3, Oranges 5) with a basket value of 348. When I take my assumed weights above (0,83,17) I get a total value of 334 – not correct! Running this by my script, I see the closest match is 0 apples, 76 pears, 24 oranges which although does equal 348 when % change of factored in it’s a 38% change so it’s not possible!

I know I can completely brute force this but if I have 1000 fruits, it won’t scale. Not to jump on any band wagon but can something like a neural net quickly rule out the unlikely so I calculate large volumes of data? I think they has to be a more scalable/quicker way than pure brute force? Or is there any other type solution that could can get result?

Here is the raw data (remember program can only see prices and total basket value only):

enter image description here

Here's some brute force code (Thank you @paul Hankin for a cleaner example than mine):

def possibilities(value, prices):     for i in range(0, value+1, prices[0]):         for j in range(0, value+1-i, prices[1]):             k = value - i - j             if k % prices[2] == 0:                 yield i//prices[0], j//prices[1], k//prices[2]  def merge_totals(last, this, r):     ok = []     for t in this:         for l in last:             f = int(sum(l) * r)             if all(l[i] -f <= t[i] <= l[i] + f for i in range(len(l))):                 ok.append(t)                 break     return ok  days = [     (217, (1, 2, 3)),     (348, (2, 3, 5)),     (251, (1, 2, 4)), ]  ps = None for i, d in enumerate(days):     new_ps = list(possibilities(*d))     if ps is None:         ps = new_ps     ps = merge_totals(ps, new_ps, 0.10)      print('Day %d' % (i+1))     for p in ps:         print('Day %d,' % (i+1), 'apples: %s, pears: %s, oranges: %s' % p)     print 

Update - The info so far is awesome. Does it make sense to break the problem into two problems? One is generating the possibilities while the the other is finding the relationship between the possibilities(no more than a 10% daily change). By ruling out possibilities, couldn't that also be used to help only generate possibilities that are possible to begin with? I'm not sure the approach still but I do feel both problems are different but tightly related. Your thoughts?

Update 2 - there are a lot of questions around the % change. This is the total volume of items in the basket that can change. To use the game example, Imagine the store says - you can sell/return/buy fruits but they cannot be more than 10% of your last bill. So although the change in fruit prices can cause changes in your basket value, the user cannot take any action that would impact it by more than 10%. So if the value was 100, they can make changes that create get it to 110 but not more.

6 Answers

Answers 1

I hate to let you down but I really don't think a neural net will help at all for this problem, and IMO the best answer to your question is the advice "don't waste your time trying neural nets".

An easy rule of thumb for deciding whether or not neural networks are applicable is to think, "can an average adult human solve this problem reasonably well in a few seconds?" For problems like "what's in this image", "respond to this question", or "transcribe this audio clip", the answer is yes. But for your problem, the answer is a most definite no.

Neural networks have limitations, and one is that they don't deal well with highly logical problems. This is because the answers are generally not "smooth". If you take an image and slightly change a handful of pixels, the content of the image is still the same. If you take an audio clip and insert a few milliseconds of noise, a neural net will probably still be able to figure out what's said. But in your problem, change a single day's "total basket value" by only 1 unit, and your answer(s) will drastically change.

It seems that the only way to solve your problem is with a "classical" algorithmic approach. As currently stated, there might not be any algorithm better than brute force, and it might not be possible to rule out much. For example, what if every day has the property that all fruits are priced the same? The count of each fruit can vary, as long as the total number of fruits is fixed, so the number of possibilities is still exponential in the number of fruits. If your goal is to "produce a list of possibilities", then no algorithm can be better than exponential time since this list can be exponentially large in some cases.

It's interesting that part of your problem can be reduced to an integer linear program (ILP). Consider a single day, where you are given the basket total B and each fruit's cost c_i, for i=1 through i=n (if n is the total number of distinct fruits). Let's say the prices are large, so it's not obvious that you can "fill up" the basket with unit cost fruits. It can be hard in this situation to even find a single solution. Formulated as an ILP, this is equivalent to finding integer values of x_i such that:

sum_i (x_i*c_i) = x_1*c_1 + x_2*c_2 + ... + x_n*c_n = B 

and x_i >= 0 for all 1 <= i <= n (can't have negative fruits), and sum_i x_i <= 100 (can have at most 100 fruits).

The good news is that decent ILP solvers exist -- you can just hand over the above formulas and the solver will do its best to find a single solution. You can even add an "objective function" that the solver will maximize or minimize -- minimizing sum_i x_i has the effect of minimizing the total number of fruits in the basket. The bad news is that ILP is NP-complete, so there is almost no hope of finding an efficient solution for a large number of fruits (which equals the number of variables x_i).

I think the best approach forward is to try the ILP approach, but also introduce some more constraints on the scenario. For example, what if all fruits had a different prime number cost? This has the nice property that if you find one solution, you can enumerate a bunch of other related solutions. If an apple costs m and an orange costs n, where m and n are relatively prime, then you can "trade" n*x apples for m*x oranges without changing the basket total, for any integer x>0 (so long as you have enough apples and oranges to begin with). If you choose all fruits to have different prime number costs, then all of the costs will be pairwise relatively prime. I think this approach will result in relatively few solutions for a given day.

You might also consider other constraints, such as "there can't be more than 5 fruits of a single kind in the basket" (add the constraint x_i <= 5), or "there can be at most 5 distinct kinds of fruits in the basket" (but this is harder to encode as an ILP constraint). Adding these kinds of constraints will make it easier for the ILP solver to find a solution.

Of course the above discussion is focused on a single day, and you have multiple days' worth of data. If the hardest part of the problem is finding any solution for any day at all (which happens if your prices are large), then using an ILP solver will give you a large boost. If solutions are easy to find (which happens if you have a very-low-cost fruit that can "fill up" your basket), and the hardest part of the problem is finding solutions that are "consistent" across multiple days, then the ILP approach might not be the best fit, and in general this problem seems much more difficult to reason about.

Edit: and as mentioned in the comments, for some interpretations of the "10% change" constraint, you can even encode the entire multi-day problem as an ILP.

Answers 2

It seems to me like your approach is reasonable, but whether it is depends on the size of the numbers in the actual game. Here's a complete implementation that's a lot more efficient than yours (but still has plenty of scope for improvement). It keeps a list of possibilities for the previous day, and then filters the current day amounts to those that are within 5% of some possibility from the previous day, and prints them out per day.

def possibilities(value, prices):     for i in range(0, value+1, prices[0]):         for j in range(0, value+1-i, prices[1]):             k = value - i - j             if k % prices[2] == 0:                 yield i//prices[0], j//prices[1], k//prices[2]  def merge_totals(last, this, r):     ok = []     for t in this:         for l in last:             f = int(sum(l) * r)             if all(l[i] -f <= t[i] <= l[i] + f for i in range(len(l))):                 ok.append(t)                 break     return ok  days = [     (26, (1, 2, 3)),     (51, (2, 3, 4)),     (61, (2, 4, 5)), ]  ps = None for i, d in enumerate(days):     new_ps = list(possibilities(*d))     if ps is None:         ps = new_ps     ps = merge_totals(ps, new_ps, 0.05)      print('Day %d' % (i+1))     for p in ps:         print('apples: %s, pears: %s, oranges: %s' % p)     print 

Answers 3

Not an answer, but an attempt to make the one information about what "% change" might be supposed to mean (sum of change in count of each item computed backwards) more accessible to non-believers in pixel heaps:

        | Day 1        ! Day 2   change      ! Day 3   change      ! Day 4   change        |$/1|  # |  $  !$/1|  # |   %  |  $  !$/1|  # |   %  |  $  !$/1|  # |   %  |  $ Apples | 1 | 20 |  20 ! 2 | 21 | 4.76 |  42 ! 1 | 21 |  0   |  21 ! 1 | 22 | 4.55 |  22 Pears  | 2 | 43 |  86 ! 3 | 42 | 2.38 | 126 ! 2 | 43 | 2.33 |  86 ! 2 | 43 |  0   |  86 Oranges| 3 | 37 | 111 ! 5 | 36 | 2.78 | 180 ! 4 | 36 |  0   | 144 ! 3 | 35 | 2.86 | 105 Total  |    100 | 217 !    100 | 9.92 | 348 !    100 | 2.33 | 251 !    100 | 7.40 | 213 

Answers 4

Problem Framing

This problem can be described as a combinatorial optimization problem. You're trying to find an optimal object (a combination of fruit items) from a finite set of objects (all possible combinations of fruit items). With the proper analogy and transformations, we can reduce this fruit basket problem to the well known, and extensively studied (since 1897), knapsack problem.

Solving this class of optimization problems is NP-hard. The decision problem of answering "Can we find a combination of fruit items with a value of X?" is NP-complete. Since you want to account for a worst case scenario when you have thousands of fruit items, your best bet is to use a metaheuristic, like evolutionary computation.

Proposed Solution

Evolutionary computation is a family of biologically inspired metaheuristics. They work by revising and mixing (evolving) the most fit candidate solutions based on a fitness function and discarding the least fit ones over many iterations. The higher the fitness of a solution, the more likely it will reproduce similar solutions and survive to the next generation (iteration). Eventually, a local or global optimal solution is found.

These methods provide a needed compromise when the search space is too large to cover with traditional closed form mathematical solutions. Due to the stochastic nature of these algorithms, different executions of the algorithms may lead to different local optima, and there is no guarantee that the global optimum will be found. The odds are good in our case since we have multiple valid solutions.

Example

Let's use the Distributed Evolutionary Algorithms in Python (DEAP) framework and retrofit their Knapsack problem example to our problem. In the code below we apply strong penalty for baskets with 100+ items. This will severely reduce their fitness and have them taken out of the population pool in one or two generations. There are other ways to handle constraints that are also valid.

#    This file is part of DEAP. # #    DEAP is free software: you can redistribute it and/or modify #    it under the terms of the GNU Lesser General Public License as #    published by the Free Software Foundation, either version 3 of #    the License, or (at your option) any later version. # #    DEAP is distributed in the hope that it will be useful, #    but WITHOUT ANY WARRANTY; without even the implied warranty of #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #    GNU Lesser General Public License for more details. # #    You should have received a copy of the GNU Lesser General Public #    License along with DEAP. If not, see <http://www.gnu.org/licenses/>.  import random  import numpy as np  from deap import algorithms from deap import base from deap import creator from deap import tools  IND_INIT_SIZE = 5 # Calls to `individual` function MAX_ITEM = 100   # Max 100 fruit items in basket NBR_ITEMS = 50   # Start with 50 items in basket FRUIT_TYPES = 10 # Number of fruit types (apples, bananas, ...)  # Generate a dictionary of random fruit prices. fruit_price = {i: random.randint(1, 5)  for i in range(FRUIT_TYPES)}  # Create fruit items dictionary.  The key is item ID, and the  # value is a (weight, price) tuple.  Weight is always 1 here. items = {} # Create random items and store them in the items' dictionary. for i in range(NBR_ITEMS):     items[i] = (1, fruit_price[i])  # Create fitness function and an individual (solution candidate) # A solution candidate in our case is a collection of fruit items. creator.create("Fitness", base.Fitness, weights=(-1.0, 1.0)) creator.create("Individual", set, fitness=creator.Fitness)  toolbox = base.Toolbox()  # Randomly initialize the population (a set of candidate solutions) toolbox.register("attr_item", random.randrange, NBR_ITEMS) toolbox.register("individual", tools.initRepeat, creator.Individual,  toolbox.attr_item, IND_INIT_SIZE)   def evalBasket(individual):     """Evaluate the value of the basket and     apply constraints penalty.     """     value = 0 # Total value of the basket     for item in individual:         value += items[item][1]      # Heavily penalize baskets with 100+ items     if len(individual) > MAX_ITEM:         return 10000, 0     return len(individual), value  # (items in basket, value of basket)   def cxSet(ind1, ind2):     """Apply a crossover operation on input sets.     The first child is the intersection of the two sets,     the second child is the difference of the two sets.     This is one way to evolve new candidate solutions from     existing ones.  Think of it as parents mixing their genes     to produce a child.     """     temp = set(ind1)                # Used in order to keep type     ind1 &= ind2                    # Intersection (inplace)     ind2 ^= temp                    # Symmetric Difference (inplace)     return ind1, ind2   def mutSet(individual):     """Mutation that pops or add an element.     In nature, gene mutations help offspring express new traits     not found in their ancestors.  That could be beneficial or      harmful.  Survival of the fittest at play here.     """     if random.random() < 0.5:  # 50% chance of mutation         if len(individual) > 0:             individual.remove(random.choice(sorted(tuple(individual))))     else:         individual.add(random.randrange(NBR_ITEMS))     return individual,  # Register evaluation, mating, mutation and selection functions # so the framework can use them to run the simulation. toolbox.register("evaluate", evalKnapsack) toolbox.register("mate", cxSet) toolbox.register("mutate", mutSet) toolbox.register("select", tools.selNSGA2)   def main():     random.seed(64)     NGEN = 50     MU = 50     LAMBDA = 100     CXPB = 0.7     MUTPB = 0.2      pop = toolbox.population(n=MU)  # Initial population size     hof = tools.ParetoFront()    # Using Pareto front to rank fitness      # Keep track of population fitness stats which should      # improve over generations (iterations).     stats = tools.Statistics(lambda ind: ind.fitness.values)     stats.register("avg", numpy.mean, axis=0)     stats.register("std", numpy.std, axis=0)     stats.register("min", numpy.min, axis=0)     stats.register("max", numpy.max, axis=0)      algorithms.eaMuPlusLambda(pop, toolbox, MU,LAMBDA,\                               CXPB, MUTPB, NGEN, stats,\                               halloffame=hof)     return pop, stats, hof   if __name__ == "__main__":     main()    

Answers 5

You got a logic problem on integers, not a representation problem. Neural networks are relevant to problem with complex representation (eg., image with pixels, objects in differents shape and color, sometimes hidden etc), as they build their own set of features (descriptors) and mipmaps; they also are a good match with problems dealing with reals, not integer; and last, as they are today, they don't really deal with reasonning and logic, or eventually with simple logic like a small succession of if/else or switch but we don't really have a control over that.

What I see is closer to a cryptographic-ish problem with constraints (10% change, max 100 articles).

Solution for all sets of fruits

There is a way to reach all solutions very quickly. We start by factoring into primes the total, then we find few solutions through brute force. From there we can change the set of fruits with equal total. Eg., we exchange 1 orange for 1 apple and 1 pear with prices = (1,2,3). This way we can navigate through solutions without having to go through brute force.

Algorithm(s): you factorize in prime numbers the total, then you split them into two or more groups; let's take 2 groups: let A be one common multiplier, and let B the other(s). Then you can add your fruits to reach the total B.

Examples:

Day 1: Apple = 1, Pears = 2, Oranges = 3, Basket Value = 217

Day 2: Apple = 2, Pears = 3, Oranges = 5, Basket Value = 348

  • 217 factorizes into [7, 31], we pick 31 as A (common multiplier), then let say 7=3*2+1 (2 orange, 0 pear, 1 apple), you got an answer: 62 oranges, 0 pears, 31 apples. 62+31<100: valid.
  • 348 factorizes into [2, 2, 3, 29], you have several ways to group your factors and multiply your fruits inside this. The multiplier can be 29, (or 2*29 etc), then you pick your fruits to reach 12. Let's say 12=2*2+3+5. You got (2 apples, 1 pear, 1 orange) * 29, but it's more than 100 articles. You can fuse recursively 1 apple and 1 pear into 1 orange until you are below 100 articles, or you can go directly with the solution with a minimum of articles: (2 oranges, 1 apple)*29 = (58 oranges, 29 apples). And at last:

    -- 87<100 valid;

    -- the change is (-4 oranges, -2 apples), 6/93=6.45% <10% change: valid.

Code

Remark: no implementation of the 10% variation

Remark: I didn't implement the "fruit exchange" process that allows the "solution navigation"

Run with python -O solution.py to optimize and remove the debug messages.

def prime_factors(n):     i = 2     factors = []     while i * i <= n:         if n % i:             i += 1         else:             n //= i             factors.append(i)     if n > 1:         factors.append(n)     return factors  def possibilities(value, prices):     for i in range(0, value + 1, prices[0]):         for j in range(0, value + 1-i, prices[1]):             k = value - i - j             if k % prices[2] == 0:                 yield i//prices[0], j//prices[1], k//prices[2]  days = [     (217, (1, 2, 3)),     (348, (2, 3, 5)),     (251, (1, 2, 4)),     (213, (1, 2, 3)), ]  for set in days:     total = set[0]     (priceApple, pricePear, priceOrange) = set[1]      factors = prime_factors(total)     if __debug__:         print(str(total) + " -> " + str(factors))      # remove small article to help factorize (odd helper)     evenHelper = False     if len(factors) == 1 :         evenHelper = True         t1 = total - priceApple         factors = prime_factors(t1)         if __debug__:             print(str(total) + " --> " + str(factors))      # merge factors on left     while factors[0] < priceOrange :         factors = [factors[0] * factors[1]] + factors[2:]         if __debug__:             print("merging: " + str(factors))      # merge factors on right     if len(factors) > 2:         multiplier = 1         for f in factors[1:]:             multiplier *= f         factors = [factors[0]] + [multiplier]      (smallTotal, multiplier) = factors     if __debug__:         print("final factors: " + str(smallTotal) + " (small total) , " + str(multiplier) + " (multiplier)")      # solutions satisfying #<100     smallMax = 100 / multiplier     solutions = [o for o in possibilities(smallTotal, set[1]) if sum(o) < smallMax ]     for solution in solutions:         (a,p,o) = [i * multiplier for i in solution]          # if we used it, we need to add back the odd helper to reach the actual solution         if evenHelper:             a += 1          print(str(a) + " apple(s), " + str(p) + " pear(s), " + str(o) + " orange(s)")       # separating solutions     print() 

I timed the program with a 10037 total with (5, 8, 17) prices, and maximum 500 articles: it's about 2ms (on i7 6700k). The "solution navigation" process is very simple and shouldn't add significant time.

There might be a heuristic to go from day to day without having to do the factorization + navigation + validation process. I'll think about it.

Answers 6

Integer Linear Programming Approach

This sets up naturally as a multi-step Integer Program, with the holdings in {apples, pears, oranges} from the previous step in the calculation of the relative change in holdings that must be constrained. There is no notion of optimal here, but we can turn the "turnover" constraint into an objective and see what happens.

We in fact do get feasible integer solutions at each step, requiring smaller % changes to the basket than in your chart.

Comments -

  • I don't know how you calculated the "% change" column in your table. A change from Day 1 to Day 2 of 20 apples to 21 apples is a 4.76% change?

  • On all days, your total holdings in fruits is exactly 100. There is a constraint that the sum of holdings is <= 100. No violation, I just want to confirm.

We can set this up as an integer linear program, using the integer optimization routine from ortools. I haven't used an ILP solver for a long time, and this one is kind of flaky I think (the solver.OPTIMAL flag is never true it seems, even for toy problems. In addition the ortools LP solver fails to find an optimal solution in cases where scipy.linprog works without a hitch)

h1,d = holdings in apples (number of apples) at end of day d h2,d = holdings in pears at end of day d h3,d = holdings in oranges at end of day d 

I'll give two proposals here, one which minimizes the l1 norm of the absolute error, the other the l0norm.

The l1 solution finds the minimum of abs(h1,(d+1) - h1,d)/h1 + ... + abs(h3,(d+1) - h3,d)/h3), hoping that the constraint that each relative change in holdings is under 10% if the sum of the relative change in holdings is minimized.

The only thing that prevents this from being a linear program (aside from the integer requirement) is the nonlinear objective function. No problem, we can introduce slack variables and make everything linear. For the l1 formulation, 6 additional slack variables are introduced, 2 per fruit, and 6 additional inequality constraints. For the l0 formulation, 1 slack variable is introduced, and 6 additional inequality constraints.

This is a two step process, for example, replacing |apples_new - apples_old|/|apples_old| with the variable |e|, and adding inequality constraints to ensure the e measures what we'd like. We then replace|e| with (e+ - e-), each of e+, e- >0. It can be shown that one of e+, e- will be 0, and that (e+ + e-) is the absolute value of e. That way the pair (e+, e-) can represent a positive or negative number. Standard stuff, but that adds a bunch of variables and constraints. I can explain this in a bit more detail if necessary.

import numpy as np from ortools.linear_solver import pywraplp   def fruit_basket_l1_ortools():      UPPER_BOUND = 1000      prices = [[2,3,5],               [1,2,4],               [1,2,3]]      holdings = [20,43,37]      values = [348, 251, 213]      for day in range(len(values)):          solver = pywraplp.Solver('ILPSolver',                                   pywraplp.Solver.BOP_INTEGER_PROGRAMMING)         # solver = pywraplp.Solver('ILPSolver',         #                          pywraplp.Solver.CLP_LINEAR_PROGRAMMING)           c = ([1,1] * 3) + [0,0,0]          price = prices[day]         value = values[day]          A_eq = [[ 0,  0, 0,  0, 0,  0, price[0], price[1], price[2]]]          b_eq = [value]          A_ub = [[-1*holdings[0], 1*holdings[0],              0,             0,              0,              0,  1.0,    0,    0],                 [-1*holdings[0], 1*holdings[0],              0,             0,              0,              0, -1.0,    0,    0],                 [             0,             0, -1*holdings[1], 1*holdings[1],              0,              0,    0,  1.0,    0],                 [             0,             0, -1*holdings[1], 1*holdings[1],              0,              0,    0, -1.0,    0],                 [             0,             0,              0,              0, -1*holdings[2], 1*holdings[2],    0,    0,  1.0],                 [             0,             0,              0,              0, -1*holdings[2], 1*holdings[2],    0,    0, -1.0]]          b_ub = [1*holdings[0], -1*holdings[0], 1*holdings[1], -1*holdings[1], 1*holdings[2], -1*holdings[2]]          num_vars             = len(c)         num_ineq_constraints = len(A_ub)         num_eq_constraints   = len(A_eq)                          data = [[]] * num_vars          data[0]  = solver.IntVar(           0, UPPER_BOUND, 'e1_p')         data[1]  = solver.IntVar(           0, UPPER_BOUND, 'e1_n')         data[2]  = solver.IntVar(           0, UPPER_BOUND, 'e2_p')         data[3]  = solver.IntVar(           0, UPPER_BOUND, 'e2_n')         data[4]  = solver.IntVar(           0, UPPER_BOUND, 'e3_p')         data[5]  = solver.IntVar(           0, UPPER_BOUND, 'e3_n')         data[6]  = solver.IntVar(           0, UPPER_BOUND, 'x1')         data[7]  = solver.IntVar(           0, UPPER_BOUND, 'x2')         data[8]  = solver.IntVar(           0, UPPER_BOUND, 'x3')          constraints = [0] * (len(A_ub) + len(b_eq))          # Inequality constraints         for i in range(0,num_ineq_constraints):             constraints[i] = solver.Constraint(-solver.infinity(), b_ub[i])             for j in range(0,num_vars):                 constraints[i].SetCoefficient(data[j], A_ub[i][j])          # Equality constraints         for i in range(num_ineq_constraints, num_ineq_constraints+num_eq_constraints):             constraints[i] = solver.Constraint(b_eq[i-num_ineq_constraints], b_eq[i-num_ineq_constraints])             for j in range(0,num_vars):                 constraints[i].SetCoefficient(data[j], A_eq[i-num_ineq_constraints][j])          # Objective function         objective = solver.Objective()         for i in range(0,num_vars):             objective.SetCoefficient(data[i], c[i])          # Set up as minization problem         objective.SetMinimization()          # Solve it         result_status = solver.Solve()          solution_set = [data[i].solution_value() for i in range(len(data))]          print('DAY: {}'.format(day+1))         print('======')         print('SOLUTION FEASIBLE: {}'.format(solver.FEASIBLE))         print('SOLUTION OPTIMAL:  {}'.format(solver.OPTIMAL))         print('VALUE OF BASKET:   {}'.format(np.dot(A_eq[0], solution_set)))         print('SOLUTION   (apples,pears,oranges): {!r}'.format(solution_set[-3:]))         print('PCT CHANGE (apples,pears,oranges): {!r}\n\n'.format([round(100*(x-y)/y,2) for x,y in zip(solution_set[-3:], holdings)]))          # Update holdings for the next day         holdings = solution_set[-3:] 

A single run gives:

DAY: 1 ====== SOLUTION FEASIBLE: 1 SOLUTION OPTIMAL:  0 VALUE OF BASKET:   348.0 SOLUTION   (apples,pears,oranges): [20.0, 41.0, 37.0] PCT CHANGE (apples,pears,oranges): [0.0, -4.65, 0.0]   DAY: 2 ====== SOLUTION FEASIBLE: 1 SOLUTION OPTIMAL:  0 VALUE OF BASKET:   251.0 SOLUTION   (apples,pears,oranges): [21.0, 41.0, 37.0] PCT CHANGE (apples,pears,oranges): [5.0, 0.0, 0.0]   DAY: 3 ====== SOLUTION FEASIBLE: 1 SOLUTION OPTIMAL:  0 VALUE OF BASKET:   213.0 SOLUTION   (apples,pears,oranges): [20.0, 41.0, 37.0] PCT CHANGE (apples,pears,oranges): [-4.76, 0.0, 0.0] 

The l0 formulation is also presented:

def fruit_basket_l0_ortools():      UPPER_BOUND = 1000      prices = [[2,3,5],               [1,2,4],               [1,2,3]]      holdings = [20,43,37]      values = [348, 251, 213]      for day in range(len(values)):          solver = pywraplp.Solver('ILPSolver',                                   pywraplp.Solver.BOP_INTEGER_PROGRAMMING)         # solver = pywraplp.Solver('ILPSolver',         #                          pywraplp.Solver.CLP_LINEAR_PROGRAMMING)          c = [1, 0, 0, 0]          price = prices[day]         value = values[day]          A_eq = [[0, price[0], price[1], price[2]]]          b_eq = [value]          A_ub = [[-1*holdings[0],  1.0,    0,    0],                 [-1*holdings[0], -1.0,    0,    0],                 [-1*holdings[1],    0,  1.0,    0],                 [-1*holdings[1],    0, -1.0,    0],                 [-1*holdings[2],    0,    0,  1.0],                 [-1*holdings[2],    0,    0, -1.0]]           b_ub = [holdings[0], -1*holdings[0], holdings[1], -1*holdings[1], holdings[2], -1*holdings[2]]           num_vars             = len(c)         num_ineq_constraints = len(A_ub)         num_eq_constraints   = len(A_eq)                          data = [[]] * num_vars          data[0]  = solver.IntVar(-UPPER_BOUND, UPPER_BOUND, 'e' )         data[1]  = solver.IntVar(           0, UPPER_BOUND, 'x1')         data[2]  = solver.IntVar(           0, UPPER_BOUND, 'x2')         data[3]  = solver.IntVar(           0, UPPER_BOUND, 'x3')          constraints = [0] * (len(A_ub) + len(b_eq))          # Inequality constraints         for i in range(0,num_ineq_constraints):             constraints[i] = solver.Constraint(-solver.infinity(), b_ub[i])             for j in range(0,num_vars):                 constraints[i].SetCoefficient(data[j], A_ub[i][j])          # Equality constraints         for i in range(num_ineq_constraints, num_ineq_constraints+num_eq_constraints):             constraints[i] = solver.Constraint(int(b_eq[i-num_ineq_constraints]), b_eq[i-num_ineq_constraints])             for j in range(0,num_vars):                 constraints[i].SetCoefficient(data[j], A_eq[i-num_ineq_constraints][j])          # Objective function         objective = solver.Objective()         for i in range(0,num_vars):             objective.SetCoefficient(data[i], c[i])          # Set up as minization problem         objective.SetMinimization()          # Solve it         result_status = solver.Solve()          solution_set = [data[i].solution_value() for i in range(len(data))]          print('DAY: {}'.format(day+1))         print('======')         print('SOLUTION FEASIBLE: {}'.format(solver.FEASIBLE))         print('SOLUTION OPTIMAL:  {}'.format(solver.OPTIMAL))         print('VALUE OF BASKET:   {}'.format(np.dot(A_eq[0], solution_set)))         print('SOLUTION   (apples,pears,oranges): {!r}'.format(solution_set[-3:]))         print('PCT CHANGE (apples,pears,oranges): {!r}\n\n'.format([round(100*(x-y)/y,2) for x,y in zip(solution_set[-3:], holdings)]))          # Update holdings for the next day         holdings = solution_set[-3:] 

A single run of this gives

DAY: 1 ====== SOLUTION FEASIBLE: 1 SOLUTION OPTIMAL:  0 VALUE OF BASKET:   348.0 SOLUTION   (apples,pears,oranges): [33.0, 79.0, 9.0] PCT CHANGE (apples,pears,oranges): [65.0, 83.72, -75.68]   DAY: 2 ====== SOLUTION FEASIBLE: 1 SOLUTION OPTIMAL:  0 VALUE OF BASKET:   251.0 SOLUTION   (apples,pears,oranges): [49.0, 83.0, 9.0] PCT CHANGE (apples,pears,oranges): [48.48, 5.06, 0.0]   DAY: 3 ====== SOLUTION FEASIBLE: 1 SOLUTION OPTIMAL:  0 VALUE OF BASKET:   213.0 SOLUTION   (apples,pears,oranges): [51.0, 63.0, 12.0] PCT CHANGE (apples,pears,oranges): [4.08, -24.1, 33.33] 

Summary

The l1 formulation gives more sensible results, lower turnover, much lower. The optimality check fails on all runs, however, which is concerning. I included a linear solver too and that fails the feasiblity check somehow, I don't know why. The Google people provide precious little documentation for the ortools lib, and most of it is for the C++ lib. But the l1 formulation may be a solution to your problem, which may scale. ILP is in general NP-complete, and so is your problem most likely.

Also - does a solution exist on day 2? How do you define % change so that it does in your chart above? If I knew I could recast the inequalities above and we would have the general solution.

Read More