简体   繁体   English

如何在 Tensorflow 2 中的嵌入层之后放置 Conv1D 层?

[英]How do I put a Conv1D layer after an Embedding layer in Tensorflow 2?

For an evaluation, I need to be able to apply a convolutional layer to text data.对于评估,我需要能够将卷积层应用于文本数据。 So I'm trying to perform sentiment analysis on Amazon reviews.所以我正在尝试对亚马逊评论进行情绪分析。 After the Embedding layer, however, the Conv1D layer will not get the required shape.然而,在Embedding层之后, Conv1D层将无法获得所需的形状。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
print(f'Tensorflow version {tf.__version__}')
from tensorflow import keras
from tensorflow.keras.layers import Dense, Conv1D, GlobalAveragePooling1D, Embedding
import tensorflow_datasets as tfds
from tensorflow.keras.models import Model

(train_data, test_data), info = tfds.load('imdb_reviews/subwords8k',
                                          split=[tfds.Split.TRAIN, tfds.Split.TEST],
                                          as_supervised=True, with_info=True)

padded_shapes = ([None], ())

train_dataset = train_data.shuffle(25000).padded_batch(padded_shapes=padded_shapes, batch_size=16)
test_dataset = test_data.shuffle(25000).padded_batch(padded_shapes=padded_shapes, batch_size=16)

n_words = info.features['text'].encoder.vocab_size


class ConvModel(Model):
    def __init__(self):
        super(ConvModel, self).__init__()
        self.embe = Embedding(n_words, output_dim=16)
        self.conv = Conv1D(32, kernel_size=6, activation='elu')
        self.glob = GlobalAveragePooling1D()
        self.dens = Dense(2)

    def call(self, x, training=None, mask=None):
        x = self.embe(x)
        x = self.conv(x)
        x = self.glob(x)
        x = self.dens(x)
        return x

conv = ConvModel()

conv(next(iter(train_data))[0])

ValueError: Input 0 of layer conv1d_25 is incompatible with the layer: expected ndim=3, found ndim=2. ValueError: 层 conv1d_25 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。 Full shape received: [163, 16]收到的完整形状:[163, 16]

How is it possible to achieve this, and if I'm wrong, what is the proper way to use a Conv1D layer to text sequences?怎么可能实现这一点,如果我错了,将Conv1D层用于文本序列的正确方法是什么?

it's conv(next(iter(train_dataset))[0]) and not conv(next(iter(train_data))[0])它是conv(next(iter(train_dataset))[0])而不是conv(next(iter(train_data))[0])

the network structure is ok网络结构没问题

you have done it so far so good.到目前为止,你做得很好。 The last line of the code should be changed.应更改代码的最后一行。 That's all.就这样。 The parameter should be train_data not the train_dataset.参数应该是 train_data 而不是 train_dataset。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
print(f'Tensorflow version {tf.__version__}')
from tensorflow import keras
from tensorflow.keras.layers import Dense, Conv1D, GlobalAveragePooling1D, Embedding
import tensorflow_datasets as tfds
from tensorflow.keras.models import Model

(train_data, test_data), info = tfds.load('imdb_reviews/subwords8k',
                                          split=[tfds.Split.TRAIN, tfds.Split.TEST],
                                          as_supervised=True, with_info=True)

padded_shapes = ([None], ())

train_dataset = train_data.shuffle(25000).padded_batch(padded_shapes=padded_shapes, batch_size=16)
test_dataset = test_data.shuffle(25000).padded_batch(padded_shapes=padded_shapes, batch_size=16)

n_words = info.features['text'].encoder.vocab_size


class ConvModel(Model):
    def __init__(self):
        super(ConvModel, self).__init__()
        self.embe = Embedding(n_words, output_dim=16)
        self.conv = Conv1D(32, kernel_size=6, activation='elu')
        self.glob = GlobalAveragePooling1D()
        self.dens = Dense(2)

    def call(self, x, training=None, mask=None):
        x = self.embe(x)
        x = self.conv(x)
        x = self.glob(x)
        x = self.dens(x)
        return x

conv = ConvModel()

conv(next(iter(train_data))[0])

Hope you fix the error.希望你修复错误。

The out_dim of word embedding layer should match with conv1D input filter size.词嵌入层的 out_dim 应与 conv1D 输入过滤器大小匹配。 Try changing the out_dim to 32. Proper way: https://machinelearningmastery.com/predict-sentiment-movie-reviews-using-deep-learning/尝试将 out_dim 更改为 32。正确方法: https://machinelearningmastery.com/predict-sentiment-movie-reviews-using-deep-learning/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM