Search code examples
neural-networktensorflowsigmoid

Teaching a fully connected feed-forward neural network XOR function


I'm trying to teach my multilayer neural network the XOR function. I have a network with architecture [2, 2, 1]. I define the loss as sum of square errors (I know it's not ideal, but I need it like that). If I set the activation function for all layers to be the sigmoid function, I always get stuck in the local optimum (somewhere around 0.25, all outputs are around 0.5). If I change the activation function of the hidden layer to ReLU, I sometimes get stuck in the same optimum, but sometimes I solve it. Could this be because I'm using the mean square error instead of cross entropy? Just in case, here's my code for the neural network:

import tensorflow as tf

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.5)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

class FCLayer():
    def __init__(self, inputs, outputs, activation):
        self.W = weight_variable([inputs, outputs])
        self.b = bias_variable([outputs])
        self.activation = activation

    def forward(self, X):
        s = tf.matmul(X, self.W) + self.b
        return self.activation(s)

class Network:
    def __init__(self, architecture, activations=None):

        self.layers = []

        for i in range(len(architecture)-1):
            self.layers.append(FCLayer(architecture[i], architecture[i+1],
                                       tf.nn.sigmoid if activations==None else activations[i]))

        self.x = tf.placeholder(tf.float32, shape=[None, architecture[0]])

        self.out = self.x
        for l in self.layers:
            self.out = l.forward(self.out)

        self.session = tf.Session();
        self.session.run(tf.initialize_all_variables())

    def train(self, X, Y_, lr, niter):

        y = tf.placeholder(tf.float32, shape=[None, Y_.shape[1]])
        loss = tf.reduce_mean((self.out - y)**2)
        #loss = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(self.out, y))

        train_step = tf.train.GradientDescentOptimizer(lr).minimize(loss)

        errs = [];
        for i in range(niter):
            train_step.run(feed_dict={self.x: X, y: Y_},session=self.session)
            errs.append(loss.eval(feed_dict={self.x: X, y: Y_},session=self.session))

        return errs;

    def predict(self, X):
        return self.out.eval(feed_dict={self.x: X}, session = self.session)

Update: I tried more complex architecture ([2,2,2,1]), but still no success.


Solution

  • Solved it, the learning rate of 0.1 was too small for some reason. I'm gonna say this problem is solved, I only had to increase the learning rate.