Showing posts with label neural-network. Show all posts
Showing posts with label neural-network. Show all posts

Saturday, May 5, 2018

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

Leave a Comment

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

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

OUTPUT:

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

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

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

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

Any help is appreciated.

0 Answers

Read More

Sunday, April 29, 2018

Getting same predicted values for all inputs in trained tensor flow network

Leave a Comment

I have created a tensorflow network designed to read data from this dataset (note: the information in this dataset is designed purely for test purposes and is not real):enter image description here and am trying to build a tensorflow network designed to essentially predict values in the 'Exited' column. My network is structured to take 11 inputs, pass through 2 hidden layers (6 neurons each) with relu activation, and output a single binary value using a sigmoid activation function in order to produce a probability distribution. I am using a gradient descent optimizer and a mean squared error cost function. However, after training the network on my training data and predicting off my testing data, all my predicted values are greater than 0.5 meaning likely to be true and I'm not sure what the problem is:

X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.2, random_state=101) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.fit_transform(X_test)  training_epochs = 200 n_input = 11 n_hidden_1 = 6 n_hidden_2 = 6 n_output = 1  def neuralNetwork(x, weights):      layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])      layer_1 = tf.nn.relu(layer_1)      layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])      layer_2 = tf.nn.relu(layer_2)      output_layer = tf.add(tf.matmul(layer_2, weights['output']), biases['output'])      output_layer = tf.nn.sigmoid(output_layer)      return output_layer  weights = {     'h1': tf.Variable(tf.random_uniform([n_input, n_hidden_1])),     'h2': tf.Variable(tf.random_uniform([n_hidden_1, n_hidden_2])),     'output': tf.Variable(tf.random_uniform([n_hidden_2, n_output])) }  biases = {     'b1': tf.Variable(tf.random_uniform([n_hidden_1])),     'b2': tf.Variable(tf.random_uniform([n_hidden_2])),     'output': tf.Variable(tf.random_uniform([n_output])) }  x = tf.placeholder('float', [None, n_input]) # [?, 11] y = tf.placeholder('float', [None, n_output]) # [?, 1]  output = neuralNetwork(x, weights) cost = tf.reduce_mean(tf.square(output - y)) optimizer = tf.train.AdamOptimizer().minimize(cost)  with tf.Session() as session:     session.run(tf.global_variables_initializer())     for epoch in range(training_epochs):         session.run(optimizer, feed_dict={x:X_train, y:y_train.reshape((-1,1))})     print('Model has completed training.')     test = session.run(output, feed_dict={x:X_test})     predictions = (test>0.5).astype(int)     print(predictions) 

All help is appreciated! I have been looking through questions related to my problem but none of the suggestions have seemed to help.

1 Answers

Answers 1

Initial assumption: I won't access data from a personal link for security reasons. It's your responsibility to create a reproducible code snippet based solely on secure/persistent artifacts.
However, I can confirm your problem happens when your code is ran against keras.datasets.mnist, with a small change: each sample is associated with a label 0: odd or 1: even.

Short answer: you messed up the initialization. Change tf.random_uniform to tf.random_normal and set biases to a deterministic 0.

Actual answer: ideally, you want the model to start predicting randomly, close to the 0.5. This will prevent the saturation of the sigmoid's output and result in large gradients in early stages of training.

The sigmoid's eq. is s(y) = 1/(1 + e**-y), and s(y) = 0.5 <=> y = 0. Therefore, the layer's output y = w * x + b must be 0.

If you used StandardScaler, then your input data follows a Gaussian distribution, mean = 0.5, std = 1.0. Your parameters must sustain this distribution! However, you've initialized your biases with tf.random_uniform, which uniformly draws values from the [0, 1) interval.

By starting your biases at 0, y will be close to 0:

y = w * x + b = sum(.1 * -1, .9 * -.9, ..., .1 * 1, .9 * .9) + 0 = 0 

So your biases should be:

biases = {     'b1': tf.Variable(tf.zeros([n_hidden_1])),     'b2': tf.Variable(tf.zeros([n_hidden_2])),     'output': tf.Variable(tf.zeros([n_output])) } 

This is sufficient to output numbers smaller than 0.5:

[1.        0.4492423 0.4492423 ... 0.4492423 0.4492423 1.       ] predictions mean: 0.7023628 confusion matrix: [[4370 1727]  [1932 3971]] accuracy: 0.6950833333333334 

Further corrections:

  • Your neuralNetwork function does not take a biases parameter. It instead uses the one defined in the other scope, which seems like a mistake.

  • You should not fit the scaler to the test data, because you will lose the statistics from train and because it violates the principle that that chunk of data is purely observational. Do this:

    scaler = StandardScaler() x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) 
  • It's very uncommon to use MSE with sigmoid output. Use binary cross-entropy instead:

    logits = tf.add(tf.matmul(layer_2, weights['output']), biases['output']) output = tf.nn.sigmoid(logits) cost = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits) 
  • It's more reliable to initialize the weights from a normal distribution:

    weights = {     'h1': tf.Variable(tf.random_uniform([n_input, n_hidden_1])),     'h2': tf.Variable(tf.random_uniform([n_hidden_1, n_hidden_2])),     'output': tf.Variable(tf.random_uniform([n_hidden_2, n_output])) } 
  • You are feeding the entire train dataset at each epoch, instead of batching it, which is the default in Keras. Therefore, it's reasonable to assume Keras implementation will converge faster and the results might differ.

By making a few teaks, I manage to achieve this results:

