2017-07-03 56 views
0

爲什麼x需要是float?爲什麼不能這樣做int因爲我傳遞了一個類型的列表int爲什麼這個tf.placeholder是一個浮點數?

代碼:

x = tf.placeholder(tf.float32, shape=[None, 1]) # Why must this be a float? 
y = tf.placeholder(tf.int32, shape=[None, 2]) 

with tf.name_scope("network"): 
    layer1 = tf.layers.dense(x, 100, activation=tf.nn.relu, name="hidden_layer") 
    output = tf.layers.dense(layer1, 2, name="output_layer") 

with tf.name_scope("loss"): 
    xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=output) 
    loss = tf.reduce_mean(xentropy, name="loss") 

with tf.name_scope("train"): 
    optimizer = tf.train.AdamOptimizer() 
    training_op = optimizer.minimize(loss) 

with tf.name_scope("eval"): 
    with tf.Session() as sess: 
     for i in range(1, 50): 
      sess.run(tf.global_variables_initializer()) 
      saver = tf.train.Saver() 
      sess.run(training_op, feed_dict={x: np.array(train_data).reshape([-1, 1]), y: label}) 
      if i % 10 == 0: 
       saver.save(sess, "saved_models/testing") 
       print "Saved" 

當我改變它tf.int32,它提供了以下錯誤:

TypeError: Value passed to parameter 'features' has DataType int32 not in list of allowed values: float16, float32, float64 

,如果需要,我可以提供更多的代碼。

+0

輸入以'train_data = range(1,10000,1) – Bosen

回答

1

這是由於tf.nn.softmax_cross_entropy_with_logits

logits and labels must have the same shape [batch_size, num_classes] and the same dtype (either float16, float32, or float64).

我想你可能計算整數輸入的損失。然而,大多數情況下,這種損失是通過梯度下降來最小化的 - 就像您所做的那樣 - 這意味着輸入需要編碼實數以獲得任意更新。

問題是,tf.layers.dense不會改變您的輸入類型。所以它會產生一個整數輸出它的輸入是一個整數。 (至少如果激活與整數兼容,如relu - sigmoid會引發錯誤)。

你可能想要做的是提供整數輸入然後做所有計算在說tf.float32。要做到這一點,請在將其輸入之前先將其輸入:dense

layer1 = tf.layers.dense(tf.to_float(x), 100, activation=tf.nn.relu, name="hidden_layer")