Untitled

 avatar
unknown
c_cpp
a month ago
2.5 kB
3
Indexable
# 1. Importing Required Libraries
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, LSTM, Dense, Reshape
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt

# 2. Generating Synthetic Time Series Data
def generate_data(seq_length=100):
    x = np.linspace(0, 50, seq_length)
    y = np.sin(x) + np.random.normal(0, 0.1, seq_length)  # Adding noise
    return y

# 3. Preparing the Dataset for CNN-LSTM
def create_dataset(data, time_steps=10):
    X, Y = [], []
    for i in range(len(data) - time_steps):
        X.append(data[i:i + time_steps])  # Take last 10 values as input
        Y.append(data[i + time_steps])    # Next value as output
    return np.array(X), np.array(Y)

# 4. Normalizing the Data
data = generate_data(100)  # Generate synthetic data
scaler = MinMaxScaler()
data_scaled = scaler.fit_transform(data.reshape(-1, 1))  # Normalize between 0 and 1

# 5. Creating Training and Testing Data
time_steps = 10  # Defining the number of time steps
X, Y = create_dataset(data_scaled, time_steps)
X = X.reshape(X.shape[0], X.shape[1], 1)  # Reshape for CNN-LSTM

split = int(len(X) * 0.8)  # 80% for training, 20% for testing
X_train, Y_train = X[:split], Y[:split]
X_test, Y_test = X[split:], Y[split:]

# 6. Building the CNN-LSTM Model
model = Sequential([
    Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(time_steps, 1)),  # Fixed input_shape here
    MaxPooling1D(pool_size=2),
    Flatten(),  # Flatten to make it 1D for the LSTM layer
    Reshape((-1, 1)),  # Reshape to 3D tensor for LSTM (samples, time_steps, features)
    LSTM(50, activation='relu'),
    Dense(1)
])

# 7. Compiling the Model
model.compile(optimizer='adam', loss='mse')

# 8. Training the Model
model.fit(X_train, Y_train, epochs=20, batch_size=16, validation_data=(X_test, Y_test))

# 9. Making Predictions
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)  # Inverse transform to match original scale
Y_test_actual = scaler.inverse_transform(Y_test.reshape(-1, 1))  # Actual test values

# 10. Visualizing the Results
plt.figure(figsize=(10, 5))
plt.plot(Y_test_actual, label='Actual')
plt.plot(predictions, label='Predicted')
plt.legend()
plt.title("CNN-LSTM Time Series Prediction")
plt.show()
Editor is loading...
Leave a Comment