import tensorflow as tf from keras.datasets.mnist import load_data from sacred import Experiment from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler  ex = Experiment('test-16')   @ex.config def my_config():     training_epochs = 200     n_input = 784     n_hidden_1 = 32     n_hidden_2 = 32     n_output = 1   def neuralNetwork(x, weights, biases):     layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])     layer_1 = tf.nn.relu(layer_1)     layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])     layer_2 = tf.nn.relu(layer_2)     logits = tf.add(tf.matmul(layer_2, weights['output']), biases['output'])     predictions = tf.nn.sigmoid(logits)     return logits, predictions   @ex.automain def main(training_epochs, n_input, n_hidden_1, n_hidden_2, n_output):     (x_train, y_train), _ = load_data()     x_train = x_train.reshape(x_train.shape[0], -1).astype(float)     y_train = (y_train % 2 == 0).reshape(-1, 1).astype(float)      x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2, random_state=101)     print('y samples:', y_train, y_test, sep='\n')      scaler = StandardScaler()     x_train = scaler.fit_transform(x_train)     x_test = scaler.transform(x_test)      weights = {         'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),         'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),         'output': tf.Variable(tf.random_normal([n_hidden_2, n_output]))     }      biases = {         'b1': tf.Variable(tf.zeros([n_hidden_1])),         'b2': tf.Variable(tf.zeros([n_hidden_2])),         'output': tf.Variable(tf.zeros([n_output]))     }      x = tf.placeholder('float', [None, n_input])  # [?, 11]     y = tf.placeholder('float', [None, n_output])  # [?, 1]      logits, output = neuralNetwork(x, weights, biases)     # cost = tf.reduce_mean(tf.square(output - y))     cost = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits)     optimizer = tf.train.AdamOptimizer().minimize(cost)      with tf.Session() as session:         session.run(tf.global_variables_initializer())         try:             for epoch in range(training_epochs):                 print('epoch #%i' % epoch)                 session.run(optimizer, feed_dict={x: x_train, y: y_train})          except KeyboardInterrupt:             print('interrupted')          print('Model has completed training.')         p = session.run(output, feed_dict={x: x_test})         p_labels = (p > 0.5).astype(int)          print(p.ravel())         print('predictions mean:', p.mean())          print('confusion matrix:', confusion_matrix(y_test, p_labels), sep='\n')         print('accuracy:', accuracy_score(y_test, p_labels)) 
[0.        1.        0.        ... 0.0302309 0.        1.       ] predictions mean: 0.48261687 confusion matrix: [[5212  885]  [ 994 4909]] accuracy: 0.8434166666666667 
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

Friday, March 23, 2018

Implement early stopping in tf.estimator.DNNRegressor using the available training hooks

Leave a Comment

I am new to tensorflow and want to implement early stopping in tf.estimator.DNNRegressor with available training hooksTraining Hooks for the MNIST dataset. The early stopping hook will stop training if the loss does not improve for some specified number of steps. Tensorflow documentaton only provides example for Logging hooks. Can someone write a code snippet for implementing it?

1 Answers

Answers 1

Here is a EarlyStoppingHook sample implementation:

import numpy as np import tensorflow as tf import logging from tensorflow.python.training import session_run_hook   class EarlyStoppingHook(session_run_hook.SessionRunHook):     """Hook that requests stop at a specified step."""      def __init__(self, monitor='val_loss', min_delta=0, patience=0,                  mode='auto'):         """         """         self.monitor = monitor         self.patience = patience         self.min_delta = min_delta         self.wait = 0         if mode not in ['auto', 'min', 'max']:             logging.warning('EarlyStopping mode %s is unknown, '                             'fallback to auto mode.', mode, RuntimeWarning)             mode = 'auto'          if mode == 'min':             self.monitor_op = np.less         elif mode == 'max':             self.monitor_op = np.greater         else:             if 'acc' in self.monitor:                 self.monitor_op = np.greater             else:                 self.monitor_op = np.less          if self.monitor_op == np.greater:             self.min_delta *= 1         else:             self.min_delta *= -1          self.best = np.Inf if self.monitor_op == np.less else -np.Inf      def begin(self):         # Convert names to tensors if given         graph = tf.get_default_graph()         self.monitor = graph.as_graph_element(self.monitor)         if isinstance(self.monitor, tf.Operation):             self.monitor = self.monitor.outputs[0]      def before_run(self, run_context):  # pylint: disable=unused-argument         return session_run_hook.SessionRunArgs(self.monitor)      def after_run(self, run_context, run_values):         current = run_values.results          if self.monitor_op(current - self.min_delta, self.best):             self.best = current             self.wait = 0         else:             self.wait += 1             if self.wait >= self.patience:                 run_context.request_stop() 

This implementation is based on Keras implementation.

To use it with CNN MNIST example create hook and pass it to train.

early_stopping_hook = EarlyStoppingHook(monitor='sparse_softmax_cross_entropy_loss/value', patience=10)  mnist_classifier.train(   input_fn=train_input_fn,   steps=20000,   hooks=[logging_hook, early_stopping_hook]) 

Here sparse_softmax_cross_entropy_loss/value is the name of the loss op in that example.

EDIT 1:

