2017-08-02 45 views
3

我正在爲某個任務編寫二元分類器,而不是在輸出層中使用2個神經元我只想使用一個具有S形函數的函數如果它低於0.5,基本上輸出0級,否則基本輸出0。當使用具有單輸出神經元張量流的神經網絡時,損失和準確性爲0

圖像被加載,調整大小爲64x64並展平,以創建問題的傳真)。數據加載代碼將在最後出現。我創建佔位符。

​​

並定義模型如下。

def create_model_linear(data): 

    fcl1_desc = {'weights': weight_variable([4096,128]), 'biases': bias_variable([128])} 
    fcl2_desc = {'weights': weight_variable([128,1]), 'biases': bias_variable([1])} 

    fc1 = tf.nn.relu(tf.matmul(data, fcl1_desc['weights']) + fcl1_desc['biases']) 
    fc2 = tf.nn.sigmoid(tf.matmul(fc1, fcl2_desc['weights']) + fcl2_desc['biases']) 

    return fc2 

功能weight_variablebias_variable簡單地返回給定形狀的tf.Variable()。 (代碼也是最後的。)

然後我定義瞭如下的訓練函數。

def train(x, hm_epochs): 
    prediction = create_model_linear(x) 
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = prediction, labels = y)) 
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) 
    batch_size = 100 
    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 

     for epoch in range(hm_epochs): 
      epoch_loss = 0 
      i = 0 
      while i < len(train_x): 
       start = i 
       end = i + batch_size 
       batch_x = train_x[start:end] 
       batch_y = train_y[start:end] 
       _, c = sess.run([optimizer, cost], feed_dict = {x:batch_x, y:batch_y}) 

       epoch_loss += c 
       i+=batch_size 

      print('Epoch', epoch+1, 'completed out of', hm_epochs,'loss:',epoch_loss) 
     correct = tf.greater(prediction,[0.5]) 
     accuracy = tf.reduce_mean(tf.cast(correct, 'float')) 
     i = 0 
     acc = [] 
     while i < len(train_x): 
      acc +=[accuracy.eval({x:train_x[i:i+1000], y:train_y[i:i + 1000]})] 
      i+=1000 
    print sum(acc)/len(acc) 

train(x, 10)輸出是

( '時代',1 '完成了的',10, '損失:',0.0) ( '時代',2「,完成('Epoch',3,''out of',10,'loss:',0.0) ('Epoch',4,'out of','out of',10,'loss:',0.0) 10,'loss:',0.0) ('Epoch',5,'completed out',10,'loss:',0.0) ('Epoch',6''out of',10,'loss :',0.0) ('Epoch',7,'out of',10,'loss:',0.0)('Epoch',8,'out of',10,'loss:',0.0) ('Epoch',9,'completed out',10,'loss:',0.0) ('Epoch' ',10,'out of',10,'loss:',0.0)

0.0 我錯過了什麼?

這裏是所有實用功能的承諾代碼:

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

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

def getLabel(wordlabel): 
    if wordlabel == 'Class_A': 
     return [1] 
    elif wordlabel == 'Class_B': 
     return [0] 
    else: 
     return -1 

def loadImages(pathToImgs): 
    images = [] 
    labels = [] 
    filenames = os.listdir(pathToImgs) 
    imgCount = 0 
    for i in tqdm(filenames): 
     wordlabel = i.split('_')[1] 
     oneHotLabel = getLabel(wordlabel) 
     img = cv2.imread(pathToImgs + i,cv2.IMREAD_GRAYSCALE) 
     if oneHotLabel != -1 and type(img) is np.ndarray: 
      images += [cv2.resize(img,(64,64)).flatten()] 
      labels += [oneHotLabel] 
      imgCount+=1 
    print imgCount 
    return (images,labels) 
+0

我認爲,因爲你用乙狀結腸和輸出層神經元1,你應該使用tf.nn.sigmoid_cross_entropy_with_logits代替tf.nn.softmax_cross_entropy_with_logits。 –

+1

其實就是這樣。不能相信我錯過了。我也應該從最後一層刪除sifmoid –

+0

我很高興它幫助解決了這個問題!然後,我將發表我的評論作爲一個單獨的答案。 –

回答

1

我認爲,因爲你用乙狀結腸和輸出層神經元1,你應該使用tf.nn.sigmoid_cross_entropy_with_logits而不是tf.nn.softmax_cross_entropy_with_logits

此外,您還需要從create_model_linear 的最後一層刪除S形標籤,並且您沒有使用標籤,準確性必須符合以下形式。

correct = tf.equal(tf.greater(tf.nn.sigmoid(prediction),[0.5]),tf.cast(y,'bool'))