2016-05-27 58 views
0

我試圖完成以下tensorflow教程和(試圖問題4):https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/3_regularization.ipynb多級神經網絡

不過,我想我可能會設置下面的錯誤權重的陣列。只要我將hidden_layer更改爲[image_size * image_size,1024,num_labels](即只有一個隱藏層),就可以正常工作。目前我得到的損失是NaN

一個可能的解決方案是塊 for i in range(1,len(weights)-1): relus = tf.nn.dropout(tf.nn.relu(tf.matmul(relus, weights[i]) + biases[i]),p_hide) 原因造成的問題,因爲我破壞relus的過去值和神經網絡需要他們做反向傳播。事實上,當有一個隱藏層時,這個塊不會被執行。

batch_size = 128 
hidden_layer = [image_size * image_size,1024,300,num_labels] 
l2_regulariser = 0.005 
p_hide = 0.5 

graph = tf.Graph() 
with graph.as_default(): 
    # Input data. For the training data, we use a placeholder that will be fed 
    # at run time with a training minibatch. 
    tf_train_dataset = tf.placeholder(tf.float32,shape=(batch_size, image_size * image_size)) 
    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) 
    tf_valid_dataset = tf.constant(valid_dataset) 
    tf_test_dataset = tf.constant(test_dataset) 

    # Variables. 
    weights = [None]*(len(hidden_layer)-1) 
    biases = [None]*(len(hidden_layer)-1) 
    for i in range(len(weights)): 
     weights[i] = tf.Variable(tf.truncated_normal([hidden_layer[i], hidden_layer[i+1]])) 
     biases[i] = tf.Variable(tf.zeros([hidden_layer[i+1]])) 

    # Training computation. 
    relus = tf.nn.dropout(tf.nn.relu(tf.matmul(tf_train_dataset, weights[0]) + biases[0]),p_hide) 
    for i in range(1,len(weights)-1): 
     relus = tf.nn.dropout(tf.nn.relu(tf.matmul(relus, weights[i]) + biases[i]),p_hide) 
    logits = tf.matmul(relus, weights[len(weights)-1]) + biases[len(weights)-1] 

    loss = 0 
    for weight in weights: 
     loss += tf.nn.l2_loss(weight) 

    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))+ l2_regulariser*loss 


    # Optimizer. 
    global_step = tf.Variable(0) # count the number of steps taken. 
    learning_rate = tf.train.exponential_decay(0.5, global_step, decay_steps=20, decay_rate=0.9) 
    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) 


    # Predictions for the training, validation, and test data. 
    train_prediction = tf.nn.softmax(logits) 

    relus = tf.nn.relu(tf.matmul(tf_valid_dataset, weights[0]) + biases[0]) 
    for i in range(1,len(weights)-1): 
     relus = tf.nn.relu(tf.matmul(relus, weights[i]) + biases[i]) 
    valid_prediction = tf.nn.softmax(tf.matmul(relus, weights[len(weights)-1]) + biases[len(weights)-1]) 

    relus = tf.nn.relu(tf.matmul(tf_test_dataset, weights[0]) + biases[0]) 
    for i in range(1,len(weights)-1): 
     relus = tf.nn.relu(tf.matmul(relus, weights[i]) + biases[i]) 
    test_prediction = tf.nn.softmax(tf.matmul(relus, weights[len(weights)-1]) + biases[len(weights)-1]) 

###################### 
# The NN training part 
###################### 
num_steps = 3001 

with tf.Session(graph=graph) as session: 
    tf.initialize_all_variables().run() 
    print("Initialized") 
    for step in range(num_steps): 
    # Pick an offset within the training data, which has been randomized. 
    # Note: we could use better randomization across epochs. 
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size) 
    # Generate a minibatch. 
    batch_data = train_dataset[offset:(offset + batch_size), :] 
    batch_labels = train_labels[offset:(offset + batch_size), :] 
    # Prepare a dictionary telling the session where to feed the minibatch. 
    # The key of the dictionary is the placeholder node of the graph to be fed, 
    # and the value is the numpy array to feed to it. 
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, global_step : int(step)} 
    _, l, predictions = session.run(
     [optimizer, loss, train_prediction], feed_dict=feed_dict) 
    if (step % 500 == 0): 
     print("Minibatch loss at step %d: %f" % (step, l)) 
     print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels)) 
     print("Validation accuracy: %.1f%%" % accuracy(
     valid_prediction.eval(), valid_labels)) 
    print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels)) 

回答

1

你應該更好地初始化權重:

tf.truncated_normal([hidden_layer[i], hidden_layer[i+1]], stddev=0.1) 

最重要的是,你應該降低你的學習速度的東西左右0.010.001 ...

我想你因爲學習率太高而導致網絡崩潰(你會得到爆炸式的權重),所以會損失NaN

+0

這當然似乎有伎倆。但是我能問一下你在學習率太高的時候是如何選擇的?神經網絡中是否存在指數運算?或者某種拇指規則初始化? –

+0

一般而言,您不希望學習率高於「0.1」。查看網絡訓練效果的最好方法是繪製損失(你可以用Tensorboard來完成,參見[本教程])(https://www.tensorflow.org/versions/r0.8/how_tos/summaries_and_tensorboard/ index.html)),如果您看到損失太大並且上升,則可能表明您的學習速度太高。 –

+0

對於權重初始化,它們需要具有較低的方差('<0.1'),請參見[本文](http://deepdish.io/2015/02/24/network-initialization/) –