List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Build a Deep Neural Network (DNN) Model for Weather Forecast Classification Using Weather Data

Building an Deep Neural Network (DNN) Model for Weather Forecast Classification Using Weather Data

Condition for Building an Deep Neural Network (DNN) Model for Weather Forecast Classification Using Weather Data

  • Description:
    This code performs classification on a weather forecast dataset, predicting whether it will rain based on various weather features. It preprocesses the data by encoding categorical variables, scaling the features, and splitting the dataset for training and testing. A deep neural network (DNN) model is built, trained, and evaluated using performance metrics such as accuracy, F1-score, and confusion matrix.
Step-by-Step Process
  • Import Necessary Libraries:
    Import essential libraries like Pandas, Matplotlib, Seaborn, and Scikit-learn for data manipulation, visualization, and model evaluation. TensorFlow and Keras are imported for building and training the deep neural network model.
  • Load Dataset:
    Load the weather forecast dataset using pd.read_csv() and display the first five rows to preview the data.
  • Split Dataset:
    Split the dataset into independent variables (x) and the target variable (y). The Rain column is the dependent variable.
  • Check Class Imbalance:
    Plot the distribution of the target variable using a pie chart to check for class imbalance.
  • Data Preprocessing:
    Encode the target variable and scale the feature variables using LabelEncoder and StandardScaler, respectively.
  • Train-Test Split:
    Split the dataset into training and testing sets using train_test_split().
  • Build and Train the Model:
    Define the DNN model with one input layer, two hidden layers, and an output layer, and train it using the training data.
  • Evaluate and Visualize:
    Evaluate the model using performance metrics like classification report, confusion matrix, accuracy, F1-score, recall, and precision. Display the confusion matrix using a heatmap.
Sample Source Code
  • # Import Necessary Libraries
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    from sklearn.preprocessing import LabelEncoder, StandardScaler
    from sklearn.model_selection import train_test_split
    from tensorflow.keras.models import Model
    from tensorflow.keras.layers import Input, Dense
    from sklearn.metrics import (classification_report, confusion_matrix, accuracy_score, f1_score, recall_score, precision_score)

    df = pd.read_csv("/home/soft12/Downloads/sample_dataset/Website/Dataset/weather_forecast_data.csv")

    # Print data
    print(df.head())

    # Split the dependent and Independent Variable
    x = df.drop('Rain', axis=1)
    y = df['Rain']

    # Check Class Imbalance
    class_counts = df['Rain'].value_counts()
    plt.figure(figsize=(6, 6))
    plt.pie(class_counts, labels=class_counts.index, autopct='%1.1f%%', startangle=90, colors=sns.color_palette('Set3', len(class_counts)))
    plt.title('Class Distribution in Training Data')
    plt.show()

    # Convert categorical data into numeric data
    label = LabelEncoder()
    y = label.fit_transform(y)

    # Scaling the data
    scaler = StandardScaler()
    x = scaler.fit_transform(x)

    # Split the Dataset for Training and Testing
    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)

    def DNN_model(input_shape):
    # Input layer
    inputs = Input(shape=input_shape)

    # First dense layer
    dense_layer1 = Dense(64, activation='relu')(inputs)
    dense_layer2 = Dense(32, activation='relu')(dense_layer1)

    # Output layer
    output_layer = Dense(1, activation='sigmoid')(dense_layer2)

    # Build the model
    lstm_model = Model(inputs=inputs, outputs=output_layer)

    # Compile the model with Adam optimizer and binary crossentropy loss function
    lstm_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

    return lstm_model

    model = DNN_model((X_train.shape[1],))

    # Summary of the model
    model.summary()

    # Train the model
    history = model.fit(X_train, y_train, batch_size=32, epochs=10, validation_data=(X_test, y_test), verbose=1)

    y_pred = model.predict(X_test)
    y_pred = [1 if i > 0.5 else 0 for i in y_pred]

    print("___Performance_Metrics___\n")
    print('Classification_Report:\n', classification_report(y_test, y_pred))
    print('Confusion_Matrix:\n', confusion_matrix(y_test, y_pred))
    print('Accuracy_Score: ', accuracy_score(y_test, y_pred))
    print('F1_Score: ', f1_score(y_test, y_pred))
    print('Recall_Score: ', recall_score(y_test, y_pred))
    print('Precision_Score: ', precision_score(y_test, y_pred))

    # Plot Confusion Matrix
    # Compute confusion matrix
    cm = confusion_matrix(y_test, y_pred)

    # Plot confusion matrix using seaborn heatmap
    plt.figure(figsize=(6, 6))
    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Not Rain', 'Rain'], yticklabels=['Not Rain', 'Rain'])
    plt.title('Confusion Matrix')
    plt.xlabel('Predicted Label')
    plt.ylabel('True Label')
    plt.show()
Screenshots
  • Weather Forecast Model Screenshot