kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
12,980,839
def LGB_bayesian( num_leaves, bagging_fraction, feature_fraction, min_child_weight, min_data_in_leaf, max_depth, reg_alpha, reg_lambda ): num_leaves = int(num_leaves) min_data_in_leaf = int(min_data_in_leaf) max_depth = int(max_depth) assert type(num_leaves)== int assert type(min_data_in_leaf)== int assert type(ma...
params = { 'leaf_size': list(range(20, 50)) , 'n_neighbors': list(range(3, 30)) , 'p': [1, 2] } knn_tuned = random_search(X_train, y_train, estimator=knn, params=params )
Titanic - Machine Learning from Disaster
12,980,839
bounds_LGB = { 'num_leaves':(31, 500), 'min_data_in_leaf':(20, 200), 'bagging_fraction' :(0.1, 0.9), 'feature_fraction' :(0.1, 0.9), 'min_child_weight':(0.00001, 0.01), 'reg_alpha':(1, 2), 'reg_lambda':(1, 2), 'max_depth':(-1,50), }<choose_model_class>
y_pred = knn_tuned.predict(X_val) accuracy_knn = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_knn )
Titanic - Machine Learning from Disaster
12,980,839
LGB_BO = BayesianOptimization(LGB_bayesian, bounds_LGB, random_state=42 )<define_variables>
logistic_regression = LogisticRegression(random_state=SEED) logistic_regression.get_params()
Titanic - Machine Learning from Disaster
12,980,839
init_points = 10 n_iter = 15<find_best_params>
params = { 'C': scipy.stats.loguniform(1e-5, 100), 'penalty': ['l1', 'l2', 'elasticnet'], 'solver': ['newton-cg', 'lbfgs', 'liblinear'] } logistic_regression_tuned = random_search( X_train, y_train, estimator=logistic_regression, params=params )
Titanic - Machine Learning from Disaster
12,980,839
print('-' * 130) with warnings.catch_warnings() : warnings.filterwarnings('ignore') LGB_BO.maximize(init_points=init_points, n_iter=n_iter, acq='ucb', xi=0.0, alpha=1e-6 )<init_hyperparams>
y_pred = logistic_regression_tuned.predict(X_val) accuracy_logistic_regression = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_logistic_regression )
Titanic - Machine Learning from Disaster
12,980,839
param_lgb = { 'min_data_in_leaf': int(LGB_BO.max['params']['min_data_in_leaf']), 'num_leaves': int(LGB_BO.max['params']['num_leaves']), 'min_child_weight': LGB_BO.max['params']['min_child_weight'], 'bagging_fraction': LGB_BO.max['params']['bagging_fraction'], 'feature_fraction': LGB_BO.max['params']['feature_fraction']...
naive_bayes = GaussianNB() naive_bayes.get_params()
Titanic - Machine Learning from Disaster
12,980,839
plt.rcParams["axes.grid"] = True nfold = 5 skf = StratifiedKFold(n_splits=nfold, shuffle=True, random_state=42) oof = np.zeros(len(train_df)) mean_fpr = np.linspace(0,1,100) cms= [] tprs = [] aucs = [] y_real = [] y_proba = [] recalls = [] roc_aucs = [] f1_scores = [] accuracies = [] precisions = [] predictions = np....
params = { 'var_smoothing': [np.exp(-i)for i in range(1, 15)] } naive_bayes_tuned = random_search( X_train, y_train, estimator=naive_bayes, params=params, n_iter=15-1 )
Titanic - Machine Learning from Disaster
12,980,839
sample_submission['isFraud'] = predictions sample_submission.to_csv('submission_IEEE.csv' )<set_options>
y_pred = naive_bayes_tuned.predict(X_val) accuracy_naive_bayes = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_naive_bayes )
Titanic - Machine Learning from Disaster
12,980,839
%matplotlib inline for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) <define_variables>
voting = VotingClassifier( estimators=[('rf', random_forest_tuned), ('xgb', xgb_tuned), ('knn', knn_tuned), ('svc', svc_tuned), ('lr', logistic_regression_tuned), ('dt', decision_tree_tuned), ('nb', naive_bayes_tuned)], voting='soft', n_jobs=-1) voting = voting.fit(X_train, y_train )
Titanic - Machine Learning from Disaster
12,980,839
def prepare_altair() : vega_url = 'https://cdn.jsdelivr.net/npm/vega@' + v5.SCHEMA_VERSION vega_lib_url = 'https://cdn.jsdelivr.net/npm/vega-lib' vega_lite_url = 'https://cdn.jsdelivr.net/npm/vega-lite@' + alt.SCHEMA_VERSION vega_embed_url = 'https://cdn.jsdelivr.net/npm/vega-embed@3' noext = "?noext" paths = { 'vega...
y_pred = voting.predict(X_val) accuracy_voting = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_voting )
Titanic - Machine Learning from Disaster
12,980,839
sample_sub = pd.read_csv('/kaggle/input/ieee-fraud-detection/sample_submission.csv') sample_sub.head(10 )<drop_column>
model = voting predictions = model.predict(X_test) output = pd.DataFrame({'PassengerId': test['PassengerId'], 'Survived': predictions}) output.to_csv('my_submission.csv', index=False) print("The results successfully saved!" )
Titanic - Machine Learning from Disaster
12,490,647
del sample_sub<load_from_csv>
sub_data = pd.read_csv('/kaggle/input/titanic/gender_submission.csv') sub_data.head()
Titanic - Machine Learning from Disaster
12,490,647
train_identity = pd.read_csv('/kaggle/input/ieee-fraud-detection/train_identity.csv') train_transaction = pd.read_csv('/kaggle/input/ieee-fraud-detection/train_transaction.csv') test_identity = pd.read_csv('/kaggle/input/ieee-fraud-detection/test_identity.csv') test_transaction = pd.read_csv('/kaggle/input/ieee-frau...
train_data = pd.read_csv('/kaggle/input/titanic/train.csv') train_data.head()
Titanic - Machine Learning from Disaster
12,490,647
train = pd.merge(train_transaction, train_identity, on='TransactionID', how='left') test = pd.merge(test_transaction, test_identity, on='TransactionID', how='left' )<train_model>
test_data = pd.read_csv('/kaggle/input/titanic/test.csv') test_data.head()
Titanic - Machine Learning from Disaster
12,490,647
print(f'Train dataset: {train.shape[0]} rows & {train.shape[1]} columns') print(f'Test dataset: {test.shape[0]} rows & {test.shape[1]} columns' )<drop_column>
train_data.drop_duplicates(keep='first',inplace=True) train_data.shape
Titanic - Machine Learning from Disaster
12,490,647
train = reduce_mem_usage(train) test = reduce_mem_usage(test )<drop_column>
train_survived = train_data['Survived'].value_counts() not_surv =(train_survived[0]/(train_survived[1]+train_survived[0])) *100 print('Not survived %: ',"{:.2f}".format(not_surv)) print('Survived %: ',"{:.2f}".format(100-not_surv))
Titanic - Machine Learning from Disaster
12,490,647
del train_identity, train_transaction, test_identity, test_transaction<prepare_output>
train_data['PassengerId'][train_data['Age']>20][train_data['Age']<55].count()
Titanic - Machine Learning from Disaster
12,490,647
data_null = train.isnull().sum() /len(train)* 100 data_null = data_null.drop(data_null[data_null == 0].index ).sort_values(ascending=False)[:500] missing_data = pd.DataFrame({'Missing Ratio': data_null}) missing_data.head()<count_missing_values>
train_data['Cabin'].isnull().sum()
Titanic - Machine Learning from Disaster
12,490,647
def get_too_many_null_attr(data): many_null_cols = [col for col in data.columns if data[col].isnull().sum() / data.shape[0] > 0.9] return many_null_cols<count_values>
train_df = train_data.copy() train_df.drop(columns=['PassengerId','Cabin','Name'],inplace=True) train_df.head()
Titanic - Machine Learning from Disaster
12,490,647
def get_too_many_repeated_val(data): big_top_value_cols = [col for col in train.columns if train[col].value_counts(dropna=False, normalize=True ).values[0] > 0.9] return big_top_value_cols<count_values>
test_df = test_data.copy() test_df.drop(columns=['PassengerId','Cabin','Name'],inplace=True) test_df.head()
Titanic - Machine Learning from Disaster
12,490,647
train['id_03'].value_counts(dropna=False, normalize=True ).head()<count_values>
test_df.isnull().sum()
Titanic - Machine Learning from Disaster
12,490,647
train['id_11'].value_counts(dropna=False, normalize=True ).head()<define_variables>
train_df.isnull().sum()
Titanic - Machine Learning from Disaster
12,490,647
for i in range(1, 10): print(train['M' + str(i)].value_counts(dropna=False, normalize=True ).head()) print(' ' )<drop_column>
x_df = train_df.iloc[:,1:11] y_df = train_df.iloc[:,0:1] x_df.head(10) print(type(x_df))
Titanic - Machine Learning from Disaster
12,490,647
del charts<define_variables>
x_train,x_val,y_train,y_val = train_test_split(x_df,y_df,test_size=.20,random_state=1,stratify=y_df) x_train.head()
Titanic - Machine Learning from Disaster
12,490,647
def seed_everything(seed=0): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) <define_variables>
print(x_train.isnull().sum() )
Titanic - Machine Learning from Disaster
12,490,647
SEED = 42 seed_everything(SEED) TARGET = 'isFraud' START_DATE = datetime.datetime.strptime('2017-11-30', '%Y-%m-%d' )<data_type_conversions>
x_val.isnull().sum()
Titanic - Machine Learning from Disaster
12,490,647
def addNewFeatures(data): data['uid'] = data['card1'].astype(str)+'_'+data['card2'].astype(str) data['uid2'] = data['uid'].astype(str)+'_'+data['card3'].astype(str)+'_'+data['card5'].astype(str) data['uid3'] = data['uid2'].astype(str)+'_'+data['addr1'].astype(str)+'_'+data['addr2'].astype(str) return data<feature_en...
values_age = x_train['Age'].values.reshape(-1,1) num_imputer = SimpleImputer(missing_values=np.nan,strategy='mean') x_train[['Age']] = num_imputer.fit_transform(values_age) values_embarked = x_train[['Embarked']].values alpha_imputer = SimpleImputer(missing_values=np.nan,strategy='most_frequent') x_train[['Embarked...
Titanic - Machine Learning from Disaster
12,490,647
train = addNewFeatures(train) test = addNewFeatures(test )<data_type_conversions>
x_train.isnull().sum()
Titanic - Machine Learning from Disaster
12,490,647
i_cols = ['card1','card2','card3','card5','uid','uid2','uid3'] for col in i_cols: for agg_type in ['mean','std']: new_col_name = col+'_TransactionAmt_'+agg_type temp_df = pd.concat([train[[col, 'TransactionAmt']], test[[col,'TransactionAmt']]]) temp_df = temp_df.groupby([col])['TransactionAmt'].agg([agg_type] ).reset_...
print(x_val.isnull().sum() )
Titanic - Machine Learning from Disaster
12,490,647
train = train.replace(np.inf,999) test = test.replace(np.inf,999 )<feature_engineering>
def imputer_null(df): for cols in df.columns.values: if df[cols].values.dtype=='object': df[[cols]]=alpha_imputer.transform(df[cols].values.reshape(-1,1)) else: df[[cols]]=num_imputer.transform(df[cols].values.reshape(-1,1)) return df
Titanic - Machine Learning from Disaster
12,490,647
train['TransactionAmt'] = np.log1p(train['TransactionAmt']) test['TransactionAmt'] = np.log1p(test['TransactionAmt'] )<define_variables>
x_val = imputer_null(x_val) print(x_val.isnull().sum() )
Titanic - Machine Learning from Disaster
12,490,647
emails = {'gmail': 'google', 'att.net': 'att', 'twc.com': 'spectrum', 'scranton.edu': 'other', 'optonline.net': 'other', 'hotmail.co.uk': 'microsoft', 'comcast.net': 'other', 'yahoo.com.mx': 'yahoo', 'yahoo.fr': 'yahoo', 'yahoo.es': 'yahoo', 'charter.net': 'spectrum', 'live.com': 'microsoft', 'aim.com': 'aol', 'hotmail...
x_train.reset_index(drop=True,inplace=True) x_train x_val.reset_index(drop=True,inplace=True) x_val
Titanic - Machine Learning from Disaster
12,490,647
p = 'P_emaildomain' r = 'R_emaildomain' uknown = 'email_not_provided' def setDomain(df): df[p] = df[p].fillna(uknown) df[r] = df[r].fillna(uknown) df['email_check'] = np.where(( df[p]==df[r])&(df[p]!=uknown),1,0) df[p+'_prefix'] = df[p].apply(lambda x: x.split('.')[0]) df[r+'_prefix'] = df[r].apply(lambda x: x.spli...
y_train.reset_index(drop=True,inplace=True) y_train y_val.reset_index(drop=True,inplace=True )
Titanic - Machine Learning from Disaster
12,490,647
def setTime(df): df['TransactionDT'] = df['TransactionDT'].fillna(df['TransactionDT'].median()) df['DT'] = df['TransactionDT'].apply(lambda x:(START_DATE + datetime.timedelta(seconds = x))) df['DT_M'] =(df['DT'].dt.year-2017)*12 + df['DT'].dt.month df['DT_W'] =(df['DT'].dt.year-2017)*52 + df['DT'].dt.weekofyear df['D...
ticket_new = x_train['Ticket'].str.split(" ",n=1,expand=True) print(ticket_new) print(type(ticket_new)) print(x_train.head() )
Titanic - Machine Learning from Disaster
12,490,647
train["lastest_browser"] = np.zeros(train.shape[0]) test["lastest_browser"] = np.zeros(test.shape[0]) def setBrowser(df): df.loc[df["id_31"]=="samsung browser 7.0",'lastest_browser']=1 df.loc[df["id_31"]=="opera 53.0",'lastest_browser']=1 df.loc[df["id_31"]=="mobile safari 10.0",'lastest_browser']=1 df.loc[df["id_31"...
x_train_new = pd.concat([x_train,ticket_new],axis=1 ).drop(['Ticket'],axis=1) x_train_new
Titanic - Machine Learning from Disaster
12,490,647
def setDevice(df): df['DeviceInfo'] = df['DeviceInfo'].fillna('unknown_device' ).str.lower() df['device_name'] = df['DeviceInfo'].str.split('/', expand=True)[0] df.loc[df['device_name'].str.contains('SM', na=False), 'device_name'] = 'Samsung' df.loc[df['device_name'].str.contains('SAMSUNG', na=False), 'device_name'] = ...
x_train_new.rename(columns={0:"Ticket_ind",1:"Ticket_no"},inplace=True) x_train=x_train_new.copy() x_train.head()
Titanic - Machine Learning from Disaster
12,490,647
i_cols = ['card1','card2','card3','card5', 'C1','C2','C3','C4','C5','C6','C7','C8','C9','C10','C11','C12','C13','C14', 'D1','D2','D3','D4','D5','D6','D7','D8', 'addr1','addr2', 'dist1','dist2', 'P_emaildomain', 'R_emaildomain', 'DeviceInfo','device_name', 'id_30','id_33', 'uid','uid2','uid3', ] for col in i_cols: temp_...
x_train['Ticket_no'].values x_train.drop(columns=['Ticket_no'],axis=1,inplace=True) x_train.head()
Titanic - Machine Learning from Disaster
12,490,647
train = train.drop(cols_to_drop, axis=1 )<categorify>
x_num = x_train[x_train['Ticket_ind'].str.isnumeric() ] x_num
Titanic - Machine Learning from Disaster
12,490,647
class ModifiedLabelEncoder(LabelEncoder): def fit_transform(self, y, *args, **kwargs): return super().fit_transform(y ).reshape(-1, 1) def transform(self, y, *args, **kwargs): return super().transform(y ).reshape(-1, 1 )<train_model>
x_alpha = x_train[x_train['Ticket_ind'].str.isalpha() ] x_alpha.head(30 )
Titanic - Machine Learning from Disaster
12,490,647
class DataFrameSelector(BaseEstimator, TransformerMixin): def __init__(self, attr): self.attributes = attr def fit(self, X, y=None): return self def transform(self, X): return X[self.attributes].values<drop_column>
x_train.drop(columns=['Ticket_ind'],axis=1,inplace=True )
Titanic - Machine Learning from Disaster
12,490,647
cat_attr = list(train.select_dtypes(include=['object'] ).columns) num_attr = list(train.select_dtypes(exclude=['object'] ).columns) num_attr.remove('isFraud') for col in noisy_cat_cols: if col in cat_attr: print("Deleting " + col) cat_attr.remove(col) for col in noisy_num_cold: if col in num_attr: print("Deleting ...
x_val.drop(columns=['Ticket'],axis=1,inplace=True )
Titanic - Machine Learning from Disaster
12,490,647
num_pipeline = Pipeline([ ('selector', DataFrameSelector(num_attr)) , ('imputer', SimpleImputer(strategy="median")) , ('scaler', StandardScaler()), ]) cat_pipeline = Pipeline([ ('selector', DataFrameSelector(cat_attr)) , ('imputer', SimpleImputer(strategy="most_frequent")) , ]) full_pipeline = FeatureUnion(trans...
one_enc = OneHotEncoder(handle_unknown='ignore') df_new=pd.DataFrame() col_names={} to_be_enc_cols = ['Pclass','Sex','Embarked'] for column_ind in range(len(to_be_enc_cols)) : one_hot_enc = one_enc.fit_transform(np.array(x_train[to_be_enc_cols[column_ind]] ).reshape(-1,1)).toarray() col_names[to_be_enc_cols[column_ind...
Titanic - Machine Learning from Disaster
12,490,647
def encodeCategorical(df_train, df_test): for f in df_train.drop('isFraud', axis=1 ).columns: if df_train[f].dtype=='object' or df_test[f].dtype=='object': lbl = preprocessing.LabelEncoder() lbl.fit(list(df_train[f].values)+ list(df_test[f].values)) df_train[f] = lbl.transform(list(df_train[f].values)) df_test[f] = lbl...
def one_hot(df): df2=pd.DataFrame() col_names={} to_be_enc_cols = ['Pclass','Sex','Embarked'] for column_ind in range(len(to_be_enc_cols)) : one_hot_enc = one_enc.fit_transform(np.array(df[to_be_enc_cols[column_ind]] ).reshape(-1,1)).toarray() col_names[to_be_enc_cols[column_ind]] = one_enc.get_feature_names([to_be_enc...
Titanic - Machine Learning from Disaster
12,490,647
y_train = train['isFraud'] train, test = encodeCategorical(train, test )<create_dataframe>
Titanic - Machine Learning from Disaster
12,490,647
X_train = pd.DataFrame(full_pipeline.fit_transform(train)) gc.collect()<drop_column>
Titanic - Machine Learning from Disaster
12,490,647
del train<create_dataframe>
Titanic - Machine Learning from Disaster
12,490,647
test = test.drop(cols_to_drop, axis=1) test = pd.DataFrame(full_pipeline.transform(test))<find_best_model_class>
x_val = one_hot(x_val) x_val
Titanic - Machine Learning from Disaster
12,490,647
def makePredictions(tr_df, tt_df, target, lgb_params, NFOLDS=2): folds = KFold(n_splits=NFOLDS, shuffle=True, random_state=SEED) X,y = tr_df, y_train P = tt_df predictions = np.zeros(len(tt_df)) for fold_,(trn_idx, val_idx)in enumerate(folds.split(X, y)) : print('Fold:',fold_) tr_x, tr_y = X.iloc[trn_idx,:], y[trn_id...
def add_family_feature(df): df['Family'] = df['SibSp']+df['Parch'] df.drop(['SibSp','Parch'],axis=1,inplace=True) return df
Titanic - Machine Learning from Disaster
12,490,647
lgb_params = { 'objective':'binary', 'boosting_type':'gbdt', 'metric':'auc', 'n_jobs':-1, 'learning_rate':0.064, 'num_leaves': 2**8, 'max_depth':-1, 'tree_learner':'serial', 'colsample_bytree': 0.7, 'subsample_freq':1, 'subsample':0.7, 'n_estimators':800, 'max_bin':255, 'verbose':-1, 'seed': SEED, 'early_stopping_round...
x_train = add_family_feature(x_train) x_val = add_family_feature(x_val) x_val.head()
Titanic - Machine Learning from Disaster
12,490,647
lgb_params['learning_rate'] = 0.005 lgb_params['n_estimators'] = 1800 lgb_params['early_stopping_rounds'] = 100 test_predictions = makePredictions(X_train, test, TARGET, lgb_params, NFOLDS=8 )<create_dataframe>
normalize = MinMaxScaler() normalize_col = ['Age','Fare'] df_new = pd.DataFrame() for cols in normalize_col: x_train_scaled = normalize.fit_transform(np.array(x_train[cols] ).reshape(-1,1)) df_scaled = pd.DataFrame(x_train_scaled,columns=[cols+'_new']) df_new = pd.concat([df_new,df_scaled],axis=1) print(df_new) x_tr...
Titanic - Machine Learning from Disaster
12,490,647
lgb_submission = pd.DataFrame({ "isFraud": test_predictions['prediction'], } )<save_to_csv>
def normalize_feature(df): normalize_col = ['Age','Fare'] df_new = pd.DataFrame() for cols in normalize_col: x_scaled = normalize.fit_transform(np.array(df[cols] ).reshape(-1,1)) df_scaled = pd.DataFrame(x_scaled,columns=[cols+'_new']) df_new = pd.concat([df_new,df_scaled],axis=1) df = pd.concat([df,df_new],axis=1) ...
Titanic - Machine Learning from Disaster
12,490,647
lgb_submission.insert(0, "TransactionID", np.arange(3663549, 3663549 + 506691)) lgb_submission.to_csv('prediction.csv', index=False )<set_options>
x_val = normalize_feature(x_val) x_val.head()
Titanic - Machine Learning from Disaster
12,490,647
warnings.filterwarnings('ignore' )<init_hyperparams>
x_train_data = x_train.copy() x_train_data.head() x_val_data = x_val.copy()
Titanic - Machine Learning from Disaster
12,490,647
def seed_everything(seed=0): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) def reduce_mem_usage(df, verbose=True): numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] start_mem = df.memory_usage().sum() / 1024**2 for col in df.columns: col_type = df[col].dtypes i...
train_all = pd.concat([x_train,y_train],axis=1) train_all.head()
Titanic - Machine Learning from Disaster
12,490,647
def make_predictions(tr_df, tt_df, features_columns, target, cat_params, NFOLDS=2, kfold_mode='grouped'): X,y = tr_df[features_columns], tr_df[target] P,P_y = tt_df[features_columns], tt_df[target] split_groups = tr_df['DT_M'] tt_df = tt_df[['TransactionID',target]] tr_df = tr_df[['TransactionID',target]] predictions =...
clf_log_reg = LogisticRegression(penalty='l2',random_state=1,solver='lbfgs',tol=0.001 ).fit(x_train,y_train )
Titanic - Machine Learning from Disaster
12,490,647
SEED = 42 seed_everything(SEED) LOCAL_TEST = False TARGET = 'isFraud' START_DATE = datetime.datetime.strptime('2017-11-30', '%Y-%m-%d' )<init_hyperparams>
clf_log_reg.predict(x_val )
Titanic - Machine Learning from Disaster
12,490,647
cat_params = { 'n_estimators':5000, 'learning_rate': 0.07, 'eval_metric':'AUC', 'loss_function':'Logloss', 'random_seed':SEED, 'metric_period':500, 'od_wait':500, 'task_type':'GPU', 'depth': 8, }<load_pretrained>
print(clf_log_reg.decision_function(x_val))
Titanic - Machine Learning from Disaster
12,490,647
print('Load Data') if LOCAL_TEST: train_df = pd.read_pickle('.. /input/ieee-fe-for-local-test/train_df.pkl') test_df = pd.read_pickle('.. /input/ieee-fe-for-local-test/test_df.pkl') else: train_df = pd.read_pickle('.. /input/ieee-fe-with-some-eda/train_df.pkl') test_df = pd.read_pickle('.. /input/ieee-fe-with-some-...
clf_log_reg.predict_proba(x_val )
Titanic - Machine Learning from Disaster
12,490,647
nans_groups = {} temp_df = train_df.isna() temp_df2 = test_df.isna() nans_df = pd.concat([temp_df, temp_df2]) for col in list(nans_df): cur_group = nans_df[col].sum() if cur_group>0: try: nans_groups[cur_group].append(col) except: nans_groups[cur_group]=[col] add_category = [] for col in nans_groups: if len(nans_grou...
clf_log_reg.get_params()
Titanic - Machine Learning from Disaster
12,490,647
categorical_features = ['ProductCD','M4', 'card1','card2','card3','card4','card5','card6', 'addr1','addr2','dist1','dist2', 'P_emaildomain','R_emaildomain', ] o_trans = pd.concat([pd.read_pickle('.. /input/ieee-data-minification/train_transaction.pkl'), pd.read_pickle('.. /input/ieee-data-minification/test_transaction....
clf_log_reg.score(x_val,y_val )
Titanic - Machine Learning from Disaster
12,490,647
total_items = len(train_df) keep_cols = [TARGET,'C3_fq_enc'] for col in list(train_df): if train_df[col].dtype.name!='category': cur_dominator = list(train_df[col].fillna(-999 ).value_counts())[0] if(cur_dominator/total_items > 0.85)and(col not in keep_cols): cur_dominator = train_df[col].fillna(-999 ).value_counts()....
test_df = imputer_null(test_df) test_df = one_hot(test_df) test_df = add_family_feature(test_df) test_df = normalize_feature(test_df) test_df.head()
Titanic - Machine Learning from Disaster
12,490,647
restore_features = [ 'uid','uid2','uid3','uid4','uid5','bank_type', ] for col in restore_features: categorical_features.append(col) remove_features.remove(col )<define_variables>
test_df.drop(columns=['Ticket'],axis=1,inplace=True) test_pred = clf_log_reg.predict(test_df) test_pred_df = pd.DataFrame(test_pred,columns=['Survived']) test_pred_df y_test = pd.concat([test_data[['PassengerId']],test_pred_df],axis=1) y_test.head()
Titanic - Machine Learning from Disaster
12,490,647
cols_sum = {} bad_types = ['datetime64[ns]', 'category','object'] for col in list(train_df): if train_df[col].dtype.name not in bad_types: cur_col = train_df[col].values cur_sum = cur_col.mean() try: cols_sum[cur_sum].append(col) except: cols_sum[cur_sum] = [col] cols_sum = {k:v for k,v in cols_sum.items() if len(v)>1...
val_prob = np.array(clf_log_reg.predict_proba(x_val)) print(val_prob[:,1] )
Titanic - Machine Learning from Disaster
12,490,647
for col in list(train_df): if train_df[col].dtype=='O': print(col) train_df[col] = train_df[col].fillna('unseen_before_label') test_df[col] = test_df[col].fillna('unseen_before_label') train_df[col] = train_df[col].astype(str) test_df[col] = test_df[col].astype(str) le = LabelEncoder() le.fit(list(train_df[col])+l...
val_score = clf_log_reg.score(x_val,y_val) print("Score of Validation set is :" "{:.2f}".format(val_score*100))
Titanic - Machine Learning from Disaster
12,490,647
features_columns = [col for col in list(train_df)if col not in remove_features] categorical_features = [col for col in categorical_features if col in features_columns] if not LOCAL_TEST: train_df = reduce_mem_usage(train_df) test_df = reduce_mem_usage(test_df) train_df = train_df[['TransactionID','DT_M',TARGET]+featu...
roc_auc = "{:.2f}".format(roc_auc_score(y_val,val_prob[:,1])*100) print(roc_auc )
Titanic - Machine Learning from Disaster
12,490,647
if LOCAL_TEST: test_predictions = make_predictions(train_df, test_df, features_columns, TARGET, cat_params, NFOLDS=4, kfold_mode='grouped') else: NFOLDS = 6 folds = GroupKFold(n_splits=NFOLDS) X,y = train_df[features_columns], train_df[TARGET] P,P_y = test_df[features_columns], test_df[TARGET] split_groups = train_df...
from sklearn.metrics import roc_curve
Titanic - Machine Learning from Disaster
12,490,647
if not LOCAL_TEST: test_df['isFraud'] = test_df['prediction'] test_df[['TransactionID','isFraud']].to_csv('submission.csv', index=False )<set_options>
y_test.to_csv("logistic_submission.csv",index=False )
Titanic - Machine Learning from Disaster
12,490,647
warnings.filterwarnings('ignore' )<init_hyperparams>
clf_svc = svm.NuSVC().fit(x_train,y_train )
Titanic - Machine Learning from Disaster
12,490,647
def seed_everything(seed=0): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) def reduce_mem_usage(df, verbose=True): numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] start_mem = df.memory_usage().sum() / 1024**2 for col in df.columns: col_type = df[col].dtypes i...
clf_svc.predict(x_val )
Titanic - Machine Learning from Disaster
12,490,647
def make_predictions(tr_df, tt_df, features_columns, target, lgb_params, NFOLDS=2): folds = GroupKFold(n_splits=NFOLDS) X,y = tr_df[features_columns], tr_df[target] P,P_y = tt_df[features_columns], tt_df[target] split_groups = tr_df['DT_M'] tt_df = tt_df[['TransactionID',target]] predictions = np.zeros(len(tt_df)) oof...
clf_svc.score(x_val,y_val )
Titanic - Machine Learning from Disaster
12,490,647
SEED = 42 seed_everything(SEED) LOCAL_TEST = False TARGET = 'isFraud' START_DATE = datetime.datetime.strptime('2017-11-30', '%Y-%m-%d' )<init_hyperparams>
test_pred = clf_svc.predict(test_df) test_pred_df = pd.DataFrame(test_pred,columns=['Survived']) test_pred_df y_test = pd.concat([test_data[['PassengerId']],test_pred_df],axis=1) y_test.head()
Titanic - Machine Learning from Disaster
12,490,647
lgb_params = { 'objective':'binary', 'boosting_type':'gbdt', 'metric':'auc', 'n_jobs':-1, 'learning_rate':0.01, 'num_leaves': 2**8, 'max_depth':-1, 'tree_learner':'serial', 'colsample_bytree': 0.5, 'subsample_freq':1, 'subsample':0.7, 'n_estimators':800, 'max_bin':255, 'verbose':-1, 'seed': SEED, 'early_stopping_rounds...
y_test.to_csv("svc.submission.csv",index=False )
Titanic - Machine Learning from Disaster
12,490,647
print('Load Data') if LOCAL_TEST: train_df = pd.read_pickle('.. /input/ieee-fe-for-local-test/train_df.pkl') test_df = pd.read_pickle('.. /input/ieee-fe-for-local-test/test_df.pkl') else: train_df = pd.read_pickle('.. /input/ieee-fe-with-some-eda/train_df.pkl') test_df = pd.read_pickle('.. /input/ieee-fe-with-some-...
clf_nb = GaussianNB().fit(x_train,y_train) clf_nb.predict(x_val )
Titanic - Machine Learning from Disaster
12,490,647
features_columns = [col for col in list(train_df)if col not in remove_features] if not LOCAL_TEST: train_df = reduce_mem_usage(train_df) test_df = reduce_mem_usage(test_df )<predict_on_test>
clf_nb.score(x_val,y_val )
Titanic - Machine Learning from Disaster
12,490,647
if LOCAL_TEST: lgb_params['learning_rate'] = 0.01 lgb_params['n_estimators'] = 10000 lgb_params['early_stopping_rounds'] = 100 test_predictions = make_predictions(train_df, test_df, features_columns, TARGET, lgb_params, NFOLDS=4) else: lgb_params['learning_rate'] = 0.007 lgb_params['n_estimators'] = 10000 lgb_params['...
y_test = clf_nb.predict(test_df) y_test
Titanic - Machine Learning from Disaster
12,490,647
if not LOCAL_TEST: test_predictions['isFraud'] = test_predictions['prediction'] test_predictions[['TransactionID','isFraud']].to_csv('submission.csv', index=False )<prepare_x_and_y>
y_pred_df = pd.DataFrame(y_test,columns=['Survived']) test_data = pd.concat([test_data[['PassengerId']],y_pred_df],axis=1) test_data.head()
Titanic - Machine Learning from Disaster
12,490,647
train, test = amazon() print(train.shape, test.shape) target = "ACTION" col4train = [x for x in train.columns if x not in [target, "ROLE_TITLE"]] y = train[target].values<import_modules>
test_data.to_csv("naive_bayes_submission.csv",index=False )
Titanic - Machine Learning from Disaster
12,490,647
def get_model() : params = { "n_estimators":300, "n_jobs": 3, "random_state":5436, } return ExtraTreesClassifier(**params) def validate_model(model, data): skf = StratifiedKFold(n_splits=5, random_state = 4141, shuffle = True) stats = cross_validate( model, data[0], data[1], groups=None, scoring='roc_auc', cv=skf, n...
clf_dt = tree.DecisionTreeClassifier(max_depth=3,min_samples_split=15,min_samples_leaf=3,random_state=1 ).fit(x_train,y_train) clf_dt.predict(x_val)
Titanic - Machine Learning from Disaster
12,490,647
new_train, new_test = transform_dataset( train[col4train], test[col4train], assign_rnd_integer, {"number_of_times":5} ) print(new_train.shape, new_test.shape) new_train.head(5 )<train_model>
clf_dt.score(x_val,y_val )
Titanic - Machine Learning from Disaster
12,490,647
validate_model( model = get_model() , data = [new_train.values, y] )<train_model>
clf_dt.get_params()
Titanic - Machine Learning from Disaster
12,490,647
new_train, new_test = transform_dataset( train[col4train], test[col4train], assign_rnd_integer, {"number_of_times":1} ) print(new_train.shape, new_test.shape) validate_model( model = get_model() , data = [new_train.values, y] )<train_model>
y_test = clf_dt.predict(test_df) y_test = pd.DataFrame(y_test,columns=['Survived']) y_test = pd.concat([test_data[['PassengerId']],y_test],axis=1) y_test
Titanic - Machine Learning from Disaster
12,490,647
new_train, new_test = transform_dataset( train[col4train], test[col4train], assign_rnd_integer, {"number_of_times":10} ) print(new_train.shape, new_test.shape) validate_model( model = get_model() , data = [new_train.values, y] )<categorify>
y_test.to_csv("dt_submission.csv",index=False )
Titanic - Machine Learning from Disaster
12,490,647
def one_hot(dataset): ohe = OneHotEncoder(sparse=True, dtype=np.float32, handle_unknown='ignore') return ohe.fit_transform(dataset.values )<prepare_x_and_y>
rf = RandomForestClassifier(n_estimators=200,max_depth=3,min_samples_split=5,random_state=1,oob_score=True) clf_rf = rf.fit(x_train,y_train) clf_rf
Titanic - Machine Learning from Disaster
12,490,647
new_train, new_test = transform_dataset( train[col4train], test[col4train], one_hot) print(new_train.shape, new_test.shape )<train_model>
clf_rf.predict(x_val )
Titanic - Machine Learning from Disaster
12,490,647
validate_model( model = get_model() , data = [new_train, y] )<feature_engineering>
clf_rf.score(x_val,y_val )
Titanic - Machine Learning from Disaster
12,490,647
def extract_col_interaction(dataset, col1, col2, tfidf = True): data = dataset.groupby([col1])[col2].agg(lambda x: " ".join(list([str(y)for y in x]))) if tfidf: vectorizer = TfidfVectorizer(tokenizer=lambda x: x.split(" ")) else: vectorizer = CountVectorizer(tokenizer=lambda x: x.split(" ")) data_X = vectorizer.fit_tr...
y_test = clf_rf.predict(test_df) y_test = pd.DataFrame(y_test,columns=['Survived']) y_pred = pd.concat([test_data[['PassengerId']],y_test],axis=1) y_pred
Titanic - Machine Learning from Disaster
12,490,647
validate_model( model = get_model() , data = [new_train.values, y] )<merge>
y_pred.to_csv("rf_submission.csv",index=False )
Titanic - Machine Learning from Disaster
13,189,930
def get_freq_encoding(dataset): new_dataset = pd.DataFrame() for c in dataset.columns: data = dataset.groupby([c] ).size().reset_index() new_dataset[c+"_freq"] = dataset[[c]].merge(data, on = c, how = "left")[0] return new_dataset<categorify>
train_df=pd.read_csv('/kaggle/input/titanic/train.csv') test_df=pd.read_csv('/kaggle/input/titanic/test.csv') test_PassengerId=test_df['PassengerId']
Titanic - Machine Learning from Disaster
13,189,930
new_train, new_test = transform_dataset( train[col4train], test[col4train], get_freq_encoding ) print(new_train.shape, new_test.shape) new_train.head(5 )<train_model>
train_df['Sex'].value_counts()
Titanic - Machine Learning from Disaster
13,189,930
validate_model( model = get_model() , data = [new_train.values, y] )<concatenate>
category2 = ['Ticket', 'Name', 'Cabin'] for c in category2: print('{} '.format(train_df[c].value_counts()))
Titanic - Machine Learning from Disaster
13,189,930
new_train1, new_test1 = transform_dataset( train[col4train], test[col4train], get_freq_encoding ) new_train2, new_test2 = transform_dataset( train[col4train], test[col4train], get_col_interactions_svd ) new_train3, new_test3 = transform_dataset( train[col4train], test[col4train], assign_rnd_integer, {"number_of_...
train_df[['Pclass','Survived']].groupby('Pclass', as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
13,189,930
validate_model( model = get_model() , data = [new_train.values, y] )<save_to_csv>
train_df[['Sex','Survived']].groupby('Sex', as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
13,189,930
model = get_model() model.fit(new_train.values, y) predictions = model.predict_proba(new_test)[:,1] submit = pd.DataFrame() submit["Id"] = test["id"] submit["ACTION"] = predictions submit.to_csv("submission.csv", index = False )<set_options>
train_df[['SibSp','Survived']].groupby('SibSp', as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
13,189,930
%matplotlib inline %config InlineBackend.figure_format = 'svg' warnings.filterwarnings("ignore") plt.rcParams['figure.figsize'] =(12, 9) plt.style.use('ggplot') pd.options.display.max_rows = 64 pd.options.display.max_columns = 512<load_from_csv>
train_df[['Parch','Survived']].groupby('Parch', as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
13,189,930
train = pd.read_csv('.. /input/train/train.csv') train['AdoptionSpeed'].astype(np.int32) test = pd.read_csv('.. /input/test/test.csv') df = pd.concat([train,test],ignore_index=True )<define_variables>
def detect_outliers(df,columns): outlier_list=[] for c in columns: Q1 = np.percentile(df[c],25) Q3 = np.percentile(df[c],75) IQR = Q3-Q1 outlier_step = 1.5*IQR indices = df[(df[c] < Q1-outlier_step)|(df[c] > Q3+outlier_step)].index outlier_list.extend(indices) outlier_list_counter=Counter(outlier_list) final_outlie...
Titanic - Machine Learning from Disaster
13,189,930
train_sentiment_files = sorted(glob.glob('.. /input/train_sentiment/*.json')) test_sentiment_files = sorted(glob.glob('.. /input/test_sentiment/*.json')) sentimental_analysis = train_sentiment_files + test_sentiment_files<define_variables>
final_outlier_list = detect_outliers(train_df, ['Age', 'Fare', 'SibSp', 'Parch']) train_df.loc[final_outlier_list]
Titanic - Machine Learning from Disaster
13,189,930
score_dict = dict(zip(petid,score)) magnitude_dict = dict(zip(petid,magnitude))<feature_engineering>
train_df = train_df.drop(final_outlier_list, axis=0 ).reset_index(drop=True )
Titanic - Machine Learning from Disaster
13,189,930
df['Score'] = df['PetID'].map(score_dict) df['Score'][df.Score.isnull() ] = 0 df['Magnitude'] = df['PetID'].map(magnitude_dict) df['Magnitude'][df.Magnitude.isnull() ] = 0 df.set_index('PetID',inplace=True )<feature_engineering>
train_df_len = len(train_df) train_df = pd.concat([train_df,test_df], axis=0 ).reset_index(drop=True )
Titanic - Machine Learning from Disaster
13,189,930
def namevaild(name): if name == np.nan: return 0 elif len(str(name)) < 3: return 1 elif re.match(u'[0-9]', str(name ).lower()): return 1 elif len(set(str(name ).lower().split(' ')+['no','not','yet','male','female','unnamed'])) != len(set(str(name ).lower().split(' ')))+6: return 1 else: return 2 df['Name_state'] = df['...
train_df.columns[train_df.isnull().any() ]
Titanic - Machine Learning from Disaster
13,189,930
df['Fee_per_pet'] = df.Fee/df.Quantity df['Fee_Bin']=pd.factorize(pd.cut(df.Fee_per_pet,bins=[0,0.01,50,100,200,500,3000],right=False)) [0] fee_bin_dummies_df = pd.get_dummies(df['Fee_Bin'] ).rename(columns=lambda x: 'Fee_Bin_' + str(x)) df = pd.concat([df, fee_bin_dummies_df], axis=1 )<categorify>
train_df.isnull().sum()
Titanic - Machine Learning from Disaster