It looks like there is no "official" way of finding loss node when using estimators (or I can't find it).

For the DNNRegressor this node has name dnn/head/weighted_loss/Sum.

Here is how to find it in the graph:

  1. Start tensorboard in model directory. In my case I didn't set any directory so estimator used temporary directory and printed this line:
    WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpInj8SC
    Start tensorboard:

    tensorboard --logdir /tmp/tmpInj8SC 
  2. Open it in browser and navigate to GRAPHS tab. enter image description here

  3. Find loss in the graph. Expand blocks in the sequence: dnn → head → weighted_loss and click on the Sum node (note that there is summary node named loss connected to it). enter image description here

  4. Name shown in the info "window" to the right is the name of the selected node, that need to be passed to monitor argument pf EarlyStoppingHook.

Loss node of the DNNClassifier has the same name by default. Both DNNClassifier and DNNRegressor have optional argument loss_reduction that influences loss node name and behavior (defaults to losses.Reduction.SUM).

EDIT 2:

There is a way of finding loss without looking at the graph.
You can use GraphKeys.LOSSES collection to get the loss. But this way will work only after training started. So you can use it only in a hook.

For example you can remove monitor argument from the EarlyStoppingHook class and change its begin function to always use the first loss in the collection:

self.monitor = tf.get_default_graph().get_collection(tf.GraphKeys.LOSSES)[0] 

You also probably need to check that there is a loss in the collection.

Read More

Monday, February 5, 2018

Tensorflow can't detect GPU when invoked by Ray worker

Leave a Comment

When I try the following code sample for using Tensorflow with Ray, Tensorflow fails to detect the GPU's on my machine when invoked by the "remote" worker but it does find the GPU's when invoked "locally". I put "remote" and "locally" in scare quotes because everything is running on my desktop which has two GPU's and is running Ubuntu 16.04 and I installed Tensorflow using the tensorflow-gpu Anaconda package.

The local_network seems to be responsible for these messages in the logs:

2018-01-26 17:24:33.149634: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro M5000, pci bus id: 0000:03:00.0) 2018-01-26 17:24:33.149642: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Quadro M5000, pci bus id: 0000:04:00.0) 

And the remote_network seems to be responsible for this message:

2018-01-26 17:24:34.309270: E tensorflow/stream_executor/cuda/cuda_driver.cc:406] failed call to cuInit: CUDA_ERROR_NO_DEVICE 

Why is Tensorflow able to detect the GPU in one case but not the other?

import tensorflow as tf import numpy as np import ray  ray.init()  BATCH_SIZE = 100 NUM_BATCHES = 1 NUM_ITERS = 201  class Network(object):     def __init__(self, x, y):         # Seed TensorFlow to make the script deterministic.         tf.set_random_seed(0)         # Define the inputs.         x_data = tf.constant(x, dtype=tf.float32)         y_data = tf.constant(y, dtype=tf.float32)         # Define the weights and computation.         w = tf.Variable(tf.random_uniform([1], -1.0, 1.0))         b = tf.Variable(tf.zeros([1]))         y = w * x_data + b         # Define the loss.         self.loss = tf.reduce_mean(tf.square(y - y_data))         optimizer = tf.train.GradientDescentOptimizer(0.5)         self.grads = optimizer.compute_gradients(self.loss)         self.train = optimizer.apply_gradients(self.grads)         # Define the weight initializer and session.         init = tf.global_variables_initializer()         self.sess = tf.Session()         # Additional code for setting and getting the weights         self.variables = ray.experimental.TensorFlowVariables(self.loss, self.sess)         # Return all of the data needed to use the network.         self.sess.run(init)      # Define a remote function that trains the network for one step and returns the     # new weights.     def step(self, weights):         # Set the weights in the network.         self.variables.set_weights(weights)         # Do one step of training. We only need the actual gradients so we filter over the list.         actual_grads = self.sess.run([grad[0] for grad in self.grads])         return actual_grads      def get_weights(self):         return self.variables.get_weights()  # Define a remote function for generating fake data. @ray.remote(num_return_vals=2) def generate_fake_x_y_data(num_data, seed=0):     # Seed numpy to make the script deterministic.     np.random.seed(seed)     x = np.random.rand(num_data)     y = x * 0.1 + 0.3     return x, y  # Generate some training data. batch_ids = [generate_fake_x_y_data.remote(BATCH_SIZE, seed=i) for i in range(NUM_BATCHES)] x_ids = [x_id for x_id, y_id in batch_ids] y_ids = [y_id for x_id, y_id in batch_ids] # Generate some test data. x_test, y_test = ray.get(generate_fake_x_y_data.remote(BATCH_SIZE, seed=NUM_BATCHES))  # Create actors to store the networks. remote_network = ray.remote(Network) actor_list = [remote_network.remote(x_ids[i], y_ids[i]) for i in range(NUM_BATCHES)] local_network = Network(x_test, y_test)  # Get initial weights of local network. weights = local_network.get_weights()  # Do some steps of training. for iteration in range(NUM_ITERS):     # Put the weights in the object store. This is optional. We could instead pass     # the variable weights directly into step.remote, in which case it would be     # placed in the object store under the hood. However, in that case multiple     # copies of the weights would be put in the object store, so this approach is     # more efficient.     weights_id = ray.put(weights)     # Call the remote function multiple times in parallel.     gradients_ids = [actor.step.remote(weights_id) for actor in actor_list]     # Get all of the weights.     gradients_list = ray.get(gradients_ids)      # Take the mean of the different gradients. Each element of gradients_list is a list     # of gradients, and we want to take the mean of each one.     mean_grads = [sum([gradients[i] for gradients in gradients_list]) / len(gradients_list) for i in range(len(gradients_list[0]))]      feed_dict = {grad[0]: mean_grad for (grad, mean_grad) in zip(local_network.grads, mean_grads)}     local_network.sess.run(local_network.train, feed_dict=feed_dict)     weights = local_network.get_weights()      # Print the current weights. They should converge to roughly to the values 0.1     # and 0.3 used in generate_fake_x_y_data.     if iteration % 20 == 0:         print("Iteration {}: weights are {}".format(iteration, weights)) 

1 Answers

Answers 1

The GPUs are cut off by ray.remote decorator itself. From its source code:

def remote(*args, **kwargs):     ...     num_cpus = kwargs["num_cpus"] if "num_cpus" in kwargs else 1     num_gpus = kwargs["num_gpus"] if "num_gpus" in kwargs else 0  # !!!     ... 

So the following call effectively sets num_gpus=0:

remote_network = ray.remote(Network) 

Ray API is a bit strange, and you can't simply say ray.remote(Network, num_gpus=2) (though that's exactly what you want). Here's what I did and it seems to work on my machine:

