congrads 0.1.0__py3-none-any.whl → 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- congrads/__init__.py +10 -20
- congrads/callbacks/base.py +357 -0
- congrads/callbacks/registry.py +106 -0
- congrads/checkpoints.py +178 -0
- congrads/constraints/base.py +242 -0
- congrads/constraints/registry.py +1255 -0
- congrads/core/batch_runner.py +200 -0
- congrads/core/congradscore.py +271 -0
- congrads/core/constraint_engine.py +209 -0
- congrads/core/epoch_runner.py +119 -0
- congrads/datasets/registry.py +799 -0
- congrads/descriptor.py +147 -43
- congrads/metrics.py +116 -41
- congrads/networks/registry.py +68 -0
- congrads/py.typed +0 -0
- congrads/transformations/base.py +37 -0
- congrads/transformations/registry.py +86 -0
- congrads/utils/preprocessors.py +439 -0
- congrads/utils/utility.py +506 -0
- congrads/utils/validation.py +182 -0
- congrads-0.3.0.dist-info/METADATA +234 -0
- congrads-0.3.0.dist-info/RECORD +23 -0
- congrads-0.3.0.dist-info/WHEEL +4 -0
- congrads/constraints.py +0 -507
- congrads/core.py +0 -211
- congrads/datasets.py +0 -742
- congrads/learners.py +0 -233
- congrads/networks.py +0 -91
- congrads-0.1.0.dist-info/LICENSE +0 -34
- congrads-0.1.0.dist-info/METADATA +0 -196
- congrads-0.1.0.dist-info/RECORD +0 -13
- congrads-0.1.0.dist-info/WHEEL +0 -5
- congrads-0.1.0.dist-info/top_level.txt +0 -1
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Preprocessing functions for various datasets.
|
|
2
|
+
|
|
3
|
+
This module provides preprocessing pipelines for multiple datasets:
|
|
4
|
+
- BiasCorrection: Temperature bias correction dataset
|
|
5
|
+
- FamilyIncome: Family income and expenses dataset
|
|
6
|
+
- AdultCensusIncome: Adult Census Income dataset
|
|
7
|
+
|
|
8
|
+
Each preprocessing function applies appropriate transformations including
|
|
9
|
+
normalization, feature engineering, constraint filtering, and sampling.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def preprocess_BiasCorrection(df: pd.DataFrame) -> pd.DataFrame: # noqa: N802
|
|
17
|
+
"""Preprocesses the given dataframe for bias correction by performing a series of transformations.
|
|
18
|
+
|
|
19
|
+
The function sequentially:
|
|
20
|
+
|
|
21
|
+
- Drops rows with missing values.
|
|
22
|
+
- Converts a date string to datetime format and adds year, month,
|
|
23
|
+
and day columns.
|
|
24
|
+
- Normalizes the columns with specific logic for input and output variables.
|
|
25
|
+
- Adds a multi-index indicating which columns are input or output variables.
|
|
26
|
+
- Samples 2500 examples from the dataset without replacement.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
df (pd.DataFrame): The input dataframe containing the data
|
|
30
|
+
to be processed.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
pd.DataFrame: The processed dataframe after applying
|
|
34
|
+
the transformations.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def date_to_datetime(df: pd.DataFrame) -> pd.DataFrame:
|
|
38
|
+
"""Transform the string that denotes the date to the datetime format in pandas."""
|
|
39
|
+
# make copy of dataframe
|
|
40
|
+
df_temp = df.copy()
|
|
41
|
+
# add new column at the front where the date string is
|
|
42
|
+
# transformed to the datetime format
|
|
43
|
+
df_temp.insert(0, "DateTransformed", pd.to_datetime(df_temp["Date"]))
|
|
44
|
+
return df_temp
|
|
45
|
+
|
|
46
|
+
def add_year(df: pd.DataFrame) -> pd.DataFrame:
|
|
47
|
+
"""Extract the year from the datetime cell and add it as a new column to the dataframe at the front."""
|
|
48
|
+
# make copy of dataframe
|
|
49
|
+
df_temp = df.copy()
|
|
50
|
+
# extract year and add new column at the front containing these numbers
|
|
51
|
+
df_temp.insert(0, "Year", df_temp["DateTransformed"].dt.year)
|
|
52
|
+
return df_temp
|
|
53
|
+
|
|
54
|
+
def add_month(df: pd.DataFrame) -> pd.DataFrame:
|
|
55
|
+
"""Extract the month from the datetime cell and add it as a new column to the dataframe at the front."""
|
|
56
|
+
# make copy of dataframe
|
|
57
|
+
df_temp = df.copy()
|
|
58
|
+
# extract month and add new column at index 1 containing these numbers
|
|
59
|
+
df_temp.insert(1, "Month", df_temp["DateTransformed"].dt.month)
|
|
60
|
+
return df_temp
|
|
61
|
+
|
|
62
|
+
def add_day(df: pd.DataFrame) -> pd.DataFrame:
|
|
63
|
+
"""Extract the day from the datetime cell and add it as a new column to the dataframe at the front."""
|
|
64
|
+
# make copy of dataframe
|
|
65
|
+
df_temp = df.copy()
|
|
66
|
+
# extract day and add new column at index 2 containing these numbers
|
|
67
|
+
df_temp.insert(2, "Day", df_temp["DateTransformed"].dt.day)
|
|
68
|
+
return df_temp
|
|
69
|
+
|
|
70
|
+
def add_input_output_temperature(df: pd.DataFrame) -> pd.DataFrame:
|
|
71
|
+
"""Add a multiindex denoting if the column is an input or output variable."""
|
|
72
|
+
# copy the dataframe
|
|
73
|
+
temp_df = df.copy()
|
|
74
|
+
# extract all the column names
|
|
75
|
+
column_names = temp_df.columns.tolist()
|
|
76
|
+
# only the last 2 columns are output variables, all others are input
|
|
77
|
+
# variables. So make list of corresponding lengths of
|
|
78
|
+
# 'Input' and 'Output'
|
|
79
|
+
input_list = ["Input"] * (len(column_names) - 2)
|
|
80
|
+
output_list = ["Output"] * 2
|
|
81
|
+
# concat both lists
|
|
82
|
+
input_output_list = input_list + output_list
|
|
83
|
+
# define multi index for attaching this 'Input' and 'Output' list with
|
|
84
|
+
# the column names already existing
|
|
85
|
+
multiindex_bias = pd.MultiIndex.from_arrays([input_output_list, column_names])
|
|
86
|
+
# transpose such that index can be adjusted to multi index
|
|
87
|
+
new_df = pd.DataFrame(df.transpose().to_numpy(), index=multiindex_bias)
|
|
88
|
+
# transpose back such that columns are the same as before
|
|
89
|
+
# except with different labels
|
|
90
|
+
return new_df.transpose()
|
|
91
|
+
|
|
92
|
+
def normalize_columns_bias(df: pd.DataFrame) -> pd.DataFrame:
|
|
93
|
+
"""Normalize the columns for the bias correction dataset.
|
|
94
|
+
|
|
95
|
+
This is different from normalizing all the columns separately
|
|
96
|
+
because the upper and lower bounds for the output variables
|
|
97
|
+
are assumed to be the same.
|
|
98
|
+
"""
|
|
99
|
+
# copy the dataframe
|
|
100
|
+
temp_df = df.copy()
|
|
101
|
+
# normalize each column
|
|
102
|
+
for feature_name in df.columns:
|
|
103
|
+
# the output columns are normalized using the same upper and
|
|
104
|
+
# lower bound for more efficient check of the inequality
|
|
105
|
+
if feature_name == "Next_Tmax" or feature_name == "Next_Tmin":
|
|
106
|
+
max_value = 38.9
|
|
107
|
+
min_value = 11.3
|
|
108
|
+
# the input columns are normalized using their respective
|
|
109
|
+
# upper and lower bounds
|
|
110
|
+
else:
|
|
111
|
+
max_value = df[feature_name].max()
|
|
112
|
+
min_value = df[feature_name].min()
|
|
113
|
+
temp_df[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
|
|
114
|
+
return temp_df
|
|
115
|
+
|
|
116
|
+
def sample_2500_examples(df: pd.DataFrame) -> pd.DataFrame:
|
|
117
|
+
"""Sample 2500 examples from the dataframe without replacement."""
|
|
118
|
+
temp_df = df.copy()
|
|
119
|
+
sample_df = temp_df.sample(n=2500, replace=False, random_state=3, axis=0)
|
|
120
|
+
return sample_df
|
|
121
|
+
|
|
122
|
+
return (
|
|
123
|
+
# drop missing values
|
|
124
|
+
df.dropna(how="any")
|
|
125
|
+
# transform string date to datetime format
|
|
126
|
+
.pipe(date_to_datetime)
|
|
127
|
+
# add year as a single column
|
|
128
|
+
.pipe(add_year)
|
|
129
|
+
# add month as a single column
|
|
130
|
+
.pipe(add_month)
|
|
131
|
+
# add day as a single column
|
|
132
|
+
.pipe(add_day)
|
|
133
|
+
# remove original date string and the datetime format
|
|
134
|
+
.drop(["Date", "DateTransformed"], axis=1, inplace=False)
|
|
135
|
+
# convert all numbers to float32
|
|
136
|
+
.astype("float32")
|
|
137
|
+
# normalize columns
|
|
138
|
+
.pipe(normalize_columns_bias)
|
|
139
|
+
# add multi index indicating which columns are corresponding
|
|
140
|
+
# to input and output variables
|
|
141
|
+
.pipe(add_input_output_temperature)
|
|
142
|
+
# sample 2500 examples out of the dataset
|
|
143
|
+
.pipe(sample_2500_examples)
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def preprocess_FamilyIncome(df: pd.DataFrame) -> pd.DataFrame: # noqa: N802
|
|
148
|
+
"""Preprocesses the given Family Income dataframe.
|
|
149
|
+
|
|
150
|
+
The function sequentially:
|
|
151
|
+
|
|
152
|
+
- Drops rows with missing values.
|
|
153
|
+
- Converts object columns to appropriate data types and
|
|
154
|
+
removes string columns.
|
|
155
|
+
- Removes certain unnecessary columns like
|
|
156
|
+
'Agricultural Household indicator' and related features.
|
|
157
|
+
- Adds labels to columns indicating whether they are
|
|
158
|
+
input or output variables.
|
|
159
|
+
- Normalizes the columns individually.
|
|
160
|
+
- Checks and removes rows that do not satisfy predefined constraints
|
|
161
|
+
(household income > expenses, food expenses > sub-expenses).
|
|
162
|
+
- Samples 2500 examples from the dataset without replacement.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
df (pd.DataFrame): The input Family Income dataframe containing
|
|
166
|
+
the data to be processed.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
pd.DataFrame: The processed dataframe after applying the
|
|
170
|
+
transformations and constraints.
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
def normalize_columns_income(df: pd.DataFrame) -> pd.DataFrame:
|
|
174
|
+
"""Normalize each column of the dataframe independently.
|
|
175
|
+
|
|
176
|
+
This function scales each column to have values between 0 and 1
|
|
177
|
+
(or another standard normalization, depending on implementation),
|
|
178
|
+
making it suitable for numerical processing. While designed for
|
|
179
|
+
the Family Income dataset, it can be applied to any dataframe
|
|
180
|
+
with numeric columns.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
df (pd.DataFrame): Input dataframe to normalize.
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
pd.DataFrame: Dataframe with each column normalized independently.
|
|
187
|
+
"""
|
|
188
|
+
# copy the dataframe
|
|
189
|
+
temp_df = df.copy()
|
|
190
|
+
# normalize each column
|
|
191
|
+
for feature_name in df.columns:
|
|
192
|
+
max_value = df[feature_name].max()
|
|
193
|
+
min_value = df[feature_name].min()
|
|
194
|
+
temp_df[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
|
|
195
|
+
return temp_df
|
|
196
|
+
|
|
197
|
+
def check_constraints_income(df: pd.DataFrame) -> pd.DataFrame:
|
|
198
|
+
"""Filter rows that violate income-related constraints.
|
|
199
|
+
|
|
200
|
+
This function is specific to the Family Income dataset. It removes rows
|
|
201
|
+
that do not satisfy the following constraints:
|
|
202
|
+
1. Household income must be greater than all expenses.
|
|
203
|
+
2. Food expense must be greater than the sum of detailed food expenses.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
df (pd.DataFrame): Input dataframe containing income and expense data.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
pd.DataFrame: Filtered dataframe containing only rows that satisfy
|
|
210
|
+
all constraints.
|
|
211
|
+
"""
|
|
212
|
+
temp_df = df.copy()
|
|
213
|
+
# check that household income is larger than expenses in the output
|
|
214
|
+
input_array = temp_df["Input"].to_numpy()
|
|
215
|
+
income_array = np.add(
|
|
216
|
+
np.multiply(
|
|
217
|
+
input_array[:, [0, 1]],
|
|
218
|
+
np.subtract(np.asarray([11815988, 9234485]), np.asarray([11285, 0])),
|
|
219
|
+
),
|
|
220
|
+
np.asarray([11285, 0]),
|
|
221
|
+
)
|
|
222
|
+
expense_array = temp_df["Output"].to_numpy()
|
|
223
|
+
expense_array = np.add(
|
|
224
|
+
np.multiply(
|
|
225
|
+
expense_array,
|
|
226
|
+
np.subtract(
|
|
227
|
+
np.asarray(
|
|
228
|
+
[
|
|
229
|
+
791848,
|
|
230
|
+
437467,
|
|
231
|
+
140992,
|
|
232
|
+
74800,
|
|
233
|
+
2188560,
|
|
234
|
+
1049275,
|
|
235
|
+
149940,
|
|
236
|
+
731000,
|
|
237
|
+
]
|
|
238
|
+
),
|
|
239
|
+
np.asarray([3704, 0, 0, 0, 1950, 0, 0, 0]),
|
|
240
|
+
),
|
|
241
|
+
),
|
|
242
|
+
np.asarray([3704, 0, 0, 0, 1950, 0, 0, 0]),
|
|
243
|
+
)
|
|
244
|
+
expense_array_without_dup = expense_array[:, [0, 4, 5, 6, 7]]
|
|
245
|
+
sum_expenses = np.sum(expense_array_without_dup, axis=1)
|
|
246
|
+
total_income = np.sum(income_array, axis=1)
|
|
247
|
+
sanity_check_array = np.greater_equal(total_income, sum_expenses)
|
|
248
|
+
temp_df["Unimportant"] = sanity_check_array.tolist()
|
|
249
|
+
reduction = temp_df[temp_df.Unimportant]
|
|
250
|
+
drop_reduction = reduction.drop("Unimportant", axis=1)
|
|
251
|
+
|
|
252
|
+
# check that the food expense is larger than all the sub expenses
|
|
253
|
+
expense_reduced_array = drop_reduction["Output"].to_numpy()
|
|
254
|
+
expense_reduced_array = np.add(
|
|
255
|
+
np.multiply(
|
|
256
|
+
expense_reduced_array,
|
|
257
|
+
np.subtract(
|
|
258
|
+
np.asarray(
|
|
259
|
+
[
|
|
260
|
+
791848,
|
|
261
|
+
437467,
|
|
262
|
+
140992,
|
|
263
|
+
74800,
|
|
264
|
+
2188560,
|
|
265
|
+
1049275,
|
|
266
|
+
149940,
|
|
267
|
+
731000,
|
|
268
|
+
]
|
|
269
|
+
),
|
|
270
|
+
np.asarray([3704, 0, 0, 0, 1950, 0, 0, 0]),
|
|
271
|
+
),
|
|
272
|
+
),
|
|
273
|
+
np.asarray([3704, 0, 0, 0, 1950, 0, 0, 0]),
|
|
274
|
+
)
|
|
275
|
+
food_mul_expense_array = expense_reduced_array[:, [1, 2, 3]]
|
|
276
|
+
food_mul_expense_array_sum = np.sum(food_mul_expense_array, axis=1)
|
|
277
|
+
food_expense_array = expense_reduced_array[:, 0]
|
|
278
|
+
sanity_check_array = np.greater_equal(food_expense_array, food_mul_expense_array_sum)
|
|
279
|
+
drop_reduction["Unimportant"] = sanity_check_array.tolist()
|
|
280
|
+
new_reduction = drop_reduction[drop_reduction.Unimportant]
|
|
281
|
+
satisfied_constraints_df = new_reduction.drop("Unimportant", axis=1)
|
|
282
|
+
|
|
283
|
+
return satisfied_constraints_df
|
|
284
|
+
|
|
285
|
+
def add_input_output_family_income(df: pd.DataFrame) -> pd.DataFrame:
|
|
286
|
+
"""Add a multiindex denoting if the column is an input or output variable."""
|
|
287
|
+
# copy the dataframe
|
|
288
|
+
temp_df = df.copy()
|
|
289
|
+
# extract all the column names
|
|
290
|
+
column_names = temp_df.columns.tolist()
|
|
291
|
+
# the 2nd-9th columns correspond to output variables and all
|
|
292
|
+
# others to input variables. So make list of corresponding
|
|
293
|
+
# lengths of 'Input' and 'Output'
|
|
294
|
+
input_list_start = ["Input"]
|
|
295
|
+
input_list_end = ["Input"] * (len(column_names) - 9)
|
|
296
|
+
output_list = ["Output"] * 8
|
|
297
|
+
# concat both lists
|
|
298
|
+
input_output_list = input_list_start + output_list + input_list_end
|
|
299
|
+
# define multi index for attaching this 'Input' and
|
|
300
|
+
# 'Output' list with the column names already existing
|
|
301
|
+
multiindex_bias = pd.MultiIndex.from_arrays([input_output_list, column_names])
|
|
302
|
+
# transpose such that index can be adjusted to multi index
|
|
303
|
+
new_df = pd.DataFrame(df.transpose().to_numpy(), index=multiindex_bias)
|
|
304
|
+
# transpose back such that columns are the same as
|
|
305
|
+
# before except with different labels
|
|
306
|
+
return new_df.transpose()
|
|
307
|
+
|
|
308
|
+
def sample_2500_examples(df: pd.DataFrame) -> pd.DataFrame:
|
|
309
|
+
"""Sample 2500 examples from the dataframe without replacement."""
|
|
310
|
+
temp_df = df.copy()
|
|
311
|
+
sample_df = temp_df.sample(n=2500, replace=False, random_state=3, axis=0)
|
|
312
|
+
return sample_df
|
|
313
|
+
|
|
314
|
+
return (
|
|
315
|
+
# drop missing values
|
|
316
|
+
df.dropna(how="any")
|
|
317
|
+
# convert object to fitting dtype
|
|
318
|
+
.convert_dtypes()
|
|
319
|
+
# remove all strings (no other dtypes are present
|
|
320
|
+
# except for integers and floats)
|
|
321
|
+
.select_dtypes(exclude=["string"])
|
|
322
|
+
# transform all numbers to same dtype
|
|
323
|
+
.astype("float32")
|
|
324
|
+
# drop column with label Agricultural Household indicator
|
|
325
|
+
# because this is not really a numerical input but
|
|
326
|
+
# rather a categorical/classification
|
|
327
|
+
.drop(["Agricultural Household indicator"], axis=1, inplace=False)
|
|
328
|
+
# this column is dropped because it depends on
|
|
329
|
+
# Agricultural Household indicator
|
|
330
|
+
.drop(["Crop Farming and Gardening expenses"], axis=1, inplace=False)
|
|
331
|
+
# use 8 output variables and 24 input variables
|
|
332
|
+
.drop(
|
|
333
|
+
[
|
|
334
|
+
"Total Rice Expenditure",
|
|
335
|
+
"Total Fish and marine products Expenditure",
|
|
336
|
+
"Fruit Expenditure",
|
|
337
|
+
"Restaurant and hotels Expenditure",
|
|
338
|
+
"Alcoholic Beverages Expenditure",
|
|
339
|
+
"Tobacco Expenditure",
|
|
340
|
+
"Clothing, Footwear and Other Wear Expenditure",
|
|
341
|
+
"Imputed House Rental Value",
|
|
342
|
+
"Transportation Expenditure",
|
|
343
|
+
"Miscellaneous Goods and Services Expenditure",
|
|
344
|
+
"Special Occasions Expenditure",
|
|
345
|
+
],
|
|
346
|
+
axis=1,
|
|
347
|
+
inplace=False,
|
|
348
|
+
)
|
|
349
|
+
# add input and output labels to each column
|
|
350
|
+
.pipe(add_input_output_family_income)
|
|
351
|
+
# normalize all the columns
|
|
352
|
+
.pipe(normalize_columns_income)
|
|
353
|
+
# remove all datapoints that do not satisfy the constraints
|
|
354
|
+
.pipe(check_constraints_income)
|
|
355
|
+
# sample 2500 examples
|
|
356
|
+
.pipe(sample_2500_examples)
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def preprocess_AdultCensusIncome(df: pd.DataFrame) -> pd.DataFrame: # noqa: N802
|
|
361
|
+
"""Preprocesses the Adult Census Income dataset for PyTorch ML.
|
|
362
|
+
|
|
363
|
+
Sequential steps:
|
|
364
|
+
- Drop rows with missing values.
|
|
365
|
+
- Encode categorical variables to integer labels.
|
|
366
|
+
- Map the target 'income' column to 0/1.
|
|
367
|
+
- Convert all data to float32.
|
|
368
|
+
- Add a multiindex to denote Input vs Output columns.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
df (pd.DataFrame): Raw dataframe containing Adult Census Income data.
|
|
372
|
+
|
|
373
|
+
Returns:
|
|
374
|
+
pd.DataFrame: Preprocessed dataframe.
|
|
375
|
+
"""
|
|
376
|
+
|
|
377
|
+
def drop_missing(df: pd.DataFrame) -> pd.DataFrame:
|
|
378
|
+
"""Drop rows with any missing values."""
|
|
379
|
+
return df.dropna(how="any")
|
|
380
|
+
|
|
381
|
+
def drop_columns(df: pd.DataFrame) -> pd.DataFrame:
|
|
382
|
+
return df.drop(columns=["fnlwgt", "education.num"], errors="ignore")
|
|
383
|
+
|
|
384
|
+
def label_encode_column(series: pd.Series, col_name: str = None) -> pd.Series:
|
|
385
|
+
"""Encode a pandas Series of categorical strings into integers."""
|
|
386
|
+
categories = series.dropna().unique().tolist()
|
|
387
|
+
cat_to_int = {cat: i for i, cat in enumerate(categories)}
|
|
388
|
+
if col_name:
|
|
389
|
+
print(f"Column '{col_name}' encoding:")
|
|
390
|
+
for cat, idx in cat_to_int.items():
|
|
391
|
+
print(f" {cat} -> {idx}")
|
|
392
|
+
return series.map(cat_to_int).astype(int)
|
|
393
|
+
|
|
394
|
+
def encode_categorical(df: pd.DataFrame) -> pd.DataFrame:
|
|
395
|
+
"""Convert categorical string columns to integer labels using label_encode_column."""
|
|
396
|
+
df_temp = df.copy()
|
|
397
|
+
categorical_cols = [
|
|
398
|
+
"workclass",
|
|
399
|
+
"education",
|
|
400
|
+
"marital.status",
|
|
401
|
+
"occupation",
|
|
402
|
+
"relationship",
|
|
403
|
+
"race",
|
|
404
|
+
"sex",
|
|
405
|
+
"native.country",
|
|
406
|
+
]
|
|
407
|
+
for col in categorical_cols:
|
|
408
|
+
df_temp[col] = label_encode_column(df_temp[col].astype(str), col_name=col)
|
|
409
|
+
return df_temp
|
|
410
|
+
|
|
411
|
+
def map_target(df: pd.DataFrame) -> pd.DataFrame:
|
|
412
|
+
"""Map income column to 0 (<=50K) and 1 (>50K)."""
|
|
413
|
+
df_temp = df.copy()
|
|
414
|
+
df_temp["income"] = df_temp["income"].map({"<=50K": 0, ">50K": 1})
|
|
415
|
+
return df_temp
|
|
416
|
+
|
|
417
|
+
def convert_float32(df: pd.DataFrame) -> pd.DataFrame:
|
|
418
|
+
"""Convert all data to float32 for PyTorch compatibility."""
|
|
419
|
+
return df.astype("float32")
|
|
420
|
+
|
|
421
|
+
def add_input_output_index(df: pd.DataFrame) -> pd.DataFrame:
|
|
422
|
+
"""Add a multiindex indicating input and output columns."""
|
|
423
|
+
temp_df = df.copy()
|
|
424
|
+
column_names = temp_df.columns.tolist()
|
|
425
|
+
# Only the 'income' column is output
|
|
426
|
+
input_list = ["Input"] * (len(column_names) - 1)
|
|
427
|
+
output_list = ["Output"]
|
|
428
|
+
multiindex_list = input_list + output_list
|
|
429
|
+
multiindex = pd.MultiIndex.from_arrays([multiindex_list, column_names])
|
|
430
|
+
return pd.DataFrame(temp_df.to_numpy(), columns=multiindex)
|
|
431
|
+
|
|
432
|
+
return (
|
|
433
|
+
df.pipe(drop_missing)
|
|
434
|
+
.pipe(drop_columns)
|
|
435
|
+
.pipe(encode_categorical)
|
|
436
|
+
.pipe(map_target)
|
|
437
|
+
.pipe(convert_float32)
|
|
438
|
+
.pipe(add_input_output_index)
|
|
439
|
+
)
|