Roby - Alfred AI Code

import pandas as pd
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.neighbors import KernelDensity
from geopy.distance import geodesic
import matplotlib.pyplot as plt

# Load the data
crime_data = pd.read_csv(‘REDACTED’)
crime_data[‘Date’] = pd.to_datetime(crime_data[‘Date’], errors=’coerce’)

# Filter for the last 3 years
recent_crime_data = crime_data[crime_data[‘Date’].dt.year >= 2017]

# Kernel Density Estimation for identifying the probable location
location_data = recent_crime_data[[‘Latitude’, ‘Longitude’]].dropna()
X = location_data.values

kde = KernelDensity(bandwidth=0.01, metric=’haversine’, kernel=’gaussian’, algorithm=’ball_tree’)
kde.fit(np.radians(X))

latitude_range = (location_data[‘Latitude’].min(), location_data[‘Latitude’].max())
longitude_range = (location_data[‘Longitude’].min(), location_data[‘Longitude’].max())

x_mesh, y_mesh = np.linspace(latitude_range[0], latitude_range[1], 100), np.linspace(longitude_range[0], longitude_range[1], 100)
X_mesh, Y_mesh = np.meshgrid(x_mesh, y_mesh)
XY_samples = np.vstack([X_mesh.ravel(), Y_mesh.ravel()]).T

Z = np.exp(kde.score_samples(np.radians(XY_samples)))
predicted_idx = np.unravel_index(np.argmax(Z, axis=None), Z.shape)
predicted_lat_lon = (x_mesh[predicted_idx[0]], y_mesh[predicted_idx[1]])

# Predict the most likely crime type
radius = 2.0
filtered_recent_crimes = recent_crime_data.dropna(subset=[‘Latitude’, ‘Longitude’])
nearby_crimes_extended = filtered_recent_crimes[filtered_recent_crimes.apply(lambda row: geodesic((row[‘Latitude’], row[‘Longitude’]), predicted_lat_lon).kilometers <= radius, axis=1)]
crime_counts_extended = nearby_crimes_extended[‘Primary Type’].value_counts()

most_likely_crime_extended = crime_counts_extended.idxmax() if not crime_counts_extended.empty else filtered_recent_crimes[‘Primary Type’].value_counts().idxmax()

# Predict the exact spot for the theft
theft_nearby = nearby_crimes_extended[nearby_crimes_extended[‘Primary Type’] == ‘THEFT’]
most_recent_theft = theft_nearby[theft_nearby[‘Date’] == theft_nearby[‘Date’].max()]
exact_spot = most_recent_theft[[‘Latitude’, ‘Longitude’]].iloc[0] if not most_recent_theft.empty else None

print(f”Predicted Location: {predicted_lat_lon}”)
print(f”Most Likely Crime Type: {most_likely_crime_extended}”)
print(f”Exact Spot for Theft: {exact_spot}”)