ray.init(num_gpus=2)  ...  @ray.remote(num_gpus=2) class RemoteNetwork(Network):     pass  actor_list = [RemoteNetwork.remote(x_ids[i],y_ids[i]) for i in range(NUM_BATCHES)] 
Read More

Saturday, November 25, 2017

Modify neural net to classify single example

Leave a Comment

This is my custom extension of one of Andrew NG's neural network from deep learning course where instead of producing 0 or 1 for binary classification I'm attempting to classify multiple examples.

Both the inputs and outputs are one hot encoded.

With not much training I receive an accuracy of 'train accuracy: 67.51658067499625 %'

How can I classify a single training example instead of classifying all training examples?

I think a bug exists in my implementation as an issue with this network is training examples (train_set_x) and output values (train_set_y) both need to have same dimensions or an error related to the dimensionality of matrices is received. For example using :

train_set_x = np.array([     [1,1,1,1],[0,1,1,1],[0,0,1,1] ])  train_set_y = np.array([     [1,1,1],[1,1,0],[1,1,1] ]) 

returns error :

ValueError                                Traceback (most recent call last) <ipython-input-11-0d356e8d66f3> in <module>()      27 print(A)      28  ---> 29 np.multiply(train_set_y,A)      30       31 def initialize_with_zeros(numberOfTrainingExamples): 

ValueError: operands could not be broadcast together with shapes (3,3) (1,4)

network code :

import numpy as np import matplotlib.pyplot as plt import h5py import scipy from scipy import ndimage import pandas as pd %matplotlib inline  train_set_x = np.array([     [1,1,1,1],[0,1,1,1],[0,0,1,1] ])  train_set_y = np.array([     [1,1,1,0],[1,1,0,0],[1,1,1,1] ])  numberOfFeatures = 4 numberOfTrainingExamples = 3  def sigmoid(z):     s = 1 / (1 + np.exp(-z))       return s  w = np.zeros((numberOfTrainingExamples , 1)) b = 0 A = sigmoid(np.dot(w.T , train_set_x))     print(A)  np.multiply(train_set_y,A)  def initialize_with_zeros(numberOfTrainingExamples):     w = np.zeros((numberOfTrainingExamples , 1))     b = 0     return w, b  def propagate(w, b, X, Y):      m = X.shape[1]      A = sigmoid(np.dot(w.T , X) + b)          cost = -(1/m)*np.sum(np.multiply(Y,np.log(A)) + np.multiply((1-Y),np.log(1-A)), axis=1)      dw =  ( 1 / m ) *   np.dot( X, ( A - Y ).T )    # consumes ( A - Y )     db =  ( 1 / m ) *   np.sum( A - Y )    # consumes ( A - Y ) again  #     cost = np.squeeze(cost)      grads = {"dw": dw,              "db": db}      return grads, cost  def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = True):      costs = []      for i in range(num_iterations):          grads, cost = propagate(w, b, X, Y)          dw = grads["dw"]         db = grads["db"]          w = w - (learning_rate * dw)         b = b - (learning_rate * db)          if i % 100 == 0:             costs.append(cost)          if print_cost and i % 10000 == 0:             print(cost)      params = {"w": w,               "b": b}      grads = {"dw": dw,              "db": db}      return params, grads, costs  def model(X_train, Y_train, num_iterations, learning_rate = 0.5, print_cost = False):      w, b = initialize_with_zeros(numberOfTrainingExamples)      parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost = True)     w = parameters["w"]     b = parameters["b"]     Y_prediction_train = sigmoid(np.dot(w.T , X_train) + b)       print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))  model(train_set_x, train_set_y, num_iterations = 20000, learning_rate = 0.0001, print_cost = True) 

Update: A bug exists in this implementation in that the training example pairs (train_set_x , train_set_y) must contain the same dimensions. Can point in direction of how linear algebra should be modified?

Update 2 :

I modified @Paul Panzer answer so that learning rate is 0.001 and train_set_x , train_set_y pairs are unique :

train_set_x = np.array([     [1,1,1,1,1],[0,1,1,1,1],[0,0,1,1,0],[0,0,1,0,1] ])  train_set_y = np.array([     [1,0,0],[0,0,1],[0,1,0],[1,0,1] ])  grads = model(train_set_x, train_set_y, num_iterations = 20000, learning_rate = 0.001, print_cost = True)  # To classify single training example :   print(sigmoid(dw @ [0,0,1,1,0] + db)) 

This update produces following output :

-2.09657359028 -3.94918577439 [[ 0.74043089  0.32851512  0.14776077  0.77970162]  [ 0.04810012  0.08033521  0.72846174  0.1063849 ]  [ 0.25956911  0.67148488  0.22029838  0.85223923]] [[1 0 0 1]  [0 0 1 0]  [0 1 0 1]] train accuracy: 79.84462279013312 % [[ 0.51309252  0.48853845  0.50945862]  [ 0.5110232   0.48646923  0.50738869]  [ 0.51354109  0.48898712  0.50990734]] 

Should print(sigmoid(dw @ [0,0,1,1,0] + db)) produce a vector that once rounded matches train_set_y corresponding value : [0,1,0] ?

Modifying to produce a vector with (adding [0,0,1,1,0] to numpy array and taking transpose):

print(sigmoid(dw @ np.array([[0,0,1,1,0]]).T + db)) 

returns :

array([[ 0.51309252],        [ 0.48646923],        [ 0.50990734]]) 

Again, rounding these values to nearest whole number produces vector [1,0,1] when [0,1,0] is expected.

These are incorrect operations to produce a prediction for single training example ?

3 Answers

Answers 1

Your difficulties come from mismatched dimensions, so let's walk through the problem and try and get them straight.

Your network has a number of inputs, the features, let's call their number N_in (numberOfFeatures in your code). And it has a number of outputs which correspond to different classes let's call their number N_out. Inputs and outputs are connected by the weights w.

