所以我有一个与this问题相同的问题。除了我找不到哪个名字冲突。您能指出变量名冲突发生的确切位置吗,我尝试了很多却无济于事。或者,您可以建议一些方法来找出错误点。这是我的TensorFlow代码:
def convolutionForwardPropagation(features, labels, mode, params):
img = features['x']
c1 = tf.layers.conv2d(img, filters = 32, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0))
c2 = tf.layers.conv2d(c1, filters = 64, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0))
c3 = tf.layers.conv2d(c2, filters = 64, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0))
c4 = tf.layers.conv2d(c3, filters = 64, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0))
c5 = tf.layers.conv2d(c4, filters = 128, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0))
shape1 = c5.get_shape().as_list()
fr = tf.reshape(c5, shape = (-1, shape1[3] * shape1[2]))
fc1 = tf.contrib.layers.fully_connected(fr, 20, activation_fn = tf.nn.relu, weights_regularizer = tf.contrib.layers.l2_regularizer(500.0))
fc2 = tf.contrib.layers.fully_connected(fc1, 2, activation_fn = tf.nn.sigmoid, weights_regularizer = tf.contrib.layers.l2_regularizer(500.0))
entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits = fc2, labels = labels, name = 'cross_entropy')
loss = tf.reduce_mean(entropy, name = 'loss')
optimizer = tf.train.AdamOptimizer(params)
hypothesis = tf.nn.softmax(fc2)
y_pred_class = tf.argmax(hypothesis, axis = 1)
sparseLabels = tf.argmax(labels, axis = 1)
if(mode == tf.estimator.ModeKeys.PREDICT):
spec = tf.estimator.EstimatorSpec(mode = mode, predictions = y_pred_class)
return spec
elif(mode == tf.estimator.ModeKeys.TRAIN):
train_op = optimizer.minimize(loss = loss)
metrics = {'accuracy':tf.metrics.accuracy(labels = sparseLabels, predictions = y_pred_class)}
spec = tf.estimator.EstimatorSpec(mode = mode, predictions = y_pred_class, loss = loss, train_op = train_op, eval_metric_ops = metrics)
return spec
elif(mode == tf.estimator.ModeKeys.EVAL):
metrics = {'accuracy':tf.metrics.accuracy(labels = sparseLabels, predictions = y_pred_class)}
spec = tf.estimator.EstimatorSpec(mode = mode, predictions = y_pred_class, loss = loss, eval_metric_ops = metrics)
return spec
train_input_fn = tf.estimator.inputs.numpy_input_fn(x = {'x':testDataset}, y = labelsTest, batch_size = 350, num_epochs = 20, shuffle = False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(x = {'x':CVDataset}, y = labelsCV, batch_size = 200, num_epochs = 1, shuffle = False)
model = tf.estimator.Estimator(model_fn = convolutionForwardPropagation, params = learning_rate, model_dir = './checpoints/CNN')
k = model.train(input_fn = train_input_fn, steps = 1)
writer = tf.summary.FileWriter('./graphs/logreg', tf.get_default_graph())
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run([train_input_fn, eval_input_fn])
sess.run([model, k])
writer.close()
这是我的错误消息:
Traceback (most recent call last):
File "<ipython-input-36-08caa0f29863>", line 1, in <module>
runfile('/home/abhigyan/Programming_Projects/Python_Projects/tensorflow_env/Programs/tfCNN3.py', wdir='/home/abhigyan/Programming_Projects/Python_Projects/tensorflow_env/Programs')
File "/home/abhigyan/.local/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "/home/abhigyan/.local/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/abhigyan/Programming_Projects/Python_Projects/tensorflow_env/Programs/tfCNN3.py", line 222, in <module>
sess.run([train_input_fn, eval_input_fn])
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 900, in run
run_metadata_ptr)
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1120, in _run
self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 427, in __init__
self._fetch_mapper = _FetchMapper.for_fetch(fetches)
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 245, in for_fetch
return _ListFetchMapper(fetch)
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 352, in __init__
self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 352, in <listcomp>
self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 253, in for_fetch
return _ElementFetchMapper(fetches, contraction_fn)
File "/home/abhigyan/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 286, in __init__
(fetch, type(fetch), str(e)))
TypeError: Fetch argument <function numpy_input_fn.<locals>.input_fn at 0x7f52300b2510> has invalid type <class 'function'>, must be a string or Tensor. (Can not convert a function into a Tensor or Operation.)
答案 0 :(得分:2)
出现错误是因为方法sess.run()
试图执行张量,而您对方法[train_input_fn, eval_input_fn]
的输入是函数。
但是,使用Estimator API时不需要tf.Session()
。训练模型:
model = tf.estimator.Estimator(model_fn = convolutionForwardPropagation,
params = learning_rate, model_dir = './checpoints/CNN')
train_input_fn = tf.estimator.inputs.numpy_input_fn(x = {'x':testDataset},
y = labelsTest, batch_size = 350, num_epochs = 20,
shuffle = False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(x = {'x':CVDataset},
y = labelsCV, batch_size = 200, num_epochs = 1,
shuffle = False)
现在您可以执行以下操作:
for epoch in range(20):
model.train(input_fn = train_input_fn, steps = None)
training_score = model.evaluate(input_fn=train_input_fn)
validation_score = model.evaluate(input_fn=eval_input_fn)