2017-12-15 6 views
1

2 레이어 MLP (Relu) + SoftmaxMLP (ReLu)는 몇 번의 반복 작업 후에 학습을 중지합니다. Tensor Flow

반복 횟수가 20 회가되면 Tensor Flow는 모든 무게 또는 편향의 업데이트를 포기하고 중지합니다.

나는 처음에는 내 ReLu가 죽어 가고 있다고 생각 했으므로 히스토그램을 표시하여 아무도 0이 아닌지 확인했습니다. 그리고 그 중 누구도 아닙니다!

반복 횟수가 거의 줄어들지 않고 교차 엔트로피가 여전히 높습니다. ReLu, Sigmoid 및 tanh도 동일한 결과를 제공합니다. GradientDescentOptimizer를 0.01에서 0.5로 조정해도 큰 변화는 없습니다.

어딘가에 버그가 있어야합니다. 내 코드의 실제 버그처럼. 나는 작은 샘플 세트를 너무 과장 할 수 없다!

여기 내 히스토그램이며 여기에 내 코드가 있습니다. 누구든지 체크 아웃 할 수 있다면 큰 도움이됩니다.

우리는 3000 개의 클래스로 분류하는 0과 255 사이의 6 개 개의 값으로 스칼라가 [1,0] 또는 [0,1] 가

 def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): 
     with tf.name_scope(layer_name): 
      weights = tf.Variable(tf.truncated_normal([input_dim, output_dim], stddev=1.0/math.sqrt(float(6)))) 
      tf.summary.histogram('weights', weights) 

      biases = tf.Variable(tf.constant(0.4, shape=[output_dim])) 
      tf.summary.histogram('biases', biases) 

      preactivate = tf.matmul(input_tensor, weights) + biases 
      tf.summary.histogram('pre_activations', preactivate) 

      #act=tf.nn.relu 
      activations = act(preactivate, name='activation') 
      tf.summary.histogram('activations', activations) 

      return activations 


    #We have 3000 scalars with 6 values between 0 and 255 to classify in two classes 
    x = tf.placeholder(tf.float32, [None, 6]) 
    y = tf.placeholder(tf.float32, [None, 2]) 

    #After normalisation, input is between 0 and 1 
    normalised = tf.scalar_mul(1/255,x) 

    #Two layers 
    hidden1 = nn_layer(normalised, 6, 4, "hidden1") 
    hidden2 = nn_layer(hidden1, 4, 2, "hidden2") 

    #Finish by a softmax 
    softmax = tf.nn.softmax(hidden2) 

    #Defining loss, accuracy etc.. 
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=softmax))  
    tf.summary.scalar('cross_entropy', cross_entropy) 

    correct_prediction = tf.equal(tf.argmax(softmax, 1), tf.argmax(y, 1)) 

    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
    tf.summary.scalar('accuracy', accuracy) 

    #Init session and writers and misc 
    session = tf.Session() 

    train_writer = tf.summary.FileWriter('log', session.graph) 
    train_writer.add_graph(session.graph) 

    init= tf.global_variables_initializer() 
    session.run(init) 

    merged = tf.summary.merge_all() 

    #Train 
    train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy) 

    batch_x, batch_y = self.trainData 
    for _ in range(1000): 
     session.run(train_step, {x: batch_x, y: batch_y}) 
     #Every 10 steps, add to the summary 
     if _ % 10 == 0: 
      s = session.run(merged, {x: batch_x, y: batch_y}) 
      train_writer.add_summary(s, _) 


    #Evaluate 
    evaluate_x, evaluate_y = self.evaluateData 
    print(session.run(accuracy, {x: batch_x, y: batch_y})) 
    print(session.run(accuracy, {x: evaluate_x, y: evaluate_y})) 

(I 주문을 randomise 확인했다) 숨겨진 레이어 1. 출력이 0이 아니므로 죽어가는 ReLu 문제가 아닙니다. 하지만 여전히 가중치는 일정합니다! TF는도 2 TF 그들에게 조금 조정 시도하고 꽤 빨리 포기 숨겨진 레이어에 대한 그들에게

Hidden Layer 1. Output isn't zero, so that's not a dying ReLu problem. but still, weights are constant ! TF didn't even try to modify them

동일을 수정하려고하지 않았다.

Same for Hidden Layer 2. TF tried tweaking them a bit and gave up pretty fast.

크로스 엔트로피는 감소 않지만, 압도적으로 높은 유지됩니다.

Cross entropy does decrease, but stays staggeringly high.

편집 : 내 코드에서 실수 많죠. 첫 번째 것은 파이썬에서 1/255 = 0입니다 ... 1.0/255.0으로 변경하고 코드가 시작되었습니다.

