CoolFace
Apppublic

NoCommentsElder/Machine_Learning_Model

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py73 linesDownload Raw Back to root
1# Importing necessary libraries2import pandas as pd3import seaborn as sns4import matplotlib.pyplot as plt5 6# Setting up seaborn7sns.set(color_codes=True)8 9# Function to load and preprocess data10def load_and_preprocess_data(filepath):11    try:12        df = pd.read_csv(filepath)13        df['Start_Time'] = pd.to_datetime(df['Start_Time'], format='mixed', errors='coerce')14        return df15    except Exception as e:16        print(f"An error occurred while loading data: {e}")17        return None18 19# Function for plotting hourly accidents distribution20def plot_hourly_accidents(df):21    try:22        fig, axes = plt.subplots(4, 2, figsize=(18, 10))23        plt.subplots_adjust(hspace=0.5)24        blue_palette = sns.light_palette("blue", n_colors=8, reverse=True)25 26        for i in range(8):27            ax = axes[i//2, i%2]28            if i == 0:29                sns.histplot(df['Start_Time'].dt.hour, bins=24, ax=ax, color=blue_palette[i])30                ax.set_title("Overall Hourly Accident Distribution")31            else:32                day_data = df[df['Start_Time'].dt.dayofweek == i-1]33                sns.histplot(day_data['Start_Time'].dt.hour, bins=24, ax=ax, color=blue_palette[i])34                ax.set_title(f"Hourly Distribution: {day_data['Start_Time'].dt.day_name().iloc[0]}")35            ax.set_xlabel("Hour")36            ax.set_ylabel("Accidents")37 38        plt.tight_layout()39        plt.show()40    except Exception as e:41        print(f"An error occurred while plotting hourly accidents: {e}")42 43# Function for plotting weather conditions44def plot_weather_conditions(df):45    try:46        weather = df['Weather_Condition'].value_counts().head(15)47        plt.figure(figsize=(30, 10))48        sns.barplot(x=weather.index, y=weather.values, palette="Reds_r")49        plt.xticks(rotation=45, fontsize=15)50        plt.yticks(fontsize=15)51        plt.xlabel("Weather Condition", fontsize=20)52        plt.ylabel("Count", fontsize=20)53        plt.title("Weather Condition vs Accidents", fontsize=30)54        plt.show()55    except Exception as e:56        print(f"An error occurred while plotting weather conditions: {e}")57 58# Main script59def main():60    # Load and preprocess data61    df = load_and_preprocess_data('US_Accidents_March23.csv')62 63    # Check if DataFrame is loaded correctly64    if df is not None and not df.empty:65        # Plotting functions66        plot_hourly_accidents(df)67        plot_weather_conditions(df)68    else:69        print("Data loading failed or the DataFrame is empty.")70 71# Run the main script72main()73