《Python 深度学习》6.4 用卷积神经网络处理序列

# 用卷积神经网络处理序列

 1. 实现一维卷积神经网络


Keras 中的一维卷积神经网络是 Conv1D 层,其接口类似于 Conv2D。它接收的输入是形状 为 (samples, time, features) 的三维张量,并返回类似形状的三维张量。卷积窗口是时间轴上的一维窗口(时间轴是输入张量的第二个轴)。

我们来构建一个简单的两层一维卷积神经网络,并将其应用于我们熟悉的 IMDB 情感分类任务。

提醒一下,获取数据并预处理的代码如下所示。

from keras.datasets import imdb
from keras.preprocessing import sequence

max_features = 10000  
# Number of words to consider as features(作为特征的单词个数)
max_len = 500  
# cut texts after this number of words (among top max_features most common words)
# 在这么多单词之后截断文本(这些单词都属于前 max_features 个最常见的单词)
print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')

print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)

一维卷积神经网络的架构与第 5 章的二维卷积神经网络相同,它是 Conv1D 层和 MaxPooling1D 层的堆叠,最后是一个全局池化层或 Flatten 层,将三维输出转换为二维输出,让你可以向模型中添加一个或多个 Dense 层,用于分类或回归。

不过二者有一点不同:一维卷积神经网络可以使用更大的卷积窗口。对于二维卷积层,3×3 的卷积窗口包含 3×3=9 个特征向量;但对于一位卷积层,大小为 3 的卷积窗口只包含3个卷积向量。因此,你可以轻松使用大小等于 7 或 9 的一维卷积窗口。

用于 IMDB 数据集的一维卷积神经网络示例如下所示。

# 在 IMDB 上训练并评估一个简单的一维卷积神经网络

from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import RMSprop

model = Sequential()
model.add(layers.Embedding(max_features, 128, input_length=max_len))

model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.MaxPooling1D(5))

model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.GlobalMaxPooling1D())

model.add(layers.Dense(1))

model.summary()

model.compile(optimizer=RMSprop(lr=1e-4),
              loss='binary_crossentropy',
              metrics=['acc'])
history = model.fit(x_train, y_train,
                    epochs=10,
                    batch_size=128,
                    validation_split=0.2)


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值