2

我試圖構建一個卷積神經網絡,但我偶然發現了一些非常奇怪的問題。Tensorflow:權重不變,成本設置爲1.0

第一件事第一,這裏是我的代碼:

import tensorflow as tf 
import numpy as np 
import matplotlib.image as mpimg 
import glob 

x = [] 
y = 1 

for filename in glob.glob('trainig_data/*.jpg'): 
    im = mpimg.imread(filename) 
    x.append(im) 
    if len(x) == 10: 
     break 
epochs = 5 

weights = [tf.Variable(tf.random_normal([5,5,3,32],0.1)), 
      tf.Variable(tf.random_normal([5,5,32,64],0.1)), 
      tf.Variable(tf.random_normal([5,5,64,128],0.1)), 
      tf.Variable(tf.random_normal([75*75*128,1064],0.1)), 
      tf.Variable(tf.random_normal([1064,1],0.1))] 

def CNN(x, weights): 
    output = tf.nn.conv2d([x], weights[0], [1,1,1,1], 'SAME') 
    output = tf.nn.relu(output) 
    output = tf.nn.conv2d(output, weights[1], [1,2,2,1], 'SAME') 
    output = tf.nn.relu(output) 
    output = tf.nn.conv2d(output, weights[2], [1,2,2,1], 'SAME') 
    output = tf.nn.relu(output) 
    output = tf.reshape(output, [-1,75*75*128]) 
    output = tf.matmul(output, weights[3]) 
    output = tf.nn.relu(output) 
    output = tf.matmul(output, weights[4]) 
    output = tf.reduce_sum(output) 
    return output 


sess = tf.Session() 
prediction = CNN(tf.cast(x[0],tf.float32), weights) 
cost = tf.reduce_mean(tf.square(prediction-y)) 
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost) 
init = tf.global_variables_initializer() 

sess.run(init) 
for e in range(epochs): 
    print('epoch:',e+1) 
    for x_i in x: 
     prediction = CNN(tf.cast(x_i,tf.float32), weights) 
     sess.run([cost, train]) 
     print(sess.run(cost)) 
print('optimization finished!') 
print(sess.run(prediction)) 

現在,這裏是我的問題:

  1. 的權重和過濾器的值不會改變
  2. 變量「成本」是總是1.0
  3. 預測總是會顯示一個0

在做了一些調試之後,我發現問題必須來自優化器,因爲在我將優化器放入優化器之前,成本和預測不是1.0和0。

我希望這是足夠的信息,你可以幫我解決我的問題。

回答

0

嘗試更改初始化權重的方式,使用tf.truncated_normal初始化權重。請參閱answer,其中指出tf.truncated_normal之間的差異。

tf.truncted_normal:從截斷的正態分佈中輸出隨機值。生成的值遵循具有指定平均值和標準偏差的正態分佈,不同之處在於其平均值大於2個標準差的值將被丟棄並重新挑選。

tf.random_normal:從正態分佈中輸出隨機值。

+0

沒有改變任何東西 –