-
Notifications
You must be signed in to change notification settings - Fork 2
/
master.py
178 lines (155 loc) · 4.6 KB
/
master.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# -*- coding: utf-8 -*-
"""master.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1P7F1FH_JrnKQ3Ov-LBm2mU7PSNGEtVlZ
"""
# Commented out IPython magic to ensure Python compatibility.
from sklearn.cluster import KMeans
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import plotly.graph_objects as go
import matplotlib.cm as cm
import plotly.express as px
# %matplotlib inline
#df = pd.read_csv("/content/drive/My Drive/Crimes_-_2001_to_present.csv",nrows=48601)
df = pd.read_csv("https://raw.githubusercontent.com/namanvashistha/doctor_strange/master/crime.csv")
df = df[np.isfinite(df['Latitude'])]
df = df[np.isfinite(df['Longitude'])]
df
crime_count = pd.DataFrame(df.groupby('Primary Type').size().sort_values(ascending=False).rename('counts').reset_index())
crime_count
plt.scatter(df.Latitude,df.Longitude)
plt.xlabel('Latitude')
plt.ylabel('Longitude')
fig = go.Figure(data=go.Scattergeo(
lon = df['Longitude'],
lat = df['Latitude'],
text = df['Latitude'],
mode = 'markers',
marker_color = 25129,
))
fig.update_layout(
title = 'Crime Report',
geo_scope='usa',
)
fig.show()
#Elbow Plot
sse = []
K = []
k_rng = range(1,50)
for k in k_rng:
km = KMeans(n_clusters=k)
km.fit(df[['Latitude','Longitude']])
sse.append(km.inertia_)
K.append(k)
plt.xlabel('K')
plt.ylabel('Sum of squared error')
axes= plt.axes()
axes.set_xticks(K)
plt.grid()
plt.plot(k_rng,sse)
plt.scatter(k_rng,sse,color='green')
km = KMeans(n_clusters=8)
y_predicted = km.fit_predict(df[['Latitude','Longitude']])
np.random.seed(1)
Dim = 2
Rows = 30; Cols = 30
RangeMax = Rows + Cols
LearnMax = 0.5
StepsMax = 10000
print("Constructing a SOM ")
map = np.random.random_sample(size=(Rows,Cols,Dim))
for s in range(StepsMax):
if s % (StepsMax/10) == 0: print("step = ", str(s))
pct_left = 1.0 - ((s * 1.0) / StepsMax)
curr_range = (int)(pct_left * RangeMax)
curr_rate = pct_left * LearnMax
t = np.random.randint(5)
for i in range(Rows):
for j in range(Cols):
map[i][j] = map[i][j] + curr_rate
print("SOM construction complete \n")
print("Constructing U-Matrix from SOM")
u_matrix = np.zeros(shape=(Rows,Cols), dtype=np.float64)
for i in range(Rows):
for j in range(Cols):
v = map[i][j]
sum_dists = 0.0; ct = 0
if i-1 >= 0:
sum_dists += map[i-1][j]; ct += 1
if i+1 <= Rows-1:
sum_dists += map[i+1][j]; ct += 1
if j-1 >= 0:
sum_dists += map[i][j-1]; ct += 1
if j+1 <= Cols-1:
sum_dists += map[i][j+1]; ct += 1
print("U-Matrix constructed \n")
df['cluster']=y_predicted
centroids=km.cluster_centers_
centroids
#magnitude based
#Elbow Plot
sse = []
K = []
k_rng = range(1,50)
for k in k_rng:
km = KMeans(n_clusters=k)
km.fit(df[['Beat','District']])
sse.append(km.inertia_)
K.append(k)
plt.xlabel('K')
plt.ylabel('Sum of squared error')
axes= plt.axes()
axes.set_xticks(K)
plt.grid()
plt.plot(k_rng,sse)
#plt.scatter(k_rng,sse,color='green')
km = KMeans(n_clusters=28)
y_predicted = km.fit_predict(df[['Beat','Ward']])
df['cluster']=y_predicted
centroids=km.cluster_centers_
df,
centroids
colors = cm.rainbow(np.linspace(0, 1,10))
plt.scatter(df.Latitude,df.Longitude,color=colors[df.cluster])
plt.scatter(centroids[:,0],
centroids[:,1],
color='purple',marker='*',
label='centroid')
plt.xlabel('latitude')
plt.ylabel('longitude')
plt.legend()
fig = px.scatter_mapbox(df,
lat="Latitude",
lon="Longitude",zoom=10,
color="cluster",
color_continuous_scale=px.colors.qualitative.G10,
height=500,
opacity=0.05)
fig.add_trace(go.Scattermapbox(
lat=centroids[:,0],
lon=centroids[:,1],
mode='markers',
marker=go.scattermapbox.Marker(
size=10,
color='rgb(255, 0, 0)',
)
))
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
fig = go.Figure(go.Densitymapbox(
lat=df.Latitude,
lon=df.Longitude,
z=df.index,
radius=1,)
)
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
import seaborn as sns
sns.jointplot(x=df["Latitude"], y=df["Longitude"], kind='kde', color="grey", space=0)
sns.jointplot(x=df["Latitude"], y=df["Longitude"], kind='kde', color="grey", space=3)
sns.jointplot(x=df["Latitude"], y=df["Longitude"], kind='kde',ratio=1)