python - 使用预训练的 BERT 嵌入作为带有 tensorflow.keras 的 CNN 的输入会导致 ValueError
问题描述
我是 NLP 和深度学习的新手,所以我遇到了(可能)一个非常基本的问题。
我正在尝试创建一个基于预先训练的 BERT 嵌入作为特征的二进制分类器。到目前为止,我已经成功创建了嵌入,并使用 tensorflow.keras 构建了一个简单的 Sequential() 模型。下面的代码有效:
model = tf.keras.Sequential([
Dense(4, activation = 'relu', input_shape = (768,)),
Dense(4, activation = 'relu'),
Dense(1, activation = 'sigmoid')])
model.compile(optimizer = 'adam',
loss = 'binary_crossentropy',
metrics = ['accuracy'])
我想做的是将这段代码改编为现在的 CNN。但是,当我添加卷积层时,出现错误:
model = tf.keras.Sequential([
Conv1D(filters = 250, kernel_size = 3, padding='valid', activation='relu', strides=1, input_shape = (768,)),
GlobalMaxPooling1D(),
Dense(4, activation = 'relu'),
Dense(1, activation = 'sigmoid')])
model.compile(optimizer = 'adam',
loss = 'binary_crossentropy',
metrics = ['accuracy'])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-59695050a94e> in <module>()
3 GlobalMaxPooling1D(),
4 Dense(4, activation = 'relu'),
----> 5 Dense(1, activation = 'sigmoid')])
6
7 model.compile(optimizer = 'adam',
5 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
178 'expected ndim=' + str(spec.ndim) + ', found ndim=' +
179 str(ndim) + '. Full shape received: ' +
--> 180 str(x.shape.as_list()))
181 if spec.max_ndim is not None:
182 ndim = x.shape.ndims
ValueError: Input 0 of layer conv1d_2 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 768]
这是我使用的数据的样子。
特征:
train_features[0]
array([-4.97862399e-01, 1.49541467e-01, 5.81708886e-02, 1.63668215e-01,
-2.77605206e-01, 3.57868642e-01, 1.70950562e-01, 2.69330859e-01,
-3.29369396e-01, 2.12891083e-02, -4.02462274e-01, -1.98120754e-02,
-2.18944401e-01, 4.34780568e-01, -2.75409579e-01, 2.03015730e-01,...
train_features[0].shape
(768,)
标签:
train_labels.iloc[0:3]
turnout
0 73446 0
1 53640 1
16895 1
Name: turnout, dtype: int64
非常感谢任何建议。太感谢了!
解决方案
2D 卷积需要 4D 输入:(batch_size, width1, width2, channels)
.
您的数据是具有 shape 的单个数组(batch_size, 768)
。如果您真的想使用卷积(如果您认为数据中可能存在空间关系),则需要在将其输入模型之前对其进行适当的整形。
1D 卷积需要 3D 输入:(batch_size, length, channels)
.
推荐阅读
- c++ - OpenImageDenoise - 在 C++ 中使用预编译头文件时架构 x86_64 的未定义符号
- python - 递归地找到所有可能的路径,在每个节点上具有一定数量的移动和不同的选项
- javascript - 自定义细化列表时 Algolia 和 VueJs 的计时问题
- python - 如何在 Python 中扫描特定子字符串的输入?
- ios - Swift - 像带有文本换行的段落一样连接按钮
- sql - PostgreSQL - 对表“foo_bar”的 FROM 子句条目的无效引用
- amazon-web-services - 如何使用 Fargate 创建 AWS Kubernetes 集群 (EKS)?
- typo3 - 如何使用数组键中的特殊字符访问数组
- javascript - 反应:返回字母而不是整个值
- python - 为什么 Pandas 不会在匹配的日期时间索引上加入 DataFrame,即使它们看起来相同?