2017-06-18 75 views
1

我試圖將Keras中的tutorial轉換爲TF。 我收到以下錯誤:Tensorflow佔位符聲明

Traceback (most recent call last): 
    File "/Users/spicyramen/Documents/Development/google/python/machine_learning/deep_learning/exercise1_tf.py", line 64, in <module> 
    sess.run(train_step, feed_dict=train_data) 
    File "/Library/Python/2.7/site-packages/tensorflow/python/client/session.py", line 789, in run 
    run_metadata_ptr) 
    File "/Library/Python/2.7/site-packages/tensorflow/python/client/session.py", line 975, in _run 
    % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) 
ValueError: Cannot feed value of shape (768,) for Tensor u'Placeholder_1:0', which has shape '(?, 1)' 

這似乎是我如何傳遞目標標籤和我的佔位符值是如何聲明有關。 當我返回標籤我有這樣的:

>>> dataset[:, 8].shape 
(768,) 
>>> dataset[:, 0:8].shape 
(768, 8) 

代碼

import tensorflow as tf 
import numpy as np 

print("Tensorflow version: " + tf.__version__) 
tf.set_random_seed(0) 

FILENAME = 'pima-indians-diabetes.csv' 
_LEARNING_RATE = 0.003 
_NUM_FEATURES = 8 
_NUM_LABELS = 1 
_NUM_EPOCHS = 150 
_BATCH_SIZE = 10 


def import_data(filename): 
    if filename: 
     dataset = np.loadtxt(filename, delimiter=",") 
     return dataset[:, 0:8], dataset[:, 8] 


# create placeholder. Dataset contains _NUM_FEATURES features: 
X = tf.placeholder(tf.float32, [None, _NUM_FEATURES]) 
Y_ = tf.placeholder(tf.float32,[None, _NUM_LABELS]) # Placeholder for correct answers 

# weights and biases 
W = tf.Variable(tf.random_normal([_NUM_FEATURES, _NUM_LABELS], 
           mean=0, 
           stddev=0.1, 
           name='weights')) 

b = tf.Variable(tf.random_normal([1, _NUM_LABELS], 
           mean=0, 
           stddev=0.1, 
           name='bias')) 

# activation function 
Y = tf.nn.relu(tf.matmul(X, W) + b, name='activation') 

# cost function i.e. sigmoid_cross_entropy_with_logits 
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=Y_, logits=Y, name='loss_function') 
optimizer = tf.train.AdamOptimizer(_LEARNING_RATE) # Formal derivation 
train_step = optimizer.minimize(cross_entropy) 

# cost function i.e. RMSE 
# cross_entropy = tf.nn.l2_loss(Y - Y_, name="squared_error_cost") 
# optimizer = tf.train.GradientDescentOptimizer(_LEARNING_RATE) 
# train_step = optimizer.minimize(cross_entropy) 

is_correct = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1)) 
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32)) 

# init 
init = tf.global_variables_initializer() 
sess = tf.Session() 
sess.run(init) 

for i in range(_NUM_EPOCHS): 
    # data 
    batch_X, batch_Y = import_data(FILENAME) 
    # train 
    train_data = {X: batch_X, Y_: batch_Y} 
    sess.run(train_step, feed_dict=train_data) 
    a, c = sess.run([accuracy, cross_entropy], feed_dict=train_data)   
    print(str(i) + ": accuracy:" + str(a) + " loss: " + str(c)) 

回答

2

這是你的問題就在這裏:

>>> dataset[:, 8].shape 
(768,) 

TensorFlow期待形狀(768,1),而不是一個數組作爲錯誤參考的(768,)

Cannot feed value of shape (768,) for Tensor u'Placeholder_1:0', which has shape '(?, 1)' 

兩種形狀之間的差異有點小,Numpy通常會在很多情況下爲您播放這些,但TF不會。看到這兩種形狀之間的區別in this question with a great answer

幸好在你的情況下,解決方案非常簡單。您可以使用np.expand_dims()把你(768,)載體引入(768,1)載體,這表現在這裏:

>>> np.array([5,5,5]).shape 
(3,) 
>>> np.expand_dims(np.array([5,5,5]), axis=1).shape 
(3, 1) 

在你import_data功能,只需將回線改爲

return dataset[:, 0:8], np.expand_dims(dataset[:, 8], axis=1) 

編輯:我喜歡上面的原因np.expand_dims稍微更加明確一點,但還有另外一種同樣簡單的方式,其他人可能會認爲它更加清晰 - 僅取決於您習慣的方式。我想包括它的完整性。 (N,)(N,1)陣列之間的差異是0維陣列中的第一個保持值np.array([5, 5, 5]),而第二個保持1維陣列中的值np.array([[5],[5],[5]])。您可以通過在其周圍添加一個括號將您的0-d數組轉換爲1-d數組;但它是一排而不是一列,所以它需要轉置。所以這兩個建議的方法在一起。 B是新的建議,C是上述建議:

>>> A = np.array([5,5,5]) 
>>> B = np.array([A]).T 
>>> C = np.expand_dims(A, axis=1) 
>>> A; A.shape 
array([5, 5, 5]) 
(3,) 
>>> B; B.shape 
array([[5], 
     [5], 
     [5]]) 
(3, 1) 
>>> C; C.shape 
array([[5], 
     [5], 
     [5]]) 
(3, 1) 

EDIT2:也TensorFlow本身具有tf.expand_dims()功能。