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

Office Address

Social List

How to Classify Weather Types Using a GRU Neural Network Model

Classifying Weather Types with GRU

Condition for Classifying Weather Types Using a GRU Neural Network

  • Description:
    A GRU-based neural network to classify weather types using a weather dataset. It preprocesses the data by encoding categorical variables, scaling features, and reshaping the input for the GRU model. The model is trained, evaluated, and visualized using metrics such as accuracy, F1 score, and a confusion matrix heatmap.
Step-by-Step Process
  • Import Libraries:
    Essential libraries such as Pandas, Numpy, TensorFlow, and Scikit-Learn are imported for data preprocessing, model building, and evaluation. Visualization libraries like Matplotlib and Seaborn are included for plotting.
  • Load and Inspect Dataset:
    The weather classification dataset is loaded using Pandas' read_csv() function. It contains various features related to weather and the target variable 'Weather Type.'
  • Check for Missing Data:
    The dataset is checked for null and NaN values using isnull().sum() to ensure data completeness before proceeding with further steps.
  • Visualize Correlations:
    The correlation matrix is computed and visualized using Seaborn's heatmap. This helps identify relationships between features and detect possible redundancies.
  • Prepare Data:
    The feature set (x) is prepared by dropping the target column, and the target variable (y) is set to 'Weather Type.' Categorical variables in x are label-encoded to convert them into numerical form.
  • Encode Target Variable:
    The target variable 'Weather Type' is encoded into numeric labels using LabelEncoder(). A list of unique weather types is stored for future reference.
  • Scale Features:
    The features are scaled using StandardScaler() to standardize data, improving model performance. The input is reshaped to a 3D array suitable for the GRU model.
  • Train-Test Split:
    The dataset is split into training and testing sets using an 80:20 ratio with train_test_split(). This ensures a separate set of data for model evaluation.
  • Build and Train GRU Model:
    A GRU-based neural network is defined with an input layer, a GRU layer, and a dense output layer. It is trained for 10 epochs with a batch size of 2.
  • Evaluate and Visualize:
    Predictions are made on the test set, and evaluation metrics such as accuracy, F1 score, recall, and precision are computed. A confusion matrix is plotted to visualize classification results.
Sample Source Code
  • # Import Necessary Libraries
    import pandas as pd
    import numpy as np
    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.layers import Dense, Input, GRU
    from tensorflow.keras.models import Model
    from sklearn.metrics import (classification_report, confusion_matrix, accuracy_score, f1_score, recall_score, precision_score)

    import warnings
    warnings.filterwarnings("ignore")

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

    # Check null values
    print("Check null values")
    df.isnull().sum()

    # Check NaN values
    print("Check NaN values")
    print(df.isnull().sum())

    # Check column data types
    print("Check data types of columns")
    print(df.dtypes)

    # Find Correlation
    correlation_matrix = df.corr()

    # Display the correlation matrix
    print(correlation_matrix)

    # Plot the heatmap
    plt.figure(figsize=(10, 8))
    sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5)
    plt.title('Correlation Heatmap')
    plt.show()

    x = df.drop('Weather Type', axis=1)
    y = df['Weather Type']

    labels = list(y.unique())

    # Label Encoding
    label = LabelEncoder()
    y = label.fit_transform(y)

    for i in x.columns:
    if x[i].dtypes == 'object':
    x[i] = label.fit_transform(x[i])

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

    x = x.reshape(x.shape[0], 1, x.shape[1])

    # Split train-test data
    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=.2, random_state=42)

    def GRU_model(input_shape):
    # Input layer
    inputs = Input(shape=input_shape)
    # GRU layer
    gru_layer = GRU(32, activation='relu', return_sequences=False)(inputs)
    # Output layer
    output_layer = Dense(4, activation='softmax')(gru_layer)
    # Build the model
    gru_model = Model(inputs=inputs, outputs=output_layer)
    # Compile the model with Adam optimizer and sparse_categorical_crossentropy loss function
    gru_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    return gru_model

    input_shape = (X_train.shape[1], X_train.shape[2])

    model = GRU_model(input_shape)

    # Summary of Model
    model.summary()

    model.fit(X_train, y_train, batch_size=2, epochs=10, validation_data=(X_test, y_test))

    y_pred = model.predict(X_test)
    y_pred = [np.argmax(i) for i in y_pred]

    # Calculate confusion matrix
    cm = confusion_matrix(y_test, y_pred)

    # Plot the heatmap with correct labels
    plt.figure(figsize=(6, 5))
    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=labels, yticklabels=labels)
    plt.title('Confusion Matrix Heatmap')
    plt.xlabel('Predicted Label')
    plt.ylabel('True Label')
    plt.show()

    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 (macro): ', f1_score(y_test, y_pred, average='macro'))
    print('Recall Score (macro): ', recall_score(y_test, y_pred, average='macro'))
    print('Precision Score (macro): ', precision_score(y_test, y_pred, average='macro'))
Screenshots
  • GRU Model Output Screenshot