class CrimeRateModel: def __init__(self): self.dr = DataReader() def hook(self): self.create_crime_rate() def create_crime_rate(self): self.dr.context = './data/' self.dr.fname = 'saved/crime_police.csv' police_crime = self.dr.csv_to_dframe() print('---------- pivotal 전 ------------------') print(police_crime.columns) """ Index(['Unnamed: 0', '관서명', '살인 발생', '살인 검거', '강도 발생', '강도 검거', '강간 발생', '강간 검거', '절도 발생', '절도 검거', '폭력 발생', '폭력 검거', '구별'], dtype='object') """ police = pd.pivot_table(police_crime, index='구별', aggfunc=np.sum) print('---------- pivotal 후 ------------------') print(police.columns) print(police) """ Index(['Unnamed: 0', '강간 검거', '강간 발생', '강도 검거', '강도 발생', '살인 검거', '살인 발생'], dtype='object') """ arrest_crime_1 = pd.to_numeric(police['살인 검거']) occurr_crime_1 = pd.to_numeric(police['살인 발생']) print('살인 검거 출력: %s'% (arrest_crime_1)) print('살인 발생 출력: %s'% (occurr_crime_1)) police['살인검거율'] = (arrest_crime_1 / occurr_crime_1) * 100 print('살인검거율 출력: %s'% (police['살인검거율'])) arrest_crime_2 = pd.to_numeric(police['강도 검거']) occurr_crime_2 = pd.to_numeric(police['강도 발생']) police['강도검거율'] = (arrest_crime_2 / occurr_crime_2) * 100 arrest_crime_3 = pd.to_numeric(police['강간 검거']) occurr_crime_3 = pd.to_numeric(police['강간 발생']) police['강간검거율'] = (arrest_crime_3 / occurr_crime_3) * 100 print('강간검거율 출력: %s' % (police['강간검거율'])) """ print('--------->> 이슈 발생') print(police['절도 검거']) arrest_crime_4 = pd.to_numeric(police['절도 검거']) print(arrest_crime_4) occurr_crime_4 = pd.to_numeric(police['절도 발생']) print('절도 검거 출력: %s' % (arrest_crime_4)) print('절도 발생 출력: %s' % (occurr_crime_4)) police['절도검거율'] = (arrest_crime_4 / occurr_crime_4) * 100 print('절도검거율 출력: %s' % (police['절도검거율'])) arrest_crime_5 = pd.to_numeric(police['폭력 검거']) occurr_crime_5 = pd.to_numeric(police['폭력 발생']) police['폭력검거율'] = (arrest_crime_5 / occurr_crime_5) * 100 """ police.drop(columns={'살인 검거','강도 검거','강간 검거'}, axis=1) print(police.columns)
class CrimeModel: def __init__(self): self.dr = DataReader() def hook(self) -> object: self.create_crime_police() def create_crime_police(self): self.dr.context = './data/' self.dr.fname = 'crime_in_Seoul.csv' crime = self.dr.csv_to_dframe() # print(crime) station_names = [] for name in crime['관서명']: station_names.append('서울'+str(name[:-1])+'경찰서') station_addrs = [] station_lats = [] # 위도 station_lngs= [] # 경도 gmaps = self.dr.create_gmaps() for name in station_names: tmp = gmaps.geocode(name, language='ko') station_addrs.append(tmp[0].get('formatted_address')) tmp_loc = tmp[0].get('geometry') station_lats.append(tmp_loc['location']['lat']) station_lngs.append(tmp_loc['location']['lng']) # print(name + '---> '+tmp[0].get('formatted_address')) gu_names = [] for name in station_addrs: tmp = name.split() gu_name = [gu for gu in tmp if gu[-1] == '구'][0] gu_names.append(gu_name) crime['구별'] = gu_names # 만약에 구와 경찰서 위치가 다른 경우 수작업이 필요합니다. crime.loc[crime['관서명']=='혜화서',['구별']] == '종로구' crime.loc[crime['관서명'] == '서부서', ['구별']] == '은평구' crime.loc[crime['관서명'] == '강서서', ['구별']] == '양천구' crime.loc[crime['관서명'] == '종암서', ['구별']] == '성북구' crime.loc[crime['관서명'] == '방배서', ['구별']] == '서초구' crime.loc[crime['관서명'] == '수서서', ['구별']] == '강남구' # print(crime) crime.to_csv(self.dr.context+'saved/crime_police.csv')
class PoliceChart: def __init__(self): self.dr = DataReader() def hook(self): police_norm = self.create_police_norm() #self.show_sns(police_norm) self.show_heatmap(police_norm) def create_police_norm(self): self.dr.context = './data/' self.dr.fname = 'saved/police_norm.csv' police_norm = self.dr.csv_to_dframe() #print(police_norm) return police_norm def show_sns(self, pn): font = 'C:/Windows/Fonts/malgun.ttf' font_name = font_manager.FontProperties(fname=font).get_name() print('폰트명 %s : ' % (font_name)) rc('font', family=font_name) sns.pairplot(pn, vars=['강도', '살인', '폭력'], kind='reg', height=3) sns.pairplot(pn, x_vars=['인구수', 'CCTV'], y_vars=['살인', '강도'], kind='reg', height=3) tmp_max = pn['검거'].max() pn['검거'] = pn['검거'] / tmp_max * 100 plt.figure(figsize=(10, 10)) plt.show() def show_heatmap(self, pn): font = 'C:/Windows/Fonts/malgun.ttf' font_name = font_manager.FontProperties(fname=font).get_name() print('폰트명 %s : ' % (font_name)) rc('font', family=font_name) pn_sort = pn.sort_values(by='검거', ascending=False) crime_rate_columns = ["살인검거율", "강도검거율", "강간검거율", "절도검거율", "폭력검거율"] sns.heatmap(pn_sort[crime_rate_columns], annot=True, fmt='f', linewidths=5) plt.title('범죄 검거 비율') #plt.show() crime_columns = ["살인", "강도", "강간", "절도", "폭력"] pn['범죄'] = pn['범죄'] / 5 pn_sort = pn.sort_values(by='범죄', ascending=False) plt.figure(figsize=(10, 10)) sns.heatmap(pn_sort[crime_columns], annot=True, fmt='f', linewidths=5) plt.title('범죄 비율') plt.show()
def __init__(self): self.dr = DataReader()
class CrimeMap: def __init__(self): self.dr = DataReader() def hook(self): #self.create_seoul_crime_map() self.create_map() def create_seoul_crime_map(self): self.dr.context = './data/' self.dr.fname = 'saved/police_norm.csv' pn = self.dr.csv_to_dframe() print(pn) self.dr.fname = 'geo_simple.json' geo_str = self.dr.json_load() map = folium.Map(location=[37.5502, 126.982], zoom_start=12, tiles='Stamen Toner') map.choropleth(geo_data=geo_str, name='choropleth', data=tuple(zip(pn['구별'], pn['범죄'])), columns=['State', 'Unemployment'], key_on='feature.id', fill_color='PuRd') map.save(self.dr.context + 'saved/seoul_crime_map.html') def create_map(self): print('-----------') self.dr.context = './data/' self.dr.fname = 'saved/police_norm.csv' pn = self.dr.csv_to_dframe() self.dr.fname = 'crime_in_Seoul.csv' crime = self.dr.csv_to_dframe() # print(crime) station_names = [] for name in crime['관서명']: station_names.append('서울' + str(name[:-1]) + '경찰서') station_addrs = [] station_lats = [] # 위도 station_lngs = [] # 경도 gmaps = self.dr.create_gmaps() for name in station_names: tmp = gmaps.geocode(name, language='ko') station_addrs.append(tmp[0].get('formatted_address')) tmp_loc = tmp[0].get('geometry') station_lats.append(tmp_loc['location']['lat']) station_lngs.append(tmp_loc['location']['lng']) print(name + '---> ' + tmp[0].get('formatted_address')) self.dr.fname = 'police_position.csv' police_pos = self.dr.csv_to_dframe() police_pos['lat'] = station_lats police_pos['lng'] = station_lngs print(police_pos.columns) col = ["살인 검거", "강도 검거", "강간 검거", "절도 검거", "폭력 검거"] tmp = police_pos[col] / police_pos[col].max() police_pos['검거'] = np.sum(tmp, axis=1) self.dr.fname = 'geo_simple.json' geo_str = self.dr.json_load() map = folium.Map(location=[37.5502, 126.982], zoom_start=12, tiles='Stamen Toner') map.choropleth(geo_data=geo_str, name='choropleth', data=tuple(zip(pn['구별'], pn['범죄'])), key_on='feature.id', fill_color='PuRd') for i in police_pos.index: folium.CircleMarker([police_pos['lat'][i], police_pos['lng'][i]], radius=police_pos['검거'][i] * 10, color='#0a0a32', fill_color='#0a0a32').add_to(map) map.save(self.dr.context + 'saved/seoul_police_map.html')
class CCTVModel: def __init__(self): self.dr = DataReader() def hook(self) -> object: self.create_cctv_pop() def create_cctv_pop(self) -> object: self.dr.context = './data/' self.dr.fname = 'CCTV_in_Seoul.csv' cctv = self.dr.csv_to_dframe() # print(cctv) cctv_idx = cctv.columns # print(cctv_idx) # print('::::::::::::::::::::::::::::') self.dr.fname = 'population_in_Seoul.xls' pop = self.dr.xls_to_dframe(2, 'B,D,G,J,N') # print(pop) pop_idx = pop.columns # print(pop_idx) cctv.rename(columns={cctv.columns[0]: '구별'}, inplace=True) pop.rename(columns={ pop.columns[0]: '구별', pop.columns[1]: '인구수', pop.columns[2]: '한국인', pop.columns[3]: '외국인', pop.columns[4]: '고령자' }, inplace=True) # cctv.sort_values(by='소계', ascending=True) pop.drop([0], inplace=True) # print(pop['구별'].unique()) # print(pop['구별'].isnull()) # 26행이 null pop.drop([26], inplace=True) pop['외국인비율'] = pop['외국인'] / pop['인구수'] * 100 pop['고령자비율'] = pop['고령자'] / pop['인구수'] * 100 cctv.drop(['2013년도 이전', '2014년', '2015년', '2016년'], 1, inplace=True) cctv_pop = pd.merge(cctv, pop, on='구별') cctv_pop.set_index('구별', inplace=True) cor1 = np.corrcoef(cctv_pop['고령자비율'], cctv_pop['소계']) cor2 = np.corrcoef(cctv_pop['외국인비율'], cctv_pop['소계']) print('고령자비율 과 CCTV 상관계수 {} \n 외국인비율 과 CCTV 상관계수 {}'.format( cor1, cor2)) """ r이 -1.0과 -0.7 사이이면, 강한 음적 선형관계, r이 -0.7과 -0.3 사이이면, 뚜렷한 음적 선형관계, r이 -0.3과 -0.1 사이이면, 약한 음적 선형관계, r이 -0.1과 +0.1 사이이면, 거의 무시될 수 있는 선형관계, r이 +0.1과 +0.3 사이이면, 약한 양적 선형관계, r이 +0.3과 +0.7 사이이면, 뚜렷한 양적 선형관계, r이 +0.7과 +1.0 사이이면, 강한 양적 선형관계 고령자비율 과 CCTV 상관계수 [[ 1. -0.28078554] 약한 음적 선형관계 [-0.28078554 1. ]] 외국인비율 과 CCTV 상관계수 [[ 1. -0.13607433] 거의 무시될 수 있는 [-0.13607433 1. ]] """ cctv_pop.to_csv(self.dr.context + 'saved/cctv_pop.csv')
class PoliceNormModel: def __init__(self): self.dr = DataReader() def hook(self): self.create_crime_rate() def create_crime_rate(self): self.dr.context = './data/' self.dr.fname = 'saved/crime_police.csv' police_crime = self.dr.csv_to_dframe() police = pd.pivot_table(police_crime, index='구별', aggfunc=np.sum) """ Index(['Unnamed: 0', '강간 검거', '강간 발생', '강도 검거', '강도 발생', '살인 검거', '살인 발생'], dtype='object') """ police['살인검거율'] = (police['살인 검거'] / police['살인 발생']) * 100 police['강도검거율'] = (police['강도 검거'] / police['강도 발생']) * 100 police['강간검거율'] = (police['강간 검거'] / police['강간 발생']) * 100 police['절도검거율'] = (police['절도 검거'] / police['절도 발생']) * 100 police['폭력검거율'] = (police['폭력 검거'] / police['폭력 발생']) * 100 police.drop(columns={'살인 검거','강도 검거','강간 검거'}, axis=1) crime_rate_columns = ["살인검거율","강도검거율","강간검거율","절도검거율","폭력검거율"] for i in crime_rate_columns: police.loc[police[i] > 100, 1] = 100 police.rename(columns = { '살인 발생': '살인', '강도 발생': '강도', '강간 발생': '강간', '절도 발생': '절도', '폭력 발생': '폭력' }, inplace=True) crime_columns = ["살인", "강도", "강간", "절도", "폭력"] x = police[crime_rate_columns].values min_max_scalar = preprocessing.MinMaxScaler() """ 스케일링은 선형변환을 적용하여 전체 자료의 분포를 평균 0, 분산 1이 되도록 만드는 과정 """ x_scaled = min_max_scalar.fit_transform(x.astype(float)) """ 정규화(normalization) 많은 양의 데이터를 처리함에 있어 여러 이유로 정규화, 즉 데이터의 범위를 일치시키거나 분포를 유사하게 만들어 주는 등의 작업. 평균값 정규화, 중간값 정규화, Quantile 정규화 -- 제일 작은 값들은 갖은 값을 갖고, -- 두 번째로 작은 값들이 같은 값을 갖고... """ police_norm = pd.DataFrame(x_scaled, columns=crime_columns, index=police.index) police_norm[crime_rate_columns] = police[crime_rate_columns] self.dr.fname='saved/cctv_pop.csv' cctv_pop = pd.read_csv(self.dr.new_file(), encoding='UTF-8', sep=',', index_col='구별') police_norm[['인구수','CCTV']] = cctv_pop[['인구수','소계']] # 소계는 CCTV 갯수 print('>>') print(police_norm) police_norm['범죄'] = np.sum(police_norm[crime_rate_columns], axis=1) police_norm['검거'] = np.sum(police_norm[crime_columns], axis=1) print(police_norm.columns) police_norm.to_csv(self.dr.context + 'saved/police_norm.csv', sep=',', encoding='utf-8')