Now here is the problem. Connections are all-to-all, so we need a weight for each of the N_out x N_in pairs of outputs and inputs. Therefore in your code the shape of w must be changed to (N_out, N_in). You probably also want an offset b for each output, so b should be a vector of size (N_out,) or rather (N_out, 1) so it plays well with the 2d terms.

I've fixed that in the modified code below and I tried to make it very explicit. I've also thrown a mock data creator into the bargain.

Re the one-hot encoded categorical output, I'm not an expert on neural networks but I think, most people understand it so that classes are mutually exclusive, so each sample in your mock output should have one one and the rest zeros.

Side note:

At one point a competing answer advised you to get rid of the 1-... terms in the cost function. While that looks like an interesting idea to me my gut feeling (Edit Now confirmed using gradient-free minimizer; use activation="hybrid" in code below. Solver will simply maximize all outputs which are active in at least one training example.) is it won't work just like that because the cost will then fail to penalise false positives (see below for detailed explanation). To make it work you'd have to add some kind of regularization. One method that appears to work is using the softmax instead of the sigmoid. The softmax is to one-hot what the sigmoid is to binary. It makes sure the output is "fuzzy one-hot".

Therefore my recommendation is:

  • If you want to stick with sigmoid and not explicitly enforce one-hot predictions. Keep the 1-... term.
  • If you want to use the shorter cost function. Enforce one-hot predictions. For example by using softmax instead of sigmoid.

I've added an activation="sigmoid"|"softmax"|"hybrid" parameter to the code that switches between models. I've also made the scipy general purpose minimizer available, which may be useful when the gradient of the cost is not at hand.

Recap on how the cost function works:

The cost is a sum over all classes and all training samples of the term

-y log (y') - (1-y) log (1-y') 

where y is the expected response, i.e. the one given by the "y" training sample for the input (the "x" training sample). y' is the prediction, the response the network with its current weights and biases generates. Now, because the expected response is either 0 or 1 the cost for a single category and a single training sample can be written

-log (y')   if   y = 1 -log(1-y')  if   y = 0 

because in the first case (1-y) is zero, so the second term vanishes and in the secondo case y is zero, so the first term vanishes. One can now convince oneself that the cost is high if

  • the expected response y is 1 and the network prediction y' is close to zero
  • the expected response y is 0 and the network prediction y' is close to one

