python - model.fit(...) 和“无法将 NumPy 数组转换为张量”
问题描述
我正在使用 TensorFlow 2.0 进行文本分类。
数据的结构或多或少看起来像这样:
第一种方法:
x: List[List[int]] # list of sentences consisting of a list of word IDs for each word in the sentence
y: List[int] # binary truth indicator
但是,在调用时,model.fit(...)
我收到以下错误消息:
Failed to find data adapter that can handle input: (<class 'list'> containing values of types {'(<class \'list\'> containing values of types {"<class \'int\'>"})', "(<class 'list'> containing values of types set())"}), <class 'numpy.ndarray'>
尽管没有set
在任何地方使用。
第二种方法:
我尝试对内部列表使用 numpy 数组,如下所示:
x: List[np.ndarray[np.int32]]
y: np.ndarray[np.int32]
但我收到以下错误:
Input arrays should have the same number of samples as target arrays. Found 32 input samples and 479 target samples.
第三种方法:
这促使我将数据结构更改为:
x: np.ndarray[np.ndarray[np.int32]]
y: np.ndarray[np.int32]
这导致了以下错误:
Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).
第四种方法:
试,
x: np.ndarray[List[int]]
y: np.ndarray[int]
导致以下类似的错误消息:
Failed to convert a NumPy array to a Tensor (Unsupported object type list).
TLDR;
所以问题是:发生了什么事?为什么不model.fit(...)
接受这些参数?
请看下面我的回答。
解决方案
我记录这种混乱的原因是根本问题与错误消息无关。
根本问题是输入数据 ( x
) 需要填充。
句子自然有不同的长度。TensorFlowmodel.fit(...)
不喜欢这样。为了让它玩得更好,我需要填充句子以确保句子列表中每个句子包含相同数量的单词。(我只是对它们进行了零填充。)
如果你填充输入,两者都3rd Approach
应该4th Approach
工作。
推荐阅读
- oracle - 在 ubuntu 18.04 上安装 oracle 12c R2
- java - db 调用 javax.sql.rowset.spi.SyncFactoryException 中的奇怪错误:找不到资源 javax/sql/rowset/rowset.properties
- csv - 如何将响应数据保存到我在 JMeter 的简单数据编写器中生成的 CSV 文件
- c# - 加载 XAML 设计器时的 C# WPF 错误代码 32
- legend - 高库存。不更新导航器系列可见性
- kubernetes - 在 kubernetes 中找不到 persistentvolumeclaim
- php - 在 Woocommerce 3 中的结帐和我的帐户上启用自定义字段
- java - 使用 PDFBox 在 PDF 中断言文本 - Selenium/java
- python - 如何在 Python 中格式化具有多列但单行的数据框?
- ios - ios swift上的购物添加到购物车图标徽章通知