简单的一个两层的一维卷积网络

以下是一个两层的一维卷积神经网络的示例代码:

import tensorflow as tf

# 输入层
input_shape = (batch_size, input_length, input_channels)
inputs = tf.keras.Input(shape=input_shape)

# 第一层卷积层
conv1_filters = 32
conv1_kernel = 3
conv1_pool = 2
conv1_padding = 'same'
conv1_activation = 'relu'

conv1 = tf.keras.layers.Conv1D(
    filters=conv1_filters,
    kernel_size=conv1_kernel,
    padding=conv1_padding,
    activation=conv1_activation)(inputs)

conv1_pool = tf.keras.layers.MaxPooling1D(pool_size=conv1_pool)(conv1)

# 第二层卷积层
conv2_filters = 64
conv2_kernel = 3
conv2_pool = 2
conv2_padding = 'same'
conv2_activation = 'relu'

conv2 = tf.keras.layers.Conv1D(
    filters=conv2_filters,
    kernel_size=conv2_kernel,
    padding=conv2_padding,
    activation=conv2_activation)(conv1_pool)

conv2_pool = tf.keras.layers.MaxPooling1D(pool_size=conv2_pool)(conv2)

# 展平层
flatten = tf.keras.layers.Flatten()(conv2_pool)

# 全连接层
fc_units = 128
fc_activation = 'relu'

fc = tf.keras.layers.Dense(units=fc_units, activation=fc_activation)(flatten)

# 输出层
output_units = num_classes
output_activation = 'softmax'

outputs = tf.keras.layers.Dense(units=output_units, activation=output_activation)(fc)

# 定义模型
model = tf.keras.Model(inputs=inputs, outputs=outputs)

这个模型包括两层卷积层,每一层都是由一个卷积层和一个最大池化层构成的。输入层是一个一维张量,形状为(batch_size, input_length, input_channels),输出层是一个softmax分类器。模型可以通过下面的代码进行编译和训练:

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=batch_size, epochs=num_epochs, validation_data=(x_val, y_val))

其中x_train和y_train是训练数据和标签,x_val和y_val是验证数据和标签。

你可能感兴趣的:(卷积神经网络)