Ошибка типа: не удается преобразовать встроенную функцию или метод в тензор или операцию

#python #tensorflow #pycharm

#python #тензорный поток #pycharm

Вопрос:

В настоящее время я занимаюсь самообучением tensorflow и пытаюсь использовать этот код прямо здесь

 import tensorflow as tf

a = tf.constant(2.5)
b = tf.constant(4.5)
total = a   b

tf.summary.scalar("a", a)
tf.summary.scalar("b", b)
tf.summary.scalar("total", total)

merged_op = tf.summary.merge_all()

with tf.Session() as sess:
    _, summary = sess.run([sum,merged_op])
  

который должен выполняться. В настоящее время я покидаю книгу Tensorflow для чайников, и она продолжает выдавать мне эту ошибку

 C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkdtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkdtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkdtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkdtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkdtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkdtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorboardcompattensorflow_stubdtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorboardcompattensorflow_stubdtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorboardcompattensorflow_stubdtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorboardcompattensorflow_stubdtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorboardcompattensorflow_stubdtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
C:Anaconda3envsTensorflowlibsite-packagestensorboardcompattensorflow_stubdtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
WARNING:tensorflow:From C:/Users/brent/PycharmProjects/pythonProject/main.py:7: The name tf.summary.scalar is deprecated. Please use tf.compat.v1.summary.scalar instead.

WARNING:tensorflow:From C:/Users/brent/PycharmProjects/pythonProject/main.py:11: The name tf.summary.merge_all is deprecated. Please use tf.compat.v1.summary.merge_all instead.

WARNING:tensorflow:From C:/Users/brent/PycharmProjects/pythonProject/main.py:13: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.

2020-10-15 20:45:34.368712: I tensorflow/core/platform/cpu_feature_guard.cc:145] This TensorFlow binary is optimized with Intel(R) MKL-DNN to use the following CPU instructions in performance critical operations:  AVX AVX2
To enable them in non-MKL-DNN operations, rebuild TensorFlow with the appropriate compiler flags.
2020-10-15 20:45:34.372328: I tensorflow/core/common_runtime/process_util.cc:115] Creating new thread pool with default inter op setting: 24. Tune using inter_op_parallelism_threads for best performance.
Traceback (most recent call last):
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 303, in __init__
    fetch, allow_tensor=True, allow_operation=True))
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkops.py", line 3796, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonframeworkops.py", line 3885, in _as_graph_element_locked
    (type(obj).__name__, types_str))
TypeError: Can not convert a builtin_function_or_method into a Tensor or Operation.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/brent/PycharmProjects/pythonProject/main.py", line 14, in <module>
    _, summary = sess.run([sum,merged_op])
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 950, in run
    run_metadata_ptr)
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 1158, in _run
    self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 474, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 264, in for_fetch
    return _ListFetchMapper(fetch)
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 373, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 373, in <listcomp>
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 274, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "C:Anaconda3envsTensorflowlibsite-packagestensorflowpythonclientsession.py", line 307, in __init__
    (fetch, type(fetch), str(e)))
TypeError: Fetch argument <built-in function sum> has invalid type <class 'builtin_function_or_method'>, must be a string or Tensor. (Can not convert a builtin_function_or_method into a Tensor or Operation.)

  

Каждый раз, когда я импортирую tensorflow, он всегда выдает мне огромный блок ошибок перед запуском моего кода. Как мне избавиться от этого?

Ответ №1:

sum является встроенной функцией в Python.

Использовать его в качестве имени переменной — плохая практика. Тем не менее, вы используете его, не инициализируя нигде в своем коде:

 with tf.Session() as sess:
    _, summary = sess.run([sum,merged_op])
  

Я считаю, что вам нужно заменить sum на переменную total , инициализированную выше:

 total = a   b
  

Итак, что-то вроде:

 with tf.Session() as sess:
        _, summary = sess.run([total,merged_op])