kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
449,069
test['item_cnt_month'] = 0<concatenate>
def mytree(df): Model = pd.DataFrame(data = {'Predict':[]}) male_title = ['Master'] for index, row in df.iterrows() : Model.loc[index, 'Predict'] = 0 if(df.loc[index, 'Sex'] == 'female'): Model.loc[index, 'Predict'] = 1 if(( df.loc[index, 'Sex'] == 'female')& (df.loc[index, 'Pclass'] == 3)& (df.loc[index, 'Embarked'...
Titanic - Machine Learning from Disaster
449,069
new_train = new_train.append(test.drop(['ID'], axis=1))<merge>
dtree = tree.DecisionTreeClassifier(random_state = 0) base_results = model_selection.cross_validate(dtree, data1[data1_x_bin], data1[Target], cv = cv_split) dtree.fit(data1[data1_x_bin], data1[Target]) print('BEFORE DT Parameters: ', dtree.get_params()) print("BEFORE DT Training w/bin score mean: {:.2f}".format(bas...
Titanic - Machine Learning from Disaster
449,069
new_train = pd.merge(new_train, shop, on=['shop_id'], how='left') new_train.head()<merge>
print('BEFORE DT RFE Training Shape Old: ', data1[data1_x_bin].shape) print('BEFORE DT RFE Training Columns Old: ', data1[data1_x_bin].columns.values) print("BEFORE DT RFE Training w/bin score mean: {:.2f}".format(base_results['train_score'].mean() *100)) print("BEFORE DT RFE Test w/bin score mean: {:.2f}".format(bas...
Titanic - Machine Learning from Disaster
449,069
new_train = pd.merge(new_train, items.drop('item_name', axis = 1), on=['item_id'], how='left') new_train.head()<merge>
dot_data = tree.export_graphviz(dtree, out_file=None, feature_names = data1_x_bin, class_names = True, filled = True, rounded = True) graph = graphviz.Source(dot_data) graph
Titanic - Machine Learning from Disaster
449,069
new_train = pd.merge(new_train, item_cat.drop('item_category_name', axis = 1), on=['item_category_id'], how='left') new_train.head()<merge>
vote_est = [ ('ada', ensemble.AdaBoostClassifier()), ('bc', ensemble.BaggingClassifier()), ('etc',ensemble.ExtraTreesClassifier()), ('gbc', ensemble.GradientBoostingClassifier()), ('rfc', ensemble.RandomForestClassifier()), ('gpc', gaussian_process.GaussianProcessClassifier()), ('lr', linear_model.LogisticRegres...
Titanic - Machine Learning from Disaster
449,069
def generate_lag(train, months, lag_column): for month in months: train_shift = train[['date_block_num', 'shop_id', 'item_id', lag_column]].copy() train_shift.columns = ['date_block_num', 'shop_id', 'item_id', lag_column+'_lag_'+ str(month)] train_shift['date_block_num'] += month train = pd.merge(train, train_shift, on...
grid_n_estimator = [50,100,300] grid_ratio = [.1,.25,.5,.75,1.0] grid_learn = [.01,.03,.05,.1,.25] grid_max_depth = [2,4,6,None] grid_min_samples = [5,10,.03,.05,.10] grid_criterion = ['gini', 'entropy'] grid_bool = [True, False] grid_seed = [0] vote_param = [{ 'ada__n_estimators': grid_n_estimator, 'ada__learning_rate...
Titanic - Machine Learning from Disaster
449,069
new_train = downcast_dtypes(new_train )<set_options>
grid_n_estimator = [10, 50, 100, 300] grid_ratio = [.1,.25,.5,.75, 1.0] grid_learn = [.01,.03,.05,.1,.25] grid_max_depth = [2, 4, 6, 8, 10, None] grid_min_samples = [5, 10,.03,.05,.10] grid_criterion = ['gini', 'entropy'] grid_bool = [True, False] grid_seed = [0] grid_param = [ [{ 'n_estimators': grid_n_estimator, 'lea...
Titanic - Machine Learning from Disaster
449,069
gc.collect() <categorify>
grid_hard = ensemble.VotingClassifier(estimators = vote_est , voting = 'hard') grid_hard_cv = model_selection.cross_validate(grid_hard, data1[data1_x_bin], data1[Target], cv = cv_split) grid_hard.fit(data1[data1_x_bin], data1[Target]) print("Hard Voting w/Tuned Hyperparameters Training w/bin score mean: {:.2f}".form...
Titanic - Machine Learning from Disaster
449,069
%%time new_train = generate_lag(new_train, [1, 2, 3, 4, 5, 6, 12], 'item_cnt_month' )<merge>
print(data_val.info()) print("-"*10) data_val['Survived'] = mytree(data_val ).astype(int) data_val['Survived'] = grid_hard.predict(data_val[data1_x_bin]) submit = data_val[['PassengerId','Survived']] submit.to_csv(".. /working/submit.csv", index=False) print('Validation Data Distribution: ', data_val['Survived'].v...
Titanic - Machine Learning from Disaster
5,206,845
%%time group = new_train.groupby(['date_block_num', 'item_id'])['item_cnt_month'].mean().rename('item_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'item_id'], how='left') new_train = generate_lag(new_train, [1,2,3,4,5,6,12], 'item_month_mean') new_train.drop(['item_month_me...
import pandas as pd import numpy as np from scipy.stats import mode from sklearn.svm import SVC from sklearn import svm from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier
Titanic - Machine Learning from Disaster
5,206,845
%%time group = new_train.groupby(['date_block_num', 'shop_id'])['item_cnt_month'].mean().rename('shop_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'shop_id'], how='left') new_train = generate_lag(new_train, [1,2,3,6,12], 'shop_month_mean') new_train.drop(['shop_month_mean']...
titanic=pd.read_csv("/kaggle/input/train.csv") df=titanic.copy() df.head()
Titanic - Machine Learning from Disaster
5,206,845
%%time group = new_train.groupby(['date_block_num', 'shop_id', 'item_category_id'])['item_cnt_month'].mean().rename('item_category_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'shop_id', 'item_category_id'], how='left') new_train = generate_lag(new_train, [1, 2], 'item_categ...
df.isnull().sum()
Titanic - Machine Learning from Disaster
5,206,845
%%time group = new_train.groupby(['date_block_num', 'main_category_id'])['item_cnt_month'].mean().rename('main_category_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'main_category_id'], how='left') new_train = generate_lag(new_train, [1], 'main_category_month_mean') new_tra...
test=pd.read_csv("/kaggle/input/test.csv") test_df=test.copy() test_df.isnull().sum()
Titanic - Machine Learning from Disaster
5,206,845
%%time group = new_train.groupby(['date_block_num', 'sub_category_id'])['item_cnt_month'].mean().rename('sub_category_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'sub_category_id'], how='left') new_train = generate_lag(new_train, [1], 'sub_category_month_mean') new_train.d...
df["Initial"]=df["Name"].str.extract('([A-Za-z]+)\.') print(df["Initial"].unique()) df["Initial"].replace(['Mlle','Mme','Ms','Dr','Major','Lady','Countess','Jonkheer','Col','Rev','Capt','Sir','Don'], ['Miss','Miss','Miss','Mr','Mr','Mrs','Mrs','Other','Other','Other','Mr','Mr','Mr'],inplace=True )
Titanic - Machine Learning from Disaster
5,206,845
new_train = downcast_dtypes(new_train )<import_modules>
df.groupby("Initial")["Age"].mean()
Titanic - Machine Learning from Disaster
5,206,845
import xgboost as xgb<filter>
df.loc[(df.Age.isnull())&(df.Initial=='Master'),"Age"]=5 df.loc[(df.Age.isnull())&(df.Initial=='Miss'),"Age"]=22 df.loc[(df.Age.isnull())&(df.Initial=='Mr'),"Age"]=33 df.loc[(df.Age.isnull())&(df.Initial=='Mrs'),"Age"]=36 df.loc[(df.Age.isnull())&(df.Initial=='Other'),"Age"]=46
Titanic - Machine Learning from Disaster
5,206,845
new_train = new_train[new_train.date_block_num > 11]<set_options>
print(df.Embarked.mode()) df.Embarked.fillna("S",inplace=True )
Titanic - Machine Learning from Disaster
5,206,845
gc.collect()<data_type_conversions>
df["Family_size"]=df["SibSp"]+df["Parch"] df["Alone"]=0 df.loc[df.Family_size==0,"Alone"]=1
Titanic - Machine Learning from Disaster
5,206,845
def fill_na(df): for col in df.columns: if('_lag_' in col)&(df[col].isnull().any()): df[col].fillna(0, inplace=True) return df<correct_missing_values>
df['Age_band']=0 df.loc[df['Age']<=16,'Age_band']=0 df.loc[(df['Age']>16)&(df['Age']<=32),'Age_band']=1 df.loc[(df['Age']>32)&(df['Age']<=48),'Age_band']=2 df.loc[(df['Age']>48)&(df['Age']<=64),'Age_band']=3 df.loc[df['Age']>64,'Age_band']=4
Titanic - Machine Learning from Disaster
5,206,845
new_train = fill_na(new_train) <train_model>
df['Fare_cat']=0 df.loc[df['Fare']<=7.91,'Fare_cat']=0 df.loc[(df['Fare']>7.91)&(df['Fare']<=14.454),'Fare_cat']=1 df.loc[(df['Fare']>14.454)&(df['Fare']<=31),'Fare_cat']=2 df.loc[(df['Fare']>31)&(df['Fare']<=513),'Fare_cat']=3
Titanic - Machine Learning from Disaster
5,206,845
def xgtrain() : regressor = xgb.XGBRegressor(n_estimators = 5000, learning_rate = 0.01, max_depth = 10, subsample = 0.5, colsample_bytree = 0.5) regressor_ = regressor.fit(new_train[new_train.date_block_num < 33].drop(['item_cnt_month'], axis=1 ).values, new_train[new_train.date_block_num < 33]['item_cnt_month'].value...
df['Sex'].replace(['male','female'],[0,1],inplace=True) df['Embarked'].replace(['S','C','Q'],[0,1,2],inplace=True) df['Initial'].replace(['Mr','Mrs','Miss','Master','Other'],[0,1,2,3,4],inplace=True )
Titanic - Machine Learning from Disaster
5,206,845
%%time regressor_ = xgtrain()<predict_on_test>
df.drop(['Name','Age','Ticket','Fare','Cabin','Fare_Range','PassengerId'],axis=1,inplace=True )
Titanic - Machine Learning from Disaster
5,206,845
predictions = regressor_.predict(new_train[new_train.date_block_num == 34].drop(['item_cnt_month'], axis = 1 ).values )<load_from_csv>
df.isnull().sum()
Titanic - Machine Learning from Disaster
5,206,845
submission = pd.read_csv('/kaggle/input/competitive-data-science-predict-future-sales/sample_submission.csv' )<feature_engineering>
test_df.loc[(test_df.Age.isnull())&(test_df.Initial=='Master'),"Age"]=5 test_df.loc[(test_df.Age.isnull())&(test_df.Initial=='Miss'),"Age"]=22 test_df.loc[(test_df.Age.isnull())&(test_df.Initial=='Mr'),"Age"]=33 test_df.loc[(test_df.Age.isnull())&(test_df.Initial=='Mrs'),"Age"]=36 test_df.loc[(test_df.Age.isnull())&(te...
Titanic - Machine Learning from Disaster
5,206,845
submission['item_cnt_month'] = predictions<save_to_csv>
test_df["Family_size"]=test_df["SibSp"]+test_df["Parch"] test_df["Alone"]=0 test_df.loc[df.Family_size==0,"Alone"]=1
Titanic - Machine Learning from Disaster
5,206,845
submission.to_csv('saleslearn.csv', index=False )<set_options>
test_df['Age_band']=0 test_df.loc[test_df['Age']<=16,'Age_band']=0 test_df.loc[(test_df['Age']>16)&(test_df['Age']<=32),'Age_band']=1 test_df.loc[(test_df['Age']>32)&(test_df['Age']<=48),'Age_band']=2 test_df.loc[(test_df['Age']>48)&(test_df['Age']<=64),'Age_band']=3 test_df.loc[test_df['Age']>64,'Age_band']=4
Titanic - Machine Learning from Disaster
5,206,845
%matplotlib inline<load_from_csv>
test_df[test_df.Fare.isnull() ]
Titanic - Machine Learning from Disaster
5,206,845
items = pd.read_csv('/kaggle/input/competitive-data-science-predict-future-sales/items.csv') shops = pd.read_csv('/kaggle/input/competitive-data-science-predict-future-sales/shops.csv') categories = pd.read_csv('/kaggle/input/competitive-data-science-predict-future-sales/item_categories.csv') train = pd.read_csv('/k...
test_df['Fare_cat']=0 test_df.loc[test_df['Fare']<=7.91,'Fare_cat']=0 test_df.loc[(test_df['Fare']>7.91)&(test_df['Fare']<=14.454),'Fare_cat']=1 test_df.loc[(test_df['Fare']>14.454)&(test_df['Fare']<=31),'Fare_cat']=2 test_df.loc[(test_df['Fare']>31)&(test_df['Fare']<=513),'Fare_cat']=3
Titanic - Machine Learning from Disaster
5,206,845
train['item_id'].value_counts(ascending = False)[:5]<filter>
test_df['Sex'].replace(['male','female'],[0,1],inplace=True) test_df['Embarked'].replace(['S','C','Q'],[0,1,2],inplace=True) test_df['Initial'].replace(['Mr','Mrs','Miss','Master','Other'],[0,1,2,3,4],inplace=True )
Titanic - Machine Learning from Disaster
5,206,845
items.loc[items.item_id == 20949]<filter>
test_df.drop(['Name','Age','Ticket','Fare','Cabin','PassengerId'],axis=1,inplace=True )
Titanic - Machine Learning from Disaster
5,206,845
categories.loc[categories.item_category_id == 71]<sort_values>
test_df.isnull().sum()
Titanic - Machine Learning from Disaster
5,206,845
train['item_cnt_day'].sort_values(ascending=False)[:5]<filter>
ytrain=df["Survived"] del df["Survived"]
Titanic - Machine Learning from Disaster
5,206,845
train[train.item_cnt_day == 2169]<filter>
xtrain=df.values xtest=test_df.values
Titanic - Machine Learning from Disaster
5,206,845
items[items.item_id == 11373]<filter>
n_estimators=list(range(100,1100,100)) learn_rate=[0.05,0.1,0.2,0.3,0.25,0.4,0.5,0.6,0.7,0.8,0.9,1] hyper={'n_estimators':n_estimators,'learning_rate':learn_rate} gd=GridSearchCV(estimator=AdaBoostClassifier() ,param_grid=hyper,verbose=True) gd.fit(xtrain,ytrain) print(gd.best_score_) print(gd.best_estimator_ )
Titanic - Machine Learning from Disaster
5,206,845
train = train[train.item_cnt_day < 2000]<sort_values>
clf=AdaBoostClassifier(n_estimators=200,random_state=0,learning_rate=0.05) clf.fit(xtrain,ytrain) print(clf.score(xtrain,ytrain)) ypred=clf.predict(xtest )
Titanic - Machine Learning from Disaster
5,206,845
train['item_price'].sort_values(ascending = False)[:5]<filter>
submission = pd.DataFrame({ "PassengerId": test["PassengerId"], "Survived": ypred }) submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
3,999,796
train[train.item_price == 307980]<filter>
def create_download_link(df, title = "Download CSV file", filename = "data.csv"): csv = df.to_csv() b64 = base64.b64encode(csv.encode()) payload = b64.decode() html = '<a download="{filename}" href="data:text/csv;base64,{payload}" target="_blank">{title}</a>' html = html.format(payload=payload,title=title,filename=fil...
Titanic - Machine Learning from Disaster
3,999,796
items[items.item_id == 6066]<filter>
train_data = pd.read_csv(".. /input/train.csv") test_data = pd.read_csv(".. /input/test.csv" )
Titanic - Machine Learning from Disaster
3,999,796
train[train.item_id == 6066]<filter>
passenger_id = test_data["PassengerId"]
Titanic - Machine Learning from Disaster
3,999,796
train = train[train.item_price < 300000]<sort_values>
train_data[['SibSp','Survived']].groupby(['SibSp'],as_index=False ).count().sort_values(by='Survived',ascending=False)
Titanic - Machine Learning from Disaster
3,999,796
train['item_price'].sort_values() [:5]<filter>
train_data[['Parch','Survived']].groupby(['Parch'],as_index=False ).count().sort_values(by='Survived',ascending=False)
Titanic - Machine Learning from Disaster
3,999,796
train[train.item_price == -1]<feature_engineering>
train_data[['Pclass','Survived']].groupby(['Pclass'],as_index=False ).count().sort_values(by='Survived',ascending=False)
Titanic - Machine Learning from Disaster
3,999,796
price_correction = train[(train.shop_id == 32)&(train.item_id == 2973)&(train.date_block_num ==4)&(train.item_price > 0)].item_price.median() train.loc[train.item_price<0, 'item_price'] = price_correction<count_unique_values>
train_data[['Embarked','Survived']].groupby(['Embarked'],as_index=False ).count().sort_values(by='Survived',ascending=False)
Titanic - Machine Learning from Disaster
3,999,796
shops_train = train.shop_id.nunique() shops_test = test.shop_id.nunique() print("Shops in training set = ", shops_train) print("Shops in test set = ", shops_test )<feature_engineering>
train_data[['Age','Survived']].groupby(['Age'],as_index=False ).count().sort_values(by='Survived',ascending=False ).head()
Titanic - Machine Learning from Disaster
3,999,796
shops['city'] = shops['shop_name'].str.split(' ' ).map(lambda x: x[0] )<categorify>
target_variable = train_data["Survived"] train_data.drop(["Survived"], axis = 1, inplace=True )
Titanic - Machine Learning from Disaster
3,999,796
LE = preprocessing.LabelEncoder() LE.fit_transform(shops['city'] )<categorify>
all_data = pd.concat([train_data, test_data], axis = 0 )
Titanic - Machine Learning from Disaster
3,999,796
shops['city_label'] = LE.fit_transform(shops['city']) shops.drop(['shop_name', 'city'], axis = 1, inplace = True) shops.head()<count_values>
all_data.drop(["PassengerId", "Ticket" ], axis=1, inplace = True )
Titanic - Machine Learning from Disaster
3,999,796
len(set(items_test_list)-set(items_train_list))<categorify>
total = all_data.isnull().sum().sort_values(ascending=False) percent =(all_data.isnull().sum() /all_data.isnull().count() ).sort_values(ascending=False) missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent']) missing_data[total > 0]
Titanic - Machine Learning from Disaster
3,999,796
LE = preprocessing.LabelEncoder() category_split = categories['item_category_name'].str.split('-') categories['main_categories_id'] = category_split.map(lambda row: row[0].strip()) categories['main_categories_id'] = LE.fit_transform(categories['main_categories_id']) categories['sub_category_id'] = category_split.map...
all_data["Cabin"] = all_data["Cabin"].fillna("None" )
Titanic - Machine Learning from Disaster
3,999,796
train['date'] = pd.to_datetime(train['date'], format = '%d.%m.%Y') train.info()<concatenate>
all_data["Age"] = all_data["Age"].fillna(all_data["Age"].mean()) all_data["Fare"] = all_data["Fare"].fillna(all_data["Fare"].mean() )
Titanic - Machine Learning from Disaster
3,999,796
cartesian_test = [] cartesian_test.append(np.array(jan)) cartesian_test.append(np.array(feb))<prepare_output>
embarked_mode = all_data["Embarked"].mode() [0] all_data["Embarked"] = all_data["Embarked"].fillna(embarked_mode )
Titanic - Machine Learning from Disaster
3,999,796
cartesian_test = np.vstack(cartesian_test) cartesian_test_df = pd.DataFrame(cartesian_test, columns = ['shop_id', 'item_id', 'date_block_num']) cartesian_test_df.head()<data_type_conversions>
simplify_ages(all_data )
Titanic - Machine Learning from Disaster
3,999,796
def downcast_dtypes(df): float_cols = [c for c in df if df[c].dtype == "float64"] int_cols = [c for c in df if df[c].dtype == "int64"] df[float_cols] = df[float_cols].astype(np.float16) df[int_cols] = df[int_cols].astype(np.int16) return df<groupby>
simplify_fares(all_data )
Titanic - Machine Learning from Disaster
3,999,796
x = train.groupby(['shop_id', 'item_id', 'date_block_num'])['item_cnt_day'].sum().rename('item_cnt_month' ).reset_index() x.head()<merge>
def format_name(df): df['Lname'] = df.Name.apply(lambda x: x.split(' ')[0]) df['NamePrefix'] = df.Name.apply(lambda x: x.split(' ')[1]) return df
Titanic - Machine Learning from Disaster
3,999,796
new_train = pd.merge(cartesian_df, x, on=['shop_id', 'item_id', 'date_block_num'], how='left' ).fillna(0) new_train['item_cnt_month'] = np.clip(new_train['item_cnt_month'], 0, 20 )<drop_column>
format_name(all_data) all_data.drop(['Name'], axis=1, inplace=True )
Titanic - Machine Learning from Disaster
3,999,796
del x del cartesian_df del cartesian del cartesian_test del cartesian_test_df del feb del jan del items_test_list del items_train_list del train<sort_values>
all_data["family_members"] = all_data["SibSp"] + all_data["Parch"] all_data.drop(["SibSp", "Parch" ], axis=1 )
Titanic - Machine Learning from Disaster
3,999,796
new_train.sort_values(['date_block_num','shop_id','item_id'], inplace = True) new_train.head()<feature_engineering>
all_data.head()
Titanic - Machine Learning from Disaster
3,999,796
test.insert(loc=3, column='date_block_num', value=34) test['item_cnt_month'] = 0 test.head()<concatenate>
def encode_features(df): features = ['Sex', 'Age', 'Fare', 'Embarked', 'Lname', 'NamePrefix', 'Cabin'] for feature in features: le = preprocessing.LabelEncoder() le = le.fit(df[feature]) df[feature] = le.transform(df[feature]) return df all_data = encode_features(all_data) all_data.head()
Titanic - Machine Learning from Disaster
3,999,796
new_train = new_train.append(test.drop('ID', axis = 1))<merge>
train_data = all_data[:train_data.shape[0]] test_data = all_data[train_data.shape[0]:] y = target_variable
Titanic - Machine Learning from Disaster
3,999,796
new_train = pd.merge(new_train, shops, on=['shop_id'], how='left') new_train.head()<merge>
X_train, X_test, y_train, y_test = train_test_split(train_data, y, test_size=0.2, random_state=42 )
Titanic - Machine Learning from Disaster
3,999,796
new_train = pd.merge(new_train, items.drop('item_name', axis = 1), on=['item_id'], how='left') new_train.head()<merge>
clf = RandomForestClassifier() parameters = {'n_estimators': [4, 6, 9], 'max_features': ['log2', 'sqrt','auto'], 'criterion': ['entropy', 'gini'], 'max_depth': [2, 3, 5, 10], 'min_samples_split': [2, 3, 5], 'min_samples_leaf': [1,5,8] } acc_scorer = make_scorer(accuracy_score) grid_obj = GridSearchCV(clf, parameters, ...
Titanic - Machine Learning from Disaster
3,999,796
new_train = pd.merge(new_train, categories.drop('item_category_name', axis = 1), on=['item_category_id'], how='left') new_train.head()<merge>
predictions = clf.predict(X_test) print("Accuracy of Random forest classifier" , accuracy_score(y_test, predictions))
Titanic - Machine Learning from Disaster
3,999,796
def generate_lag(train, months, lag_column): for month in months: train_shift = train[['date_block_num', 'shop_id', 'item_id', lag_column]].copy() train_shift.columns = ['date_block_num', 'shop_id', 'item_id', lag_column+'_lag_'+ str(month)] train_shift['date_block_num'] += month train = pd.merge(train, train_shift, on...
lreg = LogisticRegression() lreg.fit(X_train, y_train) predictions = lreg.predict(X_test) print("Accuracy of Logistic Regression" , accuracy_score(y_test, predictions))
Titanic - Machine Learning from Disaster
3,999,796
del items del categories del shops del test<categorify>
predict_survival = lreg.predict(test_data) my_submission = pd.DataFrame({'PassengerId': passenger_id, 'Survived': predict_survival}) my_submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
9,895,226
new_train = downcast_dtypes(new_train )<set_options>
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import Perceptron from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC fro...
Titanic - Machine Learning from Disaster
9,895,226
gc.collect()<define_search_space>
data = pd.read_csv("/kaggle/input/titanic/train.csv") test_data = pd.read_csv("/kaggle/input/titanic/test.csv") data.shape
Titanic - Machine Learning from Disaster
9,895,226
%%time new_train = generate_lag(new_train, [1,2,3,4,5,6,12], 'item_cnt_month' )<merge>
data.nunique().sort_values(ascending=False ).head(5 )
Titanic - Machine Learning from Disaster
9,895,226
%%time group = new_train.groupby(['date_block_num', 'item_id'])['item_cnt_month'].mean().rename('item_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'item_id'], how='left') new_train = generate_lag(new_train, [1,2,3,6,12], 'item_month_mean') new_train.drop(['item_month_mean']...
data.drop(["Name","Ticket","Cabin"],axis=1,inplace=True) data.head() ,data.shape
Titanic - Machine Learning from Disaster
9,895,226
%%time group = new_train.groupby(['date_block_num', 'shop_id'])['item_cnt_month'].mean().rename('shop_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'shop_id'], how='left') new_train = generate_lag(new_train, [1,2,3,6,12], 'shop_month_mean') new_train.drop(['shop_month_mean']...
imp = SimpleImputer(missing_values=np.nan, strategy='mean') data.Age = imp.fit_transform(data[['Age']] ).ravel() imp2 = SimpleImputer(missing_values=np.nan,strategy='most_frequent') data.Embarked = imp2.fit_transform(data[['Embarked']] ).ravel() data.Age.mean() ,data.Age.std() ,data.Age.isnull().sum()
Titanic - Machine Learning from Disaster
9,895,226
%%time group = new_train.groupby(['date_block_num', 'shop_id', 'item_category_id'])['item_cnt_month'].mean().rename('shop_category_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'shop_id', 'item_category_id'], how='left') new_train = generate_lag(new_train, [1, 2], 'shop_categ...
data.groupby('Sex' ).Survived.mean()
Titanic - Machine Learning from Disaster
9,895,226
%%time group = new_train.groupby(['date_block_num', 'main_category_id'])['item_cnt_month'].mean().rename('main_category_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'main_category_id'], how='left') new_train = generate_lag(new_train, [1], 'main_category_month_mean') new_tra...
data['relatives'] = data['SibSp'] + data['Parch'] data.loc[data['relatives'] > 0, 'not_alone'] = 0 data.loc[data['relatives'] == 0, 'not_alone'] = 1 data['not_alone'] = data['not_alone'].astype(int )
Titanic - Machine Learning from Disaster
9,895,226
%%time group = new_train.groupby(['date_block_num', 'sub_category_id'])['item_cnt_month'].mean().rename('sub_category_month_mean' ).reset_index() new_train = pd.merge(new_train, group, on=['date_block_num', 'sub_category_id'], how='left') new_train = generate_lag(new_train, [1], 'sub_category_month_mean') new_train.d...
data = data.join(pd.get_dummies(data['Sex'])) data = data.join(pd.get_dummies(data['Embarked'])) data.tail()
Titanic - Machine Learning from Disaster
9,895,226
new_train['month'] = new_train['date_block_num'] % 12<categorify>
test_data.drop(["Name","Ticket","Cabin"],axis=1,inplace=True) test_data['relatives'] = test_data['SibSp'] + test_data['Parch'] test_data.loc[test_data['relatives'] > 0, 'not_alone'] = 0 test_data.loc[test_data['relatives'] == 0, 'not_alone'] = 1 test_data['not_alone'] = test_data['not_alone'].astype(int) test_data.Ag...
Titanic - Machine Learning from Disaster
9,895,226
holiday_dict = { 0: 6, 1: 3, 2: 2, 3: 8, 4: 3, 5: 3, 6: 2, 7: 8, 8: 4, 9: 8, 10: 5, 11: 4, } new_train['holidays_in_month'] = new_train['month'].map(holiday_dict )<categorify>
f = ['Pclass','Age','SibSp','Parch','Fare','relatives','not_alone','female','C','Q'] len(f )
Titanic - Machine Learning from Disaster
9,895,226
moex = { 12: 659, 13: 640, 14: 1231, 15: 881, 16: 764, 17: 663, 18: 743, 19: 627, 20: 692, 21: 736, 22: 680, 23: 1092, 24: 657, 25: 863, 26: 720, 27: 819, 28: 574, 29: 568, 30: 633, 31: 658, 32: 611, 33: 770, 34: 723, } new_train['moex_value'] = new_train.date_block_num.map(moex) new_train = downcast_dtypes(new_train ...
test_data.Fare.fillna(method = 'ffill',inplace=True )
Titanic - Machine Learning from Disaster
9,895,226
gc.collect()<filter>
X = data[f] X_test = test_data[f] y = data['Survived']
Titanic - Machine Learning from Disaster
9,895,226
new_train = new_train[new_train.date_block_num > 11]<data_type_conversions>
level1 = LogisticRegression()
Titanic - Machine Learning from Disaster
9,895,226
def fill_na(df): for col in df.columns: if('_lag_' in col)&(df[col].isnull().any()): df[col].fillna(0, inplace=True) return df new_train = fill_na(new_train )<train_model>
model = StackingClassifier(estimators=level0, final_estimator=level1 )
Titanic - Machine Learning from Disaster
9,895,226
def xgtrain() : regressor = xgb.XGBRegressor(n_estimators = 5000, learning_rate = 0.01, max_depth = 10, subsample = 0.5, colsample_bytree = 0.5) regressor_ = regressor.fit(new_train[new_train.date_block_num < 33].drop(['item_cnt_month'], axis=1 ).values, new_train[new_train.date_block_num < 33]['item_cnt_month'].value...
model.fit(X,y )
Titanic - Machine Learning from Disaster
9,895,226
%%time regressor_ = xgtrain()<predict_on_test>
pred_y = model.predict(X_test )
Titanic - Machine Learning from Disaster
9,895,226
<save_to_csv><EOS>
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': pred_y}) output.to_csv('my_submission.csv', index=False) print("Submitted successfully!" )
Titanic - Machine Learning from Disaster
8,370,213
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<set_options>
warnings.filterwarnings("ignore", category=DeprecationWarning) sns.set()
Titanic - Machine Learning from Disaster
8,370,213
%matplotlib inline pd.set_option('display.float_format', lambda x: '%.3f' % x) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) print('Done' )<load_from_csv>
train_data = pd.read_csv(".. /input/titanic/train.csv" )
Titanic - Machine Learning from Disaster
8,370,213
path = '.. /input/competitive-data-science-predict-future-sales/' DF_sales = pd.read_csv(path + 'sales_train.csv') DF_items = pd.read_csv(path + 'items.csv') DF_item_cat = pd.read_csv(path + 'item_categories.csv') DF_shops = pd.read_csv(path + 'shops.csv') DF_test = pd.read_csv(path + 'test.csv') DF_sample_subs = ...
train_data.drop(columns=['Name', 'Ticket', 'Cabin','PassengerId'], axis=1, inplace=True )
Titanic - Machine Learning from Disaster
8,370,213
print('---' * 10) print('sales_train check ') print(DF_sales.isna().sum()) print('---' * 10) print('item_cat check ') print(DF_items.isna().sum()) print('---' * 10) print('item check ') print(DF_item_cat.isna().sum()) print('---' * 10) print('shops check ') print(DF_shops.isna().sum() )<feature_engineering>
train_data['Sex'] = train_data['Sex'].map({'male':0,'female':1} )
Titanic - Machine Learning from Disaster
8,370,213
DF_sales = DF_sales[DF_sales.item_price<100000] DF_sales = DF_sales[DF_sales.item_cnt_day<1000] DF_sales = DF_sales[DF_sales.item_price > 0].reset_index(drop=True) DF_sales.loc[DF_sales.item_cnt_day < 0, 'item_cnt_day'] = 0<feature_engineering>
train_data['Age'].isnull().sum()
Titanic - Machine Learning from Disaster
8,370,213
DF_sales.loc[DF_sales.shop_id == 0, 'shop_id'] = 57 DF_sales.loc[DF_sales.shop_id == 1, 'shop_id'] = 58 DF_sales.loc[DF_sales.shop_id == 11, 'shop_id'] = 10<feature_engineering>
train_data['Embarked'].value_counts()
Titanic - Machine Learning from Disaster
8,370,213
DF_shops.loc[DF_shops.shop_name == 'Сергиев Посад ТЦ "7Я"', 'shop_name'] = 'СергиевПосад ТЦ "7Я"' DF_shops['shop_city'] = DF_shops['shop_name'].str.split(' ' ).map(lambda x: x[0]) DF_shops['shop_cat'] = DF_shops['shop_name'].str.split(' ' ).map(lambda x: x[1]) DF_shops.head(5 )<categorify>
train_data['Embarked'].fillna(value='S',axis=0, inplace=True )
Titanic - Machine Learning from Disaster
8,370,213
DF_shops['shop_city'] = LabelEncoder().fit_transform(DF_shops['shop_city']) DF_shops['shop_cat'] = LabelEncoder().fit_transform(DF_shops['shop_cat']) DF_shops.drop(['shop_name'], axis=1, inplace= True) DF_shops.head(5 )<merge>
train_data['Embarked'] = train_data['Embarked'].map({'S':0,'C':1,'Q':2} )
Titanic - Machine Learning from Disaster
8,370,213
DF_items = pd.merge(DF_items, DF_item_cat, on = 'item_category_id') DF_items<feature_engineering>
train_data.fillna(value=train_data['Age'].mean() , axis=0, inplace=True )
Titanic - Machine Learning from Disaster
8,370,213
DF_items['item_sub_cat_1'] = np.select( [DF_items.item_category_id.isin(range(0,8)) , DF_items.item_category_id.isin(range(10,18)) , DF_items.item_category_id.isin(range(18,32)) , DF_items.item_category_id.isin(range(32,37)) , DF_items.item_category_id.isin(range(37,42)) , DF_items.item_category_id.isin(range(42,55)) ...
train_data[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False ).mean()
Titanic - Machine Learning from Disaster
8,370,213
DF_items['item_sub_cat_1'] = LabelEncoder().fit_transform(DF_items['item_sub_cat_1']) DF_items.drop(['item_name','item_category_name'], axis=1, inplace= True) DF_items<data_type_conversions>
train_data[['Sex', 'Survived']].groupby(['Sex'], as_index=False ).mean()
Titanic - Machine Learning from Disaster
8,370,213
DF_all = [] cols = ['date_block_num','shop_id','item_id'] for i in range(34): sales = DF_sales[DF_sales.date_block_num==i] DF_all.append(np.array(list(product([i], sales.shop_id.unique() , sales.item_id.unique())) , dtype='int16')) DF_all = pd.DataFrame(np.vstack(DF_all), columns=cols) DF_all['date_block_num'] = DF_al...
train_data[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False ).mean()
Titanic - Machine Learning from Disaster
8,370,213
DF_test.drop(['ID'], axis=1, inplace = True) DF_test['date_block_num'] = 34 DF_test['date_block_num'] = DF_test['date_block_num'] DF_test['shop_id'] = DF_test['shop_id'] DF_test['item_id'] = DF_test['item_id'] DF_test.head()<merge>
train_data[['SibSp', 'Survived']].groupby('SibSp', as_index=False ).mean()
Titanic - Machine Learning from Disaster
8,370,213
DF_all = pd.concat([DF_all, DF_test], ignore_index=True, sort=False, keys=cols) DF_all = pd.merge(DF_all, DF_shops, on=['shop_id'], how='left') DF_all = pd.merge(DF_all, DF_items, on=['item_id'], how='left') DF_all.fillna(0, inplace=True) DF_all<data_type_conversions>
train_data[['Parch', 'Survived']].groupby('Parch', as_index=False ).mean()
Titanic - Machine Learning from Disaster
8,370,213
DF_all.date_block_num = DF_all.date_block_num.astype(np.int8) DF_all.shop_id = DF_all.shop_id.astype(np.int8) DF_all.item_id = DF_all.item_id.astype(np.int16) DF_all.shop_city = DF_all.shop_city.astype(np.int8) DF_all.shop_cat = DF_all.shop_cat.astype(np.int8) DF_all.item_category_id = DF_all.item_category_id.asty...
train_data['AgeBand'] = pd.cut(train_data['Age'], 9 )
Titanic - Machine Learning from Disaster
8,370,213
def lag_feature(df, lags, col): tmp = df[['date_block_num','shop_id','item_id',col]] for i in lags: shifted = tmp.copy() shifted.columns = ['date_block_num','shop_id','item_id', col+'_lag_'+str(i)] shifted['date_block_num'] += i df = pd.merge(df, shifted, on=['date_block_num','shop_id','item_id'], how='left') return d...
train_data[['AgeBand','Survived']].groupby('AgeBand', as_index=False ).mean()
Titanic - Machine Learning from Disaster
8,370,213
temp = DF_sales.groupby(['shop_id','item_id','date_block_num'] ).agg(item_cnt_month=('item_cnt_day',sum)) temp.columns = ['item_cnt_month'] temp.reset_index(inplace=True) DF_all = pd.merge(DF_all, temp, on=cols, how='left') DF_all['item_cnt_month'] =(DF_all['item_cnt_month'] .fillna(0) .clip(0,20) .astype(np.float16...
train_data.loc[ train_data['Age'] <= 18, 'Age'] = 0 train_data.loc[(train_data['Age'] > 18)&(train_data['Age'] <= 44), 'Age'] = 1 train_data.loc[(train_data['Age'] > 44)&(train_data['Age'] <= 53), 'Age'] = 2 train_data.loc[(train_data['Age'] > 53)&(train_data['Age'] <= 62), 'Age'] = 3 train_data.loc[ train_data['Age'] ...
Titanic - Machine Learning from Disaster
8,370,213
ts = time.time() DF_all = lag_feature(DF_all, [1, 2, 3], 'item_cnt_month') temp = DF_all.groupby(['date_block_num'] ).agg({'item_cnt_month' : ['mean']}) temp.columns = ['avg_month'] temp.reset_index(inplace=True) DF_all = pd.merge(DF_all, temp, on=['date_block_num'], how='left') DF_all = lag_feature(DF_all, [1, 2, ...
train_data.drop(labels='AgeBand', axis=1, inplace=True )
Titanic - Machine Learning from Disaster
8,370,213
DF_all['month'] = DF_all['date_block_num'] % 12 days = pd.Series([31,28,31,30,31,30,31,31,30,31,30,31]) DF_all['days'] = DF_all['month'].map(days) DF_all['years'] = np.select( [DF_all.date_block_num.isin(range(0,12)) , DF_all.date_block_num.isin(range(12,25)) , DF_all.date_block_num.isin(range(25,35)) ], ['13','14',...
train_data['FareBand'] = pd.qcut(train_data['Fare'], 5 )
Titanic - Machine Learning from Disaster