如何使用Keras为1D输入向量构建卷积神经网络(CNN)?
Hey there! Let's work through building a 1D CNN for your input-output setup in Keras. From your examples, it looks like you're tackling a sequence-to-sequence regression task—your input is a 1D vector of length 16, and your output is another 1D vector (also length 16, based on the df_y snippet). Here's a step-by-step guide to get this working smoothly:
Keras 1D CNN layers expect input in the shape (number_of_samples, sequence_length, number_of_features). Since each of your inputs is a flat 1D vector (16 values), we need to reshape them to add a "feature dimension" (set to 1, since each position is a single feature). Same goes for your output labels.
Here's how to do that with your DataFrames:
import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv1D, Dense # Convert DataFrames to numpy arrays X = df_x.values y = df_y.values # Reshape for 1D CNN compatibility # Shape becomes (samples, 16, 1) for both inputs and outputs X = X.reshape(X.shape[0], X.shape[1], 1) y = y.reshape(y.shape[0], y.shape[1], 1)
The goal here is to let the model learn patterns in your 1D sequence, then output a sequence of the same length for regression. We'll use Conv1D layers with padding='same'—this ensures the output sequence length stays identical to the input, which is critical for your task.
Here's a solid starter model:
model = Sequential() # First convolutional layer: extract local patterns model.add(Conv1D( filters=32, # Number of feature detectors kernel_size=3, # Sliding window size over the sequence activation='relu', # Non-linear activation to learn complex patterns padding='same', # Keep sequence length the same input_shape=(16, 1) # Match our reshaped input )) # Second convolutional layer to deepen feature learning model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding='same')) # Final layer: map each timestep to a single continuous output value model.add(Dense(1, activation='linear')) # Linear activation for regression (no squashing) # Check the model structure model.summary()
For regression tasks, we use a loss function like Mean Squared Error (MSE) which measures the average squared difference between predictions and true values. We'll use the Adam optimizer (a reliable default) and track Mean Absolute Error (MAE) as an additional metric.
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mae']) # Train the model—adjust epochs/batch size based on your dataset size history = model.fit( X, y, epochs=50, batch_size=32, validation_split=0.2 # Reserve 20% of data for validation )
Once trained, you can predict on the specific sample you mentioned (df_x.iloc[300]):
# Grab the 300th sample and reshape it to match model input sample_input = df_x.iloc[300].values.reshape(1, 16, 1) # Generate prediction predicted_output = model.predict(sample_input) # Flatten the result back to a 1D vector (like your original df_y format) predicted_output = predicted_output.flatten() print("Predicted output for sample 300:", predicted_output)
Quick Notes to Keep in Mind
- Stick with
padding='same': If you skip this, convolution will shrink your sequence length, and your output won't match the shape ofdf_y. - Adjust model depth: If your task is complex, add more
Conv1Dlayers or increase the number of filters. If it's simple, you can reduce layers/filters to avoid overfitting. - Check output shape: Double-check that
df_yhas the same sequence length asdf_x(16 in your example). If it's different, you'll need to adjust the model (e.g., add pooling/upsampling layers or use a different output structure).
内容的提问来源于stack exchange,提问作者CezarySzulc

