首页 > 解决方案 > Tensorflow TypeError:无法将 NoneType 转换为张量或操作

问题描述

我正在学习 TensorFlow,并且正在阅读这个分步指南。以下代码与网站上的完全相同。但是,在运行它时,尝试拟合模型时出现错误。我得到的完整回溯如下:

Traceback (most recent call last):
  File "C:\users\name\desktop\python ml tutorial\embedding.py", line 49, in <module>
    model.fit(x=padded_docs, y=labels, epochs=50, verbose=0)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\training.py", line 1213, in fit
    self._make_train_function()
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\training.py", line 316, in _make_train_function
    loss=self.total_loss)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\optimizer_v2\optimizer_v2.py", line 506, in get_updates
    return [self.apply_gradients(grads_and_vars)]
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\optimizer_v2\optimizer_v2.py", line 441, in apply_gradients
    kwargs={"name": name})
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\distribute\distribute_lib.py", line 1917, in merge_call
    return self._merge_call(merge_fn, args, kwargs)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\distribute\distribute_lib.py", line 1924, in _merge_call
    return merge_fn(self._strategy, *args, **kwargs)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\optimizer_v2\optimizer_v2.py", line 494, in _distributed_apply
    with ops.control_dependencies(update_ops):
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 5257, in control_dependencies
    return get_default_graph().control_dependencies(control_inputs)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\func_graph.py", line 356, in control_dependencies
    return super(FuncGraph, self).control_dependencies(filtered_control_inputs)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 4691, in control_dependencies
    c = self.as_graph_element(c)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 3610, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "C:\Users\name\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 3699, in _as_graph_element_locked
    (type(obj).__name__, types_str))
TypeError: Can not convert a NoneType into a Tensor or Operation.

完整的代码如下:

from numpy import array
from keras.preprocessing.text import one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers.embeddings import Embedding

# define document
docs = ['Well done!',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent!',
        'Weak',
        'Poor effort!',
        'not good',
        'poor work',
        'Could have done better.']

# define class labels
labels = array([1,1,1,1,1,0,0,0,0,0])

# integer-encode the documents
vocab_size = 50
encoded_docs = [one_hot(d, vocab_size) for d in docs]
print(encoded_docs)

# padding
max_length = 4
padded_docs = pad_sequences(encoded_docs, maxlen = max_length, padding = 'post')
print(padded_docs)

# define model
model = Sequential()
model.add(Embedding(vocab_size, 8, input_length=max_length))
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))

# compile the model
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics=['accuracy'])

# summarize
print(model.summary())

# fit the model
model.fit(x=padded_docs, y=labels, epochs=50, verbose=0)

# evaluate the model
loss, accuracy = model.evaluate(x=padded_docs, y=labels, verbose=0)
print("Accuracy: {}".format(accuracy))

这里发生了什么?这篇文章最初是在 2017 年写的,但它的最后一次修订和更新是在一周前。我想他们会不断调整 TensorFlow,因为它仍然是最先进的,需要大量改进。

关于如何规避这个问题的任何想法?

编辑: 我开始试图找出脚本可能出错的地方。我将在这里列出我发现的内容,希望它能帮助我们发现一些东西:

标签: pythontensorflowkeras

解决方案


推荐阅读