3

I'm training myself over learning neural network. There is a function that I can't make my neural network learn: f(x) = max(x_1, x_2). It seems like a very simple function with 2 inputs and 1 input but yet a 3 layer neural network trained over a thousand sample with 2000 epochs get it completly wrong. I'm using deeplearning4j.

Is there any reason why the max function would be very hard to learn for a neural network or am I just tuning it wrong?

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
Atol
  • 569
  • 4
  • 12

2 Answers2

4

Just wanted to point out: If you use relu instead of tanh than there is actually an exact solution, and I guess if you would shrink down the network to this exact same size (1 hidden layer with 3 nodes), you would always end up with these weights (module permutations of nodes and scaling of weights (first layer scaled by gamma, second by 1/gamma)):

max(a,b) = ((1, 1, -1)) * relu( ((1,-1), (0,1), (0,-1)) * ((a,b)) )

where * is the matrix multiplication.

This equation translates the following human-readable version into NN-language:

max(a,b) = relu(a-b) + b = relu(a-b) + relu(b) - relu(-b)

I have not actually tested it, my point is, that it should theoretically be very easy for networks to learn this function.

EDIT: I just tested this and the result was as I expected it:

[[-1.0714666e+00 -7.9943770e-01  9.0549403e-01]
 [ 1.0714666e+00 -7.7552663e-08  2.6146751e-08]]

and

[[ 0.93330014]
 [-1.250879  ]
 [ 1.1043695 ]]

where the corresponding first and second layer. Transposing the second and multiplying with the first set of weights one ends up with a normalized version which can be compared to my theoretic results very easily:

[[-9.9999988e-01  9.9999988e-01  1.0000000e+00]
 [ 9.9999988e-01  9.7009000e-08  2.8875675e-08]]
David S.
  • 303
  • 2
  • 10
0

It isnt that hard, at least, if you restrict x1 and x2 to be within an interval, e.g. between [0,3]. Taken the "RegressionSum" example from the deeplearning4j examples I quickly rewrote it to learn max instead sum and it works quite ok giving me that results:

Max(0.6815540048808918,0.3112081053899819) = 0.64
Max(2.0073597506364407,1.93796211086664) = 2.09
Max(1.1792029272560556,2.5514324329058233) = 2.58
Max(2.489185375059013,0.0818746888836388) = 2.46
Max(2.658169689797984,1.419135581889197) = 2.66
Max(2.855509810112818,2.9661811672685086) = 2.98
Max(2.774757710538552,1.3988513143140069) = 2.79
Max(1.5852295273047565,1.1228662895771744) = 1.56
Max(0.8403435207065576,2.5595015474951195) = 2.60
Max(0.06913178775631723,2.61883825802004) = 2.54

Below is my modified Version of the RegressionSum example, which was originally from Anwar 3/15/16:

public class RegressionMax {
    //Random number generator seed, for reproducability
    public static final int seed = 12345;
    //Number of iterations per minibatch
    public static final int iterations = 1;
    //Number of epochs (full passes of the data)
    public static final int nEpochs = 200;
    //Number of data points
    public static final int nSamples = 10000;
    //Batch size: i.e., each epoch has nSamples/batchSize parameter updates
    public static final int batchSize = 100;
    //Network learning rate
    public static final double learningRate = 0.01;
    // The range of the sample data, data in range (0-1 is sensitive for NN, you can try other ranges and see how it effects the results
    // also try changing the range along with changing the activation function
    public static int MIN_RANGE = 0;
    public static int MAX_RANGE = 3;

    public static final Random rng = new Random(seed);

    public static void main(String[] args){

        //Generate the training data
        DataSetIterator iterator = getTrainingData(batchSize,rng);

        //Create the network
        int numInput = 2;
        int numOutputs = 1;
        int nHidden = 10;
        MultiLayerNetwork net = new MultiLayerNetwork(new NeuralNetConfiguration.Builder()
                .seed(seed)
                .iterations(iterations)
                .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
                .learningRate(learningRate)
                .weightInit(WeightInit.XAVIER)
                .updater(Updater.NESTEROVS).momentum(0.9)
                .list()
                .layer(0, new DenseLayer.Builder().nIn(numInput).nOut(nHidden)
                        .activation("tanh")
                        .build())
                .layer(1, new OutputLayer.Builder(LossFunctions.LossFunction.MSE)
                        .activation("identity")
                        .nIn(nHidden).nOut(numOutputs).build())
                .pretrain(false).backprop(true).build()
        );
        net.init();
        net.setListeners(new ScoreIterationListener(1));


        //Train the network on the full data set, and evaluate in periodically
        for( int i=0; i<nEpochs; i++ ){
            iterator.reset();
            net.fit(iterator);
        }

        // Test the max of some numbers (Try different numbers here)
        Random rand = new Random();
        for (int i= 0; i< 10; i++) {
            double d1 = MIN_RANGE + (MAX_RANGE - MIN_RANGE) * rand.nextDouble();
            double d2 =  MIN_RANGE + (MAX_RANGE - MIN_RANGE) * rand.nextDouble();
            INDArray input = Nd4j.create(new double[] { d1, d2 }, new int[] { 1, 2 });
            INDArray out = net.output(input, false);
            System.out.println("Max(" + d1 + "," + d2 + ") = " + out);
        }

    }

    private static DataSetIterator getTrainingData(int batchSize, Random rand){
        double [] max = new double[nSamples];
        double [] input1 = new double[nSamples];
        double [] input2 = new double[nSamples];
        for (int i= 0; i< nSamples; i++) {
            input1[i] = MIN_RANGE + (MAX_RANGE - MIN_RANGE) * rand.nextDouble();
            input2[i] =  MIN_RANGE + (MAX_RANGE - MIN_RANGE) * rand.nextDouble();
            max[i] = Math.max(input1[i], input2[i]);
        }
        INDArray inputNDArray1 = Nd4j.create(input1, new int[]{nSamples,1});
        INDArray inputNDArray2 = Nd4j.create(input2, new int[]{nSamples,1});
        INDArray inputNDArray = Nd4j.hstack(inputNDArray1,inputNDArray2);
        INDArray outPut = Nd4j.create(max, new int[]{nSamples, 1});
        DataSet dataSet = new DataSet(inputNDArray, outPut);
        List<DataSet> listDs = dataSet.asList();
        Collections.shuffle(listDs,rng);
        return new ListDataSetIterator(listDs,batchSize);

    }
}
Thomas Philipp
  • 266
  • 1
  • 5