Search code examples
pythontensorflowhiddenlayer

Trouble with adding an extra layer to neural net in Tensorflow


I'm trying to add a second hidden layer to my neural net, training on the MNIST dataset. With only a simple hidden layer the training works fine, and the accuracy increases steadily.

When I try to add the second layer, the accuracy gets stuck on 0.117 each time i start training. Just can't figure out what I'm doing wrong here?

I've tried adding sigmoid to my y with no luck.

XTrain = XTrain[0:10000,:]
YTrain = YTrain[0:10000]

K = len(set(YTrain))
N = len(YTrain)
M = 12 #Hidden layer units
D = XTrain.shape[1]


tfX = tf.placeholder(tf.float32, [None, D])
tfY = tf.placeholder(tf.float32, [None, K])                    

# HIDDEN LAYER 1
W1 = tf.Variable(tf.random_normal([D,M], stddev=0.01))
b1 = tf.Variable(tf.random_normal([M], stddev=0.01))

# HIDDEN LAYER 2
W2 = tf.Variable(tf.random_normal([M,M], stddev=0.01))
b2 = tf.Variable(tf.random_normal([M], stddev=0.01))

# OUTPUT LAYER 
W3 = tf.Variable(tf.random_normal([M,K], stddev=0.01))
b3 = tf.Variable(tf.random_normal([K], stddev=0.01))

# MODEL
h1 = tf.nn.sigmoid(tf.matmul(tfX, W1) + b1)
h2 = tf.nn.sigmoid(tf.matmul(h1, W2) + b2)
y = tf.matmul(h2,W3) + b3

# Softmax and cross-entropy
cost = tf.reduce_mean(
  tf.nn.softmax_cross_entropy_with_logits_v2(
    labels = tfY,
    logits = y)
)

# Targets One-Hot encoded
T = np.zeros((N,K)) 
for i in range(N):
    T[i,YTrain[i]] = 1

#Gradient descent
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost)

predict_op = tf.argmax(y, 1)

# Start session and initialize variables
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

# TRAIN
for i in range(10000):
    sess.run(train_op, feed_dict={tfX: XTrain, tfY: T})
    pred = sess.run(predict_op, feed_dict={tfX: XTrain, tfY: T})
    if i % 20 == 0:
        print("Accuracy:", np.mean(YTrain == pred)) 

When I start training the output looks like this:

Accuracy: 0.0991 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127 Accuracy: 0.1127


Solution

  • I figured out a solution to the problem myself.

    Apparently the initialization of the weights weren't right. It works if I change the initialization to:

    # HIDDEN LAYER 1
    W1 = tf.Variable(tf.random_normal([D,M], stddev=1) / np.sqrt(D))
    b1 = tf.Variable(tf.random_normal([M], stddev=1))
    
    # HIDDEN LAYER 2
    W2 = tf.Variable(tf.random_normal([M,M], stddev=1) / np.sqrt(M))
    b2 = tf.Variable(tf.random_normal([M], stddev=1))
    
    # OUTPUT LAYER 
    W3 = tf.Variable(tf.random_normal([M,K], stddev=1) / np.sqrt(M))
    b3 = tf.Variable(tf.random_normal([K], stddev=1))
    

    Why I'm still not quite sure of, would appreciate any answers and feedback.