기본적으로 내 입력에는 0이 곱해졌으며 신경 네트워크는 순전히 눈이 멀었습니다. 그래서 그는 장님이 될 수있는 최선의 결과를 얻으려고 노력하고 포기했습니다. 그것이 완전히 반응을 설명합니다.

이제 softmax를 두 번 적용하고 있습니다 ... 수정하는 것도 도움이되었습니다. 다른 학습 속도와 다른 시대 수를 짚어 냄으로써 나는 마침내 뭔가 좋은 것을 발견했습니다.

def runModel(self): 


    def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): 
     with tf.name_scope(layer_name): 

      #This is standard weight for neural networks with ReLu. 
      #I divide by math.sqrt(float(6)) because my input has 6 values 
      weights = tf.Variable(tf.truncated_normal([input_dim, output_dim], stddev=1.0/math.sqrt(float(6)))) 
      tf.summary.histogram('weights', weights) 

      #I chose this bias myself. It work. Not sure why. 
      biases = tf.Variable(tf.constant(0.4, shape=[output_dim])) 
      tf.summary.histogram('biases', biases) 

      preactivate = tf.matmul(input_tensor, weights) + biases 
      tf.summary.histogram('pre_activations', preactivate) 

      #Some neurons will have ReLu as activation function 
      #Some won't have any activation functions 
      if act == "None": 
       activations = preactivate 
      else : 
       activations = act(preactivate, name='activation') 
       tf.summary.histogram('activations', activations) 

      return activations 


    #We have 3000 scalars with 6 values between 0 and 255 to classify in two classes 
    x = tf.placeholder(tf.float32, [None, 6]) 
    y = tf.placeholder(tf.float32, [None, 2]) 

    #After normalisation, input is between 0 and 1 
    #Normalising input really helps. Nothing is doable without it 
    #But my ERROR was to write 1/255. Becase in python 
    #1/255 = 0 .... (integer division) 
    #But 1.0/255.0 = 0,003921568 (float division) 
    normalised = tf.scalar_mul(1.0/255.0,x) 

    #Three layers total. The first one is just a matrix multiplication 
    input = nn_layer(normalised, 6, 4, "input", act="None") 
    #The second one has a ReLu after a matrix multiplication 
    hidden1 = nn_layer(input, 4, 4, "hidden", act=tf.nn.relu) 
    #The last one is also jsut a matrix multiplcation 
    #WARNING ! No softmax here ! Because later we call a function 
    #That implicitly does a softmax 
    #And it's bad practice to do two softmax one after the other 
    output = nn_layer(hidden1, 4, 2, "output", act="None") 

    #Tried different learning rates 
    #Higher learning rate means find a result faster 
    #But could be a local minimum 
    #Lower learning rate means we need much more epochs 
    learning_rate = 0.03 

    with tf.name_scope('learning_rate_'+str(learning_rate)): 
     #Defining loss, accuracy etc.. 
     cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=output))  
     tf.summary.scalar('cross_entropy', cross_entropy) 

     correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1)) 

     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
     tf.summary.scalar('accuracy', accuracy) 

    #Init session and writers and misc 
    session = tf.Session() 

    train_writer = tf.summary.FileWriter('log', session.graph) 
    train_writer.add_graph(session.graph) 

    init= tf.global_variables_initializer() 
    session.run(init) 

    merged = tf.summary.merge_all() 

    #Train 
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) 

    batch_x, batch_y = self.trainData 
    for _ in range(1000): 
     session.run(train_step, {x: batch_x, y: batch_y}) 
     #Every 10 steps, add to the summary 
     if _ % 10 == 0: 
      s = session.run(merged, {x: batch_x, y: batch_y}) 
      train_writer.add_summary(s, _) 


    #Evaluate 
    evaluate_x, evaluate_y = self.evaluateData 
    print(session.run(accuracy, {x: batch_x, y: batch_y})) 
    print(session.run(accuracy, {x: evaluate_x, y: evaluate_y})) 

Final results after fixing

답변

2

나는 당신이 당신의 학습 속도를 줄여야 할 것을 두려워 :

다음은 최종 작업 코드입니다. 그것은 높이입니다. 높은 학습 속도는 일반적으로 당신이 지역 최소로 글로벌 한되지 않습니다.

보십시오 0.001, 0.0001 또는 심지어 0.00001보십시오. 또는 학습 속도를 유연하게 만드십시오.

코드를 검사하지 않았으므로 먼저 LR을 조정하십시오.

+0

3 가지 값을 시도했습니다. 같은 문제. 내 질문에 게시하고 히스토그램으로 편집합니다 – Taiko

+0

y에있는 클래스의 잔액은 얼마입니까? – avchauzov

+0

그리고 pls는 첫 번째 레이어를 선형으로 활성화합니다. ReLu는 숨겨진 레이어에서만 사용됩니다. – avchauzov