Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

build_features.py 4.9 KB

You have to be logged in to leave a comment. Sign In
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
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2021. Jeffrey J. Nirschl. All rights reserved.
  3. #
  4. # Licensed under the MIT license. See the LICENSE.md file in the project
  5. # root directory for full license information.
  6. #
  7. # Time-stamp: <>
  8. # ======================================================================
  9. import argparse
  10. import os
  11. from pathlib import Path
  12. import numpy as np
  13. import pandas as pd
  14. from sklearn.preprocessing import PolynomialFeatures
  15. from src.data import load_data, load_params, save_as_csv
  16. def main(train_path, test_path,
  17. output_dir):
  18. """Build features
  19. TODO- Currently a placeholder script that saves existing files until feature engineering is implemented"""
  20. output_dir = Path(output_dir).resolve()
  21. assert (os.path.isdir(output_dir)), NotADirectoryError
  22. # load train and test data because feature engineering process should be identical
  23. train_df, test_df = load_data([train_path, test_path],
  24. sep=",", header=0,
  25. index_col="PassengerId")
  26. params = load_params()
  27. target_class = params["train_test_split"]["target_class"]
  28. # pop the target class
  29. train_labels = train_df.pop(target_class)
  30. # concatenate df
  31. df = pd.concat([train_df, test_df], sort=False)
  32. # load params
  33. params = load_params()
  34. params_featurize = params["feature_eng"]
  35. params_featurize["random_seed"] = params["random_seed"]
  36. # optionally normalize data
  37. if params_featurize["featurize"]:
  38. # create poly features
  39. df = create_poly_features(df, degree=2,
  40. interaction_only=True)
  41. # hand-crafted features
  42. df = hand_crafted_features(df)
  43. # bin continuous features
  44. df['Age'] = pd.qcut(df['Age'], 10,
  45. duplicates="drop").astype('category').cat.codes
  46. df['Fare'] = pd.qcut(df['Fare'], 13).astype('category').cat.codes
  47. df['family_size'] = pd.qcut(df['family_size'], 3,
  48. duplicates="drop").astype('category').cat.codes
  49. # return datasets to train and test
  50. train_df = df.loc[train_df.index, df.columns]
  51. train_df.insert(loc=0, column=target_class,
  52. value=train_labels)
  53. test_df = df.loc[test_df.index, df.columns]
  54. # save data
  55. save_as_csv([train_df, test_df],
  56. [train_path, test_path],
  57. output_dir,
  58. replace_text="_nan_imputed.csv",
  59. suffix="_featurized.csv",
  60. na_rep="nan")
  61. def hand_crafted_features(df):
  62. df["family_size"] = df["SibSp"] + df["Parch"] +1
  63. df["is_vip"] = is_vip(df)
  64. df["parent"] = is_parent(df)
  65. df["is_orphan"] = is_orphan(df)
  66. df["is_single_adult_mother"] = is_single_adult_mother(df)
  67. df["is_single_adult_male"] = is_single_adult_male(df)
  68. return df
  69. def is_vip(df):
  70. return pd.DataFrame([df["Pclass"] == 1,
  71. df["Fare"] > np.percentile(df["Fare"], 95)]).transpose().all(axis=1).astype(int)
  72. def is_parent(df):
  73. return pd.DataFrame([df["Parch"] == 1,
  74. df["Age"] >= 18]).transpose().all(axis=1).astype(int)
  75. def is_orphan(df):
  76. return pd.DataFrame([df["Parch"] == 0,
  77. df["SibSp"] == 0,
  78. df["Age"] < 18]).transpose().all(axis=1).astype(int)
  79. def is_single_adult_mother(df):
  80. return pd.DataFrame([df["Parch"] > 0,
  81. df["SibSp"] == 0,
  82. df["Sex"] == 0,
  83. df["Age"] >= 18]).transpose().all(axis=1).astype(int)
  84. def is_single_adult_male(df):
  85. return pd.DataFrame([df["Parch"] == 0,
  86. df["SibSp"] == 0,
  87. df["Sex"] == 1,
  88. df["Age"] >= 18]).transpose().all(axis=1).astype(int)
  89. def create_poly_features(df, degree=2,
  90. interaction_only=True):
  91. # create polynomial feature instance
  92. poly = PolynomialFeatures(degree=degree,
  93. interaction_only=interaction_only)
  94. poly.fit_transform(df.to_numpy())
  95. poly_cols = poly.get_feature_names(df.columns)
  96. poly_df = pd.DataFrame(poly.fit_transform(df.to_numpy()),
  97. columns=poly_cols).set_index(df.index)
  98. return poly_df.drop(columns=poly_cols[0])
  99. if __name__ == '__main__':
  100. parser = argparse.ArgumentParser()
  101. parser.add_argument("-tr", "--train", dest="train_path",
  102. required=True, help="Train CSV file")
  103. parser.add_argument("-te", "--test", dest="test_path",
  104. required=True, help="Test CSV file")
  105. parser.add_argument("-o", "--out-dir", dest="output_dir",
  106. default=Path("./data/interim").resolve(),
  107. required=False, help="output directory")
  108. args = parser.parse_args()
  109. # convert categorical variables into integer codes
  110. main(args.train_path, args.test_path,
  111. args.output_dir)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...