Tensorflow错误:不支持可调用-(来自ex ???)

时间:2019-04-05 21:58:53

标签: python tensorflow conv-neural-network

我正在尝试将教程“ Build a Convolutional Neural Network using Estimators”的CNN修改为我的数据集,并且不知道如何解决此错误

...输入文件应该很好,因为它们已经过测试并且可以,因为我当前正在另一个CNN上运行它们,但有很大的不同(它工作正常,但我愿意更改它,添加一些诸如“辍学”之类的额外功能)

事实是该错误(我将Spyder用作IDE)完全没有意义。我已经做了一些尝试,以查看错误在哪里,但是我有点困惑了,所以让我们尝试问问你们

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)

#----- global variables Start ------
nb_of_neurons=1024
model_learning_rate=0.001

#----- global variables End ------

def run_cnn(mymode, last_date, names, mydata, mylabels, run_id):
    def cnn_model_fn(cnndata, mylabels, mode):
      input_layer = tf.reshape(cnndata, [-1, 4, 5, 1])
      conv = tf.layers.conv2d(
          inputs=input_layer,
          filters=16,
          kernel_size=[2, 3],
          padding="same",
          activation=tf.nn.relu)
      print(conv.shape.dims)
      pool = tf.layers.max_pooling2d(inputs=conv, pool_size=[2, 2], strides=2)
      pool_dims=pool.shape.as_list()[1]*pool.shape.as_list()[2]*pool.shape.as_list()[3]
      pool_flat = tf.reshape(pool, [-1, pool_dims])
      dense = tf.layers.dense(inputs=pool_flat, units=nb_of_neurons, activation=tf.nn.relu)
      dropout = tf.layers.dropout(
          inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)
      logits = tf.layers.dense(inputs=dropout, units=2)
      predictions = {
          "classes": tf.argmax(input=logits, axis=1),
          "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
      }
      if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

      loss = tf.losses.sparse_softmax_cross_entropy(labels=mylabels, logits=logits)
      print(loss)
      if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=model_learning_rate)
        train_op = optimizer.minimize(
            loss=loss,
            global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
      eval_metric_ops = {
          "accuracy": tf.metrics.accuracy(
              labels=mylabels, predictions=predictions["classes"])
      }
      return tf.estimator.EstimatorSpec(
          mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)


    if mymode == 'TRAIN':
        mode= tf.estimator.ModeKeys.TRAIN
        cnn_classifier = tf.estimator.Estimator(
            model_fn=cnn_model_fn(mydata, mylabels, mode), model_dir="/sess")

        tensors_to_log = {"probabilities": "softmax_tensor"}

        logging_hook = tf.train.LoggingTensorHook(
            tensors=tensors_to_log, every_n_iter=50)

        train_input_fn = tf.estimator.inputs.numpy_input_fn(
            x=mydata,
            y=mylabels,
            batch_size=100,
            num_epochs=None,
            shuffle=True)

        cnn_classifier.train(
            input_fn=train_input_fn,
            steps=1,
            hooks=[logging_hook])
        cnn_classifier.train(input_fn=train_input_fn, steps=1000)

    elif mymode == 'PREDICT':
        mode= tf.estimator.ModeKeys.PREDICT
        cnn_classifier = tf.estimator.Estimator(
            model_fn=cnn_model_fn(mydata, mylabels, mode), model_dir="/sess")

        tensors_to_log = {"probabilities": "softmax_tensor"}

        logging_hook = tf.train.LoggingTensorHook(
            tensors=tensors_to_log, every_n_iter=50)

        eval_input_fn = tf.estimator.inputs.numpy_input_fn(
                x=mydata,
                y=mylabels,
                num_epochs=1,
                shuffle=False)
        eval_results = cnn_classifier.evaluate(input_fn=eval_input_fn)

    else:
        print('**** ->***   ????   ***')

这被另一个python脚本称为模块,该脚本传递给所有输入数据,如下所示:

  1. mymode:在['PREDICT','TRAIN']
  2. 最后日期:不相关
  3. 名称:不相关
  4. mydata:形状为(3195,20)的np数组,其值为[0.,1。](浮点数)
  5. mylabels:形状为(3195)的np数组,其值为[0,1](int)
  6. run_i:不相关

最后,错误出现在train_op之后(即tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)中),如下所示:

...
  File "C:\Users\Fulviooo\Anaconda3\lib\site-packages\tensorflow\python\util\function_utils.py", line 56, in fn_args
    args = tf_inspect.getfullargspec(fn).args

  File "C:\Users\Fulviooo\Anaconda3\lib\site-packages\tensorflow\python\util\tf_inspect.py", line 216, in getfullargspec
    if d.decorator_argspec is not None), _getfullargspec(target))

  File "C:\Users\Fulviooo\Anaconda3\lib\inspect.py", line 1095, in getfullargspec
    raise TypeError('unsupported callable') from ex

TypeError: unsupported callable

我希望有人能启发我该错误在哪里以及如何解决。 此外,我很高兴收到其他任何改进建议。

谢谢

1 个答案:

答案 0 :(得分:0)

在实践中,问题在于此估计量非常严格,并且期望具有预定义名称和格式的变量。 即设置期望的名称:

train_data=mydata
train_labels=mylabels

和格式(字典):

x={"x": train_data}

然后运行