kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
1,537,787 | index = 'Longitude'<drop_column> | POS_CASH_balance = replace_XNA_XAP(POS_CASH_balance)
pos_bin =[]
POS_CASH_balance,pos_bin = binary_encoding(POS_CASH_balance,columns=['NAME_CONTRACT_STATUS'])
POS_CASH_balance,pos_cat = one_hot_encoding(POS_CASH_balance,columns=['NAME_CONTRACT_STATUS'], nan_as_category=True)
pos_aggregate ={
'MONTHS_BALANCE':['mean','min','max'],
'CNT_INSTALMENT':['mean','min','max'],
'CNT_INSTALMENT_FUTURE':['mean','min','max'],
'SK_DPD':['min','max','mean'],
'SK_DPD_DEF':['min','max','mean']
}
for col in pos_cat+pos_bin:
pos_aggregate[col] =['sum','mean']
pos_agg = POS_CASH_balance.groupby('SK_ID_CURR' ).agg(pos_aggregate)
pos_agg.columns = pd.Index(['POS_'+ e[0]+ '_'+ e[1].upper() for e in pos_agg.columns.tolist() ])
pos_agg['POS_COUNT'] = POS_CASH_balance.groupby('SK_ID_CURR' ).size()
del POS_CASH_balance
pos_agg.head(2 ) | Home Credit Default Risk |
1,537,787 | del df_train[index]
del df_test[index]<define_variables> | gc.collect()
reduce_memory_usage(pos_agg ) | Home Credit Default Risk |
1,537,787 | index = 'Community Board'<drop_column> | credit_card_balance['AMT_CREDIT_LIMIT_ACTUAL'] = np.sqrt(credit_card_balance['AMT_CREDIT_LIMIT_ACTUAL'] ) | Home Credit Default Risk |
1,537,787 | del df_train[index]
del df_test[index]<define_variables> | credit_card_balance['CNT_DRAWINGS_CURRENT'] = np.sqrt(credit_card_balance['CNT_DRAWINGS_CURRENT'] ) | Home Credit Default Risk |
1,537,787 | index = 'Council District'<drop_column> | credit_card_balance['CNT_DRAWINGS_OTHER_CURRENT'] = credit_card_balance['CNT_DRAWINGS_OTHER_CURRENT'].astype('object' ) | Home Credit Default Risk |
1,537,787 | del df_train[index]
del df_test[index]<define_variables> | credit_card_balance['CNT_DRAWINGS_POS_CURRENT'] = np.sqrt(credit_card_balance['CNT_DRAWINGS_POS_CURRENT'] ) | Home Credit Default Risk |
1,537,787 | index = 'Census Tract'<drop_column> | credit_card_balance['CNT_INS'] = np.sqrt(credit_card_balance['CNT_INSTALMENT_MATURE_CUM'] ) | Home Credit Default Risk |
1,537,787 | del df_train[index]
del df_test[index]<define_variables> | credit_card_balance['NAME_CONTRACT_STATUS'] = credit_card_balance['NAME_CONTRACT_STATUS'].astype('object' ) | Home Credit Default Risk |
1,537,787 | index = 'NTA'<drop_column> | credit_card_balance = replace_XNA_XAP(credit_card_balance)
credit_object_col = credit_card_balance.select_dtypes('object' ).columns
credit_bin =[]
credit_card_balance,credit_bin = binary_encoding(credit_card_balance,credit_object_col)
credit_card_balance,credit_cat = one_hot_encoding(credit_card_balance,credit_object_col, nan_as_category=False)
credit_aggregation = {
'MONTHS_BALANCE':['mean','min','max'],
'AMT_BALANCE':['mean','min'],
'AMT_CREDIT_LIMIT_ACTUAL':['mean','min'],
'AMT_DRAWINGS_ATM_CURRENT':['mean','min','max'],
'AMT_DRAWINGS_CURRENT':['mean','min','max'],
'AMT_DRAWINGS_OTHER_CURRENT':['mean','min','max'],
'AMT_DRAWINGS_POS_CURRENT':['mean','min','max'],
'AMT_INST_MIN_REGULARITY':['mean','min','max'],
'AMT_PAYMENT_CURRENT':['mean','min','max'],
'AMT_PAYMENT_TOTAL_CURRENT':['mean','min','max'],
'AMT_RECEIVABLE_PRINCIPAL':['mean','min','max'],
'AMT_RECIVABLE':['mean','min','max'],
'AMT_TOTAL_RECEIVABLE':['mean','min','max'],
'CNT_DRAWINGS_ATM_CURRENT':['mean','min','max'],
'CNT_DRAWINGS_CURRENT':['mean','min','max'],
'CNT_DRAWINGS_POS_CURRENT':['mean','min','max'],
'CNT_INSTALMENT_MATURE_CUM':['mean','min','max'],
'SK_DPD':['mean','min','max'],
'SK_DPD_DEF':['mean','min','max'],
}
for col in credit_cat+credit_bin:
credit_aggregation[col] = ['mean','sum']
credit_agg = credit_card_balance.groupby('SK_ID_CURR' ).agg(credit_aggregation)
credit_agg.columns = pd.Index(['CREDIT_'+e[0]+'_'+ e[1].upper() for e in credit_agg.columns.tolist() ])
credit_agg['CREDIT_COUNT'] = credit_card_balance.groupby('SK_ID_CURR' ).size()
del credit_card_balance
credit_agg.head(2 ) | Home Credit Default Risk |
1,537,787 | del df_train[index]
del df_test[index]<define_variables> | prev_cat_col = previous_application.select_dtypes(include='object' ).columns
int_col = [i for i in previous_application.columns.values if i not in prev_cat_col] | Home Credit Default Risk |
1,537,787 | index = 'ENERGY STAR Score'<compute_test_metric> | previous_application['AMT_ANNUITY'] = np.log1p(previous_application['AMT_ANNUITY'] ) | Home Credit Default Risk |
1,537,787 | intervalo_valores(df_train[index] )<count_missing_values> | previous_application['AMT_APPLICATION'] = np.sqrt(previous_application['AMT_APPLICATION'] ) | Home Credit Default Risk |
1,537,787 | df_train.isnull().any()<count_missing_values> | previous_application['AMT_CREDIT'] = np.sqrt(previous_application['AMT_CREDIT'] ) | Home Credit Default Risk |
1,537,787 | df_test.isnull().any()<count_missing_values> | previous_application['AMT_DOWN_PAYMENT'] = np.log1p(previous_application['AMT_DOWN_PAYMENT'] ) | Home Credit Default Risk |
1,537,787 | df_train.isnull().sum()<count_missing_values> | previous_application['AMT_GOODS_PRICE'] = np.log1p(previous_application['AMT_GOODS_PRICE'] ) | Home Credit Default Risk |
1,537,787 | df_test.isnull().sum()<drop_column> | previous_application[['HOUR_APPR_PROCESS_START','NFLAG_INSURED_ON_APPROVAL']] = previous_application[['HOUR_APPR_PROCESS_START','NFLAG_INSURED_ON_APPROVAL']].astype('object' ) | Home Credit Default Risk |
1,537,787 | dataset = df_train.drop(['ENERGY STAR Score'], axis=1)
dataset['ENERGY STAR Score'] = df_train['ENERGY STAR Score']<prepare_x_and_y> | previous_application[previous_application['SELLERPLACE_AREA']>500000] | Home Credit Default Risk |
1,537,787 | X = dataset.iloc[:,:-1]
y = dataset['ENERGY STAR Score'].values<set_options> | previous_application['DAYS_FIRST_DRAWING'].replace({365243:np.nan},inplace=True)
previous_application['DAYS_FIRST_DUE'].replace({365243:np.nan},inplace=True)
previous_application['DAYS_LAST_DUE_1ST_VERSION'].replace({365243:np.nan},inplace=True)
previous_application['DAYS_LAST_DUE'].replace({365243:np.nan},inplace=True)
previous_application['DAYS_TERMINATION'].replace({365243:np.nan},inplace=True)
| Home Credit Default Risk |
1,537,787 | warnings.filterwarnings('ignore')
%matplotlib inline<import_modules> | previous_application = replace_XNA_XAP(previous_application)
prev_bin =[]
previous_application,prev_bin = binary_encoding(previous_application,prev_cat_col)
previous_application,prev_cat = one_hot_encoding(previous_application,columns= prev_cat_col,nan_as_category=True)
prev_aggregate = {
'AMT_ANNUITY':['mean','sum','min'],
'AMT_APPLICATION':['mean'],
'AMT_CREDIT':['mean','min','max'],
'AMT_DOWN_PAYMENT':['mean','min'],
'AMT_GOODS_PRICE':['mean','sum','max'],
'HOUR_APPR_PROCESS_START':['mean','min'],
'NFLAG_LAST_APPL_IN_DAY': ['mean'],
'RATE_DOWN_PAYMENT': ['mean'],
'RATE_INTEREST_PRIMARY':['mean','min','max'],
'RATE_INTEREST_PRIVILEGED':['mean','min'],
'DAYS_DECISION':['mean'],
'SELLERPLACE_AREA':['mean'],
'CNT_PAYMENT':['mean','sum'],
'DAYS_FIRST_DRAWING':['mean','min'],
'DAYS_FIRST_DUE':['mean','min'],
'DAYS_LAST_DUE_1ST_VERSION':['mean','min'],
'DAYS_LAST_DUE':['mean','max'],
'DAYS_TERMINATION':['mean','max'],
'NFLAG_INSURED_ON_APPROVAL' : ['mean'],
}
cat_prev_aggregate = {}
for col in prev_cat+prev_bin:
cat_prev_aggregate[col] =['mean','sum']
prev_agg = previous_application.groupby('SK_ID_CURR' ).agg({**prev_aggregate,**cat_prev_aggregate})
prev_agg.columns = pd.Index(['PREV_'+e[0]+ '_'+ e[1].upper() for e in prev_agg.columns.tolist() ])
prev_agg = prev_agg.reset_index()
refused = previous_application[previous_application['NAME_CONTRACT_STATUS_Refused'] ==1]
refused_agg = refused.groupby('SK_ID_CURR' ).agg(prev_aggregate)
refused_agg.columns = pd.Index(['REFUSE_'+e[0]+'_'+ e[1].upper() for e in refused_agg.columns.tolist() ])
prev_agg = prev_agg.join(refused_agg, on='SK_ID_CURR', how='left')
del refused, refused_agg
canceled = previous_application[previous_application['NAME_CONTRACT_STATUS_Canceled']==1]
canceled_agg = canceled.groupby('SK_ID_CURR' ).agg(prev_aggregate)
canceled_agg.columns = pd.Index(['CANC_'+ e[0]+ '_'+ e[1].upper() for e in canceled_agg.columns.tolist() ])
prev_agg = prev_agg.join(canceled_agg, on='SK_ID_CURR', how='left')
del canceled, canceled_agg
prev_agg['PREV_COUNT'] = previous_application.groupby('SK_ID_CURR' ).size()
prev_agg = prev_agg.set_index('SK_ID_CURR')
del previous_application
prev_agg.head() | Home Credit Default Risk |
1,537,787 | from sklearn import linear_model
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import r2_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
import statsmodels.api as sm<choose_model_class> | inst_aggregator = {
'NUM_INSTALMENT_VERSION':['mean'],
'NUM_INSTALMENT_NUMBER':['mean','max'],
'DAYS_INSTALMENT':['min','mean'],
'AMT_INSTALMENT':['mean'],
'AMT_PAYMENT':['mean']
}
inst_agg = installments_payments.groupby('SK_ID_CURR' ).agg(inst_aggregator)
inst_agg.columns = pd.Index(['INST_'+e[0]+ '_'+ e[1].upper() for e in inst_agg.columns.tolist() ])
inst_agg['INST_COUNT'] = installments_payments.groupby('SK_ID_CURR' ).size()
del installments_payments
inst_agg.head() | Home Credit Default Risk |
1,537,787 | modelo = GradientBoostingRegressor()<train_model> | train_test = train_test.join(bureau_agg,how='left',on='SK_ID_CURR')
del bureau_agg
train_test = train_test.join(pos_agg, how='left',on='SK_ID_CURR')
del pos_agg
train_test = train_test.join(inst_agg,how='left',on='SK_ID_CURR')
del inst_agg
train_test = train_test.join(credit_agg, how='left',on='SK_ID_CURR')
del credit_agg
train_test = train_test.join(prev_agg, how='left',on='SK_ID_CURR')
del prev_agg
reduce_memory_usage(train_test ) | Home Credit Default Risk |
1,537,787 | Stand_coef_linear_reg.fit(X,y)
for feature_importances_, var in sorted(zip(map(abs, Stand_coef_linear_reg.steps[1][1].feature_importances_), dataset.columns[:-1]), reverse = True):
print("%6.3f %s" %(feature_importances_,var))<define_variables> | col_drop = ['TARGET','SK_ID_CURR']
X = train_test[train_test['TARGET'].notnull() ].drop(col_drop, axis=1)
y = train_test[train_test['TARGET'].notnull() ]['TARGET']
test_new = train_test[train_test['TARGET'].isnull() ].drop(col_drop, axis=1)
| Home Credit Default Risk |
1,537,787 | cols_irr = [
'Property GFA - Self-Reported(ft²)',
'Weather Normalized Site EUI(kBtu/ft²)',
'Water Use(All Water Sources )(kgal)',
'Water Intensity(All Water Sources )(gal/ft²)',
'Electricity Use - Grid Purchase(kBtu)',
'Borough',
'Natural Gas Use(kBtu)',
'Fuel Oil
'Indirect GHG Emissions(Metric Tons CO2e)',
'Total GHG Emissions(Metric Tons CO2e)',
'Direct GHG Emissions(Metric Tons CO2e)',
'Occupancy',
'Weather Normalized Site Natural Gas Intensity(therms/ft²)',
'3rd Largest Property Use Type - Gross Floor Area(ft²)',
'Weather Normalized Site Natural Gas Use(therms)',
'Weather Normalized Site Electricity(kWh)',
'Number of Buildings - Self-reported',
'Fuel Oil
'Water Required?',
'Metered Areas(Energy)',
'Metered Areas(Water)',
'Fuel Oil
'Fuel Oil
'District Steam Use(kBtu)',
'Diesel
'3rd Largest Property Use Type'
]<drop_column> | def model(X_train, X_valid, y_train, y_valid,test_new,random_seed):
lg_param = {}
lg_param['learning_rate'] = 0.02
lg_param['n_estimators'] = 10000
lg_param['max_depth'] = 8
lg_param['num_leaves'] = 34
lg_param['boosting_type'] = 'gbdt'
lg_param['feature_fraction'] = 0.9
lg_param['bagging_fraction'] = 0.9
lg_param['min_child_samples'] = 30
lg_param['lambda_l1'] = 0.04
lg_param['lambda_l2'] = 0.08
lg_param['silent'] = -1
lg_param['verbose'] = -1
lg_param['nthread'] = 4
lg_param['seed'] = random_seed
lgb_model = lgb.LGBMClassifier(**lg_param)
print('-'*10,'*'*20,'-'*10)
lgb_model.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_valid,y_valid)],
eval_metric ='auc', verbose =100, early_stopping_rounds=200)
y_pred = lgb_model.predict_proba(X_valid)[:,1]
print('roc_auc_score',roc_auc_score(y_valid,y_pred),'-'*30,i+1)
y_pred_new = lgb_model.predict_proba(test_new)[:,1]
return y_pred,y_pred_new,lgb_model | Home Credit Default Risk |
1,537,787 | X = X.drop(columns = cols_irr )<normalization> | kf = KFold(n_splits=3, shuffle=True, random_state=seed)
y_pred_new = 0
for i,(train_index, valid_index)in enumerate(kf.split(X,y)) :
X_train, X_valid = X.loc[train_index], X.loc[valid_index]
y_train, y_valid = y[train_index], y[valid_index]
print('
{} fold of {} KFold'.format(i+1,kf.n_splits))
y_pred,y_pred2,lgb_model = model(X_train, X_valid, y_train, y_valid,test_new,random_seed = i)
y_pred_new += y_pred2
| Home Credit Default Risk |
1,537,787 | scaler = MinMaxScaler()
cols = X.columns
X[cols] = scaler.fit_transform(X)
X.head()<train_model> | feat_impo = pd.DataFrame({'Columns':X.columns,'Importance':lgb_model.feature_importances_})
feat_impo.sort_values('Importance',ascending=False ).head()
feat_impo.to_csv('feat_impo.csv',index=False ) | Home Credit Default Risk |
1,537,787 | Xc = sm.add_constant(X)
modelo_v1 = sm.OLS(y, Xc)
modelo_v2 = modelo_v1.fit()<choose_model_class> | submit = pd.DataFrame({'SK_ID_CURR':test_index,'TARGET':y_pred_new/kf.n_splits})
submit.to_csv('home_credit.csv',index=False)
submit.head() | Home Credit Default Risk |
1,537,568 | modelo = linear_model.LinearRegression(normalize = False, fit_intercept = True )<compute_test_metric> | M1 = pd.read_csv('.. /input/home123/11111.csv')
M2 = pd.read_csv('.. /input/home123/22222.csv')
M3 = pd.read_csv('.. /input/home123/33333.csv')
M4 = pd.read_csv('.. /input/home123/44444.csv')
M5 = pd.read_csv('.. /input/home123/55555.csv')
M6 = pd.read_csv('.. /input/home123/Think1.csv')
M7 = pd.read_csv('.. /input/home123/new1submit8aug.csv')
M8 = pd.read_csv('.. /input/home123/newthinking.csv')
M9 = pd.read_csv('.. /input/home123/Think123.csv' ) | Home Credit Default Risk |
1,537,568 | def r2_est(X,y):
return r2_score(y, modelo.fit(X,y ).predict(X ).clip(1,100))<compute_test_metric> | def merge_dataframes(dfs, merge_keys):
dfs_merged = reduce(lambda left,right: pd.merge(left, right, on=merge_keys), dfs)
return dfs_merged | Home Credit Default Risk |
1,537,568 | def mean_absolute_error(y, y_pred):
return(1 / len(y)) * np.sum(np.abs(y - y_pred))<compute_test_metric> | dfs = [M1,M2,M3,M4,M5,M6,M7,M8,M9]
merge_keys=['SK_ID_CURR']
df = merge_dataframes(dfs, merge_keys=merge_keys ) | Home Credit Default Risk |
1,537,568 | print('Baseline R2: %0.3f' % r2_est(X,y))<predict_on_test> | df.columns = ['SK_ID_CURR','T1','T2','T3','T4','T5','T6','T7','T8','T9']
df.head() | Home Credit Default Risk |
1,537,568 | predictions = modelo.fit(X,y ).predict(X ).clip(1,100)
predictions<compute_test_metric> | pred_prob = 0.6 * df['T9'] + 0.4 * df['T6']
pred_prob.head() | Home Credit Default Risk |
1,537,568 |
<compute_test_metric> | sub = pd.DataFrame()
sub['SK_ID_CURR'] = df['SK_ID_CURR']
sub['target']= pred_prob | Home Credit Default Risk |
1,537,568 | print('MAE test score: %0.3f' % mean_absolute_error(y, predictions))<define_variables> | sub.to_csv('ldit.csv', index=False ) | Home Credit Default Risk |
1,537,568 | num_folds = 10
num_instances = len(X)
seed = 998
modelos = []
modelos.append(( 'LINEAR', LinearRegression()))
modelos.append(( 'RIDGE', Ridge()))
modelos.append(( 'LASSO', Lasso()))
modelos.append(( 'ELASTIC', ElasticNet()))
modelos.append(( 'KNN', KNeighborsRegressor()))
modelos.append(( 'CART', DecisionTreeRegressor()))
resultados = []
nomes = []
for nome, modelo in modelos:
kfold = model_selection.KFold(n_splits = num_folds, random_state = seed)
cv_results = model_selection.cross_val_score(modelo, X, y, cv = kfold, scoring = 'neg_mean_absolute_error')
resultados.append(cv_results)
nomes.append(nome)
msg = "%s: %.3f(%.3f)" %(nome, cv_results.mean() , cv_results.std())
print(msg )<define_variables> | B_prob = 0.4 * df['T9'] + 0.15 * df['T4'] + 0.15 * df['T6'] + 0.15 *df['T1'] + 0.15*df['T5'] | Home Credit Default Risk |
1,537,568 | num_folds = 10
num_instances = len(X)
seed = 998
modelos = []
modelos.append(( 'AD', AdaBoostRegressor()))
modelos.append(( 'BG', BaggingRegressor()))
modelos.append(( 'ET', ExtraTreesRegressor()))
modelos.append(( 'GB', GradientBoostingRegressor()))
modelos.append(( 'RF', RandomForestRegressor()))
modelos.append(( 'XGB', XGBRegressor()))
resultados = []
nomes = []
for nome, modelo in modelos:
kfold = model_selection.KFold(n_splits = num_folds, random_state = seed)
cv_results = model_selection.cross_val_score(modelo, X, y, cv = kfold, scoring = 'neg_mean_absolute_error')
resultados.append(cv_results)
nomes.append(nome)
msg = "%s: %.3f(%.3f)" %(nome, cv_results.mean() , cv_results.std())
print(msg )<drop_column> | SUB = pd.DataFrame()
SUB['SK_ID_CURR'] = df['SK_ID_CURR']
SUB['TARGET'] = B_prob
SUB.to_csv('Blendss.csv', index=False ) | Home Credit Default Risk |
1,537,568 | <drop_column><EOS> | SuB = pd.DataFrame()
SuB['SK_ID_CURR'] = df['SK_ID_CURR']
SuB['TARGET'] = corr_pred
SuB.to_csv('corr_blend.csv', index=False ) | Home Credit Default Risk |
1,526,075 | <SOS> metric: AUC Kaggle data source: home-credit-default-risk<prepare_x_and_y> | N_FOLDS = 5
MAX_EVALS = 5 | Home Credit Default Risk |
1,526,075 | X_test = df_test<normalization> | features = pd.read_csv('.. /input/home-credit-default-risk/application_train.csv')
features = features.sample(n = 17000, random_state = 42)
features = features.select_dtypes('number')
labels = np.array(features['TARGET'].astype(np.int32)).reshape(( -1,))
features = features.drop(columns = ['TARGET', 'SK_ID_CURR'])
train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 7000, random_state = 37 ) | Home Credit Default Risk |
1,526,075 | scaler = MinMaxScaler()
cols = X_test.columns
X_test[cols] = scaler.fit_transform(X_test)
X_test.head()<compute_test_metric> | train_set = lgb.Dataset(data = train_features, label = train_labels)
test_set = lgb.Dataset(data = test_features, label = test_labels ) | Home Credit Default Risk |
1,526,075 | def r2_est(X,y):
return r2_score(y, modelo.fit(X,y ).predict(X ).clip(1,100))<compute_test_metric> | model = lgb.LGBMClassifier()
default_params = model.get_params()
del default_params['n_estimators']
cv_results = lgb.cv(default_params, train_set, num_boost_round = 10000, early_stopping_rounds = 100,
metrics = 'auc', nfold = N_FOLDS, seed = 42 ) | Home Credit Default Risk |
1,526,075 | def mean_absolute_error(y, y_pred):
return(1 / len(y)) * np.sum(np.abs(y - y_pred))<choose_model_class> | print('The maximum validation ROC AUC was: {:.5f} with a standard deviation of {:.5f}.'.format(cv_results['auc-mean'][-1], cv_results['auc-stdv'][-1]))
print('The optimal number of boosting rounds(estimators)was {}.'.format(len(cv_results['auc-mean'])) ) | Home Credit Default Risk |
1,526,075 | modelo = GradientBoostingRegressor()<train_model> | from sklearn.metrics import roc_auc_score | Home Credit Default Risk |
1,526,075 | model_fit = modelo.fit(X,y )<predict_on_test> | model.n_estimators = len(cv_results['auc-mean'])
model.fit(train_features, train_labels)
preds = model.predict_proba(test_features)[:, 1]
baseline_auc = roc_auc_score(test_labels, preds)
print('The baseline model scores {:.5f} ROC AUC on the test set.'.format(baseline_auc)) | Home Credit Default Risk |
1,526,075 | predictions = model_fit.predict(X ).clip(1,100)
predictions<compute_test_metric> | def objective(hyperparameters, iteration):
if 'n_estimators' in hyperparameters.keys() :
del hyperparameters['n_estimators']
cv_results = lgb.cv(hyperparameters, train_set, num_boost_round = 10000, nfold = N_FOLDS,
early_stopping_rounds = 100, metrics = 'auc', seed = 42)
score = cv_results['auc-mean'][-1]
estimators = len(cv_results['auc-mean'])
hyperparameters['n_estimators'] = estimators
return [score, hyperparameters, iteration] | Home Credit Default Risk |
1,526,075 | print('Baseline R2: %0.3f' % r2_est(X,y))<compute_test_metric> | score, params, iteration = objective(default_params, 1)
print('The cross-validation ROC AUC was {:.5f}.'.format(score)) | Home Credit Default Risk |
1,526,075 | print('MAE test score: %0.3f' % mean_absolute_error(y, predictions))<predict_on_test> | model = lgb.LGBMModel()
model.get_params() | Home Credit Default Risk |
1,526,075 | predictions = model_fit.predict(X_test ).clip(1,100)
predictions<save_to_csv> | param_grid = {
'boosting_type': ['gbdt', 'goss', 'dart'],
'num_leaves': list(range(20, 150)) ,
'learning_rate': list(np.logspace(np.log10(0.005), np.log10(0.5), base = 10, num = 1000)) ,
'subsample_for_bin': list(range(20000, 300000, 20000)) ,
'min_child_samples': list(range(20, 500, 5)) ,
'reg_alpha': list(np.linspace(0, 1)) ,
'reg_lambda': list(np.linspace(0, 1)) ,
'colsample_bytree': list(np.linspace(0.6, 1, 10)) ,
'subsample': list(np.linspace(0.5, 1, 100)) ,
'is_unbalance': [True, False]
} | Home Credit Default Risk |
1,526,075 | submission = pd.DataFrame()
submission['Property Id'] = index
submission['score'] = predictions.round().astype(int)
submission.to_csv('submission.csv', index = False )<import_modules> | a = 0
b = 0
for x in param_grid['learning_rate']:
if x >= 0.005 and x < 0.05:
a += 1
elif x >= 0.05 and x < 0.5:
b += 1
print('There are {} values between 0.005 and 0.05'.format(a))
print('There are {} values between 0.05 and 0.5'.format(b)) | Home Credit Default Risk |
1,526,075 | import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from math import log as log<load_from_csv> | random_results = pd.DataFrame(columns = ['score', 'params', 'iteration'],
index = list(range(MAX_EVALS)))
grid_results = pd.DataFrame(columns = ['score', 'params', 'iteration'],
index = list(range(MAX_EVALS)) ) | Home Credit Default Risk |
1,526,075 | df_train = pd.read_csv('.. /input/web-club-recruitment-2018/train.csv')
df_test = pd.read_csv('.. /input/web-club-recruitment-2018/test.csv')
<categorify> | com = 1
for x in param_grid.values() :
com *= len(x)
print('There are {} combinations'.format(com)) | Home Credit Default Risk |
1,526,075 | def fn(X):
X['X24']=(X.X6+X.X7+X.X8+X.X9+X.X10+X.X11)/X.X1
X['X25']=(X.X12+X.X13+X.X14+X.X15+X.X16+X.X17)/X.X1
X['X26']=(X.X18+X.X19+X.X20+X.X21+X.X22+X.X23)/X.X1
X['X28']=(X.X6+X.X7+X.X8+X.X9+X.X10+X.X11)
X['X29']=(X.X12+X.X13+X.X14+X.X15+X.X16+X.X17)
X['X30']=(X.X18+X.X19+X.X20+X.X21+X.X22+X.X23)
X['X31']=(X.X2==-1)*1+(X.X3==-1)*1+(X.X4==-1)*1+(X.X5==-1)*1
print(X.head())
return X
train_X = df_train.loc[0:19999, 'X1':'X23']
train_X = fn(train_X)
print(train_X.head())
train_y = df_train.loc[0:19999, 'Y']
data_dmatrix = xgb.DMatrix(data=train_X,label=train_y )<choose_model_class> | print('This would take {:.0f} years to finish.'.format(( 100 * com)/(60 * 60 * 24 * 365)) ) | Home Credit Default Risk |
1,526,075 | xg_reg = xgb.XGBRegressor(objective ='reg:logistic', colsample_bytree = 0.3, learning_rate = 0.024,
max_depth = 6, alpha = 10, n_estimators = 230,eval_metric='auc' )<train_model> | grid_results = grid_search(param_grid)
print('The best validation score was {:.5f}'.format(grid_results.loc[0, 'score']))
print('
The best hyperparameters were:')
pprint.pprint(grid_results.loc[0, 'params'] ) | Home Credit Default Risk |
1,526,075 | xg_reg.fit(train_X,train_y )<predict_on_test> | grid_search_params = grid_results.loc[0, 'params']
model = lgb.LGBMClassifier(**grid_search_params, random_state=42)
model.fit(train_features, train_labels)
preds = model.predict_proba(test_features)[:, 1]
print('The best model from grid search scores {:.5f} ROC AUC on the test set.'.format(roc_auc_score(test_labels, preds)) ) | Home Credit Default Risk |
1,526,075 | train_X = df_test.loc[:, 'X1':'X23']
train_X = fn(train_X)
pred = xg_reg.predict(train_X)
pred=pred*(pred>=0)
pred=(pred*(pred<=1)) + 1*(pred>1 )<save_to_csv> | pd.options.display.max_colwidth = 1000
grid_results['params'].values | Home Credit Default Risk |
1,526,075 | result = pd.DataFrame(pred)
result.index.name = 'id'
result.columns = ['predicted_val']
result.to_csv('output.csv', index=True)
X = df_train.loc[18000:19999, 'X1':'X23']
X = fn(X)
Y = df_train.loc[18000:19999, 'Y']
pred = xg_reg.predict(X)
pred=pred*(pred>=0)
pred=(pred*(pred<=1)) + 1*(pred>1)
print(roc_auc_score(Y, pred))<concatenate> | random.seed(50)
random_params = {k: random.sample(v, 1)[0] for k, v in param_grid.items() }
random_params['subsample'] = 1.0 if random_params['boosting_type'] == 'goss' else random_params['subsample']
random_params | Home Credit Default Risk |
1,526,075 | def autocorr_method(frame, sfreq, threshold=0.46, fmin=50, fmax=400):
frame = frame.astype(np.float)
frame -= frame.mean()
amax = np.abs(frame ).max()
if amax > 0:
frame /= amax
else:
return 0
corr = correlate(frame, frame)
corr = corr[len(corr)//2:]
dcorr = np.diff(corr)
rmin = np.where(dcorr > 0)[0]
if len(rmin)> 0:
rmin1 = rmin[0]
else:
return 0
peak = np.argmax(corr[rmin1:])+ rmin1
rmax = corr[peak]/corr[0]
f0 = sfreq / peak
if rmax > threshold and f0 >= fmin and f0 <= fmax:
return f0
else:
return 0<init_hyperparams> | def random_search(param_grid, max_evals = MAX_EVALS):
results = pd.DataFrame(columns = ['score', 'params', 'iteration'],
index = list(range(MAX_EVALS)))
for i in range(MAX_EVALS):
hyperparameters = {k: random.sample(v, 1)[0] for k, v in param_grid.items() }
hyperparameters['subsample'] = 1.0 if hyperparameters['boosting_type'] == 'goss' else hyperparameters['subsample']
eval_results = objective(hyperparameters, i)
results.loc[i, :] = eval_results
results.sort_values('score', ascending = False, inplace = True)
results.reset_index(inplace = True)
return results | Home Credit Default Risk |
1,526,075 | class Counters:
def __init__(self, gross_threshold=0.2):
self.num_voiced = 0
self.num_unvoiced = 0
self.num_voiced_unvoiced = 0
self.num_unvoiced_voiced = 0
self.num_voiced_voiced = 0
self.num_gross_errors = 0
self.fine_error = 0
self.e2 = 0
self.gross_threshold = gross_threshold
self.nfiles = 0
def add(self, other):
if other is not None:
self.num_voiced += other.num_voiced
self.num_unvoiced += other.num_unvoiced
self.num_voiced_unvoiced += other.num_voiced_unvoiced
self.num_unvoiced_voiced += other.num_unvoiced_voiced
self.num_voiced_voiced += other.num_voiced_voiced
self.num_gross_errors += other.num_gross_errors
self.fine_error += other.fine_error
self.e2 += other.e2
self.nfiles += 1
def __repr__(self):
nframes = self.num_voiced + self.num_unvoiced
if self.nfiles > 0:
self.fine_error /= self.nfiles
str = [
f"Num.frames:\t{self.num_unvoiced + self.num_voiced} = {self.num_unvoiced} unvoiced + {self.num_voiced} voiced",
f"Unvoiced frames as voiced:\t{self.num_unvoiced_voiced}/{self.num_unvoiced}({100*self.num_unvoiced_voiced/self.num_unvoiced:.2f}%)",
f"Voiced frames as unvoiced:\t{self.num_voiced_unvoiced}/{self.num_voiced}({100*self.num_voiced_unvoiced/self.num_voiced:.2f}%)",
f"Gross voiced errors(>{100*self.gross_threshold}%):\t{self.num_gross_errors}/{self.num_voiced_voiced}({100*self.num_gross_errors/self.num_voiced_voiced:.2f}%)",
f"MSE of fine errors:\t{100*self.fine_error:.2f}%",
f"RMSE:\t{np.sqrt(self.e2/nframes):.2f}"
]
return '
'.join(str )<normalization> | random_results = random_search(param_grid)
print('The best validation score was {:.5f}'.format(random_results.loc[0, 'score']))
print('
The best hyperparameters were:')
pprint.pprint(random_results.loc[0, 'params'] ) | Home Credit Default Risk |
1,526,075 | def compare(fref, pitch):
vref = np.loadtxt(fref)
vtest = np.array(pitch)
diff_frames = len(vref)- len(vtest)
if abs(diff_frames)> 5:
print(f"Error: number of frames in ref({len(vref)})!= number of frames in test({len(vtest)})")
return None
elif diff_frames > 0:
vref = np.resize(vref, vtest.shape)
elif diff_frames < 0:
vtest = np.resize(vtest, vref.shape)
counters = Counters()
counters.num_voiced = np.count_nonzero(vref)
counters.num_unvoiced = len(vref)- counters.num_voiced
counters.num_unvoiced_voiced = np.count_nonzero(np.logical_and(vref == 0, vtest != 0))
counters.num_voiced_unvoiced = np.count_nonzero(np.logical_and(vref != 0, vtest == 0))
voiced_voiced = np.logical_and(vref != 0, vtest != 0)
counters.num_voiced_voiced = np.count_nonzero(voiced_voiced)
f = np.absolute(vref[voiced_voiced] - vtest[voiced_voiced])/vref[voiced_voiced]
gross_errors = f > counters.gross_threshold
counters.num_gross_errors = np.count_nonzero(gross_errors)
fine_errors = np.logical_not(gross_errors)
counters.fine_error = np.sqrt(np.square(f[fine_errors] ).mean())if np.count_nonzero(fine_errors)> 0 else 0
counters.e2 = np.square(vref - vtest ).sum()
return counters<categorify> | random_search_params = random_results.loc[0, 'params']
model = lgb.LGBMClassifier(**random_search_params, random_state = 42)
model.fit(train_features, train_labels)
preds = model.predict_proba(test_features)[:, 1]
print('The best model from random search scores {:.5f} ROC AUC on the test set.'.format(roc_auc_score(test_labels, preds)) ) | Home Credit Default Risk |
1,526,075 | def wav2f0(options, gui):
fs = open(options.submission, 'w')if options.submission is not None else None
totalCounters = Counters()
with open(gui)as f:
if fs is not None:
print('id,frequency', file=fs)
for line in f:
line = line.strip()
if len(line)== 0:
continue
filename = os.path.join(options.datadir, line + ".wav")
f0ref_filename = os.path.join(options.datadir, line + ".f0ref")
print("Processing:", filename)
sfreq, data = wavfile.read(filename)
nsamples = len(data)
ns_windowlength = int(round(( options.windowlength * sfreq)/ 1000))
ns_frameshift = int(round(( options.frameshift * sfreq)/ 1000))
ns_left_padding = int(round(( options.left_padding * sfreq)/ 1000))
ns_right_padding = int(round(( options.right_padding * sfreq)/ 1000))
pitch = []
for ini in range(-ns_left_padding, nsamples - ns_windowlength + ns_right_padding + 1, ns_frameshift):
first_sample = max(0, ini)
last_sample = min(nsamples, ini + ns_windowlength)
frame = data[first_sample:last_sample]
f0 = autocorr_method(frame, sfreq)
pitch.append(f0)
if fs is not None:
for frame_id, f0 in enumerate(pitch):
print(line + '_' + str(frame_id)+ ',', f0, file=fs)
if os.path.isfile(f0ref_filename):
counters = compare(f0ref_filename, pitch)
totalCounters.add(counters)
if totalCounters.num_voiced + totalCounters.num_unvoiced > 0:
print("
print(totalCounters)
print("-------------------------------
" )<set_options> | out_file = 'random_search_trials.csv'
of_connection = open(out_file, 'w')
writer = csv.writer(of_connection)
headers = ['score', 'hyperparameters', 'iteration']
writer.writerow(headers)
of_connection.close() | Home Credit Default Risk |
1,526,075 | fda_ue_options = SimpleNamespace(
windowlength=32, frameshift=15, left_padding=16, right_padding=16, datadir='.. /input', submission=None)
wav2f0(fda_ue_options, '.. /input/fda_ue.gui' )<set_options> | def random_search(param_grid, out_file, max_evals = MAX_EVALS):
results = pd.DataFrame(columns = ['score', 'params', 'iteration'],
index = list(range(MAX_EVALS)))
for i in range(MAX_EVALS):
random_params = {k: random.sample(v, 1)[0] for k, v in param_grid.items() }
random_params['subsample'] = 1.0 if random_params['boosting_type'] == 'goss' else random_params['subsample']
eval_results = objective(random_params, i)
results.loc[i, :] = eval_results
of_connection = open(out_file, 'a')
writer = csv.writer(of_connection)
writer.writerow(eval_results)
of_connection.close()
results.sort_values('score', ascending = False, inplace = True)
results.reset_index(inplace = True)
return results | Home Credit Default Risk |
1,526,075 | test_options = SimpleNamespace(
windowlength=26.5, frameshift=10, left_padding=13.25, right_padding=7, datadir='.. /input/test', submission='submission.csv')
wav2f0(test_options, '.. /input/test.gui' )<load_from_csv> | def grid_search(param_grid, out_file, max_evals = MAX_EVALS):
results = pd.DataFrame(columns = ['score', 'params', 'iteration'],
index = list(range(MAX_EVALS)))
keys, values = zip(*param_grid.items())
i = 0
for v in itertools.product(*values):
parameters = dict(zip(keys, v))
parameters['subsample'] = 1.0 if parameters['boosting_type'] == 'goss' else parameters['subsample']
eval_results = objective(parameters, i)
results.loc[i, :] = eval_results
i += 1
of_connection = open(out_file, 'a')
writer = csv.writer(of_connection)
writer.writerow(eval_results)
of_connection.close()
if i > MAX_EVALS:
break
results.sort_values('score', ascending = False, inplace = True)
results.reset_index(inplace = True)
return results | Home Credit Default Risk |
1,526,075 | df = pd.read_csv('.. /input/2TWH_train.csv', index_col='IDNum')
for col in df:
if col[0] == ' ':
df = df.rename(columns={col : col[1:]})
dt = pd.read_csv('.. /input/test.csv', index_col='IDNum')
for col in dt:
if col[0] == ' ':
dt = dt.rename(columns={col : col[1:]} )<data_type_conversions> | random_results = pd.read_csv('.. /input/home-credit-model-tuning/random_search_trials_1000.csv')
grid_results = pd.read_csv('.. /input/home-credit-model-tuning/grid_search_trials_1000.csv' ) | Home Credit Default Risk |
1,526,075 | df['Source IP'] = df['Source IP'].apply(to_int)
df['Destination IP'] = df['Destination IP'].apply(to_int)
df['Timestamp'] = df['Timestamp'].apply(to_int)
df['Flow Bytes/s'] = df['Flow Bytes/s'].astype(float)
df['Flow Packets/s'] = df['Flow Packets/s'].astype(float)
dt['Source IP'] = dt['Source IP'].apply(to_int)
dt['Destination IP'] = dt['Destination IP'].apply(to_int)
dt['Timestamp'] = dt['Timestamp'].apply(to_int)
dt['Flow Bytes/s'] = dt['Flow Bytes/s'].astype(float)
dt['Flow Packets/s'] = dt['Flow Packets/s'].astype(float )<count_values> | grid_results['hyperparameters'] = grid_results['hyperparameters'].map(ast.literal_eval)
random_results['hyperparameters'] = random_results['hyperparameters'].map(ast.literal_eval ) | Home Credit Default Risk |
1,526,075 | MaxValueCount = 100000
df = df.drop(['Private'], axis='columns')
UselessAttribute = set(['Flow ID'])
for i in range(df.shape[1]):
value_count = len(df[df.columns[i]].value_counts())
if(value_count == 1 or value_count > MaxValueCount):
UselessAttribute.add(df.columns[i])
for attribute in UselessAttribute:
df = df.drop(attribute, axis='columns')
dt = dt.drop(attribute, axis='columns')
UselessAttribute.clear()
for i in range(dt.shape[1]):
value_count = len(dt[dt.columns[i]].value_counts())
if(value_count == 1 or value_count > MaxValueCount):
UselessAttribute.add(dt.columns[i])
for attribute in UselessAttribute:
df = df.drop(attribute, axis='columns')
dt = dt.drop(attribute, axis='columns')
del UselessAttribute<categorify> | def evaluate(results, name):
results = results.sort_values('score', ascending = False ).reset_index(drop = True)
print('The highest cross validation score from {} was {:.5f} found on iteration {}.'.format(name, results.loc[0, 'score'], results.loc[0, 'iteration']))
hyperparameters = results.loc[0, 'hyperparameters']
model = lgb.LGBMClassifier(**hyperparameters)
model.fit(train_features, train_labels)
preds = model.predict_proba(test_features)[:, 1]
print('ROC AUC from {} on test data = {:.5f}.'.format(name, roc_auc_score(test_labels, preds)))
hyp_df = pd.DataFrame(columns = list(results.loc[0, 'hyperparameters'].keys()))
for i, hyp in enumerate(results['hyperparameters']):
hyp_df = hyp_df.append(pd.DataFrame(hyp, index = [0]),
ignore_index = True)
hyp_df['iteration'] = results['iteration']
hyp_df['score'] = results['score']
return hyp_df | Home Credit Default Risk |
1,526,075 | df = df.replace([np.inf, 'Infinity', 'infinity', 'inf'], 2**31-1)
df = df.replace([np.nan, np.inf, 'NaN'], 0)
dt = dt.replace([np.inf, 'Infinity', 'infinity', 'inf'], 2**31-1)
dt = dt.replace([np.nan, 'NaN'], 0 )<categorify> | grid_hyp = evaluate(grid_results, name = 'grid search' ) | Home Credit Default Risk |
1,526,075 | X = df.iloc[:, :-1]
y = df.iloc[:, -1]
enc = LabelEncoder()
y = enc.fit_transform(y )<train_model> | random_hyp = evaluate(random_results, name = 'random search' ) | Home Credit Default Risk |
1,526,075 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 42)
ohe = OneHotEncoder(categories='auto')
y_train_ohe = ohe.fit_transform(y_train.reshape(-1, 1))
y_test_ohe = ohe.fit_transform(y_test.reshape(-1, 1))
y_ohe = ohe.fit_transform(y.reshape(-1, 1))
scaler = StandardScaler()
X_scale = scaler.fit_transform(X.astype(float))
X_train_scale = scaler.fit_transform(X_train.astype(float))
X_test_scale = scaler.transform(X_test.astype(float))<choose_model_class> | alt.renderers.enable('notebook' ) | Home Credit Default Risk |
1,526,075 | model = Sequential()
model.add(Dense(units=20, activation='relu', input_dim=X.shape[1]))
model.add(Dense(units=10, activation='relu'))
model.add(Dense(units=3, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'] )<train_model> | random_hyp['search'] = 'random'
grid_hyp['search'] = 'grid'
hyp = random_hyp.append(grid_hyp)
hyp.head() | Home Credit Default Risk |
1,526,075 | history = model.fit(X_train_scale,
y_train_ohe,
epochs=1000,
batch_size=8192,
validation_data=(X_test_scale, y_test_ohe))<compute_test_metric> | best_grid_hyp = grid_hyp.iloc[grid_hyp['score'].idxmax() ].copy()
best_random_hyp = random_hyp.iloc[random_hyp['score'].idxmax() ].copy() | Home Credit Default Risk |
1,526,075 | confusion_matrix(y, model.predict_classes(X))<save_to_csv> | print('Average validation score of grid search = {:.5f}.'.format(np.mean(grid_hyp['score'])))
print('Average validation score of random search = {:.5f}.'.format(np.mean(random_hyp['score'])) ) | Home Credit Default Risk |
1,526,075 | dt_scale = scaler.transform(dt)
dftest = pd.DataFrame(enc.inverse_transform(model.predict_classes(dt_scale)) , columns=['Label'], index=dt.index ).reset_index()
dftest.sort_values('IDNum')
dftest.to_csv('submission.csv', index=False )<load_from_csv> | random_hyp['score'] = random_hyp['score'].astype(float)
best_random_hyp = random_hyp.loc[0, :].copy() | Home Credit Default Risk |
1,526,075 | test_df = pd.read_csv('/kaggle/input/epam-ml-training-imdb/train.csv', index_col='Id')
test_df.head()<define_variables> | train = pd.read_csv('.. /input/home-credit-simple-featuers/simple_features_train.csv')
test = pd.read_csv('.. /input/home-credit-simple-featuers/simple_features_test.csv')
test_ids = test['SK_ID_CURR']
train_labels = np.array(train['TARGET'].astype(np.int32)).reshape(( -1,))
train = train.drop(columns = ['SK_ID_CURR', 'TARGET'])
test = test.drop(columns = ['SK_ID_CURR'])
print('Training shape: ', train.shape)
print('Testing shape: ', test.shape ) | Home Credit Default Risk |
1,526,075 | predictions = ['positive']*len(test_df )<prepare_output> | train_set = lgb.Dataset(train, label = train_labels)
hyperparameters = dict(**random_results.loc[0, 'hyperparameters'])
del hyperparameters['n_estimators']
cv_results = lgb.cv(hyperparameters, train_set,
num_boost_round = 10000, early_stopping_rounds = 100,
metrics = 'auc', nfold = N_FOLDS ) | Home Credit Default Risk |
1,526,075 | subm_df = pd.DataFrame({'Predicted': predictions}, index=test_df.index)
subm_df.head()<save_to_csv> | print('The cross validation score on the full dataset = {:.5f} with std: {:.5f}.'.format(
cv_results['auc-mean'][-1], cv_results['auc-stdv'][-1]))
print('Number of estimators = {}.'.format(len(cv_results['auc-mean'])) ) | Home Credit Default Risk |
1,526,075 | subm_df.to_csv('/kaggle/working/submission.csv' )<import_modules> | model = lgb.LGBMClassifier(n_estimators = len(cv_results['auc-mean']), **hyperparameters)
model.fit(train, train_labels)
preds = model.predict_proba(test)[:, 1] | Home Credit Default Risk |
1,526,075 | import numpy as np
import matplotlib.pyplot as plt<prepare_x_and_y> | submission = pd.DataFrame({'SK_ID_CURR': test_ids, 'TARGET': preds})
submission.to_csv('submission_simple_features_random.csv', index = False ) | Home Credit Default Risk |
1,526,075 | X_train = np.load('.. /input/uci-math-10-winter2020/kmnist-train-imgs.npz')['X']
y_train = np.load('.. /input/uci-math-10-winter2020/kmnist-train-labels.npz')['y']
X_test = np.load('.. /input/uci-math-10-winter2020/kmnist-test-imgs.npz')['X']<import_modules> | clf_xgBoost = xgb.XGBClassifier(
learning_rate =0.01, n_estimators=1000, max_depth=4, min_child_weight=4, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic',
nthread=4, scale_pos_weight=2, seed=27)
clf_xgBoost.fit(train,train_labels ) | Home Credit Default Risk |
1,526,075 | from sklearn.neighbors import KNeighborsClassifier<import_modules> | pred = clf_xgBoost.predict_proba(test)[:, 1] | Home Credit Default Risk |
1,526,075 | <import_modules><EOS> | submission = pd.DataFrame({'SK_ID_CURR': test_ids, 'TARGET': pred})
submission.to_csv('submission_xgboost.csv', index = False)
submission.head() | Home Credit Default Risk |
1,533,277 | <SOS> metric: AUC Kaggle data source: home-credit-default-risk<train_model> | pd.options.display.max_columns = 999
warnings.filterwarnings('ignore')
os.environ['OMP_NUM_THREADS'] = '4'
| Home Credit Default Risk |
1,533,277 | clf = KNeighborsClassifier(n_neighbors=5, weights='distance')
clf.fit(X_train, y_train )<predict_on_test> | train = pd.read_csv(".. /input/application_train.csv")
test = pd.read_csv(".. /input/application_test.csv")
previous = pd.read_csv(".. /input/previous_application.csv")
bureau = pd.read_csv(".. /input/bureau.csv" ) | Home Credit Default Risk |
1,533,277 | y_pred = clf.predict(X_test )<save_to_csv> | previous['AMT_APPLICATION'].replace(0,np.nan, inplace = True)
previous['AMT_CREDIT'].replace(0,np.nan, inplace = True)
previous['AMT_GOODS_PRICE'].replace(0,np.nan,inplace =True)
previous['RATE_DOWN_PAYMENT'].replace(0, np.nan, inplace = True)
previous['AMT_ANNUITY'].replace(0, np.nan, inplace = True)
previous['CNT_PAYMENT'].replace(0, np.nan, inplace = True ) | Home Credit Default Risk |
1,533,277 | solutions = np.zeros(( X_test.shape[0], 2))
solutions[:,0] = np.arange(1,X_test.shape[0]+1)
solutions[:,1] = y_pred
solutions = solutions.astype(int)
np.savetxt("solutions-yournames.csv", solutions,
fmt='%s', header = 'Id,Category', delimiter = ',', comments='' )<import_modules> | for i in ['Revolving loans','Cash loans', 'Consumer loans']:
tmp = previous[(previous['NAME_CONTRACT_TYPE'] == i)&(previous['DAYS_LAST_DUE'] == 365243)]
for df in [train,test]:
tmp1 = tmp.groupby(['SK_ID_CURR'])['SK_ID_PREV'].count().reset_index()
tmp1.columns = ['SK_ID_CURR','des']
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp1, on=['SK_ID_CURR'], how='left')
df['count_notfinish_' + "_".join(i.lower().split())] = tmp_merge['des'].fillna(0 ) | Home Credit Default Risk |
1,533,277 | from sklearn.feature_extraction.text import CountVectorizer
import os
import pandas as pd
import json
import numpy as np
from datetime import datetime
import xgboost as xgb<load_from_csv> | for i in ['Revolving loans','Cash loans', 'Consumer loans']:
tmp = previous[(previous['NAME_CONTRACT_TYPE'] == i)&(previous['DAYS_LAST_DUE'] == 365243)]
for df in [train,test]:
tmp1 = tmp.groupby(['SK_ID_CURR'])['AMT_CREDIT'].agg({"returns": [np.mean, np.sum]})\
.reset_index()
tmp1.columns = ['SK_ID_CURR','des1','des2']
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp1, on=['SK_ID_CURR'], how='left')
df['mean_notfinish_' + "_".join(i.lower().split())] = tmp_merge['des1'].fillna(0)
df['sum_notfinish_' + "_".join(i.lower().split())] = tmp_merge['des2'].fillna(0 ) | Home Credit Default Risk |
1,533,277 | def read_data(category, train=True):
path_dir_data = os.path.join('.. ', 'input')
path_dir_map = os.path.join('.. ', 'input')
file_data_suffix = '_data_info_train_competition.csv' if train else '_data_info_val_competition.csv'
file_data = category + file_data_suffix
file_map = category + '_profile_train.json'
path_data = os.path.join(path_dir_data, file_data)
path_map = os.path.join(path_dir_map, file_map)
df_data = pd.read_csv(path_data)
with open(path_map)as file_json:
dict_map = json.load(file_json)
return df_data, dict_map
def tidy_train_data(df_train, dict_map):
df_map = pd.DataFrame()
for attribute in list(dict_map.keys()):
df_map_attribute = pd.DataFrame(list(dict_map[attribute].items()), columns = ['class', 'class_id'])
df_map_attribute['attribute'] = attribute
df_map = pd.concat([df_map, df_map_attribute])
df_train_label =(pd.melt(df_train,
id_vars=['itemid', 'title', 'image_path'],
value_vars=list(dict_map.keys()),
var_name='attribute',
value_name='class_id')
.dropna()
.assign(class_id = lambda x: x['class_id'].apply(int))
.merge(df_map, on=['attribute', 'class_id'], how='left'))
return df_train_label
def predict_class(model, feature_test, k=2):
y_prob = model.predict_proba(feature_test)
y_pred = [model.classes_[np.flip(np.argsort(y)) [0:k]] for y in y_prob]
return y_pred
def pick_top_2(y_pred):
y_pred_1 = [y[0] for y in y_pred]
y_pred_2 = [y[1] for y in y_pred]
return y_pred_1, y_pred_2
def generate_model() :
model_class = xgb.XGBClassifier
model_params = {
"max_depth": 15,
"min_child_weight": 1,
"learning_rate": 0.2,
"n_estimators": 150,
"reg_alpha": 0,
"reg_lambda": 1,
"objective": "multi:softprob",
"n_jobs": -1
}
return model_class(**model_params)
def generate_text_features(doc_train, doc_test):
cv = CountVectorizer(analyzer='word', token_pattern=r'\S{1,}')
cv.fit(doc_train)
feature_train = cv.transform(doc_train)
feature_test = cv.transform(doc_test)
return feature_train, feature_test
def run_submission() :
df_submission = pd.DataFrame()
for category in ['fashion', 'beauty', 'mobile']:
df_train, dict_map = read_data(category, train=True)
df_test, dict_map = read_data(category, train=False)
df_train_label = tidy_train_data(df_train, dict_map)
attributes = list(dict_map.keys())
for attribute in attributes:
id_train = df_train_label.loc[df_train_label['attribute'] == attribute, 'itemid'].tolist()
doc_train = df_train_label.loc[df_train_label['attribute'] == attribute, 'title'].tolist()
image_train = df_train_label.loc[df_train_label['attribute'] == attribute, 'image_path'].tolist()
y_train = df_train_label.loc[df_train_label['attribute'] == attribute, 'class_id'].tolist()
id_test = df_test['itemid'].tolist()
doc_test = df_test['title'].tolist()
image_test = df_test['image_path'].tolist()
print("Running {c} - {a}".format(c=category, a=attribute))
feature_train, feature_test = generate_text_features(doc_train, doc_test)
model = generate_model()
model = model.fit(feature_train, y_train, verbose=True)
y_pred = predict_class(model, feature_test, k=2)
y_pred_1, y_pred_2 = pick_top_2(y_pred)
item_attr = df_test.apply(lambda x:'{}_{}'.format(x['itemid'], attribute), axis=1)
tagging = ['{} {}'.format(y1, y2)for y1, y2 in zip(y_pred_1, y_pred_2)]
df_submission_attribute = pd.DataFrame({'id': item_attr, 'tagging': tagging})
df_submission = df_submission.append(df_submission_attribute)
print('{t}: Completed {c} - {a}'.format(
t=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
c=category,
a=attribute)
)
print('Completed generating submissions!')
return df_submission<save_to_csv> | for i in ['Revolving loans','Cash loans', 'Consumer loans']:
tmp = previous[(previous['NAME_CONTRACT_TYPE'] == i)&(previous['DAYS_TERMINATION'] == 365243)]
for df in [train,test]:
tmp1 = tmp.groupby(['SK_ID_CURR'])['AMT_ANNUITY'].agg({"returns": [np.mean, np.sum]})\
.reset_index()
tmp1.columns = ['SK_ID_CURR','des1','des2']
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp1, on=['SK_ID_CURR'], how='left')
df['mean_annuity_notfinish_' + "_".join(i.lower().split())] = tmp_merge['des1'].fillna(0)
df['sum_annuity_notfinish_' + "_".join(i.lower().split())] = tmp_merge['des2'].fillna(0 ) | Home Credit Default Risk |
1,533,277 | df_submission = run_submission()
print(df_submission.shape)
print(df_submission.head())
df_submission.to_csv("xgb_baseline.csv", index=False )<load_from_csv> | previous['SELLERPLACE_AREA'].replace(0, np.nan, inplace = True)
previous['SELLERPLACE_AREA'].replace(-1, np.nan, inplace = True)
previous['DAYS_TERMINATION'].replace(365243, np.nan, inplace = True)
previous['DAYS_LAST_DUE'].replace(365243, np.nan, inplace = True)
previous['DAYS_LAST_DUE_1ST_VERSION'].replace(365243, np.nan, inplace = True)
previous['sooner'] =(previous['DAYS_LAST_DUE_1ST_VERSION'] - previous['DAYS_LAST_DUE'])/(previous['DAYS_LAST_DUE_1ST_VERSION']-previous['DAYS_DECISION'])
previous['duration'] = previous['DAYS_TERMINATION'] - previous['DAYS_DECISION']
previous['DAYS_FIRST_DRAWING'].replace(365243, np.nan, inplace = True ) | Home Credit Default Risk |
1,533,277 | data = pd.read_csv(".. /input/ai-academy-intermediate-class-competition-1/BBC News Train.csv")
data = data[["Text", "Category"]]
data
<feature_engineering> | train['DAYS_EMPLOYED'] = train['DAYS_EMPLOYED'].replace(365243, np.nan)
test['DAYS_EMPLOYED'] = test['DAYS_EMPLOYED'].replace(365243, np.nan)
tmp = train[train['DAYS_LAST_PHONE_CHANGE'] >= 0].index
train['DAYS_LAST_PHONE_CHANGE'].iloc[tmp] = np.nan
tmp = test[test['DAYS_LAST_PHONE_CHANGE'] >= 0].index
test['DAYS_LAST_PHONE_CHANGE'].iloc[tmp] = np.nan
for df in [train, test]:
df['ORGANIZATION_TYPE_v2'] = df['ORGANIZATION_TYPE']
for i in range(1,4):
df['ORGANIZATION_TYPE_v2'].replace('Business Entity Type ' + str(i), 'Business', inplace = True)
for i in range(1,14):
df['ORGANIZATION_TYPE_v2'].replace('Industry: type ' + str(i), 'Industry', inplace = True)
for i in range(1,8):
df['ORGANIZATION_TYPE_v2'].replace('Trade: type ' + str(i), 'Trade', inplace = True)
for i in range(1,8):
df['ORGANIZATION_TYPE_v2'].replace('Transport: type ' + str(i), 'Transport', inplace = True)
df['ORGANIZATION_TYPE_v2'].replace('Other','XNA', inplace = True ) | Home Credit Default Risk |
1,533,277 | vectorizer = TfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
X = vectorizer.fit_transform(data["Text"])
print(len(vectorizer.get_feature_names()))
print(X.shape )<feature_engineering> | tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['NAME_CONTRACT_TYPE'].isin(['Consumer loans','Cash loans', 'Revolving loans'])) ].groupby(['SK_ID_CURR'])['AMT_CREDIT']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_credit_master'] = tmp_merge['des1']
df['max_amt_credit_master'] = tmp_merge['des2']
df['mean_amt_credit_master'] = tmp_merge['des3'] | Home Credit Default Risk |
1,533,277 | data["category_id"]=data["Category"].factorize() [0]<remove_duplicates> | tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans'])) ].groupby(['SK_ID_CURR'])['AMT_APPLICATION']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_app'] = tmp_merge['des1']
df['max_amt_app'] = tmp_merge['des2']
df['mean_amt_app'] = tmp_merge['des3']
tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['NAME_CONTRACT_TYPE'].isin(['Consumer loans'])) ].groupby(['SK_ID_CURR'])['AMT_APPLICATION']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_app_v1'] = tmp_merge['des1']
df['max_amt_app_v1'] = tmp_merge['des2']
df['mean_amt_app_v1'] = tmp_merge['des3']
tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['NAME_CONTRACT_TYPE'].isin(['Revolving loans'])) ].groupby(['SK_ID_CURR'])['AMT_CREDIT']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_card'] = tmp_merge['des1']
df['max_amt_card'] = tmp_merge['des2']
df['mean_amt_card'] = tmp_merge['des3'] | Home Credit Default Risk |
1,533,277 | data = data[["Text", "category_id", "Category"]]
data
category_id_data = data[['Category', 'category_id']].drop_duplicates().sort_values('category_id')
category_to_id = dict(category_id_data.values)
id_to_category = dict(category_id_data[['category_id', 'Category']].values)
category_id_data
id_to_category<categorify> | tmp = previous[(previous['NAME_CONTRACT_STATUS'].isin(['Refused','Canceled'])) &(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans'])) ].groupby(['SK_ID_CURR'])['AMT_APPLICATION']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_app_fail'] = tmp_merge['des1']
df['max_amt_app_fail'] = tmp_merge['des2']
df['mean_amt_app_fail'] = tmp_merge['des3']
tmp = previous[(previous['NAME_CONTRACT_STATUS'].isin(['Refused','Canceled'])) &(previous['NAME_CONTRACT_TYPE'].isin(['Consumer loans'])) ].groupby(['SK_ID_CURR'])['AMT_APPLICATION']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_app_v1_fail'] = tmp_merge['des1']
df['max_amt_app_v1_fail'] = tmp_merge['des2']
df['mean_amt_app_v1_fail'] = tmp_merge['des3']
tmp = previous[(previous['NAME_CONTRACT_STATUS'].isin(['Refused','Canceled'])) &(previous['NAME_CONTRACT_TYPE'].isin(['Revolving loans'])) ].groupby(['SK_ID_CURR'])['AMT_CREDIT']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_card_fail'] = tmp_merge['des1']
df['max_amt_card_fail'] = tmp_merge['des2']
df['mean_amt_card_fail'] = tmp_merge['des3'] | Home Credit Default Risk |
1,533,277 | tfidf = TfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
features = tfidf.fit_transform(data.Text ).toarray()
print(features)
labels = data.category_id
print(labels)
features.shape<statistical_test> | tmp = previous[(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans'])) ].groupby(['SK_ID_CURR'])['RATE_DOWN_PAYMENT']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_goods'] = tmp_merge['des1']
df['max_amt_goods'] = tmp_merge['des2']
df['mean_amt_goods'] = tmp_merge['des3']
tmp = previous[(previous['NAME_CONTRACT_TYPE'].isin(['Consumer loans'])) ].groupby(['SK_ID_CURR'])['RATE_DOWN_PAYMENT']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_goods_v1'] = tmp_merge['des1']
df['max_amt_goods_v1'] = tmp_merge['des2']
df['mean_amt_goods_v1'] = tmp_merge['des3']
| Home Credit Default Risk |
1,533,277 | N = 5
for category, category_id in sorted(category_to_id.items()):
features_chi2 = chi2(features, labels == category_id)
indices = np.argsort(features_chi2[0])
feature_names = np.array(tfidf.get_feature_names())[indices]
unigrams = [v for v in feature_names if len(v.split(' ')) == 1]
bigrams = [v for v in feature_names if len(v.split(' ')) == 2]
print("
print(".Most correlated unigrams:
.{}".format('
.'.join(unigrams[-N:])))
print(".Most correlated bigrams:
.{}".format('
.'.join(bigrams[-N:])) )<find_best_model_class> | tmp = previous[(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans','Consumer loans'])) ].groupby(['SK_ID_CURR'])['AMT_ANNUITY']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_annuity'] = tmp_merge['des1']
df['max_amt_annuity'] = tmp_merge['des2']
df['mean_amt_annuity'] = tmp_merge['des3']
tmp = previous[(previous['NAME_CONTRACT_TYPE'].isin(['Revolving loans'])) ].groupby(['SK_ID_CURR'])['AMT_ANNUITY']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_amt_card_annuity'] = tmp_merge['des1']
df['max_amt_card_annuity'] = tmp_merge['des2']
df['mean_amt_card_annuity'] = tmp_merge['des3'] | Home Credit Default Risk |
1,533,277 | X_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(features, labels, data.index, test_size=0.20, random_state=0)
for model in models:
model.fit(X_train, y_train)
y_pred_proba = model.predict_proba(X_test)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(accuracy )<train_model> | tmp = previous[(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans','Consumer loans'])) ].groupby(['SK_ID_CURR'])['CNT_PAYMENT']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_cntpay'] = tmp_merge['des1']
df['max_cntpay'] = tmp_merge['des2']
df['mean_cntpay'] = tmp_merge['des3']
tmp = previous[(previous['NAME_CONTRACT_TYPE'].isin(['Consumer loans'])) ].groupby(['SK_ID_CURR'])['CNT_PAYMENT']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_cntpay_v1'] = tmp_merge['des1']
df['max_cntpay_v1'] = tmp_merge['des2']
df['mean_cntpay_v1'] = tmp_merge['des3']
| Home Credit Default Risk |
1,533,277 | model = models[2]
model.fit(features, labels)
model.coef_<load_from_csv> | tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['AMT_APPLICATION'] > 0)&(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans','Consumer loans'])) ].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','AMT_APPLICATION']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_app'] = tmp_merge['des']
tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['AMT_APPLICATION'] > 0)&(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans','Consumer loans'])) ].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','AMT_CREDIT']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_credit'] = tmp_merge['des']
tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['AMT_CREDIT'] > 0)&(previous['NAME_CONTRACT_TYPE'].isin(['Revolving loans'])) ].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','AMT_CREDIT']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_card'] = tmp_merge['des'] | Home Credit Default Risk |
1,533,277 | test_data = pd.read_csv(".. /input/bbc-test-3/BBC News Test.csv")
test_data<predict_on_test> | tmp = previous[(previous['NAME_CONTRACT_STATUS'] != 'Approved')&(previous['AMT_APPLICATION'] > 0)&(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans','Consumer loans'])) ].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','AMT_APPLICATION']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_app_fail'] = tmp_merge['des']
tmp = previous[(previous['NAME_CONTRACT_STATUS'] != 'Approved')&(previous['AMT_APPLICATION'] > 0)&(previous['NAME_CONTRACT_TYPE'].isin(['Cash loans','Consumer loans'])) ].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','AMT_CREDIT']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_credit_fail'] = tmp_merge['des']
tmp = previous[(previous['NAME_CONTRACT_STATUS'] != 'Approved')&(previous['AMT_CREDIT'] > 0)&(previous['NAME_CONTRACT_TYPE'].isin(['Revolving loans'])) ].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','AMT_CREDIT']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_card_fail'] = tmp_merge['des'] | Home Credit Default Risk |
1,533,277 | test_data.Text.tolist()
test_features = tfidf.transform(test_data.Text.tolist())
Y_pred = model.predict(test_features)
Y_pred
submission = []
for pred in Y_pred:
submission.append(id_to_category[pred])
submission<create_dataframe> | tmp = previous[(previous['NAME_CONTRACT_STATUS'] == 'Approved')&(previous['RATE_DOWN_PAYMENT'] > 0)].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','RATE_DOWN_PAYMENT']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_ratedown'] = tmp_merge['des']
tmp = previous[(previous['NAME_CONTRACT_STATUS'] != 'Approved')&(previous['RATE_DOWN_PAYMENT'] > 0)].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','RATE_DOWN_PAYMENT']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_ratedown_fail'] = tmp_merge['des'] | Home Credit Default Risk |
1,533,277 | submission = pd.DataFrame({
"ArticleId": test_data["ArticleId"],
"Category": submission
})
submission<save_to_csv> | tmp = previous[(previous['NAME_CONTRACT_TYPE'].isin(['Consumer loans','Cash loans'])) &(previous['CNT_PAYMENT'] > 0)].sort_values(by=['SK_ID_CURR','DAYS_DECISION'])
tmp = tmp.groupby(['SK_ID_CURR'] ).nth(-1 ).reset_index()
tmp = tmp[['SK_ID_CURR','CNT_PAYMENT']]
tmp.columns = ['SK_ID_CURR','des']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['1st_recent_cntpay'] = tmp_merge['des']
| Home Credit Default Risk |
1,533,277 | submission.to_csv('submission.csv', index=False )<save_to_csv> | tmp = previous[previous['AMT_CREDIT'] > 0]
for i in ['Cash loans','Consumer loans','Revolving loans']:
for df in [train,test]:
tmp1 = tmp[tmp['NAME_CONTRACT_TYPE'] == i].groupby(['SK_ID_CURR'])['AMT_CREDIT'].count().reset_index()
tmp1.columns = ['SK_ID_CURR','des']
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp1, on=['SK_ID_CURR'], how='left')
df['count_' + "_".join(i.lower().split())] = tmp_merge['des'] | Home Credit Default Risk |
1,533,277 | submission.to_csv('submission.csv', index=False )<load_from_csv> | tmp = previous[previous['AMT_CREDIT'].isnull() ]
for i in ['Cash loans','Consumer loans','Revolving loans']:
for df in [train,test]:
tmp1 = tmp[tmp['NAME_CONTRACT_TYPE'] == i].groupby(['SK_ID_CURR'])['SK_ID_PREV'].count().reset_index()
tmp1.columns = ['SK_ID_CURR','des']
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp1, on=['SK_ID_CURR'], how='left')
df['count_null_' + "_".join(i.lower().split())] = tmp_merge['des'] | Home Credit Default Risk |
1,533,277 | TRAIN_PATH = os.path.join(".. /input/ai-academy-intermediate-class-competition-1", "BBC News Train.csv")
df = pd.read_csv(TRAIN_PATH )<feature_engineering> | tmp = previous[previous['AMT_CREDIT'] > 0].groupby(['SK_ID_CURR'])['DAYS_DECISION']\
.agg({"returns": [np.min, np.max,np.mean]})\
.reset_index()
tmp.columns = ['SK_ID_CURR','des1','des2','des3']
for df in [train,test]:
tmp_merge = df[['SK_ID_CURR']]
tmp_merge = tmp_merge.merge(tmp, on=['SK_ID_CURR'], how='left')
df['min_day_decision'] = tmp_merge['des1']
df['max_day_decision'] = tmp_merge['des2']
df['mean_day_decision'] = tmp_merge['des3'] | Home Credit Default Risk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.