一个函数传递给另一个时的Tensorflow AttributeError

时间:2018-08-31 11:51:27

标签: python-3.x tensorflow

我是Tensorflow的新手。下面的部分代码将引发AttributeError:'NoneType'对象没有属性'dtype'。有人可以指出我做错了什么以及如何正确编码吗?

我意识到问题是当我试图最小化train_function内的“损失”时。我假设在交互式会话s期间,batch_x_train和batch_y_train将传递给“ optimizer”的函数调用,后者调用函数“ binary_logloss”,并传递batch_y_train值。我知道如何在没有张量流的情况下进行这项工作,但是当涉及到图形时,我有点困惑。

input_X = tf.placeholder('float32', [None,64])
input_y = tf.placeholder('float32', [None,num_classes])

predicted_y = tf.sigmoid(tf.matmul(input_X, weights) + b)

def binary_logloss(true_y):

    if true_y ==1.:
        return tf.reduce_mean(tf.reduce_sum(-tf.log(predicted_y) , axis=1))
    elif true_y == 0.:
        return tf.reduce_mean(tf.reduce_sum(-tf.log(1-predicted_y) , axis=1))

def train_function(X, y):
    loss = binary_logloss(input_y)
    optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
    _, c = s.run([optimizer, loss], {input_X:X, input_y:y})
    return _, c

s.run(tf.global_variables_initializer())
for epoch in epochs:     
    _, c = train_function(batch_x_train, batch_y_train) 

1 个答案:

答案 0 :(得分:0)

您必须像这样重构代码并实现批处理机制,我认为它应该执行。

input_X = tf.placeholder('float32', [None,64])
input_y = tf.placeholder('float32', [None,num_classes])

predicted_y = tf.sigmoid(tf.matmul(input_X, weights) + b)    

loss = tf.reduce_mean(-(input_y * tf.log(predicted_y) + (1 - input_y) * tf.log(1 - predicted_y)))

optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(loss)

init = (tf.global_variables_initializer(), tf.local_variables_initializer())

with tf.Session() as s:
    s.run(init)
    s.run(tf.global_variables_initializer())
    for epoch in epochs:     
       # batch_x_train, batch_y_train = Batching code
       _, c = train_function(batch_x_train, batch_y_train)