kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
9,390,314
combine.Functional.value_counts()<count_values>
train_data.drop('Cabin',axis=1,inplace=True) test_data.drop('Cabin',axis=1,inplace=True )
Titanic - Machine Learning from Disaster
9,390,314
combine['Functional']=combine['Functional'].fillna('Typ') combine.Functional.value_counts()<count_values>
def impute_age(cols): Age=cols[0] Pclass=cols[1] if pd.isnull(Age): if Pclass == 1: return 37 elif Pclass == 2: return 29 else: return 24 else: return Age
Titanic - Machine Learning from Disaster
9,390,314
combine.FireplaceQu.value_counts()<count_values>
train_data['Age'] = train_data[['Age','Pclass']].apply(impute_age,axis=1 )
Titanic - Machine Learning from Disaster
9,390,314
combine.Fireplaces.value_counts()<count_missing_values>
test_data['Age'] = test_data[['Age','Pclass']].apply(impute_age,axis=1 )
Titanic - Machine Learning from Disaster
9,390,314
combine.FireplaceQu.isnull().sum()<count_values>
train_data.isnull().sum().sort_values(ascending = False )
Titanic - Machine Learning from Disaster
9,390,314
combine['FireplaceQu']=combine['FireplaceQu'].fillna('None') combine.FireplaceQu.value_counts()<count_values>
test_data.isnull().sum().sort_values(ascending = False )
Titanic - Machine Learning from Disaster
9,390,314
combine.GarageType.value_counts()<count_values>
list_of_non_numeric_data=list(train_data.select_dtypes(include='object')) list_of_non_numeric_data
Titanic - Machine Learning from Disaster
9,390,314
combine['GarageType']=combine['GarageType'].fillna('None') combine.GarageType.value_counts()<count_missing_values>
train_data.drop('Ticket',axis=1,inplace=True) test_data.drop('Ticket',axis=1,inplace=True )
Titanic - Machine Learning from Disaster
9,390,314
combine['GarageYrBlt']=combine['GarageYrBlt'].fillna(0) combine.GarageYrBlt.isnull().sum()<count_values>
def getTitles(name): name = str(name) title = name.split('.')[0] title = title.split(',') return title[1]
Titanic - Machine Learning from Disaster
9,390,314
combine.GarageFinish.value_counts()<count_values>
train_data['Title'] = train_data['Name'].apply(getTitles) train_data['Title']
Titanic - Machine Learning from Disaster
9,390,314
combine['GarageFinish']=combine['GarageFinish'].fillna('None') combine.GarageFinish.value_counts()<count_values>
test_data['Title'] = test_data['Name'].apply(getTitles) test_data['Title']
Titanic - Machine Learning from Disaster
9,390,314
combine.GarageCars.value_counts()<count_values>
def cleanTitle(title): if title in [' Mr',' Mrs',' Master',' Miss']: return title else: return "Others"
Titanic - Machine Learning from Disaster
9,390,314
combine['GarageCars']=combine['GarageCars'].fillna(0) combine.GarageCars.value_counts()<feature_engineering>
train_data['Title'] = train_data['Title'].apply(cleanTitle) test_data['Title'] = test_data['Title'].apply(cleanTitle )
Titanic - Machine Learning from Disaster
9,390,314
combine['GarageArea']=combine['GarageArea'].fillna(0) combine.GarageArea.isnull().sum()<count_values>
Title_train = pd.get_dummies(train_data['Title'],drop_first=True) Title_test = pd.get_dummies(test_data['Title'],drop_first=True) sex_train = pd.get_dummies(train_data['Sex'],drop_first=True) embark_train = pd.get_dummies(train_data['Embarked'],drop_first=True) sex_test = pd.get_dummies(test_data['Sex'],drop_first=...
Titanic - Machine Learning from Disaster
9,390,314
combine.GarageQual.value_counts()<count_values>
train_data.drop(['Sex','Embarked','Name','Title'],axis=1,inplace=True) test_data.drop(['Sex','Embarked','Name','Title'],axis=1,inplace=True )
Titanic - Machine Learning from Disaster
9,390,314
combine['GarageQual']=combine['GarageQual'].fillna('None') combine.GarageQual.value_counts()<count_values>
train_data=pd.concat([train_data,sex_train,embark_train,Title_train],axis=1) test_data=pd.concat([test_data,sex_test,embark_test,Title_test],axis=1 )
Titanic - Machine Learning from Disaster
9,390,314
combine.GarageCond.value_counts()<count_values>
from sklearn.preprocessing import MinMaxScaler
Titanic - Machine Learning from Disaster
9,390,314
combine['GarageCond']=combine['GarageCond'].fillna('None') combine.GarageCond.value_counts()<count_values>
X_train=train_data.drop(['Survived','PassengerId'],axis=1) y_train= train_data['Survived'] X_test=test_data.drop(['PassengerId'],axis=1 )
Titanic - Machine Learning from Disaster
9,390,314
combine.PoolArea.value_counts()<count_values>
Scaler=MinMaxScaler()
Titanic - Machine Learning from Disaster
9,390,314
combine.PoolQC.value_counts()<count_values>
X_train = Scaler.fit_transform(X_train) X_test = Scaler.transform(X_test )
Titanic - Machine Learning from Disaster
9,390,314
combine['PoolQC']=combine['PoolQC'].fillna('None') combine.PoolQC.value_counts()<count_values>
from sklearn.linear_model import LogisticRegression
Titanic - Machine Learning from Disaster
9,390,314
combine.Fence.value_counts()<count_values>
logmodel = LogisticRegression(max_iter=10000) logmodel.fit(X_train,y_train )
Titanic - Machine Learning from Disaster
9,390,314
combine['Fence']=combine['Fence'].fillna('None') combine.Fence.value_counts()<count_values>
test_data['Survived']=logmodel.predict(X_test )
Titanic - Machine Learning from Disaster
9,390,314
<count_values><EOS>
test_data[['PassengerId', 'Survived']].to_csv('kaggle_submission.csv', index = False )
Titanic - Machine Learning from Disaster
9,059,975
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<count_values>
pd.set_option('display.max_columns', 500) pd.set_option('display.max_rows', 500) df_train = pd.read_csv('.. /input/titanic/train.csv') df_test = pd.read_csv('.. /input/titanic/test.csv') df_sub = pd.read_csv('.. /input/titanic/gender_submission.csv' )
Titanic - Machine Learning from Disaster
9,059,975
combine.SaleType.value_counts()<count_values>
df = pd.concat([df_train, df_test],sort=False) df.reset_index(drop=True,inplace=True )
Titanic - Machine Learning from Disaster
9,059,975
combine['SaleType']=combine['SaleType'].fillna('WD') combine.SaleType.value_counts()<feature_engineering>
df.isnull().sum()
Titanic - Machine Learning from Disaster
9,059,975
combine['SalePrice']=combine['SalePrice'].fillna(0) combine.SalePrice.isnull().sum()<count_missing_values>
df[df['Fare'].isnull() ]
Titanic - Machine Learning from Disaster
9,059,975
combine.isnull().sum().sum()<count_values>
df_dropna = df.dropna(subset=['Fare'] )
Titanic - Machine Learning from Disaster
9,059,975
combine.YrSold.value_counts()<count_values>
df['Pclass'].value_counts()
Titanic - Machine Learning from Disaster
9,059,975
test_raw.YrSold.value_counts()<feature_engineering>
grouped = df.groupby('Pclass' )
Titanic - Machine Learning from Disaster
9,059,975
combine['Age']=combine['YrSold']-combine['YearBuilt'] combine['PriceFlux']=2011-combine['YrSold'] combine['Renew']=combine['YrSold']-combine['YearRemodAdd'] combine['MSSubClass']=combine['MSSubClass'].apply(str )<categorify>
age60=df[(df['Age']>60)&(df['Age']<70)]
Titanic - Machine Learning from Disaster
9,059,975
Label_cols=['MSSubClass','LotShape','LandContour','LandSlope','BldgType','HouseStyle','ExterQual','ExterCond','BsmtQual','BsmtCond','BsmtExposure','BsmtFinType1','BsmtFinType2','HeatingQC','CentralAir','Electrical','KitchenQual','Functional','FireplaceQu','GarageFinish','GarageQual','GarageCond','PavedDrive','PoolQC','...
age60.groupby(['Pclass','Embarked'] ).mean()
Titanic - Machine Learning from Disaster
9,059,975
combine=combine.drop(['YearBuilt','YearRemodAdd','MoSold','YrSold','GarageYrBlt','GarageArea','TotRmsAbvGrd'],axis=1) combine.shape<categorify>
age60.groupby(['Pclass','Embarked','SibSp','Parch'] ).mean()
Titanic - Machine Learning from Disaster
9,059,975
combine=pd.get_dummies(combine) combine.shape<set_options>
df.loc[df['PassengerId'] == 1044, 'Fare'] = 7.9
Titanic - Machine Learning from Disaster
9,059,975
pd.options.display.max_columns=None combine.columns.values<count_values>
df[df['Fare'].isnull() ]
Titanic - Machine Learning from Disaster
9,059,975
test_raw.GarageType.value_counts()<drop_column>
df[df['PassengerId'] == 1044]
Titanic - Machine Learning from Disaster
9,059,975
combine=combine.drop(['MSZoning_None','Street_Pave','Alley_None','LotConfig_Inside','Neighborhood_NAmes','Condition1_Norm','Condition2_Norm','RoofStyle_Gable','RoofMatl_CompShg','Exterior1st_VinylSd','Exterior2nd_VinylSd','MasVnrType_None','Foundation_PConc','Heating_GasA','GarageType_None'],axis=1) combine.shape<drop...
[df.Fare]=np.round([df.Fare],1 )
Titanic - Machine Learning from Disaster
9,059,975
train=train.drop(['Id'],axis=1 )<drop_column>
print(df['Ticket'].str.split(expand=True))
Titanic - Machine Learning from Disaster
9,059,975
test=combine[combine.SalePrice==0] test=test.drop(['Id','SalePrice'],axis=1) test.shape<compute_test_metric>
Ticket = df['Ticket'].str.extract(' (.*)\s (.*)' )
Titanic - Machine Learning from Disaster
9,059,975
def root_mean_squared_log_error(y_valid, y_preds): if len(y_preds)!=len(y_valid): return 'error_mismatch' y_preds_new = [math.log(x)for x in y_preds] y_valid_new = [math.log(x)for x in y_valid] return mean_squared_error(y_valid_new, y_preds_new, squared=False )<split>
df['Ticket_head']=Ticket[0] df['Ticket_num']=Ticket[1]
Titanic - Machine Learning from Disaster
9,059,975
y=train['SalePrice'] x=train.drop(['SalePrice'],axis=1) X_train, X_valid, y_train, y_valid=train_test_split(x,y,random_state=73 )<compute_train_metric>
Ticket_head = df['Ticket_head'].apply(lambda x: x.replace(".", "")if type(x)is str else float(x)) Ticket_head=Ticket_head.fillna('0' )
Titanic - Machine Learning from Disaster
9,059,975
RF_f=RandomForestRegressor(bootstrap=False, max_depth=60, max_features='sqrt', min_samples_split=4, n_estimators=1700) RF_f.fit(X_train,y_train) y_pred_RF_f=RF_f.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_RF_f))<compute_train_metric>
df['Ticket_head'] = Ticket_head
Titanic - Machine Learning from Disaster
9,059,975
XT=ExtraTreesRegressor(n_estimators=1000,random_state=73) XT.fit(X_train,y_train) y_pred_XT=XT.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_XT))<compute_train_metric>
df['Ticket_num']=df['Ticket_num'].fillna('0') df['Ticket_num'].value_counts()
Titanic - Machine Learning from Disaster
9,059,975
Ada_f=AdaBoostRegressor(learning_rate=0.03, loss='exponential', n_estimators=2300, random_state=73) Ada_f.fit(X_train,y_train) y_pred_Ada_f=Ada_f.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_Ada_f))<compute_train_metric>
df[df['Age'].isnull() ]
Titanic - Machine Learning from Disaster
9,059,975
GB_f=GradientBoostingRegressor(max_depth=10, max_features='sqrt', min_samples_split=12, n_estimators=1500) GB_f.fit(X_train,y_train) y_pred_GB_f=GB_f.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_GB_f))<compute_train_metric>
gc = df.drop(['PassengerId'], axis=1 )
Titanic - Machine Learning from Disaster
9,059,975
HGB_f=HistGradientBoostingRegressor(learning_rate=0.02, loss='least_absolute_deviation', max_depth=40, max_iter=750, min_samples_leaf=2, random_state=73) HGB_f.fit(X_train,y_train) y_pred_HGB_f=HGB_f.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_HGB_f))<compute_train_metric>
gc['Fare']=pd.cut(gc['Fare'], 5, labels=False) column = 'Cabin' gc[column] = gc[column].fillna(0) gc[column] = gc[column].str.extract('([A-Za-z]+)', expand = False) column = 'mrms' gc[column] = gc['Name'].str.extract('([A-Za-z]+)\.', expand = False) gc[column] = gc[column].replace(['Col', 'Mlle', 'Major','Countess'...
Titanic - Machine Learning from Disaster
9,059,975
XGB=XGBRegressor(n_estimators=1200,learning_rate=0.05,random_state=73) XGB.fit(X_train,y_train) y_pred_XGB=XGB.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_XGB))<train_on_grid>
list_ce = ['Cabin','Embarked','Sex','mrms','Survived','Fare'] ce_ohe = ce.OneHotEncoder(cols=list_ce,handle_unknown='impute') gc = ce_ohe.fit_transform(gc )
Titanic - Machine Learning from Disaster
9,059,975
<choose_model_class>
gc = gc.drop(['Name','Ticket'], axis=1 )
Titanic - Machine Learning from Disaster
9,059,975
XGB_f=XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=0.6, gamma=0.5, gpu_id=-1, importance_type='gain', interaction_constraints='', learning_rate=0.05, max_delta_step=0, max_depth=4, min_child_weight=1, monotone_constraints='() ', n_estimators=1200, n_jobs=0, nu...
gccollist.remove('Age' )
Titanic - Machine Learning from Disaster
9,059,975
XGB_model_f=XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=0.5, gamma=0.2, gpu_id=-1, importance_type='gain', interaction_constraints='', learning_rate=0.05, max_delta_step=0, max_depth=4, min_child_weight=2, monotone_constraints='() ', n_estimators=1000, n_jobs...
gc.isnull().sum()
Titanic - Machine Learning from Disaster
9,059,975
LGBg_f=LGBMRegressor(objective='regression',num_leaves=5, learning_rate=0.05, n_estimators=720, max_bin = 55, bagging_fraction = 0.8, bagging_freq = 5, feature_fraction = 0.2319, feature_fraction_seed=9, bagging_seed=9, min_data_in_leaf =6, min_sum_hessian_in_leaf = 11) LGBg_f.fit(X_train,y_train) y_pred_LGBg_f=LGBg_...
gc['Age']=gc['Age'].fillna(gc.groupby(gccollist)['Age'].transform('mean'))
Titanic - Machine Learning from Disaster
9,059,975
Vote=VotingRegressor([('gb',GB_f),('hgb',HGB_f),('xgb',XGB_f),('lgb',LGBg_f)]) Vote.fit(X_train,y_train) y_pred_Vote=Vote.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_Vote))<compute_train_metric>
gc.Age.isnull().sum()
Titanic - Machine Learning from Disaster
9,059,975
estimators=[('gb',GB_f),('hgb',HGB_f),('xgb',XGB_f),('lgb',LGBg_f)] Stack=StackingRegressor(estimators=estimators,final_estimator=RandomForestRegressor(n_estimators=800,random_state=42)) Stack.fit(X_train,y_train) y_pred_Stack=Stack.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(y_valid, y_pred_Stack))<...
gc[gc['Age'].isnull() ]
Titanic - Machine Learning from Disaster
9,059,975
Voting=VotingRegressor([('gb',GB_f),('hgb',HGB_f),('xgb',XGB_f),('lgb',LGBg_f)]) Voting.fit(x,y )<save_to_csv>
gc_corr = gc.corr() corr_y = pd.DataFrame({"features":gc.columns,"corr_y":gc_corr["Age"]},index=None) corr_y = corr_y.reset_index(drop=True )
Titanic - Machine Learning from Disaster
9,059,975
preds = Voting.predict(test) output = pd.DataFrame({'Id': test_raw.Id, 'SalePrice': preds}) output.to_csv('submission.csv', index=False )<compute_test_metric>
corr_y.sort_values('corr_y' )
Titanic - Machine Learning from Disaster
9,059,975
def root_mean_squared_log_error(y_valid, y_preds): if len(y_preds)!=len(y_valid): return 'error_mismatch' y_preds_new = [math.log(x)for x in y_preds] y_valid_new = [math.log(x)for x in y_valid] return mean_squared_error(y_valid_new, y_preds_new, squared=False )<load_from_csv>
gc['Age'] = np.round(gc['Age'].fillna(gc['Age'].mean()))
Titanic - Machine Learning from Disaster
9,059,975
train_data = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv') pd.set_option('display.max_columns', None) train_data.head()<count_unique_values>
gc.Age.isnull().sum()
Titanic - Machine Learning from Disaster
9,059,975
print(train_data.columns[train_data.isna().any() ].unique()) len(train_data.columns[train_data.isna().any() ].unique() )<prepare_x_and_y>
df['Age']=gc['Age']
Titanic - Machine Learning from Disaster
9,059,975
features = [x for x in train_data.columns if x not in ['SalePrice']] X = train_data.drop(['SalePrice'], axis=1) Y = train_data['SalePrice']<split>
df['Age']=pd.cut(df['Age'], 5, labels=False )
Titanic - Machine Learning from Disaster
9,059,975
X_train, X_valid, y_train, y_valid = train_test_split(X, Y, random_state=42) numerical_cols = [cname for cname in X_train.columns if X_train[cname].dtype in ['int64', 'float64']] categorical_cols = [cname for cname in X_train.columns if X_train[cname].nunique() < 13 and X_train[cname].dtype == "object"] numerical_tran...
df.isnull().sum()
Titanic - Machine Learning from Disaster
9,059,975
random_model = RandomForestRegressor(random_state=42, n_estimators=1000) random_clf = Pipeline(steps=[('preprocessor', preprocessor), ('random_model', random_model) ]) random_clf.fit(X_train, y_train) random_clf.fit(X_train, y_train) random_preds = random_clf.predict(X_valid) print('RMSLE:', root_mean_squared_lo...
pip install --upgrade optuna
Titanic - Machine Learning from Disaster
9,059,975
xgb_model = XGBRegressor(n_estimators=1000, learning_rate=0.01, random_state=42) xgb_clf = Pipeline(steps=[('preprocessor', preprocessor), ('xgb_model', xgb_model) ]) xgb_clf.fit(X_train, y_train, xgb_model__verbose=False) xgb_clf.fit(X_train, y_train) xgb_preds = xgb_clf.predict(X_valid) print('RMSLE:', root_me...
gc=df
Titanic - Machine Learning from Disaster
9,059,975
ada_model = AdaBoostRegressor(random_state=42, learning_rate=0.01, n_estimators=1000) ada_clf = Pipeline(steps=[('preprocessor', preprocessor), ('xgb_model', ada_model) ]) ada_clf.fit(X_train, y_train) ada_clf.fit(X_train, y_train) ada_preds = ada_clf.predict(X_valid) print('RMSLE:', root_mean_squared_log_error(...
gc['Fare']=pd.cut(gc['Fare'], 5, labels=False) column = 'Cabin' gc[column] = gc[column].fillna(0) gc[column] = gc[column].str.extract('([A-Za-z]+)', expand = False) column = 'mrms' gc[column] = gc['Name'].str.extract('([A-Za-z]+)\.', expand = False) gc[column] = gc[column].replace(['Col', 'Mlle', 'Major','Countess'...
Titanic - Machine Learning from Disaster
9,059,975
train_data['OverallQual'].isnull().sum()<count_missing_values>
train=gc
Titanic - Machine Learning from Disaster
9,059,975
train_data['OverallCond'].isnull().sum()<count_missing_values>
test_x = train[train['Survived'].isnull() ] test_x = test_x.drop(['Survived'], axis=1) df_result_dropna = train.dropna(subset=['Survived']) feature_names = df_result_dropna.drop(['Survived'], axis=1) feature_names = list(feature_names.columns) train_y = df_result_dropna['Survived'].astype(int) train_x = df_result_...
Titanic - Machine Learning from Disaster
9,059,975
train_data['YearBuilt'].isnull().sum()<count_missing_values>
tr_x, va_x, tr_y, va_y = train_test_split(train_x, train_y,random_state=42,test_size=0.2 )
Titanic - Machine Learning from Disaster
9,059,975
train_data['YearRemodAdd'].isnull().sum()<count_missing_values>
import optuna.integration.lightgbm as lgb from sklearn.metrics import accuracy_score,f1_score from sklearn.metrics import confusion_matrix
Titanic - Machine Learning from Disaster
9,059,975
train_data['TotalBsmtSF'].isnull().sum()<filter>
best_params = {} tuning_history = [] params = {'objective': 'binary','metric': 'binary_logloss'} trn_data= lgb.Dataset(tr_x, label=tr_y) val_data= lgb.Dataset(va_x, label=va_y) model = lgb.train(params, trn_data, valid_sets=[trn_data, val_data], verbose_eval=0, best_params=best_params, tuning_history=tuning_history )
Titanic - Machine Learning from Disaster
9,059,975
Q1 = train_data['TotalBsmtSF'].quantile(0.25) Q3 = train_data['TotalBsmtSF'].quantile(0.75) IQR = Q3 - Q1 outliers = train_data.loc[(train_data['TotalBsmtSF'] >(Q3 + 1.75 * IQR)) |(train_data['TotalBsmtSF'] <(Q1 - 1.75 * IQR)) , 'TotalBsmtSF'] print("Percent of Outliers: ", outliers.count() / train_data['TotalBsmtSF'...
prediction = np.rint(model.predict(va_x, num_iteration=model.best_iteration))
Titanic - Machine Learning from Disaster
9,059,975
train_data.drop(train_data.loc[(train_data['TotalBsmtSF'] >(Q3 + 1.75 * IQR)) |(train_data['TotalBsmtSF'] <(Q1 - 1.75 * IQR)) ].index, inplace=True) train_data.shape<count_missing_values>
accuracy = accuracy_score(va_y, prediction) best_params = model.params print("Best params:", best_params) print("Accuracy = {}".format(accuracy)) print("Params: ") for key, value in best_params.items() : print(" {}: {}".format(key, value))
Titanic - Machine Learning from Disaster
9,059,975
train_data['1stFlrSF'].isnull().sum()<filter>
pred_x = np.rint(model.predict(test_x, num_iteration=model.best_iteration))
Titanic - Machine Learning from Disaster
9,059,975
<drop_column><EOS>
df_sub['Survived'] = pred_x.astype(int) df_sub.to_csv('df_sub_pred_x.csv', index=False )
Titanic - Machine Learning from Disaster
9,067,724
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<count_missing_values>
\ %matplotlib inline
Titanic - Machine Learning from Disaster
9,067,724
train_data['GrLivArea'].isnull().sum()<filter>
train_df = pd.read_csv('/kaggle/input/train.csv') test_df = pd.read_csv('/kaggle/input/test.csv') combine = [train_df, test_df]
Titanic - Machine Learning from Disaster
9,067,724
Q1 = train_data['GrLivArea'].quantile(0.25) Q3 = train_data['GrLivArea'].quantile(0.75) IQR = Q3 - Q1 outliers = train_data.loc[(train_data['GrLivArea'] >(Q3 + 1.75 * IQR)) |(train_data['GrLivArea'] <(Q1 - 1.75 * IQR)) , 'GrLivArea'] print("Percent of Outliers: ", outliers.count() / train_data['GrLivArea'].count() * ...
train_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
9,067,724
train_data['FullBath'].isnull().sum()<count_missing_values>
train_df[["Sex", "Survived"]].groupby(['Sex'], as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
9,067,724
train_data['TotRmsAbvGrd'].isnull().sum()<count_missing_values>
train_df[["SibSp", "Survived"]].groupby(['SibSp'], as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
9,067,724
train_data['GarageCars'].isnull().sum()<count_missing_values>
train_df[["Parch", "Survived"]].groupby(['Parch'], as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
9,067,724
train_data['GarageArea'].isnull().sum()<filter>
for dataset in combine: dataset['Title'] = dataset.Name.str.extract('([A-Za-z]+)\.', expand=False) pd.crosstab(train_df['Title'], train_df['Sex'] )
Titanic - Machine Learning from Disaster
9,067,724
Q1 = train_data['GarageArea'].quantile(0.25) Q3 = train_data['GarageArea'].quantile(0.75) IQR = Q3 - Q1 outliers = train_data.loc[(train_data['GarageArea'] >(Q3 + 1.75 * IQR)) |(train_data['GarageArea'] <(Q1 - 1.75 * IQR)) , 'GarageArea'] print("Percent of Outliers: ", outliers.count() / train_data['GarageArea'].coun...
for dataset in combine: dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col',\ 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['T...
Titanic - Machine Learning from Disaster
9,067,724
train_data.drop(train_data.loc[(train_data['GarageArea'] >(Q3 + 1.75 * IQR)) |(train_data['GarageArea'] <(Q1 - 1.75 * IQR)) ].index, inplace=True) train_data.shape<train_on_grid>
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} for dataset in combine: dataset['Title'] = dataset['Title'].map(title_mapping) dataset['Title'] = dataset['Title'].fillna(0) train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
<choose_model_class>
train_df = train_df.drop(['Name', 'PassengerId'], axis=1) test_df = test_df.drop(['Name'], axis=1) combine = [train_df, test_df] train_df.shape, test_df.shape
Titanic - Machine Learning from Disaster
9,067,724
hp_model = XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=0.6, gamma=0.5, gpu_id=-1, importance_type='gain', interaction_constraints='', learning_rate=0.02, max_delta_step=0, max_depth=4, min_child_weight=1, monotone_constraints='() ', n_estimators=1000, n_jobs=...
for dataset in combine: dataset['Sex'] = dataset['Sex'].map({'female': 1, 'male': 0} ).astype(int) train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
X = train_data.drop(['SalePrice'], axis=1) y = train_data.SalePrice<data_type_conversions>
guess_ages = np.zeros(( 2,3)) guess_ages
Titanic - Machine Learning from Disaster
9,067,724
X.columns.to_list()<feature_engineering>
for dataset in combine: for i in range(0, 2): for j in range(0, 3): guess_df = dataset[(dataset['Sex'] == i)& \ (dataset['Pclass'] == j+1)]['Age'].dropna() age_guess = guess_df.median() guess_ages[i,j] = int(age_guess/0.5 + 0.5)* 0.5 for i in range(0, 2): for j in range(0, 3): dataset.loc[(dataset.Age.isnull())&(datas...
Titanic - Machine Learning from Disaster
9,067,724
X_feat_eng = X.copy() X_feat_eng['years_since_update'] = X_feat_eng['YearRemodAdd'] - X_feat_eng['YearBuilt'] X_feat_eng['geometry'] = X_feat_eng['LotArea'] / X_feat_eng['LotFrontage'] X_feat_eng['land_topology'] = X_feat_eng['LandSlope'] + '_' + X_feat_eng['LandContour'] X_feat_eng['value_proposition'] = X_feat_eng['Y...
for dataset in combine: dataset.loc[ dataset['Age'] <= 24, 'Age'] = 0 dataset.loc[(dataset['Age'] > 24)&(dataset['Age'] <= 32), 'Age'] = 1 dataset.loc[(dataset['Age'] > 32)&(dataset['Age'] <= 80), 'Age'] = 2 train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
X_test = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv' )<feature_engineering>
train_df = train_df.drop(['AgeBand'], axis=1) combine = [train_df, test_df] train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
X_test['years_since_update'] = X_test['YearRemodAdd'] - X_test['YearBuilt'] X_test['geometry'] = X_test['LotArea'] / X_test['LotFrontage'] X_test['land_topology'] = X_test['LandSlope'] + '_' + X_test['LandContour'] X_test['value_proposition'] = X_test['YearBuilt'] * X_test['OverallQual'] X_test['finished_basement'] = X...
for i in combine: i['Fam_Size'] = np.where(( i['SibSp']+i['Parch'])== 0 , 0, np.where(( i['SibSp']+i['Parch'])<= 3,1,2)) del i['SibSp'] del i['Parch']
Titanic - Machine Learning from Disaster
9,067,724
preds = feature_clf.predict(X_test) output = pd.DataFrame({'Id': X_test.Id, 'SalePrice': preds}) output.to_csv('submission.csv', index=False )<load_from_csv>
Titanic - Machine Learning from Disaster
9,067,724
train = pd.read_csv('.. /input/ames-housing-dataset/AmesHousing.csv') train.drop(['PID'], axis=1, inplace=True) origin = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv') train.columns = origin.columns test = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv') ...
train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
missing = test.isnull().sum() missing = missing[missing>0] train.drop(missing.index, axis=1, inplace=True) train.drop(['Electrical'], axis=1, inplace=True) test.dropna(axis=1, inplace=True) test.drop(['Electrical'], axis=1, inplace=True )<feature_engineering>
Titanic - Machine Learning from Disaster
9,067,724
l_test = tqdm(range(0, len(test)) , desc='Matching') for i in l_test: for j in range(0, len(train)) : for k in range(1, len(test.columns)) : if test.iloc[i,k] == train.iloc[j,k]: continue else: break else: submission.iloc[i, 1] = train.iloc[j, -1] break l_test.close()<save_to_csv>
freq_port = train_df.Embarked.dropna().mode() [0] freq_port
Titanic - Machine Learning from Disaster
9,067,724
submission.to_csv('result-with-best.csv', index=False )<import_modules>
for dataset in combine: dataset['Embarked'] = dataset['Embarked'].fillna(freq_port) train_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
9,067,724
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.preprocessing import OneHotEncoder, LabelEncoder, StandardScaler, MinMaxScaler, RobustScaler from sklearn.neighbors import KNeighborsRegressor from sklearn.feature_selection import RFE, SelectPercentile, f_regressi...
for dataset in combine: dataset['Embarked'] = dataset['Embarked'].map({'S': 0, 'C': 1, 'Q': 2} ).astype(int) train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
random_state = 831<load_from_csv>
test_df['Fare'].fillna(test_df['Fare'].dropna().median() , inplace=True) test_df.head()
Titanic - Machine Learning from Disaster
9,067,724
data_train = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/train.csv" ).set_index("Id") data_test = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/test.csv" ).set_index("Id") data = pd.concat([data_train, data_test] )<feature_engineering>
for dataset in combine: dataset.loc[ dataset['Fare'] <= 128, 'Fare'] = 0 dataset.loc[(dataset['Fare'] > 128)&(dataset['Fare'] <= 256.2), 'Fare'] = 1 dataset.loc[(dataset['Fare'] > 265.2)&(dataset['Fare'] <= 384.3), 'Fare'] = 2 dataset.loc[ dataset['Fare'] > 384.3, 'Fare'] = 3 dataset['Fare'] = dataset['Fare'].astype(in...
Titanic - Machine Learning from Disaster
9,067,724
def expand_categorical(data, features): d = data[features] values = np.unique(d.values.flatten() ).tolist() result = pd.DataFrame(index=data.index, columns=values) for i, row in d.iterrows() : v = np.unique(row.values.flatten() ).tolist() result.loc[i,v] = 1 result.fillna(0, inplace=True) result.columns = [features[0...
train_df = train_df.drop(['Embarked', 'Title'], axis=1) test_df = test_df.drop(['Embarked', 'Title'], axis=1) combine = [train_df, test_df] train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
analyse_numeric("SalePrice" )<feature_engineering>
train_df = train_df.drop(['Pclass'], axis=1) test_df = test_df.drop(['Pclass'], axis=1) combine = [train_df, test_df] train_df.head()
Titanic - Machine Learning from Disaster
9,067,724
data["SalePrice"] = np.log(data["SalePrice"] )<data_type_conversions>
X_train = train_df.drop("Survived", axis=1) Y_train = train_df["Survived"] X_test = test_df.drop("PassengerId", axis=1 ).copy() X_train.shape, Y_train.shape, X_test.shape
Titanic - Machine Learning from Disaster