无法将函数转换为Tensor或Operation。张量错误

时间:2017-06-20 10:53:17

标签: python machine-learning tensorflow

所以我在tensorflow(1.2)(python 3)中得到了这个错误:

WARNING:tensorflow:Passing a `GraphDef` to the SummaryWriter is deprecated. Pass a `Graph` object instead, such as `sess.graph`.
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 267, in __init__
    fetch, allow_tensor=True, allow_operation=True))
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2584, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2673, in _as_graph_element_locked
    % (type(obj).__name__, types_str))
 TypeError: Can not convert a function into a Tensor or Operation.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/theshoutingparrot/Desktop/Programming/Python/MachineLearningPY/Tensorflow/NumberClassifier.py", line 54, in <module>
    summary_str = sess.run(merged_summary_op, feed_dict={x: batch_xs, y: batch_ys})
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 789, in run
    run_metadata_ptr)
   File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 984, in _run
     self._graph, fetches, feed_dict_string, feed_handles=feed_handles)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 410, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 238, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 271, in __init__
    % (fetch, type(fetch), str(e)))
 TypeError: Fetch argument <function merge_all at 0x7f7d0f3d8620> has invalid type <class 'function'>, must be a string or Tensor. (Can not convert a function    into a Tensor or Operation.)

以下是代码:

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

import tensorflow as tf


learning_rate = 0.01
training_iteration = 30
batch_size = 100
display_step = 2


x = tf.placeholder("float", [None, 784])
y = tf.placeholder("float", [None, 10])

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

with tf.name_scope("Wx_b") as scope:
    model = tf.nn.softmax(tf.matmul(x, W) + b)

w_h = tf.summary.histogram("weights", W) 
b_h = tf.summary.histogram("biases", b) 


with tf.name_scope("cost_function") as scope:
   cost_function = -tf.reduce_sum(y*tf.log(model))
   tf.summary.scalar("cost_function", cost_function)

with tf.name_scope("train") as scope:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function)

init = tf.global_variables_initializer()  #tf.initialize_all_variables()

merged_summary_op = tf.summary.merge_all

#Launch the graph

with tf.Session() as sess:
    sess.run(init)
    summary_writer = tf.summary.FileWriter('/home/theshoutingparrot/work/logs', graph_def=sess.graph_def)

    for iteration in range(training_iteration):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)  

    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)

        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})

        avg_cost += sess.run(cost_function, feed_dict={x: batch_xs, y: batch_ys})/total_batch

        summary_str = sess.run(merged_summary_op, feed_dict={x: batch_xs, y: batch_ys})
        summary_writer.add_summary(summary_str, iteration*total_batch + i)

    if iteration % display_step == 0:
        print("Iteration", '%04d' % (iteration + 1), "cost=", "{:.9f}".format(avg_cost))
    print("Tuning completed!")

    predictions = tf.equal(tf.argmax(model,1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(predictions, "float"))
    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

我是tensorflow的新手。我&#34;得到了#34;此视频中的此代码(教程) https://www.youtube.com/watch?v=2FmcHiLCwTU&list=PL2-dafEMk2A7EEME489DsI468AB0wQsMV

他(教程中的人(Siraj Raval))正在使用旧版本的tensorflow,这就是为什么一些代码与此不同的原因(例如):

w_h = tf.histogram_summary("weights", W) => w_h = tf.summary.histogram("weights", W)

更多信息:

我试图用python(2.7)运行相同的代码(当然我已经下载了Python 2.7的tensorflow)但它给了我同样的错误。

任何帮助都会很好,Thx提前。

1 个答案:

答案 0 :(得分:3)

FATAL EXCEPTION: main Process: com.audi.audidrive, PID: 21152 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.audi.audidrive/com.audi.audidrive.activities.ClaimActivity} :java.lang.ClassCastException: com.salesforce.androidsdk.app.SalesforceSDKManager cannot be cast to com.salesforce.androidsdk.smartstore.app.SmartStoreSDKManager at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3190) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300) at android.app.ActivityThread.access$1000(ActivityThread.java:211) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6946) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) Caused by: java.lang.ClassCastException: com.salesforce.androidsdk.app.SalesforceSDKManager cannot be cast to com.salesforce.androidsdk.smartstore.app.SmartStoreSDKManager atcom.salesforce.androidsdk.smartstore.app.SmartStoreSDKManager.getInstance(SmartStoreSDKManager.java:132) at com.audi.audidrive.activities.ClaimActivity.onCreate(ClaimActivity.java:88) at android.app.Activity.performCreate(Activity.java:6575) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)  at android.app.ActivityThread.access$1000(ActivityThread.java:211)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:145)  at android.app.ActivityThread.main(ActivityThread.java:6946)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)  替换为merged_summary_op = tf.summary.merge_all

这实际上是错误消息告诉您的内容:merged_summary_op = tf.summary.merge_all() - &gt; TypeError: Can not convert a function into a Tensor or Operation是一个函数,而不是张量或操作,您可以使用tf.summary.merge_all运行它,与sess.run()

相反