In other words the cost does its job in punishing wrong predictions. Now, if we drop the second term (1-y) log (1-y') half of this mechanism is gone. If the expected response is 1, a low prediction will still incur a cost, but if the expected response is 0, the cost will be zero, regardless of the prediction, in particular, a high prediction (or false positive) will go unpunished.

Now, because the total cost is a sum over all training samples, there are three possibilities.

  • all training samples prescribe that the class be zero: then the cost will be completely independent of the predictions for this class and no learning can take place

  • some training samples put the class at zero, some at one: then because "false negatives" or "misses" are still punished but false positives aren't the net will find the easiest way to minimize the cost which is to indiscriminately increase the prediction of the class for all samples

  • all training samples prescribe that the class be one: essentially the same as in the second scenario will happen, only here it's no problem, because that is the correct behavior

And finally, why does it work if we use softmax instead of sigmoid? False positives will still be invisible. Now it is easy to see that the sum over all classes of the softmax is one. So I can only increase the prediction for one class if at least one other class is reduced to compensate. In particular, there can be no false positives without a false negative, and the false negative the cost will detect.

import numpy as np from scipy import optimize as opt from collections import namedtuple  # First, a few structures to keep ourselves organized  Problem_Size = namedtuple('Problem_Size', 'Out In Samples') Data = namedtuple('Data', 'Out In') Network = namedtuple('Network', 'w b activation cost gradient')  def get_dims(Out, In, transpose=False):     """extract dimensions and ensure everything is 2d     return Data, Dims"""     # gracefully acccept lists etc.     Out, In = np.asanyarray(Out), np.asanyarray(In)     if transpose:         Out, In = Out.T, In.T     # if it's a single sample make sure it's n x 1     Out = Out[:, None] if len(Out.shape) == 1 else Out     In = In[:, None] if len(In.shape) == 1 else In     Dims = Problem_Size(Out.shape[0], *In.shape)     if Dims.Samples != Out.shape[1]:         raise ValueError("number of samples must be the same for Out and In")     return Data(Out, In), Dims   def sigmoid(z):     s = 1 / (1 + np.exp(-z))       return s  def sig_cost(Net, data):     A = process(data.In, Net)     logA = np.log(A)     return -(data.Out * logA + (1-data.Out) * (1-logA)).sum(axis=0).mean()  def sig_grad (Net, Dims, data):     A = process(data.In, Net)     return dict(dw =  (A - data.Out) @ data.In.T / Dims.Samples,                 db =  (A - data.Out).mean(axis=1, keepdims=True))  def softmax(z):     z = z - z.max(axis=0, keepdims=True)     z = np.exp(z)     return z / z.sum(axis=0, keepdims=True)  def sof_cost(Net, data):     A = process(data.In, Net)     logA = np.log(A)     return -(data.Out * logA).sum(axis=0).mean()  sof_grad = sig_grad  def get_net(Dims, activation='softmax'):     activation, cost, gradient = {         'sigmoid': (sigmoid, sig_cost, sig_grad),         'softmax': (softmax, sof_cost, sof_grad),         'hybrid': (sigmoid, sof_cost, None)}[activation]     return Network(w=np.zeros((Dims.Out, Dims.In)),                    b=np.zeros((Dims.Out, 1)),                    activation=activation, cost=cost, gradient=gradient)  def process(In, Net):     return Net.activation(Net.w @ In + Net.b)  def propagate(data, Dims, Net):     return Net.gradient(Net, Dims, data), Net.cost(Net, data)  def optimize_no_grad(Net, Dims, data):     def f(x):         Net.w[...] = x[:Net.w.size].reshape(Net.w.shape)         Net.b[...] = x[Net.w.size:].reshape(Net.b.shape)         return Net.cost(Net, data)     x = np.r_[Net.w.ravel(), Net.b.ravel()]     res = opt.minimize(f, x, options=dict(maxiter=10000)).x     Net.w[...] = res[:Net.w.size].reshape(Net.w.shape)     Net.b[...] = res[Net.w.size:].reshape(Net.b.shape)  def optimize(Net, Dims, data, num_iterations, learning_rate, print_cost = True):      w, b = Net.w, Net.b     costs = []      for i in range(num_iterations):          grads, cost = propagate(data, Dims, Net)          dw = grads["dw"]         db = grads["db"]          w -= learning_rate * dw         b -= learning_rate * db          if i % 100 == 0:             costs.append(cost)          if print_cost and i % 10000 == 0:             print(cost)      return grads, costs  def model(X_train, Y_train, num_iterations, learning_rate = 0.5, print_cost = False, activation='sigmoid'):      data, Dims = get_dims(Y_train, X_train, transpose=True)     Net = get_net(Dims, activation)      if Net.gradient is None:         optimize_no_grad(Net, Dims, data)     else:         grads, costs = optimize(Net, Dims, data, num_iterations, learning_rate, print_cost = True)      Y_prediction_train = process(data.In, Net)      print(Y_prediction_train)     print(data.Out)     print(Y_prediction_train.sum(axis=0))     print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - data.Out)) * 100))  def create_data(Dims):     Out = np.zeros((Dims.Out, Dims.Samples), dtype=int)     Out[np.random.randint(0, Dims.Out, (Dims.Samples,)), np.arange(Dims.Samples)] = 1     In = np.random.randint(0, 2, (Dims.In, Dims.Samples))     return Data(Out, In)  train_set_x = np.array([     [1,1,1,1,1],[0,1,1,1,1],[0,0,1,1,0],[0,0,1,0,1] ])  train_set_y = np.array([     [1,0,0],[1,0,0],[0,0,1],[0,0,1] ])  model(train_set_x, train_set_y, num_iterations = 20000, learning_rate = 0.001, print_cost = True, activation='sigmoid')  model(train_set_x, train_set_y, num_iterations = 20000, learning_rate = 0.001, print_cost = True, activation='softmax')  model(train_set_x, train_set_y, num_iterations = 20000, learning_rate = 0.001, print_cost = True, activation='hybrid')  Dims = Problem_Size(8, 100, 50) data = create_data(Dims) model(data.In.T, data.Out.T, num_iterations = 40000, learning_rate = 0.001, print_cost = True, activation='softmax')  model(data.In.T, data.Out.T, num_iterations = 40000, learning_rate = 0.001, print_cost = True, activation='sigmoid')  

Answers 2

Both the idea of how to fix the bug and how you can extend the implementation to classify between more classes can be solved with some dimensionality analysis.

I am assuming that you by classifying multiple examples mean multiple classes and not multiple samples, as we need multiple samples to train even for 2 classes.

Where N = number of samples, D = number of features, K = number of categories(with K=2 being a special case where one can reduce this down to one dimension,ie K=1 with y=0 signifying one class and y=1 the other). The data should have the following dimensions:

X: N * D #input y: N * K #output  W: D * K #weights, also dW has same dimensions b: 1 * K #bias, also db has same dimensions #A should have same dimensions as y 

The order of the dimensions can be switched around, as long as the dot products are done correctly.

  • First dealing with your bug: You are initializing W as N * K instead of D * K ie. in the binary case:

    w = np.zeros((numberOfTrainingExamples , 1)) #instead of  w = np.zeros((numberOfFeatures , 1)) 

    This means that the only time you are initializing W to correct dimensions is when y and X (coincidentally) have same dimensions.

    This will mess with your dot products as well:

    np.dot(X, w) # or np.dot(w.T,X.T) if you define y as [K * N] dimensions #instead of  np.dot(w.T , X)  

    and

    np.dot( X.T, ( A - Y ) ) #np.dot( X.T, ( A - Y ).T ) if y:[K * N] #instead of np.dot( X, ( A - Y ).T )   

    Also make sure that the cost function returns one number (ie. not an array).

  • Secondly going on to K>2 you need to make some changes. b is no longer a single number, but a vector (1D-array). y and W go from being 1D-array to 2D array. To avoid confusion and hard-to-find bugs it could be good to set K, N and D to different values

Answers 3

The shape of A is (1,4), while the shape of train_set_y is (3,3).

You can't element-wise multiply two matrices that don't share a common shape on one of the axis.

Try to make train_set_y to be of a shape that would match the shape of A. For example:

train_set_y = np.array([     [1,1,1,0], [1,1,0,0], [1,1,1,1], [0,0,0,0] ]) 
Read More

Wednesday, September 6, 2017

What's wrong with my implementation of Neural Networks?

Leave a Comment

enter image description hereI want to plot the learning error curve of a neural net with respect to the number of training examples. Here is the code :

import sklearn import numpy as np from sklearn.model_selection import learning_curve import matplotlib.pyplot as plt from sklearn import neural_network from sklearn import cross_validation  myList=[] myList2=[] w=[]  dataset=np.loadtxt("data", delimiter=",") X=dataset[:, 0:6] Y=dataset[:,6] clf=sklearn.neural_network.MLPClassifier(hidden_layer_sizes=(2,3),activation='tanh')  # split the data between training and testing X_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X, Y, test_size=0.25, random_state=33)  # begin with few training datas X_eff=X_train[0:int(len(X_train)/150), : ] Y_eff=Y_train[0:int(len(Y_train)/150)]  k=int(len(X_train)/150)-1   for m in range (140) :       print (m)      w.append(k)      # train the model and store the training error     A=clf.fit(X_eff,Y_eff)     myList.append(1-A.score(X_eff,Y_eff))        # compute the testing error     myList2.append(1-A.score(X_test,Y_test))      # add some more training datas     X_eff=np.vstack((X_eff,X_train[k+1:k+101,:]))     Y_eff=np.hstack((Y_eff,Y_train[k+1:k+101]))     k=k+100  plt.figure(figsize=(8, 8)) plt.subplots_adjust() plt.title("Erreur d'entrainement et de test") plt.plot(w,myList,label="training error") plt.plot(w,myList2,label="test error") plt.legend() plt.show() 

However, I get a very strange result, with curves fluctuating, the training error very close to the testing error which does not appear to be normal. Where is the mistake? I can't understand why there are so many ups and downs and why the training error does not increase, as it would be expected to.Any help would be appreciated !

EDIT : the dataset I am using is https://archive.ics.uci.edu/ml/datasets/Chess+%28King-Rook+vs.+King%29 where I got rid of the classes having less than 1000 instances. I manually re-encoded the litteral data.

3 Answers

Answers 1

I think that the reason you're seeing this kind of curve is that the performance metric you are measuring is different from the performance metric that you are optimizing.

Optimization metric

The neural network minimizes a loss function, and in the case of tanh activiations, I assume you are using a modified version of the cross entropy loss. If you were to plot the loss over time, you would see a more monotonically decreasing error function like you expect. (Not actually monotonic because neural networks are non-convex, but that's beside the point.)

Performance metric

The performance metric that you are measuring is the percent accuracy, which is different from the loss. Why are these different? The loss function tells us how much error we have in a differentiable way (which is important for fast optimization methods). The accuracy metric tells us how well we predict, which is useful for application of the neural network.

Putting it together

Because you are plotting the performance of a related metric, you can expect that the plot will look similar to that of your optimized metric. However because they are not the same, you may be introducing some unaccounted-for variance in your plot (as evidenced by the plot you posted).

There are a couple of ways to fix this.

  1. Plot the loss instead of the accuracy. This doesn't actually fix your problem if you actually need the accuracy plot, but it will give you much more smooth curves.
  2. Plot an average over multiple runs. Save the accuracy plots over 20 independent runs of your algorithm (as in train the network 20 times), then average them together and plot this. That will greatly reduce the variance.

TL;DR

Don't expect the accuracy plot to always be smooth and monotonically decreasing, it won't be.

Answers 2

Randomize training set and repeat

If you would like a fair comparison of the effect of the number of training sample on the accuracy, I suggest to randomly pick n_samples from your training set instead of adding 100 samples to the previous batch. You would also repeat the fit N_repeat times for each n_samples value.

This would give something like this (not tested):

n_samples_array = np.arange(100,len(X_train),100) N_repeat = 10  for n_samples in n_samples_array:     print(n_samples)      # repeat the fit several times and take the mean     myList_tmp, myList2_tmp = [],[]     for repeat in range(0,N_repeat):         # Randomly pick samples         selection = np.random.choice(range(0,len(X_train)),n_samples,repeat=False)          # train the model and store the training error         A=clf.fit(X_train[selection],Y_train[selection])         myList_tmp.append(1-A.score(X_train[selection],Y_train[selection]))            # compute the testing error         myList2_tmp.append(1-A.score(X_test,Y_test))      myList.append(np.mean(myList_tmp))     myList2.append(np.mean(myList2_tmp)) 

Warm start

When you use the fit function, you restart the optimization from scratch. If you would like to see the improvement on your optimization when adding a few sample to the same previously trained network, you can use the option warm_start=True

As per the documentation:

warm_start : bool, optional, default False

When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution.

Answers 3

In addition to the previous answers you should also have in mind, that you might have to tweak the learning rate (by setting learning_rate = value in the initializer) of the network. If you choose the rate to big, you will jump from on local minimum to another or circle around these points, but won't actually converge (see the image below, taken from here).

Furthermore, please also plot the loss and not just the accuracy of your network. This will give you better insights about it.

Also, keep in mind, that you have to use a lot of training and test data to get a more or less "smooth" curve, or even a representative curve; if you are using just a few (maybe a few hundred) data points, the resulting metrics will not actually be very accurate, as they contain a lot of stochastic things. To solve this error you should not train the network with the same examples every time, but rather change the orders of your training data, and maybe split it up on different mini batches. I am very confident, that you can solve or even reduce your problem by trying to mind these aspects and to implement them.

Depending on your kind of problem, you should change the activation function to something different than the tanh function. Performing a classification, a OneHotEncoder might also be useful (if your data is not already one hot encoded); the sklearn framework is offering an implementation of this, too.

Read More

Saturday, July 29, 2017

Why can't I display prediction column of Spark MultilayerPerceptronClassifier?

Leave a Comment

I am using Spark's MultilayerPerceptronClassifier. This generates a column 'predicted' in 'predictions'. When I try to show it I get the error:

SparkException: Failed to execute user defined function($anonfun$1: (vector) => double) ... Caused by: java.lang.IllegalArgumentException: requirement failed: A & B Dimension mismatch! 

Other columns, for example, vector display OK. Part of predictions schema:

|-- vector: vector (nullable = true) |-- prediction: double (nullable = true) 

My code is:

//racist is boolean, needs to be string: val train2 = train.withColumn("racist", 'racist.cast("String")) val test2 = test.withColumn("racist", 'racist.cast("String"))  val indexer = new StringIndexer().setInputCol("racist").setOutputCol("indexracist")  val word2Vec = new Word2Vec().setInputCol("lemma").setOutputCol("vector") //.setVectorSize(3).setMinCount(0)  val layers = Array[Int](4,5, 2)  val mpc = new MultilayerPerceptronClassifier().setLayers(layers).setBlockSize(128).setSeed(1234L).setMaxIter(100).setFeaturesCol("vector").setLabelCol("indexracist")  val pipeline = new Pipeline().setStages(Array(indexer, word2Vec, mpc))  val model = pipeline.fit(train2)  val predictions = model.transform(test2)  predictions.select("prediction").show() 

EDIT the proposed similar question's problem was

val layers = Array[Int](0, 0, 0, 0)  

which is not the case here, nor is it the same error.

EDIT AGAIN: part0 of train and test are saved in PARQUET format here.

1 Answers

Answers 1

The addition of .setVectorSize(3).setMinCount(0) and changnig val layers = Array[Int](3,5, 2) made it work:

val word2Vec = new Word2Vec().setInputCol("lemma").setOutputCol("vector").setVectorSize(3).setMinCount(0)  // specify layers for the neural network: // input layer of size 4 (features), two intermediate of size 5 and 4 // and output of size 3 (classes) val layers = Array[Int](3,5, 2) 
Read More

Friday, June 9, 2017

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

Leave a Comment

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

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

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

2 Answers

Answers 1

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

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

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

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

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

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

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

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

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

Here, optimize might be defined something like:

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

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

Answers 2

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

You could simply sum all the information on 1 day?

For example: enter image description here

you could have:

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

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

Read More

Tuesday, April 11, 2017

How does asynchronous training work in distributed Tensorflow?

Leave a Comment

I've read Distributed Tensorflow Doc, and it mentions that in asynchronous training,

each replica of the graph has an independent training loop that executes without coordination.

From what I understand, if we use parameter-server with data parallelism architecture, it means each worker computes gradients and updates its own weights without caring about other workers updates for distributed training Neural Network. As all weights are shared on parameter server (ps), I think ps still has to coordinate (or aggregate) weight updates from all workers in some way. I wonder how does the aggregation work in asynchronous training. Or in more general words, how does asynchronous training work in distributed Tensorflow?

3 Answers

Answers 1

Looking at the example in the documentation you link to:

with tf.device("/job:ps/task:0"):   weights_1 = tf.Variable(...)   biases_1 = tf.Variable(...)  with tf.device("/job:ps/task:1"):   weights_2 = tf.Variable(...)   biases_2 = tf.Variable(...)  with tf.device("/job:worker/task:7"):   input, labels = ...   layer_1 = tf.nn.relu(tf.matmul(input, weights_1) + biases_1)   logits = tf.nn.relu(tf.matmul(layer_1, weights_2) + biases_2)   # ...   train_op = ...  with tf.Session("grpc://worker7.example.com:2222") as sess:   for _ in range(10000):     sess.run(train_op) 

You can see that the training is distributed on three machines which all share a copy of identical weights, but as is mentioned just below the example:

In the above example, the variables are created on two tasks in the ps job, and the compute-intensive part of the model is created in the worker job. TensorFlow will insert the appropriate data transfers between the jobs (from ps to worker for the forward pass, and from worker to ps for applying gradients).

In other words, one gpu is used to calculate the forward pass and then transmits the results to the other two machines, while each of the other machines calculate the back propagation for a part of the weights and then send the results to the other machines so they can all update their weights appropriately.

GPUs are used to speed up matrix multiplications and parallel mathematical operations which are very intensive for both forward pass and back propagation. So distributed training simply means that you distribute these operations on many GPUs, the model is still synced between the machines, but now the back propagation of different weights can be calculated in parallel and the forward pass on a different mini-batch can be calculated at the same time as backprop from the previous mini-batch is still being calculated. Distributed training does not mean that you have totally independent models and weights on each machine.

Answers 2

In asynchronous training there is no synchronization of weights among the workers. The weights are stored on the parameter server. Each worker loads and changes the shared weights independently from each other. This way if one worker finished an iteration faster than the other workers, it proceeds with the next iteration without waiting. The workers only interact with the shared parameter server and don't interact with each other.

Overall it can (depending on the task) speedup the computation significantly. However the results are sometimes worse than the ones obtained with the slower synchronous updates.

Answers 3

When you train asynchronously in Distributed TensorFlow, a particular worker does the following:

  1. The worker reads all of the shared model parameters in parallel from the PS task(s), and copies them to the worker task. These reads are uncoordinated with any concurrent writes, and no locks are acquired: in particular the worker may see partial updates from one or more other workers (e.g. a subset of the updates from another worker may have been applied, or a subset of the elements in a variable may have been updated).

  2. The worker computes gradients locally, based on a batch of input data and the parameter values that it read in step 1.

  3. The worker sends the gradients for each variable to the appropriate PS task, and applies the gradients to their respective variable, using an update rule that is determined by the optimization algorithm (e.g. SGD, SGD with Momentum, Adagrad, Adam, etc.). The update rules typically use (approximately) commutative operations, so they may be applied independently on the updates from each worker, and the state of each variable will be a running aggregate of the sequence of updates received.

In asynchronous training, each update from the worker is applied concurrently, and the updates may be somewhat coordinated if the optional use_locking=True flag was set when the respective optimizer (e.g. tf.train.GradientDescentOptimizer) was initialized. Note however that the locking here only provides mutual exclusion for two concurrent updates, and (as noted above) reads do not acquire locks; the locking does not provide atomicity across the entire set of updates.

(By contrast, in synchronous training, a utility like tf.train.SyncReplicasOptimizer will ensure that all of the workers read the same, up-to-date values for each model parameter; and that all of the updates for a synchronous step are aggregated before they are applied to the underlying variables. To do this, the workers are synchronized by a barrier, which they enter after sending their gradient update, and leave after the aggregated update has been applied to all variables.)

Read More