kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
5,214,844 | data=data.drop('shot_id',axis=1 )<data_type_conversions> | best_params = space_eval(rf_space, best)
best_params | Titanic - Machine Learning from Disaster |
5,214,844 | data['game_date']=pd.to_datetime(data['game_date'])
data['game_month']=data['game_date'].dt.month
data=data.drop('game_date',axis=1 )<drop_column> | clf = RandomForestClassifier(
**best_params, random_state=4,
)
clf.fit(X_train, y_train)
y_preds= clf.predict(X_test)
submission['Survived'] = y_preds.astype(int)
submission.to_csv('Titanic_rf_model_pred.csv' ) | Titanic - Machine Learning from Disaster |
5,214,844 | data=data.drop(['game_id','game_event_id'],axis=1 )<categorify> | class_weights = class_weight.compute_class_weight('balanced',
np.unique(y_train),
y_train ) | Titanic - Machine Learning from Disaster |
5,214,844 | categorical_vars=['action_type','combined_shot_type','season','opponent','shot_type','period','shot_zone_basic','shot_zone_area','shot_zone_range','game_month']
for var in categorical_vars:
data=pd.concat([data,pd.get_dummies(data[var],prefix=var)], 1)
data=data.drop(var,1 )<prepare_x_and_y> | def objective_logreg(params):
time1 = time.time()
params = {
'tol': params['tol'],
'C': params['C'],
'solver': params['solver'],
}
print("
print(f"params = {params}")
FOLDS = 10
count=1
skf = StratifiedKFold(n_splits=FOLDS, random_state=42, shuffle=True)
kf = KFold(n_splits=FOLDS, shuffle=False, random_state=42)
sco... | Titanic - Machine Learning from Disaster |
5,214,844 | train=data[pd.notnull(data['shot_made_flag'])]
test=data[pd.isnull(data['shot_made_flag'])]
y_train=train['shot_made_flag']
train=train.drop('shot_made_flag',1)
y_train=y_train.astype('int')
test=test.drop('shot_made_flag',1 )<predict_on_test> | best = fmin(fn=objective_logreg,
space=space_logreg,
algo=tpe.suggest,
max_evals=45,
) | Titanic - Machine Learning from Disaster |
5,214,844 | def log_scorer(estimator, X, y):
pred_probs = estimator.predict_proba(X)[:, 1]
return log_loss(y, pred_probs )<train_model> | best_params = space_eval(space_logreg, best)
best_params | Titanic - Machine Learning from Disaster |
5,214,844 | <compute_test_metric><EOS> | clf = LogisticRegression(
**best_params, random_state=4,
)
clf.fit(X_train, y_train)
y_preds= clf.predict(X_test)
submission['Survived'] = y_preds.astype(int)
submission.to_csv('Titanic_logreg_model_pred.csv')
| Titanic - Machine Learning from Disaster |
6,118,299 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_train_metric> | plt.style.use('fivethirtyeight')
warnings.filterwarnings('ignore')
%matplotlib inline | Titanic - Machine Learning from Disaster |
6,118,299 | cv=cross_val_score(model,train,y_train,scoring=log_scorer,cv=5)
cv<save_to_csv> | data = pd.read_csv('.. /input/titanic/train.csv')
test_data = pd.read_csv('.. /input/titanic/test.csv' ) | Titanic - Machine Learning from Disaster |
6,118,299 | sub = pd.read_csv(".. /input/sample_submission.csv")
sub['shot_made_flag'] = target_y
sub.to_csv("submission.csv", index=False )<set_options> | print(data.isnull().sum())
print(test_data.isnull().sum() ) | Titanic - Machine Learning from Disaster |
6,118,299 | sns.set_style('darkgrid')
sns.set_palette('bone')
pd.options.display.float_format = '{:,.3f}'.format<load_from_csv> | data.groupby(['Sex', 'Survived'])['Survived'].count() | Titanic - Machine Learning from Disaster |
6,118,299 | df = pd.read_csv(".. /input/data.csv")
df.shape<count_unique_values> | data['Initial'] = 0
for i in data:
data['Initial'] = data.Name.str.extract('([A-Za-z]+)\.')
test_data['Initial'] = 0
for i in test_data:
test_data['Initial'] = test_data.Name.str.extract('([A-Za-z]+)\.' ) | Titanic - Machine Learning from Disaster |
6,118,299 | df.game_id.nunique() , df.game_date.nunique()<count_unique_values> | data['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)
test_data['Initial'].replace(['Mlle','Mme','Ms','Dr','Major','Lady','Countess','Jonkheer','Col','Rev','C... | Titanic - Machine Learning from Disaster |
6,118,299 | df.game_event_id.nunique()<count_values> | data.groupby('Initial')['Age'].mean() | Titanic - Machine Learning from Disaster |
6,118,299 | df.action_type.value_counts() [:10]<filter> | data.loc[(data.Age.isnull())&(data.Initial=='Mr'),'Age']=33
data.loc[(data.Age.isnull())&(data.Initial=='Mrs'),'Age']=36
data.loc[(data.Age.isnull())&(data.Initial=='Master'),'Age']=5
data.loc[(data.Age.isnull())&(data.Initial=='Miss'),'Age']=22
data.loc[(data.Age.isnull())&(data.Initial=='Other'),'Age']=46
test_data.l... | Titanic - Machine Learning from Disaster |
6,118,299 | _ = df[(df["minutes_remaining"] == 0)&(df["seconds_remaining"] <= 10)]
_.mean() ["shot_made_flag"], _.count() ["shot_made_flag"]<feature_engineering> | data.Age.isnull().any()
test_data.Age.isnull().any() | Titanic - Machine Learning from Disaster |
6,118,299 | df["game_year"] = df["game_date"].str[0:4].astype(int)
df["game_month"] = df["game_date"].str[5:7].astype(int)
df['action_first_words'] = df["action_type"].str.split(' ' ).str[0]
df['action_last_words'] = df["action_type"].str.split(' ' ).str[-2]
df['season_start_year'] = df.season.str.split('-' ).str[0].astype(int)
... | data['Embarked'].fillna('S', inplace=True)
test_data['Embarked'].fillna('S', inplace=True ) | Titanic - Machine Learning from Disaster |
6,118,299 | df.drop(["team_id", "team_name", "game_date", "game_event_id", "matchup"], axis=1, inplace=True )<count_missing_values> | data.Embarked.isnull().any()
test_data.Embarked.isnull().any() | Titanic - Machine Learning from Disaster |
6,118,299 | nullcount = df.isnull().sum()
nullcount[nullcount > 0]<concatenate> | pd.crosstab(data.SibSp, data.Pclass ).style.background_gradient(cmap='summer_r' ) | Titanic - Machine Learning from Disaster |
6,118,299 | _ = pd.concat([df.game_id, df.period, df.shot_made_flag, df.game_id.shift(1), df.period.shift(1), df.shot_made_flag.shift(1)], axis=1)
_.columns = ["game_id", "period", "shot_made_flag", "pre_game_id", "pre_period", "pre_shot_made_flag"]
_.dropna()
_ = _[(_["game_id"] == _["pre_game_id"])&(_["period"] == _["pre_period... | pd.crosstab(data.Parch, data.Pclass ).style.background_gradient(cmap='summer_r' ) | Titanic - Machine Learning from Disaster |
6,118,299 | df_enc = df.copy()<categorify> | data['Age_band'] = 0
data.loc[data['Age']<=16, 'Age_band'] = 0
data.loc[(data['Age']>16)&(data['Age']<=32), 'Age_band'] = 1
data.loc[(data['Age']>32)&(data['Age']<=48), 'Age_band'] = 2
data.loc[(data['Age']>48)&(data['Age']<=64), 'Age_band'] = 3
data.loc[data['Age']>64, 'Age_band'] = 4
data.head(2)
test_data['Age_band... | Titanic - Machine Learning from Disaster |
6,118,299 | for i, t in df_enc.dtypes.iteritems() :
if t == object:
le = LabelEncoder()
le.fit(df_enc[i].astype(str))
df_enc[i] = le.transform(df_enc[i].astype(str))<filter> | data['Fare_cat']=0
data.loc[data['Fare']<=7.91,'Fare_cat']=0
data.loc[(data['Fare']>7.91)&(data['Fare']<=14.454),'Fare_cat']=1
data.loc[(data['Fare']>14.454)&(data['Fare']<=31),'Fare_cat']=2
data.loc[(data['Fare']>31)&(data['Fare']<=513),'Fare_cat']=3
test_data['Fare_cat']=0
test_data.loc[test_data['Fare']<=7.91,'Fare_... | Titanic - Machine Learning from Disaster |
6,118,299 | train = df[~df.shot_made_flag.isnull() ]<sort_values> | data['Sex'].replace(['male','female'],[0,1],inplace=True)
data['Embarked'].replace(['S','C','Q'],[0,1,2],inplace=True)
data['Initial'].replace(['Mr','Mrs','Miss','Master','Other'],[0,1,2,3,4],inplace=True)
test_data['Sex'].replace(['male','female'],[0,1],inplace=True)
test_data['Embarked'].replace(['S','C','Q'],[0,... | Titanic - Machine Learning from Disaster |
6,118,299 | def shot_mean(group_col):
return train.groupby([group_col] ).mean() ["shot_made_flag"]
def sorted_shot_mean(group_col):
return train.groupby([group_col] ).mean() ["shot_made_flag"].sort_values(ascending=False )<prepare_x_and_y> | from sklearn.linear_model import LogisticRegression
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_spl... | Titanic - Machine Learning from Disaster |
6,118,299 | X_train = df_enc[~df_enc.shot_made_flag.isnull() ]
X_game_id = X_train.pop('game_id')
Y_train = X_train['shot_made_flag']
X_train = X_train.drop(['shot_id','shot_made_flag'], axis=1)
X_test = df_enc[df_enc.shot_made_flag.isnull() ].drop(['game_id','shot_id','shot_made_flag'], axis=1 )<split> | train, test = train_test_split(data, test_size=0.3, random_state=0, stratify=data['Survived'])
train_X = train[train.columns[1:]]
train_Y = train[train.columns[:1]]
test_X = test[test.columns[1:]]
test_Y = test[test.columns[:1]]
X = data[data.columns[1:]]
Y = data['Survived'] | Titanic - Machine Learning from Disaster |
6,118,299 | params={'learning_rate': 0.03,
'objective':'binary',
'metric':'binary_logloss',
'num_leaves': 31,
'verbose': 1,
'random_state':42,
'bagging_fraction': 1,
'feature_fraction': 0.8
}
folds = GroupKFold(n_splits=10)
oof_preds = np.zeros(X_train.shape[0])
sub_preds = np.zeros(X_test.shape[0])
for fold_,(trn_, val_)in enu... | model = svm.SVC(kernel='rbf', C=1, gamma=0.1)
model.fit(train_X, train_Y)
prediction1 = model.predict(test_X)
print('Accuracy for rbf SVM is ', metrics.accuracy_score(prediction1, test_Y)) | Titanic - Machine Learning from Disaster |
6,118,299 | submission = pd.DataFrame({
"shot_id": df[df.shot_made_flag.isnull() ]["shot_id"],
"shot_made_flag": pred
})
submission.to_csv("submission.csv", index=False )<import_modules> | model=svm.SVC(kernel='linear',C=0.1,gamma=0.1)
model.fit(train_X,train_Y)
prediction2=model.predict(test_X)
print('Accuracy for linear SVM is',metrics.accuracy_score(prediction2,test_Y)) | Titanic - Machine Learning from Disaster |
6,118,299 | import numpy as np
import pandas as pd
import xgboost as xgb<load_from_csv> | model = LogisticRegression()
model.fit(train_X, train_Y)
prediction3 = model.predict(test_X)
print('The accuracy of the Logistic Regression is', metrics.accuracy_score(prediction3, test_Y)) | Titanic - Machine Learning from Disaster |
6,118,299 | data = pd.read_csv('.. /input/data.csv')
data.set_index('shot_id', inplace=True )<prepare_x_and_y> | model = DecisionTreeClassifier()
model.fit(train_X, train_Y)
prediction4 = model.predict(test_X)
print('The accuracy of the Decision Tree is', metrics.accuracy_score(prediction4, test_Y)) | Titanic - Machine Learning from Disaster |
6,118,299 | unknown_mask = data['shot_made_flag'].isnull()
data_cl = data.copy()
target = data_cl['shot_made_flag'].copy()<drop_column> | model = KNeighborsClassifier()
model.fit(train_X, train_Y)
prediction5 = model.predict(test_X)
print('The accuracy of the KNN is', metrics.accuracy_score(prediction5, test_Y)) | Titanic - Machine Learning from Disaster |
6,118,299 | data_cl.drop('team_id', inplace=True, axis=1)
data_cl.drop('lat', inplace=True, axis=1)
data_cl.drop('lon', inplace=True, axis=1)
data_cl.drop('game_id', inplace=True, axis=1)
data_cl.drop('game_event_id', inplace=True, axis=1)
data_cl.drop('team_name', inplace=True, axis=1)
data_cl.drop('shot_made_flag', inplace... | a_index = list(range(1,11))
a = pd.Series()
x = [0,1,2,3,4,5,6,7,8,9,10]
for i in list(range(1,11)) :
model = KNeighborsClassifier(n_neighbors=i)
model.fit(train_X, train_Y)
prediction = model.predict(test_X)
a = a.append(pd.Series(metrics.accuracy_score(prediction, test_Y)))
plt.plot(a_index, a)
plt.xticks(x)
pl... | Titanic - Machine Learning from Disaster |
6,118,299 | data_cl['seconds_from_period_end'] = 60 * data_cl['minutes_remaining'] + data_cl['seconds_remaining']
data_cl['last_5_sec_in_period'] = data_cl['seconds_from_period_end'] < 5
data_cl['seconds_from_period_start'] = 60*(11-data_cl['minutes_remaining'])+(60-data_cl['seconds_remaining'])
data_cl['seconds_from_game_start']... | model = GaussianNB()
model.fit(train_X, train_Y)
prediction6 = model.predict(test_X)
print('The accuracy of the NaiveBayes is ', metrics.accuracy_score(prediction6, test_Y)) | Titanic - Machine Learning from Disaster |
6,118,299 | data_cl['home_play'] = data_cl['matchup'].str.contains('vs' ).astype('int')
data_cl.drop('matchup', axis=1, inplace=True )<feature_engineering> | model=RandomForestClassifier(n_estimators=100)
model.fit(train_X,train_Y)
prediction7=model.predict(test_X)
print('The accuracy of the Random Forests is',metrics.accuracy_score(prediction7,test_Y)) | Titanic - Machine Learning from Disaster |
6,118,299 | data_cl['game_date'] = pd.to_datetime(data_cl['game_date'])
data_cl['game_year'] = data_cl['game_date'].dt.year
data_cl['game_month'] = data_cl['game_date'].dt.month
data_cl['dayOfWeek'] = data_cl['game_date'].dt.dayofweek
data_cl['dayOfYear'] = data_cl['game_date'].dt.dayofyear
data_cl.drop('game_date', axis=1, inpla... | plt.subplots(figsize=(12,6))
box = pd.DataFrame(accuracy, index=[classifiers])
box.T.boxplot() | Titanic - Machine Learning from Disaster |
6,118,299 | rare_action_types = data_cl['action_type'].value_counts().sort_values().index.values[:20]
data_cl.loc[data_cl['action_type'].isin(rare_action_types), 'action_type'] = 'Other'<categorify> | C = [0.05, 0.1, 0.2, 0.3, 0.25, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
gamma = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
kernel = ['rbf', 'linear']
hyper = {'kernel': kernel, 'C': C, 'gamma': gamma}
gd = GridSearchCV(estimator=svm.SVC() , param_grid=hyper, verbose=True)
gd.fit(X,Y)
print(gd.best_score_)
print(gd.... | Titanic - Machine Learning from Disaster |
6,118,299 | categorial_cols = [
'action_type', 'combined_shot_type', 'period', 'season', 'shot_type',
'shot_zone_area', 'shot_zone_basic', 'shot_zone_range', 'game_year',
'game_month', 'opponent']
for cc in categorial_cols:
dummies = pd.get_dummies(data_cl[cc])
dummies = dummies.add_prefix("{}_".format(cc))
data_cl.drop(cc, axis=... | n_estimators = range(100, 1000, 100)
hyper = {'n_estimators': n_estimators}
gd = GridSearchCV(estimator = RandomForestClassifier(random_state=0), param_grid=hyper, verbose=True)
gd.fit(X, Y)
print(gd.best_score_)
print(gd.best_estimator_ ) | Titanic - Machine Learning from Disaster |
6,118,299 | data_submit = data_cl[unknown_mask]
X = data_cl[~unknown_mask]
Y = target[~unknown_mask]<prepare_x_and_y> | ensemble_lin_rbf = VotingClassifier(estimators=[
('KNN', KNeighborsClassifier(n_neighbors=10)) ,
('RBF', svm.SVC(probability=True, kernel='rbf', C=0.5, gamma=0.1)) ,
('RFor', RandomForestClassifier(n_estimators=500, random_state=0)) ,
('LR',LogisticRegression(C=0.05)) ,
('DT',DecisionTreeClassifier(random_state=0)... | Titanic - Machine Learning from Disaster |
6,118,299 | d_train = xgb.DMatrix(X, label=Y)
dtest = xgb.DMatrix(data_submit )<init_hyperparams> | model = BaggingClassifier(base_estimator=KNeighborsClassifier(n_neighbors=3), random_state=0, n_estimators=700)
model.fit(train_X, train_Y)
prediction = model.predict(test_X)
print('The accuracy for bagged KNN is : ', metrics.accuracy_score(prediction, test_Y))
result = cross_val_score(model, X, Y, cv = 10, scoring=... | Titanic - Machine Learning from Disaster |
6,118,299 | params = {}
params['objective'] = 'binary:logistic'
params['eval_metric'] = 'logloss'
params['max_depth'] = 7
params['silent'] = 1
params['colsample_bytree'] = 0.7
params['eta'] = 0.004
params['max_delta_step'] = 1
params['min_child_weight'] = 3<compute_test_metric> | ada = AdaBoostClassifier(n_estimators=200, random_state=0, learning_rate=0.1)
result = cross_val_score(ada, X, Y, cv = 10, scoring='accuracy')
print('The cross validated score for AdaBoost is : ', result.mean() ) | Titanic - Machine Learning from Disaster |
6,118,299 |
<train_model> | grad = GradientBoostingClassifier(n_estimators=500, random_state=0, learning_rate=0.1)
result = cross_val_score(grad,X, Y, cv = 10, scoring='accuracy')
print('The cross validated score for Gradient Boosting is : ', result.mean() ) | Titanic - Machine Learning from Disaster |
6,118,299 | clf = xgb.train(params, d_train, num_boost_round=961 )<save_to_csv> | xgboost = xg.XGBClassifier(n_estimators=900, learning_rate=0.1)
result = cross_val_score(xgboost, X, Y, cv=10, scoring='accuracy')
print('The cross validated score for XGBoost is : ', result.mean() ) | Titanic - Machine Learning from Disaster |
6,118,299 | preds = clf.predict(dtest)
submission = pd.DataFrame()
submission["shot_id"] = data_submit.index
submission["shot_made_flag"]= preds
submission.to_csv("sub_xgb.csv",index=False )<load_from_csv> | 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(X,Y)
print(gd.best_score_)
print(gd.best... | Titanic - Machine Learning from Disaster |
6,118,299 | <prepare_x_and_y><EOS> | model=AdaBoostClassifier(n_estimators=200,learning_rate=0.05,random_state=0)
model.fit(X,Y)
prediction = test_data
prediction['Survived'] = model.predict(test_data.drop(['PassengerId'], axis=1))
pd.DataFrame(prediction[['PassengerId', 'Survived']] ).to_csv('submission.csv', index=False ) | Titanic - Machine Learning from Disaster |
3,476,653 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_train_metric> | print(os.listdir("./"))
train = pd.read_csv('.. /input/train.csv',index_col = "PassengerId")
print(train.shape)
train.head() | Titanic - Machine Learning from Disaster |
3,476,653 | def eval1(y, p):
val_len = y.shape[1] - TRAIN_N
return np.sqrt(mean_squared_error(y[:, TRAIN_N:TRAIN_N+val_len].flatten() , p[:, TRAIN_N:TRAIN_N+val_len].flatten()))
def run_c(params, X, test_size=50):
gr_base = []
for i in range(X_c.shape[0]):
temp = X[i,:]
threshold = np.log(1+params['min cases for growth rate'])
nu... | test = pd.read_csv('.. /input/test.csv',index_col = "PassengerId")
print(test.shape)
test.head() | Titanic - Machine Learning from Disaster |
3,476,653 | def run_f(params, X_c, X_f, X_f_r, test_size=50):
X_f_r = np.array(np.ma.mean(np.ma.masked_outside(X_f_r, 0.06, 0.4)[:,:], axis=1))
X_f_r = np.clip(X_f_r, params['fatality_rate_lower'], params['fatality_rate_upper'])
X_c = np.clip(np.exp(X_c)-1, 0, None)
preds = X_f.copy()
train_size = X_f.shape[1] - 1
for i in range... | %matplotlib inline
| Titanic - Machine Learning from Disaster |
3,476,653 | if False:
val_len = train_p_c.values.shape[1] - TRAIN_N
for i in range(val_len):
d = i + TRAIN_N
m1 = np.sqrt(mean_squared_error(np.log(1 + train_p_c.values[:, d]), preds_c[:, d]))
m2 = np.sqrt(mean_squared_error(np.log(1 + train_p_f.values[:, d]), preds_f[:, d]))
print(f"{d}: {(m1 + m2)/2:8.5f} [{m1:8.5f} {m2:8.5f}]")... | pd.pivot_table(train, index = "Embarked", values = "Survived" ) | Titanic - Machine Learning from Disaster |
3,476,653 | temp = pd.DataFrame(np.clip(np.exp(preds_c)- 1, 0, None))
temp['Area'] = AREAS
temp = temp.melt(id_vars='Area', var_name='days', value_name="ConfirmedCases")
test = test.merge(temp, how='left', left_on=['Area', 'days'], right_on=['Area', 'days'])
temp = pd.DataFrame(np.clip(np.exp(preds_f)- 1, 0, None))
temp['Area'] ... | train.loc[train["Sex"] == "male", "enc_sex"] = 0
train.loc[train["Sex"] == "female", "enc_sex"] = 1
print(train.shape)
train[["Sex","enc_sex"]].head() | Titanic - Machine Learning from Disaster |
3,476,653 | test.to_csv("submission.csv", index=False, columns=["ForecastId", "ConfirmedCases", "Fatalities"] )<sort_values> | test.loc[test["Sex"] == "male", "enc_sex"] = 0
test.loc[test["Sex"] == "female", "enc_sex"] = 1
print(test.shape)
test[["Sex","enc_sex"]].head() | Titanic - Machine Learning from Disaster |
3,476,653 | for i, rec in test.groupby('Area' ).last().sort_values("ConfirmedCases", ascending=False ).iterrows() :
print(f"{rec['ConfirmedCases']:10.1f} {rec['Fatalities']:10.1f} {rec['Country/Region']}, {rec['Province/State']}")
<import_modules> | train["Emb_C"] = train["Embarked"] == "C"
train["Emb_S"] = train["Embarked"] == "S"
train["Emb_Q"] = train["Embarked"] == "Q"
print(train.shape)
train[["Embarked","Emb_C","Emb_S","Emb_Q"]].head() | Titanic - Machine Learning from Disaster |
3,476,653 | import numpy as np
import pandas as pd
import xgboost as xgb
from xgboost import plot_importance, plot_tree
from sklearn.metrics import mean_squared_error, mean_absolute_error
from google.cloud import bigquery<load_from_csv> | test["Emb_C"] = test["Embarked"] == "C"
test["Emb_S"] = test["Embarked"] == "S"
test["Emb_Q"] = test["Embarked"] == "Q"
print(test.shape)
test[["Embarked","Emb_C","Emb_S","Emb_Q"]].head() | Titanic - Machine Learning from Disaster |
3,476,653 | train = pd.read_csv(".. /input/covid19-global-forecasting-week-1/train.csv")
test = pd.read_csv(".. /input/covid19-global-forecasting-week-1/test.csv" )<create_dataframe> | train[train["Fare"].isnull() ] | Titanic - Machine Learning from Disaster |
3,476,653 | %%time
client = bigquery.Client()
dataset_ref = client.dataset("noaa_gsod", project="bigquery-public-data")
dataset = client.get_dataset(dataset_ref)
tables = list(client.list_tables(dataset))
table_ref = dataset_ref.table("stations")
table = client.get_table(table_ref)
stations_df = client.list_rows(table ).to_dat... | test[test["Fare"].isnull() ] | Titanic - Machine Learning from Disaster |
3,476,653 | weather_df['day_from_jan_first'] =(weather_df['da'].apply(int)
+ 31*(weather_df['mo']=='02')
+ 60*(weather_df['mo']=='03')
+ 91*(weather_df['mo']=='04')
)
mo = train['Date'].apply(lambda x: x[5:7])
da = train['Date'].apply(lambda x: x[8:10])
train['day_from_jan_first'] =(da.apply(int)
+ 31*(mo=='02')
+ 60*(mo==... | test.loc[test["Fare"].isnull() , "fillinFare"] = 0
test.loc[test["Fare"].isnull() , ["Fare", "fillinFare"]] | Titanic - Machine Learning from Disaster |
3,476,653 | weather_df['day_from_jan_first'] =(weather_df['da'].apply(int)
+ 31*(weather_df['mo']=='02')
+ 60*(weather_df['mo']=='03')
+ 91*(weather_df['mo']=='04')
)
mo = test['Date'].apply(lambda x: x[5:7])
da = test['Date'].apply(lambda x: x[8:10])
test['day_from_jan_first'] =(da.apply(int)
+ 31*(mo=='02')
+ 60*(mo=='03... | train.loc[train["Name"].str.contains("Mr"), "title"] = "Mr"
train.loc[train["Name"].str.contains("Miss"), "title"] = "Miss"
train.loc[train["Name"].str.contains("Mrs"), "title"] = "Mrs"
train.loc[train["Name"].str.contains("Master"), "title"] = "Master"
print(train.shape)
train[["Name", "title"]].head(10 ) | Titanic - Machine Learning from Disaster |
3,476,653 | train["wdsp"] = pd.to_numeric(train["wdsp"])
test["wdsp"] = pd.to_numeric(test["wdsp"] )<data_type_conversions> | train["Master"] = train["Name"].str.contains("Master")
print(train.shape)
train[["Name", "Master"]].head(20 ) | Titanic - Machine Learning from Disaster |
3,476,653 | train["fog"] = pd.to_numeric(train["fog"])
test["fog"] = pd.to_numeric(test["fog"] )<drop_column> | test["Master"] = test["Name"].str.contains("Master")
print(test.shape)
test[["Name", "Master"]].head(20 ) | Titanic - Machine Learning from Disaster |
3,476,653 | X_train = train.drop(["Fatalities", "ConfirmedCases"], axis=1 )<define_variables> | test["Child"] = test["Age"] < 14
print(test.shape)
test[["Age", "Child"]].head(10 ) | Titanic - Machine Learning from Disaster |
3,476,653 | countries = X_train["Country/Region"]<drop_column> | train["FamilySize"] = train["SibSp"] + train["Parch"] + 1
print(train.shape)
train[["SibSp", "Parch", "FamilySize"]].head() | Titanic - Machine Learning from Disaster |
3,476,653 | X_train = X_train.drop(["Id"], axis=1)
X_test = test.drop(["ForecastId"], axis=1 )<data_type_conversions> | test["FamilySize"] = test["SibSp"] + test["Parch"] + 1
print(test.shape)
test[["SibSp", "Parch", "FamilySize"]].head() | Titanic - Machine Learning from Disaster |
3,476,653 | X_train['Date']= pd.to_datetime(X_train['Date'])
X_test['Date']= pd.to_datetime(X_test['Date'] )<rename_columns> | train["Single"] = train["FamilySize"] == 1
train["Middle"] =(train["FamilySize"] > 1)&(train["FamilySize"] < 5)
train["Big"] = train["FamilySize"] >= 5
print(train.shape)
train[["FamilySize", "Single", "Middle", "Big"]].head(10 ) | Titanic - Machine Learning from Disaster |
3,476,653 | X_train = X_train.set_index(['Date'])
X_test = X_test.set_index(['Date'] )<feature_engineering> | test["Single"] = test["FamilySize"] == 1
test["Middle"] =(test["FamilySize"] > 1)&(test["FamilySize"] < 5)
test["Big"] = test["FamilySize"] >= 5
print(test.shape)
test[["FamilySize", "Single", "Middle", "Big"]].head(10 ) | Titanic - Machine Learning from Disaster |
3,476,653 | def create_time_features(df):
df['date'] = df.index
df['hour'] = df['date'].dt.hour
df['dayofweek'] = df['date'].dt.dayofweek
df['quarter'] = df['date'].dt.quarter
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year
df['dayofyear'] = df['date'].dt.dayofyear
df['dayofmonth'] = df['date'].dt.day
df['weeko... | feature = ["Pclass", "enc_sex", "Emb_C", "Emb_S", "Emb_Q","fillinFare",
"Master","Child", "Single", "Middle", "Big"]
feature | Titanic - Machine Learning from Disaster |
3,476,653 | create_time_features(X_train)
create_time_features(X_test )<drop_column> | label = "Survived"
label | Titanic - Machine Learning from Disaster |
3,476,653 | X_train.drop("date", axis=1, inplace=True)
X_test.drop("date", axis=1, inplace=True )<load_from_csv> | model = DecisionTreeClassifier(max_depth=9, random_state=0)
model | Titanic - Machine Learning from Disaster |
3,476,653 | world_happiness_index = pd.read_csv(".. /input/world-bank-datasets/World_Happiness_Index.csv" )<groupby> | model.fit(X_train, y_train ) | Titanic - Machine Learning from Disaster |
3,476,653 | world_happiness_grouped = world_happiness_index.groupby('Country name' ).nth(-1 )<drop_column> | model.fit(X_train, y_train ) | Titanic - Machine Learning from Disaster |
3,476,653 | world_happiness_grouped.drop("Year", axis=1, inplace=True )<merge> | tree = export_graphviz(model,
feature_names=feature,
class_names=["Perish", "Survived"],
out_file=None)
graphviz.Source(tree ) | Titanic - Machine Learning from Disaster |
3,476,653 | X_train = pd.merge(left=X_train, right=world_happiness_grouped, how='left', left_on='Country/Region', right_on='Country name')
X_test = pd.merge(left=X_test, right=world_happiness_grouped, how='left', left_on='Country/Region', right_on='Country name' )<load_from_csv> | prediction = model.predict(X_test)
print(prediction.shape)
prediction[0:9] | Titanic - Machine Learning from Disaster |
3,476,653 | malaria_world_health = pd.read_csv(".. /input/world-bank-datasets/Malaria_World_Health_Organization.csv" )<merge> | submission = pd.read_csv('.. /input/gender_submission.csv',index_col = "PassengerId")
print(submission.shape)
submission.tail(10 ) | Titanic - Machine Learning from Disaster |
3,476,653 | X_train = pd.merge(left=X_train, right=malaria_world_health, how='left', left_on='Country/Region', right_on='Country')
X_test = pd.merge(left=X_test, right=malaria_world_health, how='left', left_on='Country/Region', right_on='Country' )<drop_column> | submission["Survived"] = prediction
print(submission.shape)
submission.tail(10 ) | Titanic - Machine Learning from Disaster |
3,476,653 | <load_from_csv><EOS> | submission.to_csv("tree.csv" ) | Titanic - Machine Learning from Disaster |
1,602,712 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<merge> | %matplotlib inline
matplotlib.rcParams['figure.figsize'] =(12, 10)
sns.set_style('whitegrid')
| Titanic - Machine Learning from Disaster |
1,602,712 | X_train = pd.merge(left=X_train, right=human_development_index, how='left', left_on='Country/Region', right_on='Country')
X_test = pd.merge(left=X_test, right=human_development_index, how='left', left_on='Country/Region', right_on='Country' )<drop_column> | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv")
sub = pd.read_csv(".. /input/gender_submission.csv" ) | Titanic - Machine Learning from Disaster |
1,602,712 | X_train.drop(["Country", "Gross national income(GNI)per capita 2018"], axis=1, inplace=True)
X_test.drop(["Country", "Gross national income(GNI)per capita 2018"], axis=1, inplace=True )<load_from_csv> | Survival = train.Survived
full = pd.concat([train.drop('Survived', axis=1), test] ) | Titanic - Machine Learning from Disaster |
1,602,712 | night_ranger_predictors = pd.read_csv(".. /input/covid19-demographic-predictors/covid19_by_country.csv" )<drop_column> | pclass = pd.get_dummies(full1['Pclass'], prefix="Pclass_")
pclass.head() | Titanic - Machine Learning from Disaster |
1,602,712 | night_ranger_predictors = night_ranger_predictors[night_ranger_predictors.Country != "Georgia"]<merge> | full1['Sex_'] = np.where(full1.Sex == 'male', 1, 0)
full1.head() | Titanic - Machine Learning from Disaster |
1,602,712 | X_train = pd.merge(left=X_train, right=night_ranger_predictors, how='left', left_on='Country/Region', right_on='Country')
X_test = pd.merge(left=X_test, right=night_ranger_predictors, how='left', left_on='Country/Region', right_on='Country' )<drop_column> | Embarked = pd.get_dummies(full1['Embarked'], prefix="Embarked_")
Embarked.head() | Titanic - Machine Learning from Disaster |
1,602,712 | X_train.drop(["Country", "Restrictions","Quarantine", "Schools", "Total Infected", "Total Deaths", "Total Recovered"], axis=1, inplace=True)
X_test.drop(["Country", "Restrictions","Quarantine", "Schools", "Total Infected", "Total Deaths", "Total Recovered"], axis=1, inplace=True )<categorify> | full2 = pd.concat([full1, pclass, Embarked], axis=1)
full2.head() | Titanic - Machine Learning from Disaster |
1,602,712 | X_train = pd.concat([X_train,pd.get_dummies(X_train['Province/State'], prefix='ps')],axis=1)
X_train.drop(['Province/State'],axis=1, inplace=True)
X_test = pd.concat([X_test,pd.get_dummies(X_test['Province/State'], prefix='ps')],axis=1)
X_test.drop(['Province/State'],axis=1, inplace=True )<categorify> | Title = pd.get_dummies(full.Name.map(lambda x: x.split(',')[1].split('.')[0].split() [-1]))
Title.head() | Titanic - Machine Learning from Disaster |
1,602,712 | X_train = pd.concat([X_train,pd.get_dummies(X_train['Country/Region'], prefix='cr')],axis=1)
X_train.drop(['Country/Region'],axis=1, inplace=True)
X_test = pd.concat([X_test,pd.get_dummies(X_test['Country/Region'], prefix='cr')],axis=1)
X_test.drop(['Country/Region'],axis=1, inplace=True )<prepare_x_and_y> | full3['FamilySize'] = full3.SibSp + full3.Parch + 1
full3['Single'] = np.where(( full3.SibSp + full3.Parch)== 0, 1, 0 ) | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = train["Fatalities"]<choose_model_class> | full4 = pd.concat([full3, Title], axis=1)
full4.drop('Name', axis=1, inplace=True)
full4.head() | Titanic - Machine Learning from Disaster |
1,602,712 | reg = xgb.XGBRegressor(n_estimators=1000 )<train_model> | full6 = full5.drop(['SibSp','Parch'], axis=1)
full6.head() | Titanic - Machine Learning from Disaster |
1,602,712 | reg.fit(X_train, y_train, verbose=True )<groupby> | train_full = full6.iloc[:891]
test_full = full6.iloc[891:] | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = train.groupby(["Country/Region"] ).Fatalities.pct_change(periods=1 )<categorify> | train_age_imputer = SimpleImputer()
train_imputed = train_full.copy()
train_imputed['Age_'] = train_age_imputer.fit_transform(train_full.iloc[:,0:1])
train_imputed['Fare_'] = train_imputed['Fare']
train_imputed.drop(['Age', 'Fare'], axis=1, inplace=True)
train_imputed.head() | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = y_train.replace(np.nan, 0 )<define_variables> | test_age_imputer = SimpleImputer()
test_fare_imputer = SimpleImputer()
test_imputed = test_full.copy()
test_imputed['Age_'] = test_age_imputer.fit_transform(test_full.iloc[:,0:1])
test_imputed['Fare_'] = test_age_imputer.fit_transform(test_full.iloc[:,1:2])
test_imputed.drop(["Age","Fare"], axis=1, inplace=True)
tes... | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = y_train.replace(np.inf, 0 )<choose_model_class> | kfold = KFold(n_splits=5, random_state=1, shuffle=True)
kfold | Titanic - Machine Learning from Disaster |
1,602,712 | reg = xgb.XGBRegressor(n_estimators=1000 )<train_model> | accuracy = {} | Titanic - Machine Learning from Disaster |
1,602,712 | reg.fit(X_train, y_train, verbose=True )<prepare_x_and_y> | m1_nb = GaussianNB() | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = train["ConfirmedCases"]<choose_model_class> | accuracy['Gaussian Naive Bayes'] = np.mean(cross_val_score(m1_nb, train_imputed, Survival, scoring="accuracy", cv=kfold)) | Titanic - Machine Learning from Disaster |
1,602,712 | reg = xgb.XGBRegressor(n_estimators=1000 )<train_model> | m2_log = LogisticRegression(solver='newton-cg' ) | Titanic - Machine Learning from Disaster |
1,602,712 | reg.fit(X_train, y_train, verbose=True )<groupby> | accuracy['Logistic Regression'] = np.mean(cross_val_score(m2_log, train_imputed, Survival, scoring="accuracy", cv=kfold)) | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = train.groupby(["Country/Region"] ).ConfirmedCases.pct_change(periods=1 )<categorify> | m3_knn = KNeighborsClassifier(n_neighbors = 5 ) | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = y_train.replace(np.nan, 0 )<define_variables> | accuracy['K Nearest Neighbors'] = np.mean(cross_val_score(m3_knn, train_imputed, Survival, scoring="accuracy", cv=kfold)) | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = y_train.replace(np.inf, 0 )<choose_model_class> | m4_rf = RandomForestClassifier(n_estimators=10 ) | Titanic - Machine Learning from Disaster |
1,602,712 | reg = xgb.XGBRegressor(n_estimators=1000 )<train_model> | accuracy['Random Forest'] = np.mean(cross_val_score(m4_rf, train_imputed, Survival, scoring="accuracy", cv=kfold)) | Titanic - Machine Learning from Disaster |
1,602,712 | reg.fit(X_train, y_train, verbose=True )<train_model> | m5_svc = SVC(gamma='scale' ) | Titanic - Machine Learning from Disaster |
1,602,712 | y_train = train["ConfirmedCases"]
confirmed_reg = xgb.XGBRegressor(n_estimators=1000)
confirmed_reg.fit(X_train, y_train, verbose=True)
preds = confirmed_reg.predict(X_test)
preds = np.array(preds)
preds[preds < 0] = 0
preds = np.round(preds, 0 )<prepare_output> | accuracy['SVM'] = np.mean(cross_val_score(m5_svc, train_imputed, Survival, scoring="accuracy", cv=kfold)) | Titanic - Machine Learning from Disaster |
1,602,712 | preds = np.array(preds )<load_from_csv> | m6_gb = XGBClassifier(max_depth=3, n_estimators=300, learning_rate=0.05 ) | Titanic - Machine Learning from Disaster |
1,602,712 | submissionOrig = pd.read_csv(".. /input/covid19-global-forecasting-week-1/submission.csv" )<prepare_output> | accuracy['Gradient Boosting'] = np.mean(cross_val_score(m6_gb, train_imputed, Survival, scoring="accuracy", cv=kfold)) | Titanic - Machine Learning from Disaster |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.