Created
June 7, 2020 10:28
-
-
Save accessnash/2437402b58468d67411317f27e0fef63 to your computer and use it in GitHub Desktop.
Using FB'sProphet to forecast crime rate in Chicago using historical data from 2005-2017
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| """ | |
| Created on Wed Jun 3 21:13:54 2020 | |
| @author: Localuser | |
| """ | |
| import pandas as pd | |
| import numpy as np | |
| import seaborn as sns | |
| import matplotlib.pyplot as plt | |
| from fbprophet import Prophet | |
| chicago_df_1 = pd.read_csv('Chicago_Crimes_2005_to_2007.csv', error_bad_lines = False) | |
| chicago_df_2 = pd.read_csv('Chicago_Crimes_2008_to_2011.csv', error_bad_lines = False) | |
| chicago_df_3 = pd.read_csv('Chicago_Crimes_2012_to_2017.csv', error_bad_lines = False) | |
| chicago_df = pd.concat([chicago_df_1,chicago_df_2, chicago_df_3]) | |
| plt.figure(figsize = (10,10)) | |
| sns.heatmap(chicago_df.isnull(), cbar = False, cmap = 'YlGnBu') | |
| chicago_df.drop(['Unnamed: 0', 'Case Number', 'ID', 'IUCR', 'X Coordinate', 'Y Coordinate', 'Updated On', 'Year', 'FBI Code', 'Beat', 'Ward', 'Community Area', 'Location', 'District', 'Latitude', 'Longitude'], inplace = True, axis = 1) | |
| chicago_df.Date = pd.to_datetime(chicago_df.Date, format = '%m/%d/%Y %I:%M:%S: %p') | |
| chicago_df.index = pd.DateTimeIndex(chicago_df.Date) | |
| order_data = chicago_df['Primary Type'].value_counts().iloc[:15].index | |
| plt.figure(figsize = (15, 10)) | |
| sns.countplot(y = 'Primary Type', data = chicago_df, order = order_data) | |
| plt.figure(figsize = (15, 10)) | |
| sns.countplot(y = 'Location Description', data = chicago_df, order = chicago_df['Location Description'].value_counts().iloc[:15].index) | |
| chicago_df.resample('Y').size() | |
| plt.plot(chicago_df.resample('Y').size()) | |
| plt.title('Crime count per year') | |
| plt.xlabel('Years') | |
| plt.ylabel('Number of Crimes') | |
| plt.plot(chicago_df.resample('M').size()) | |
| plt.title('Crime count per month') | |
| plt.xlabel('Months') | |
| plt.ylabel('Number of Crimes') | |
| chicago_prophet = chicago_df.resample('M').size().reset_index() | |
| chicago_prophet.columns = ['Date', 'Crime Count'] | |
| chicago_prophet_df_final = chicago_prophet.rename(columns = {'Date':'ds', 'Crime Count': 'y'}) | |
| m = Prophet() | |
| m.fit(chicago_prophet_df_final) | |
| future = m.make_future_dataframe(periods = 365) | |
| forecast = m.predict(future) | |
| figure = m.plot(forecast, xlabel = 'Date', ylabel = 'Crime Rate') | |
| figure = m.plot_components(forecast) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment