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

star_type_predictions.py 7.3 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
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
  1. import numpy as np
  2. import pandas as pd
  3. import pickle
  4. import sys
  5. import os
  6. import glob
  7. import pickle
  8. import csv
  9. import timeit
  10. from sklearn.compose import ColumnTransformer
  11. from sklearn.preprocessing import StandardScaler, OneHotEncoder
  12. from sklearn.compose import make_column_selector as selector
  13. from sklearn.model_selection import train_test_split
  14. from sklearn.pipeline import Pipeline
  15. from sklearn.linear_model import LogisticRegression
  16. from sklearn.ensemble import RandomForestClassifier
  17. from sklearn.svm import SVC
  18. from sklearn.neighbors import KNeighborsClassifier
  19. from sklearn.multiclass import OneVsRestClassifier
  20. from sklearn.model_selection import GridSearchCV
  21. from sklearn.metrics import accuracy_score
  22. import matplotlib.pyplot as plt
  23. import plots
  24. class Model:
  25. def __init__(self, datafolder=None, param_grid=None):
  26. datafolder = sys.argv[1] #data/prepared
  27. self.df = pickle.load(open(os.path.join(datafolder, 'data.pkl'), 'rb'))
  28. self.standard_ml_model = LogisticRegression()
  29. os.makedirs('model', exist_ok=True)
  30. self.model_filename = sys.argv[2] #model.pkl
  31. os.makedirs('reports', exist_ok=True)
  32. os.makedirs('reports/metrics', exist_ok=True)
  33. self.scores_filename = os.path.join('reports', 'metrics', sys.argv[3]) #scores.csv
  34. os.makedirs('predicted', exist_ok=True)
  35. self.predictions_filename = os.path.join('predicted', sys.argv[4]) #predictions.csv
  36. def prepocess(self):
  37. """
  38. Preprocess the data through normalization of numeric variables and categorical transformations.
  39. """
  40. numeric_transformer = StandardScaler()
  41. categorical_transformer = OneHotEncoder(handle_unknown='ignore')
  42. self.preprocessor = ColumnTransformer(
  43. transformers=[
  44. ('num', numeric_transformer, selector(dtype_exclude=object)),#self.numeric_features),
  45. ('cat', categorical_transformer, selector(dtype_include=object))#self.categorical_features)
  46. ],
  47. remainder='passthrough'
  48. )
  49. def split(self, test_size):
  50. """
  51. Split the dataset into a training and test set for model building.
  52. """
  53. X = self.df[self.df.columns[:-1]]
  54. y = self.df['Star type']
  55. self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size=test_size, random_state=1)
  56. def fit(self):
  57. """
  58. Fit a Grid Search on multiple classification models. Save each model.
  59. """
  60. # Define hyperparameters per classification model
  61. names = [
  62. "Logistic Regression",
  63. "Random Forest",
  64. "Support Vector Machine",
  65. "KNeighbors"
  66. ]
  67. param_grid = [
  68. {'classifier': [LogisticRegression()],
  69. 'classifier__C': [0.1, 1.0, 10]},
  70. {'classifier': [RandomForestClassifier()],
  71. 'classifier__n_estimators': [50, 100],
  72. 'classifier__max_features' :['sqrt', 'log2'],
  73. 'classifier__max_depth': [4,6,8]},
  74. {'classifier': [SVC()],
  75. 'classifier__C': [0.1, 1.0, 10],
  76. 'classifier__kernel': ['linear'],
  77. 'classifier__probability': [True]},
  78. {'classifier': [KNeighborsClassifier()],
  79. 'classifier__n_neighbors': [3, 5],
  80. 'classifier__weights': ['uniform', 'distance']}
  81. ]
  82. classifier_param = list(zip(names, param_grid))
  83. # Loop over each classifier to fit the Grid Search
  84. for name, params in classifier_param:
  85. # Collect run time for each model and add to filename
  86. start = timeit.default_timer()
  87. # Create classifier
  88. clf = params['classifier'][0]
  89. # Build pipeline
  90. steps = [('preprocessor', self.preprocessor),
  91. ('classifier', OneVsRestClassifier(self.standard_ml_model))
  92. ]
  93. # Fit Grid Search using cross validation
  94. grid_search = GridSearchCV(Pipeline(steps), param_grid=params, cv=5)
  95. model = grid_search.fit(self.X_train, self.y_train)
  96. stop = timeit.default_timer()
  97. runtime = round(stop - start, 3)
  98. # Save each model
  99. pickle.dump(model, open(os.path.join('model', '{}_{}_{}'.format(name, runtime, self.model_filename)), 'wb')) #model.pkl
  100. def evaluate(self):
  101. """
  102. Evaluate the performance of each model in terms of the accuracy score.
  103. """
  104. # Create output dataframe
  105. output_cols = ["Classifier", "Accuracy", "Best parameters", "Run time"]
  106. output = pd.DataFrame(columns=output_cols)
  107. # load each model
  108. with os.scandir('model') as entries:
  109. for entry in entries:
  110. loaded_model = pickle.load(open(os.path.join(entry), 'rb'))
  111. # Get score of each model and write output to file
  112. score = accuracy_score(self.y_test, loaded_model.predict(self.X_test)) #loaded_model.score(self.X_test, self.y_test)
  113. # Extract the run time from the file name
  114. runtime = entry.name.split('_')[1]
  115. # Extract the classifier from the file name
  116. classifier = entry.name.split('_')[0]
  117. # Write results to dataframe
  118. output_entry = pd.DataFrame([[classifier, score, loaded_model.best_params_, runtime]], columns=output_cols)
  119. output = output.append(output_entry, ignore_index=True)
  120. output.sort_values(by=['Accuracy', 'Run time'], inplace=True)
  121. output.to_csv(self.scores_filename, index=False)
  122. def predict(self):
  123. """
  124. Predict the target variable for the best performing model.
  125. """
  126. # Find best model
  127. with open(os.path.join(self.scores_filename), 'rb') as fd:
  128. df = pd.read_csv(fd)
  129. # Load best model (order by first row, column 'Classifier')
  130. with os.scandir('model') as entries:
  131. for entry in entries:
  132. if entry.name.startswith(df.iloc[0,0]):
  133. best_model = pickle.load(open(os.path.join(entry), 'rb'))
  134. # Predict target variable and write to csv file
  135. predictions = best_model.predict(self.X_test)
  136. df = pd.DataFrame(predictions, columns=['predicted'])
  137. df['predicted'].map({
  138. 0: 'Brown Dwarf',
  139. 1: 'Red Dwarf',
  140. 2: 'White Dwarf',
  141. 3: 'Main Sequence',
  142. 4: 'Supergiant',
  143. 5: 'Hypergiant'
  144. },
  145. inplace=True
  146. )
  147. df.to_csv(self.predictions_filename, index=False)
  148. if __name__ == '__main__':
  149. model_instance = Model()
  150. model_instance.prepocess()
  151. model_instance.split(0.2)
  152. model_instance.fit()
  153. model_instance.evaluate()
  154. model_instance.predict()
  155. # python src/star_type_predictions.py data/prepared model.pkl scores.csv predictions.csv
Tip!

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

Comments

Loading...