-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_classification.py
More file actions
214 lines (187 loc) · 7.23 KB
/
data_classification.py
File metadata and controls
214 lines (187 loc) · 7.23 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#! /usr/bin/python
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy.stats import multivariate_normal
import typer
import lib.data_processing_functions as dpf
app = typer.Typer()
@app.command()
def data_classification(year: int):
lib_path = "lib"
sys.path.insert(0, lib_path)
sns.set_style("whitegrid", {"grid.linestyle": "--", "axes.edgecolor": "0"})
data_path = "data/"
yr = str(year)
ENIGHr = pd.read_csv(data_path + "ENIGH" + yr + "_clean.csv", index_col=[0])
ENIGH = ENIGHr.copy()
ENIGH = dpf.hhld_classification(ENIGH)
ps_list = ENIGH.node.unique()
ENIGH["count_node"] = ENIGH.groupby("node")["node"].transform("count")
d = ENIGH.sort_values(by=["count_node"], ignore_index=True)
f = plt.figure(figsize=(20, 8))
f.subplots_adjust(hspace=0.0)
fontsize_ticks = 20
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
ax.tick_params(labelsize=fontsize_ticks)
sns.despine()
sns.set_color_codes("muted")
sns.histplot(y="age_habit", data=d[d.sex_hhrp == "H"], color="y", label="Hombre", alpha=0.7)
sns.set_color_codes("muted")
sns.histplot(y="age_habit", data=d[d.sex_hhrp == "M"], color="b", label="Mujer", alpha=0.7)
ax.legend(loc="best", frameon=True, fontsize=fontsize_ticks)
plt.xscale("log")
plt.xlabel("Número de personas", fontsize=fontsize_ticks)
plt.ylabel("")
plt.savefig("reports/figures/CH_NumPersonas" + yr + ".pdf", bbox_inches="tight")
plt.show()
ENIGH.drop(columns=["sex_hhrp", "age_habit"], inplace=True)
t = "CH"
ENIGH.to_csv(data_path + "/ENIGH_" + t + yr + ".csv", index=True)
personclass = {}
for ps in ENIGH.node.unique():
personclass[ps] = ENIGH[ENIGH.node == ps]
# stadardization in dictionary
personclass_std = {}
ps_newlist = list()
for ps in ps_list:
df = dpf.standardization(personclass[ps])
if (len(df.columns) > 1) & (any(df.columns.str.contains("energia"))):
personclass_std[ps] = df
ps_newlist.append(ps)
ps_df = personclass["HAdultosMenores"].reset_index(drop=True)
ps_std_df = personclass_std["HAdultosMenores"].reset_index(drop=True)
cov_mtx = np.cov(ps_std_df.ing_cor, ps_std_df.energia)
mean1 = ps_std_df.ing_cor.mean()
mean2 = ps_std_df.energia.mean()
x, y = np.mgrid[-2:15:0.01, -2:15:0.01]
pos = np.dstack((x, y))
rv = multivariate_normal([mean1, mean2], cov_mtx)
fig, ax = plt.subplots(figsize=(8, 8))
ax.contourf(x, y, rv.pdf(pos), cmap="YlOrBr")
sns.scatterplot(
data=ps_std_df,
x="ing_cor",
y="energia",
color="lightgreen",
alpha=0.1,
size=0.005,
edgecolor=None,
)
ax.set_xlim((-2, 15))
ax.set_ylim((-2, 15))
ax.set_ylabel("Z score Energia (-)", fontsize=fontsize_ticks)
ax.set_xlabel("Z score Ingreso corriente (-)", fontsize=fontsize_ticks)
axins = ax.inset_axes([0.5, 0.5, 0.47, 0.47])
axins.contourf(x, y, rv.pdf(pos), cmap="YlOrBr")
x1, x2, y1, y2 = -2, 2, -2, 2
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
ax.indicate_inset_zoom(axins, edgecolor="black")
ax.get_legend().remove()
plt.savefig("reports/figures/Energia_Corriente_Zscore.png", bbox_inches="tight", dpi=100)
plt.show()
cov_mtx = np.cov(ps_std_df.alfabetism, ps_std_df.energia)
mean1 = ps_std_df.alfabetism.mean()
mean2 = ps_std_df.alfabetism.mean()
x, y = np.mgrid[-2:15:0.01, -2:15:0.01]
pos = np.dstack((x, y))
rv = multivariate_normal([mean1, mean2], cov_mtx)
fig, ax = plt.subplots(figsize=(8, 8))
ax.contourf(x, y, rv.pdf(pos), cmap="YlOrBr")
sns.scatterplot(
data=ps_std_df,
x="alfabetism",
y="energia",
color="lightgreen",
alpha=0.1,
size=0.005,
edgecolor=None,
)
ax.set_xlim((-2, 15))
ax.set_ylim((-2, 15))
ax.set_ylabel("Z score Energia (-)", fontsize=fontsize_ticks)
ax.set_xlabel("Z score Alfabetismo (-)", fontsize=fontsize_ticks)
axins = ax.inset_axes([0.5, 0.5, 0.47, 0.47])
axins.contourf(x, y, rv.pdf(pos), cmap="YlOrBr")
x1, x2, y1, y2 = -2, 2, -2, 2
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
ax.indicate_inset_zoom(axins, edgecolor="black")
ax.get_legend().remove()
plt.savefig("reports/figures/Energia_Alfabetismo_Zscore.png", bbox_inches="tight", dpi=100)
plt.show()
f = plt.figure(figsize=(8 * 1.6, 8))
f.subplots_adjust(hspace=0.0)
fontsize_ticks = 20
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
ax.tick_params(labelsize=fontsize_ticks)
sns.despine()
sns.scatterplot(
data=ps_df, x="ing_cor", y="energia", ax=ax, color="blue", alpha=0.5, edgecolor=None
)
ax2 = ax.twiny()
ax2.tick_params(labelsize=fontsize_ticks)
sns.scatterplot(
data=ps_df, x="alfabetism", y="energia", ax=ax2, color="orange", alpha=0.5, edgecolor=None
)
ax.set_xlim((-5, 1650000))
ax2.set_xlim((-5, 1650000))
ax.set_ylabel("Energia (MXN)", fontsize=fontsize_ticks)
ax.set_xlabel("Ingreso corriente (MXN)", fontsize=fontsize_ticks)
ax2.set_xlabel("Alfabetismo (-)", fontsize=fontsize_ticks)
plt.savefig("reports/figures/Energia_Alfabetismo_Diferencias.png", bbox_inches="tight", dpi=50)
plt.show()
f = plt.figure(figsize=(8 * 1.6, 8))
f.subplots_adjust(hspace=0.0)
fontsize_ticks = 20
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
ax.tick_params(labelsize=fontsize_ticks)
sns.despine()
sns.scatterplot(data=ps_std_df, x="ing_cor", y="energia", ax=ax, color="blue", edgecolor=None)
ax2 = ax.twiny()
ax2.tick_params(labelsize=fontsize_ticks)
sns.scatterplot(
data=ps_std_df, x="alfabetism", y="energia", ax=ax2, color="orange", edgecolor=None
)
ax.set_xlim((-1, 30))
ax2.set_xlim((-1, 30))
ax.set_ylabel("Z score Energia (-)", fontsize=fontsize_ticks)
ax.set_xlabel("Z score Ingreso corriente (-)", fontsize=fontsize_ticks)
ax2.set_xlabel("Z score Alfabetismo (-)", fontsize=fontsize_ticks)
plt.savefig(
"reports/figures/Energia_Alfabetismo_Diferencias_Zscore.png", bbox_inches="tight", dpi=50
)
plt.show()
personclass_energy = {}
for ps in ps_newlist:
personclass_energy[ps] = abs(personclass_std[ps].cov(numeric_only=True).energia)
personclass_energy[ps].drop(["energia", "vivienda"], inplace=True)
series = list()
for ps in ps_newlist:
sx = personclass_energy[ps]
sx.rename(ps, inplace=True)
series.append(sx)
cov_matrix_CH = pd.concat(series, axis=1).fillna(0)
f = plt.figure(figsize=(30, 30))
f.subplots_adjust(hspace=0.0)
fontsize_ticks = 25
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
ax.tick_params(labelsize=fontsize_ticks)
sns.heatmap(cov_matrix_CH, cmap="jet")
cax = plt.gcf().axes[-1]
cax.tick_params(labelsize=fontsize_ticks)
plt.savefig("reports/figures/CovMatrix_Heatmap" + yr + ".pdf", bbox_inches="tight")
plt.show()
# Save covariance matrix Household Classification
t = "CH"
cov_matrix_CH.to_csv(data_path + "cov_matrix_" + t + yr + ".csv", index=True)
if __name__ == "__main__":
typer.run(data_classification)