-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
343 lines (254 loc) · 10.5 KB
/
app.py
File metadata and controls
343 lines (254 loc) · 10.5 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import numpy as np
import pandas as pd
import os
import gc # For garbage collection
import warnings
# Visualization
import matplotlib.pyplot as plt
import seaborn as sns
# Stats
from scipy.stats import pearsonr
# Preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer
# Model Evaluation
from sklearn.metrics import (
r2_score,
mean_squared_error,
mean_absolute_error,
mean_squared_log_error
)
# Regression Models
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import (
RandomForestRegressor,
AdaBoostRegressor,
GradientBoostingRegressor
)
# Advanced Models
from xgboost import XGBRegressor
# print(np.__version__)
# pd.test()
# retrieving files from 'kaggle/inout' dir and listing the down below
for dirname, _, filenames in os.walk('kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# defining Training-paths
TRAIN_PATH = 'kaggle/input/drw-crypto-market-prediction/train.parquet'
TEST_PATH = 'kaggle/input/drw-crypto-market-prediction/test.parquet'
SAMPLE_SUB_PATH = 'kaggle/input/drw-crypto-market-prediction/sample_submission.csv'
# Load data
print('Loading data')
train_df = pd.read_parquet(TRAIN_PATH, engine='pyarrow')
print('Loading test data')
test_df = pd.read_parquet(TEST_PATH, engine='pyarrow')
print('Loading sample submission')
sample_data_submission = pd.read_csv(SAMPLE_SUB_PATH)
print(f'Train shape: {train_df.shape}')
print(f'Test shape: {test_df.shape}')
train_df.head()
test_df.head()
sample_data_submission
train_df.isnull().sum()
test_df.isnull().sum()
numerical_features = [feature for feature in train_df.columns if train_df[feature].dtype!='O']
categorical_features = [feature for feature in train_df.columns if train_df[feature].dtype=='O']
numerical_features
print("Total Numerical Features:",len(numerical_features))
print("Total Categorical Features:",len(categorical_features))
categorical_features
# with the following function we can select highly correlated features
# it will remove the first feature that is correlated with anything other feature
# def correlation(dataset, threshold):
# col_corr = set() # Set of all the names of correlated columns
# corr_matrix = dataset.corr()
# for i in range(len(corr_matrix.columns)):
# for j in range(i):
# if(corr_matrix.iloc[i, j]) > threshold: # we are interested in absolute coeff value
# colname = corr_matrix.columns[i] # getting the name of column
# col_corr.add(colname)
# return col_corr
# highly_correlated_feature = correlation(train,0.9)
train_df.head()
print("Shape of train:",train_df.shape)
# Observation: There exist some values with are either infinity or out of range of float64 so for this let's replace those values with np.nan then drop all nan values
train_df.replace([np.inf, -np.inf], np.nan, inplace=True)
train_df.isnull().sum().sort_values(ascending=False)
train_df.isnull().sum().sort_values(ascending=False)[lambda x: x > 0]
cols_to_drop = train_df.isnull().sum().sort_values(ascending=False)[lambda x: x > 0].index
train_df.drop(columns=cols_to_drop, inplace=True)
train_df.shape
X = train_df.drop(columns=['label']) # Independent features
y = train_df['label']
from sklearn.feature_selection import SelectKBest, f_regression
selector = SelectKBest(score_func=f_regression, k=200) # choose top 200
X_selected = selector.fit_transform(X, y)
mask = selector.get_support()
# Get names of selected features
selected_features = X.columns[mask]
print(selected_features)
# columns that we will use for training
# cols_to_keep = ['X19', 'X20', 'X21', 'X22', 'X27', 'X28', 'X29', 'X219', 'X287', 'X289',
# 'X291', 'X531', 'X858', 'X860', 'X863'] ## keeping only these features for training
# cols_to_keep = ['bid_qty','ask_qty','buy_qty','sell_qty','volume'] + list(selected_features)
# adding fix with existance handling
manual_features = ['bid_qty','ask_qty','buy_qty','sell_qty','volume']
cols_to_keep = [f for f in manual_features if f in X.columns] + list(selected_features)
X = X[cols_to_keep]
X.head()
# Split before selecting features
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Fit SelectKBest only on training data
selector = SelectKBest(score_func=f_regression, k=200)
X_train_selected = selector.fit_transform(X_train, y_train)
X_test_selected = selector.transform(X_test)
test_selected = selector.transform(test_df[selector.get_support()])
# Update columns
selected_features = X_train.columns[selector.get_support()]
X_train = pd.DataFrame(X_train_selected, columns=selected_features)
X_test = pd.DataFrame(X_test_selected, columns=selected_features)
test = pd.DataFrame(test_selected, columns=selected_features)
print("Shape of X_train:",X_train.shape)
print("Shape of X_test:",X_test.shape)
print("Shape of y_train:",y_train.shape)
print("Shape of y_test:",y_test.shape)
scaler = StandardScaler()
numerical_features_list = [feature for feature in X.columns if X[feature].dtype!='O']
transformer = ColumnTransformer(transformers=[
('standard_scalling', scaler, numerical_features_list),
], remainder='passthrough') # Keeps other columns as they are
X_train_trf = transformer.fit_transform(X_train)
X_test_trf = transformer.transform(X_test)
# Creating a function to evaluat model
def evaluate_model(true, predicted):
mae=mean_absolute_error(true,predicted)
mse=mean_squared_error(true,predicted)
rmse=np.sqrt(mse)
r2=r2_score(true,predicted)
r = np.corrcoef(true, predicted)[0, 1]
print()
print(f"Pearson Correlation Coefficient: {r}")
print("R2 Score:{:.4f}".format(r2))
print("MAE:{:.4f}".format(mae))
print("MSE:{:.4f}".format(mse))
print("RMSE:{:.4f}".format(rmse))
# ---------
return 0
test=test_df.drop(columns=['label'], errors='ignore') # dropping target feature from test dataframe
test = test[cols_to_keep]
test_trf = transformer.transform(test)
sample_data_submission
id_column = sample_data_submission['ID']
## Model training
models={
"Linear_Regression":LinearRegression(),
"Linear_Regression_with_params":LinearRegression(
fit_intercept=True,
copy_X=True,
n_jobs=-1,
positive=False
),
# "Lasso":Lasso(),
# "Ridge":Ridge(),
# "ElasticNet":ElasticNet(),
# "DecisionTreeRegressor":DecisionTreeRegressor(),
# "DecisionTreeRegressor_with_params":DecisionTreeRegressor(
# criterion='squared_error',
# splitter='best',
# max_depth=10,
# min_samples_split=10,
# min_samples_leaf=4,
# max_features='sqrt',
# random_state=42
# ),
# "AdaBoost":AdaBoostRegressor(),
# "GradientBoost":GradientBoostingRegressor(),
# "XGBRegressor":XGBRegressor(
# max_depth=10,
# colsample_bytree=0.75,
# subsample=0.9,
# n_estimators=2000,
# learning_rate=0.01,
# gamma=0.01,
# max_delta_step=2,
# eval_metric="rmse",
# enable_categorical=True,
# device = 'cuda'),
# "LGBMRegressor":LGBMRegressor(
# n_estimators=1000,
# learning_rate=0.05,
# max_depth=7,
# num_leaves=31,
# min_child_samples=20,
# subsample=0.8,
# colsample_bytree=0.8,
# random_state=42,
# n_jobs=-1
# ),
# "CatBoostRegressor":CatBoostRegressor(
# iterations= 3500,
# depth= 12,
# loss_function= 'RMSE',
# l2_leaf_reg= 3,
# random_seed= 42,
# eval_metric= 'RMSE',
# silent=True
# ),
# "RandomForest":RandomForestRegressor(
# n_estimators=300,
# max_depth=20,
# min_samples_split=5,
# min_samples_leaf=2,
# max_features='sqrt',
# random_state=42,
# n_jobs=-1
# ),
}
model_name_list = []
corrcoef_list = []
for i in range(len(list(models))):
model_name = list(models.keys())[i]
model=list(models.values())[i]
print(model_name,"=============>")
print()
try:
model.fit(X_train_trf,y_train) # Train Model on X_train
except Exception as e:
print(f"{model_name} failed with error: {e}")
continue
# Make Predictions
y_train_pred=model.predict(X_train_trf)
y_test_pred=model.predict(X_test_trf)
print()
print("Evaluating Train Dataset")
evaluate_model(y_train,y_train_pred)
print(f"\n{'-'*50}\n")
print("Evaluating Test Dataset")
evaluate_model(y_test,y_test_pred)
print("="*60)
print("\n")
# appending the vlaues in list
model_name_list.append(model_name)
corrcoef_list.append(np.corrcoef(y_test, y_test_pred)[0, 1])
# prediction
prediction = model.predict(test_trf)
result = pd.DataFrame(
{
'ID':id_column,
'prediction':prediction
}
)
result.to_csv('{}_prediction.csv'.format(model_name),index=False)
print("File saved as '{}_prediction.csv'....".format(model_name))
print()
# creating dataframe contains model name and their performance on X_test
performance_df = pd.DataFrame({
'ML Algo Name': model_name_list,
'Pearson Correlation Coefficient': corrcoef_list
})
print(performance_df)
performance_df.to_csv("model_performance_summary.csv", index=False)