-
Notifications
You must be signed in to change notification settings - Fork 0
/
ensembleArbol.py
225 lines (181 loc) · 7.12 KB
/
ensembleArbol.py
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
from __future__ import print_function
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import matplotlib as mpl
import matplotlib.ticker as tkr
import matplotlib.dates as mdates
import datetime
import pandas as pd
from pandas.tools.plotting import scatter_matrix
import seaborn as sns
import sklearn
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from scipy import stats
from sklearn import preprocessing
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import math
import csv
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
import heapq
from decimal import Decimal
from sklearn.model_selection import train_test_split
import os
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
from sklearn.ensemble import RandomForestClassifier
def clean_features(df, remove_id_era=False):
"""
Clean and preprocess features in the dataframe
Args:
df: Input dataframe
remove_id_era: Whether to remove ID and era columns
Returns:
Cleaned dataframe
"""
if remove_id_era:
df = df.drop(['id', 'era'], axis=1)
df = df.drop('data_type', axis=1)
# Remove redundant features
redundant_features = ['feature15', 'feature25', 'feature22', 'feature41',
'feature45', 'feature7', 'feature16', 'feature38',
'feature29', 'feature40', 'feature14', 'feature43',
'feature36', 'feature20', 'feature28', 'feature17',
'feature27', 'feature26', 'feature6', 'feature2',
'feature13', 'feature48', 'feature46', 'feature39',
'feature44', 'feature42', 'feature34', 'feature18',
'feature8', 'feature10', 'feature30']
df = df.drop(redundant_features, axis=1)
# Add engineered features
df['feature23_squared'] = df['feature23']**2
df['feature49_squared'] = df['feature49']**2
df['feature12_squared'] = df['feature12']**2
return df
class NanDropper(BaseEstimator, TransformerMixin):
def __init__(self, column):
self.column = column
def fit(self, X, y=None):
return self
def transform(self, X):
X = X.drop('sku', axis=1)
return X.dropna(subset=[self.column])
class DataFrameSelector(BaseEstimator, TransformerMixin):
def __init__(self, feature_names):
self.feature_names = feature_names
def fit(self, X, y=None):
return self
def transform(self, X):
return X[self.feature_names].values
class OutlierHandler(BaseEstimator, TransformerMixin):
def __init__(self, percentile):
self.percentile = percentile
def fit(self, X, y=None):
return self
def transform(self, X):
return X
def normalize_minmax(X):
"""Normalize features to 0-1 range"""
scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))
return scaler.fit_transform(X)
def prepare_matrix(df, is_training=True):
"""Convert dataframe to numpy matrices"""
X = df.drop('target', axis=1).values.astype(np.float32)
if is_training:
y = df['target'].values.reshape(-1, 1).astype(np.float32)
else:
y = []
return X, y
def split_data(df, scaler=None):
"""Split data into features and target"""
X, y = prepare_matrix(df, is_training=True)
return X, y, scaler
def split_test_data(df, scaler=None):
"""Prepare test data"""
X, _ = prepare_matrix(df, is_training=False)
return X, scaler
def print_full_df(df):
"""Print full dataframe"""
pd.set_option('display.max_rows', len(df))
print(df)
pd.reset_option('display.max_rows')
def save_predictions(predictions, ids, output_file, input_file):
"""Save predictions to CSV file and calculate logloss"""
print(f"Predictions shape: {predictions.shape}")
# Combine IDs with predictions
results = np.column_stack([ids, predictions])
np.savetxt(output_file, results, fmt="%s,%10.8f", delimiter=",")
# Calculate logloss on validation data
val_df = pd.read_csv(input_file)
val_df = val_df.dropna()
val_df = clean_features(val_df, remove_id_era=True)
X_val, y_val = split_data(val_df)[:2]
val_size = y_val.shape[0]
val_preds = predictions[:val_size]
logloss = sklearn.metrics.log_loss(y_val, val_preds)
print(f"Log loss for {output_file}: {logloss:.6f}")
# Add header to output file
with open(output_file, 'r') as f:
data = f.read()
with open(output_file, 'w') as f:
f.write("id,probability\n" + data)
return True
def prepare_input_data(csv_prefix, df):
"""Prepare and merge input data"""
df.reset_index(drop=True, inplace=True)
# Print correlations
correlations = df.corr()
print_full_df(correlations["target"].sort_values(ascending=False))
# Load and merge prediction files
pred1 = pd.read_csv(f'{csv_prefix}1.csv')
pred2 = pd.read_csv(f'{csv_prefix}2.csv')
merged = pred1.merge(pred2, on='id')
df = merged.merge(df, on='id')
df = clean_features(df, remove_id_era=False)
print(f"Final dataset shape: {df.shape}")
correlations = df.corr()
print_full_df(correlations["target"].sort_values(ascending=False))
print("Dataset preparation complete!")
return df
# Load data
tournament_data = pd.read_csv('numerai_tournament_data.csv')
training_data = pd.read_csv('numerai_training_data.csv')
# Prepare datasets
tournament_data = prepare_input_data("predictsnumer", tournament_data)
training_data = prepare_input_data("predictsnumerOld", training_data)
# Get IDs
tournament_ids = tournament_data['id'].values.reshape(-1, 1)
training_ids = training_data['id'].values.reshape(-1, 1)
# Clean and prepare features
tournament_data = tournament_data.dropna()
tournament_data = tournament_data.drop(['era', 'id'], axis=1)
X_train, y_train, _ = split_data(tournament_data)
# Prepare test data
tournament_test = tournament_data.copy()
X_test, _ = split_test_data(tournament_test)
training_data = training_data.drop(['era', 'id'], axis=1)
X_train_old, y_train_old = split_data(training_data)[:2]
# Train Random Forest model
print("Training Random Forest...")
rf_model = RandomForestClassifier(
n_estimators=350,
max_leaf_nodes=7,
n_jobs=-1,
oob_score=True
)
rf_model.fit(X_train, y_train)
print(f"Out-of-bag score: {rf_model.oob_score_}")
# Generate predictions
tournament_preds = rf_model.predict_proba(X_test)[:, 1]
training_preds = rf_model.predict_proba(X_train_old)[:, 1]
# Save predictions
save_predictions(tournament_preds, tournament_ids, "predictsnumer.csv", "numerai_tournament_data.csv")
save_predictions(training_preds, training_ids, "predictsnumerOld.csv", "numerai_training_data.csv")