kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
9,106,511
df=pd.read_csv('.. /input/kobe-bryant-shot-selection/data.csv', header=0,sep=',' )<count_values>
train_df["FamilySize"] = train_df["SibSp"] + train_df["Parch"] + 1 test_df["FamilySize"] = test_df["SibSp"] + test_df["Parch"] + 1
Titanic - Machine Learning from Disaster
9,106,511
df.shot_made_flag.value_counts()<count_missing_values>
train_df.loc[train_df['FamilySize'] <= 0.0,'IsAlone'] = 0 train_df.loc[train_df['FamilySize'] > 0.0,'IsAlone'] = 1 test_df.loc[test_df['FamilySize'] <= 0.0,'IsAlone'] = 0 test_df.loc[test_df['FamilySize'] > 0.0,'IsAlone'] = 1
Titanic - Machine Learning from Disaster
9,106,511
df.shot_made_flag.isnull().sum()<drop_column>
family_mapping = {1: 0, 2: 0.4, 3: 0.8, 4: 1.2, 5: 1.6, 6: 2, 7: 2.4, 8: 2.8, 9: 3.2, 10: 3.6, 11: 4} for dataset in train_test_data: dataset['FamilySize'] = dataset['FamilySize'].map(family_mapping )
Titanic - Machine Learning from Disaster
9,106,511
if 'lat' in df.columns: df.drop(labels='lat',axis=1,inplace=True) if 'lon' in df.columns: df.drop(labels='lon',axis=1,inplace=True )<count_values>
features_drop = ['Ticket', 'Parch', ] train_df = train_df.drop(features_drop, axis=1) test_df = test_df.drop(features_drop, axis=1) train_df = train_df.drop(['PassengerId'], axis=1 )
Titanic - Machine Learning from Disaster
9,106,511
df.team_name.value_counts()<drop_column>
train_data = train_df.drop('Survived', axis=1) target = train_df['Survived'] train_data.shape, target.shape
Titanic - Machine Learning from Disaster
9,106,511
if 'team_name' in df.columns: df.drop(labels='team_name', inplace=True, axis=1 )<drop_column>
k_fold = KFold(n_splits=10, shuffle=True, random_state=0 )
Titanic - Machine Learning from Disaster
9,106,511
if 'shot_id' in df.columns: df.drop(labels='shot_id', inplace=True, axis=1 )<count_values>
clf = KNeighborsClassifier(n_neighbors = 13) scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
df.game_id.value_counts().head(10 )<drop_column>
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
if 'game_id' in df.columns: df.drop(labels='game_id', inplace=True, axis=1) if 'game_event_id' in df.columns: df.drop(labels='game_event_id', inplace=True, axis=1 )<count_values>
clf = DecisionTreeClassifier() scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
df.matchup.str.startswith('LAL' ).value_counts()<data_type_conversions>
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
df['home_or_away']=df.matchup.apply(lambda x: 'home' if x.find('@')==-1 else 'away') df['home_or_away']=df['home_or_away'].astype('category' )<drop_column>
rand_clf = RandomForestClassifier(n_estimators=13) scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
if 'matchup' in df.columns: df.drop(labels='matchup', axis=1,inplace=True )<data_type_conversions>
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
df['opponent']=df['opponent'].astype('category' )<count_values>
clf = GaussianNB() scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
df.team_id.value_counts()<drop_column>
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
if 'team_id' in df.columns: df.drop(labels='team_id', axis=1,inplace=True )<count_values>
svm = SVC() scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
df.shot_type.value_counts()<data_type_conversions>
round(np.mean(score)*100,2 )
Titanic - Machine Learning from Disaster
9,106,511
df['shot_type']=df.shot_type.astype('category' )<data_type_conversions>
svm = SVC() clf.fit(train_data, target) test_data = test_df.drop("PassengerId", axis=1 ).copy() prediction = clf.predict(test_data )
Titanic - Machine Learning from Disaster
9,106,511
df['game_date']=pd.to_datetime(df['game_date'] )<data_type_conversions>
model = XGBClassifier() model.fit(train_data, target )
Titanic - Machine Learning from Disaster
9,106,511
df['season']=df.season.astype('category' )<feature_engineering>
y_pred = clf.predict(test_data) predictions = [round(value)for value in y_pred]
Titanic - Machine Learning from Disaster
9,106,511
df['weekofyear']=df.game_date.apply(lambda x:x.weekofyear) df['dayofweek']=df.game_date.apply(lambda x:x.dayofweek) df['year']=df.game_date.apply(lambda x:x.year) df['month']=df.game_date.apply(lambda x:x.month) df['weekofyear']=df['weekofyear'].astype('category') df['dayofweek']=df['dayofweek'].astype('category')...
run_gs = False if run_gs: parameter_grid = { 'max_depth' : [4, 6, 8], 'n_estimators': [50, 10], 'max_features': ['sqrt', 'auto', 'log2'], 'min_samples_split': [2, 3, 10], 'min_samples_leaf': [1, 3, 10], 'bootstrap': [True, False], } forest = RandomForestClassifier() cross_validation = StratifiedKFold(n_splits=5) grid_...
Titanic - Machine Learning from Disaster
9,106,511
if 'game_date' in df.columns: df.drop(labels='game_date',axis=1,inplace=True) <count_values>
output = model.predict(test_data ).astype(int )
Titanic - Machine Learning from Disaster
9,106,511
df.shot_zone_range.value_counts()<data_type_conversions>
submission = pd.DataFrame({ "PassengerId": test_df["PassengerId"], "Survived": output }) submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
9,106,511
df['shot_zone_range']=df['shot_zone_range'].astype('category' )<count_values>
Image(url= "https://i.ytimg.com/vi/1PhMWUoPDsk/maxresdefault.jpg" )
Titanic - Machine Learning from Disaster
9,106,511
df.shot_zone_basic.value_counts()<data_type_conversions>
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename))
Titanic - Machine Learning from Disaster
9,106,511
df['shot_zone_basic']=df['shot_zone_basic'].astype('category') <count_values>
train_df = pd.read_csv('.. /input/titanic/train.csv') test_df = pd.read_csv('.. /input/titanic/test.csv') survived = train_df['Survived'] passenger_id = test_df['PassengerId']
Titanic - Machine Learning from Disaster
9,106,511
df.shot_zone_area.value_counts()<data_type_conversions>
submission = pd.read_csv('/kaggle/input/titanic/gender_submission.csv') submission.head()
Titanic - Machine Learning from Disaster
9,106,511
df['shot_zone_area']=df['shot_zone_area'].astype('category' )<count_values>
print(train_df.isnull().sum()) print(test_df.isnull().sum() )
Titanic - Machine Learning from Disaster
9,106,511
df.action_type.value_counts()<data_type_conversions>
train_test_data = [train_df, test_df] print(train_test_data) for dataset in train_test_data: dataset['Title'] = dataset['Name'].str.extract('([A-Za-z]+)\.', expand=False )
Titanic - Machine Learning from Disaster
9,106,511
df['action_type']=df.action_type.astype('category' )<count_values>
train_df['Title'].value_counts()
Titanic - Machine Learning from Disaster
9,106,511
df.combined_shot_type.value_counts()<data_type_conversions>
test_df['Title'].value_counts()
Titanic - Machine Learning from Disaster
9,106,511
df['combined_shot_type']=df.combined_shot_type.astype('category' )<count_values>
title_mapping = {"Mr": 0, "Miss": 1, "Mrs": 2, "Master": 3, "Dr": 3, "Rev": 3, "Col": 3, "Major": 3, "Mlle": 3,"Countess": 3, "Ms": 3, "Lady": 3, "Jonkheer": 3, "Don": 3, "Dona" : 3, "Mme": 3,"Capt": 3,"Sir": 3 } for dataset in train_test_data: dataset['Title'] = dataset['Title'].map(title_mapping )
Titanic - Machine Learning from Disaster
9,106,511
df.minutes_remaining.value_counts()<feature_engineering>
train_df.drop('Name', axis=1, inplace=True) test_df.drop('Name', axis=1, inplace=True )
Titanic - Machine Learning from Disaster
9,106,511
df['total_seconds_remaining']=df[['minutes_remaining','seconds_remaining']].apply(lambda x:x[0]*60+x[1], axis=1 ).values bins_=[0]+list(np.linspace(6,715,71)) df['time_intervals']=pd.cut(df.total_seconds_remaining,bins=bins_,labels=list(range(1,72)) ).values plt.figure(figsize=(16,6)) df.groupby('time_intervals')['shot...
sex_mapping = {"male": 0, "female": 1} for dataset in train_test_data: dataset['Sex'] = dataset['Sex'].map(sex_mapping )
Titanic - Machine Learning from Disaster
9,106,511
df['in_last_five_seconds']=[1 if val==1 else 0 for val in df.time_intervals.values] df['in_last_five_seconds']=df['in_last_five_seconds'].astype('category') if 'minutes_remaining' in df.columns: df.drop(labels='minutes_remaining',axis=1,inplace=True) if 'seconds_remaining' in df.columns: df.drop(labels='seconds_remai...
train_df["Age"].fillna(train_df.groupby("Title")["Age"].transform("median"), inplace=True) test_df["Age"].fillna(test_df.groupby("Title")["Age"].transform("median"), inplace=True )
Titanic - Machine Learning from Disaster
9,106,511
df.period.value_counts()<count_values>
train_df.groupby("Title")["Age"].transform("median")
Titanic - Machine Learning from Disaster
9,106,511
df.playoffs.value_counts()<data_type_conversions>
for dataset in train_test_data: dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0, dataset.loc[(dataset['Age'] > 16)&(dataset['Age'] <= 26), 'Age'] = 1, dataset.loc[(dataset['Age'] > 26)&(dataset['Age'] <= 36), 'Age'] = 2, dataset.loc[(dataset['Age'] > 36)&(dataset['Age'] <= 62), 'Age'] = 3, dataset.loc[ dataset['Age'] > 6...
Titanic - Machine Learning from Disaster
9,106,511
df['period']=df['period'].astype('category') df['playoffs']=df['playoffs'].astype('category') <count_unique_values>
Pclass1 = train_df[train_df['Pclass']==1]['Embarked'].value_counts() Pclass2 = train_df[train_df['Pclass']==2]['Embarked'].value_counts() Pclass3 = train_df[train_df['Pclass']==3]['Embarked'].value_counts() df = pd.DataFrame([Pclass1, Pclass2, Pclass3]) df.index = ['1st class','2nd class', '3rd class'] df.plot(kind='b...
Titanic - Machine Learning from Disaster
9,106,511
df.shot_distance.nunique()<count_values>
for dataset in train_test_data: dataset['Embarked'] = dataset['Embarked'].fillna('S' )
Titanic - Machine Learning from Disaster
9,106,511
df.shot_distance.value_counts().head(15 )<data_type_conversions>
embarked_mapping = {"S": 0, "C": 1, "Q": 2} for dataset in train_test_data: dataset['Embarked'] = dataset['Embarked'].map(embarked_mapping )
Titanic - Machine Learning from Disaster
9,106,511
df['shot_made_flag']=df['shot_made_flag'].astype('category') <prepare_x_and_y>
train_df["Fare"].fillna(train_df.groupby("Pclass")["Fare"].transform("median"), inplace=True) test_df["Fare"].fillna(test_df.groupby("Pclass")["Fare"].transform("median"), inplace=True) train_df.head(5 )
Titanic - Machine Learning from Disaster
9,106,511
df_with_dummies=pd.get_dummies(df.drop(labels='shot_made_flag',axis=1),drop_first=True) xtrain=df_with_dummies[df.shot_made_flag.notnull() ] ytrain=df.shot_made_flag[df.shot_made_flag.notnull() ].values test=df_with_dummies[df.shot_made_flag.isnull() ]<import_modules>
train_df.Cabin.value_counts()
Titanic - Machine Learning from Disaster
9,106,511
from sklearn.ensemble import RandomForestClassifier <init_hyperparams>
for dataset in train_test_data: dataset['Cabin'] = dataset['Cabin'].str[:1]
Titanic - Machine Learning from Disaster
9,106,511
def optimization_of_parameter_of_rf(X,y,dict_of_param,name_of_parameter, list_of_values, min_estimators, max_estimators): list_of_parameter_dicts=[(value,{**dict_of_param,**{'n_estimators':100, 'warm_start':True, 'oob_score':True, 'n_jobs':-1, 'random_state':434,name_of_parameter:value}})for value in list_of_values] en...
cabin_mapping = {"A": 0, "B": 0.4, "C": 0.8, "D": 1.2, "E": 1.6, "F": 2, "G": 2.4, "T": 2.8} for dataset in train_test_data: dataset['Cabin'] = dataset['Cabin'].map(cabin_mapping )
Titanic - Machine Learning from Disaster
9,106,511
optimization_of_parameter_of_rf(xtrain.values, ytrain,{'min_samples_leaf':9},'max_features',[50,70,90],30,250 )<train_on_grid>
train_df["Cabin"].fillna(train_df.groupby("Pclass")["Cabin"].transform("median"), inplace=True) test_df["Cabin"].fillna(test_df.groupby("Pclass")["Cabin"].transform("median"), inplace=True )
Titanic - Machine Learning from Disaster
9,106,511
optimization_of_parameter_of_rf(xtrain.values, ytrain,{'max_features':50},'min_samples_leaf',[5,9,11,13],30,250 )<find_best_params>
train_df["FamilySize"] = train_df["SibSp"] + train_df["Parch"] + 1 test_df["FamilySize"] = test_df["SibSp"] + test_df["Parch"] + 1
Titanic - Machine Learning from Disaster
9,106,511
optimization_of_parameter_of_rf(xtrain.values, ytrain,{'max_features':50, 'min_samples_leaf':13},'max_depth',[15,20,25],30,250 )<train_model>
train_df.loc[train_df['FamilySize'] <= 0.0,'IsAlone'] = 0 train_df.loc[train_df['FamilySize'] > 0.0,'IsAlone'] = 1 test_df.loc[test_df['FamilySize'] <= 0.0,'IsAlone'] = 0 test_df.loc[test_df['FamilySize'] > 0.0,'IsAlone'] = 1
Titanic - Machine Learning from Disaster
9,106,511
rfc=RandomForestClassifier(n_estimators=400,max_features=50,min_samples_leaf=13, max_depth=20) rfc.fit(xtrain.values, ytrain) preds=rfc.predict_proba(test) <save_to_csv>
family_mapping = {1: 0, 2: 0.4, 3: 0.8, 4: 1.2, 5: 1.6, 6: 2, 7: 2.4, 8: 2.8, 9: 3.2, 10: 3.6, 11: 4} for dataset in train_test_data: dataset['FamilySize'] = dataset['FamilySize'].map(family_mapping )
Titanic - Machine Learning from Disaster
9,106,511
preds_df=pd.DataFrame({'shot_made_flag':preds[:,1]},index=df[df.shot_made_flag.isnull() ].index+1) preds_df.index.name='shot_id' preds_df.to_csv('submission.csv' )<set_options>
features_drop = ['Ticket', 'Parch', ] train_df = train_df.drop(features_drop, axis=1) test_df = test_df.drop(features_drop, axis=1) train_df = train_df.drop(['PassengerId'], axis=1 )
Titanic - Machine Learning from Disaster
9,106,511
%matplotlib inline py.init_notebook_mode(connected=True) warnings.filterwarnings('ignore' )<load_from_csv>
train_data = train_df.drop('Survived', axis=1) target = train_df['Survived'] train_data.shape, target.shape
Titanic - Machine Learning from Disaster
9,106,511
dfBase = pd.read_csv('.. /input/kobe-bryant-shot-selection/data.csv') dfBase.dataframeName = 'kobe-bryant-shot-selection.csv'<create_dataframe>
k_fold = KFold(n_splits=10, shuffle=True, random_state=0 )
Titanic - Machine Learning from Disaster
9,106,511
print(f'Dataset de treino tem {dfBase.shape[0]} linhas por {dfBase.shape[1]} colunas({dfBase.shape[0] * dfBase.shape[1]} celulas)' )<feature_engineering>
clf = KNeighborsClassifier(n_neighbors = 13) scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
dfPreprocess = dfBase.copy() dfPreprocess['dist'] = np.sqrt(dfPreprocess['loc_x']**2 + dfPreprocess['loc_y']**2) loc_x_zero = dfPreprocess['loc_x'] == 0 dfPreprocess['angle'] = np.array([0]*len(dfPreprocess)) dfPreprocess['angle'][~loc_x_zero] = np.arctan(dfPreprocess['loc_y'][~loc_x_zero] / dfPreprocess['loc_x'][~loc...
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
dfPreprocess['remaining_time'] = dfPreprocess['minutes_remaining'] * 60 + dfPreprocess['seconds_remaining']<feature_engineering>
clf = DecisionTreeClassifier() scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
dfPreprocess['match_elapsed_time'] =(dfPreprocess['period'] * 720)+(720 - dfPreprocess['remaining_time'] )<drop_column>
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
dfPreprocess = dfPreprocess.drop(axis=1, columns=[ 'shot_zone_range', 'shot_zone_area', 'shot_distance', 'lat', 'lon', 'loc_x', 'loc_y', 'shot_zone_basic', 'shot_type', 'team_name', 'team_id', 'matchup', 'game_event_id', 'game_id', 'season', 'game_date', 'seconds_remaining', 'minutes_remaining', 'period', ]) dfPreproc...
rand_clf = RandomForestClassifier(n_estimators=13) scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
dfPreprocess = dfPreprocess[['dist','angle', 'action_type', 'combined_shot_type', 'playoffs', 'match_elapsed_time', 'remaining_time', 'opponent', 'shot_made_flag']]<rename_columns>
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
dfPreprocess.columns = [ 'dist', 'angle', 'action_type_cat', 'combined_shot_type_cat', 'playoffs_cat', 'match_elapsed_time', 'remaining_time', 'opponent_cat', 'target' ]<remove_duplicates>
clf = GaussianNB() scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
print(f'Antes - Preprocess tem {dfPreprocess.shape[0]} linhas por {dfPreprocess.shape[1]} colunas({dfPreprocess.shape[0] * dfPreprocess.shape[1]} celulas)') dfPreprocess.drop_duplicates() print(f'Depois - Preprocess tem {dfPreprocess.shape[0]} linhas por {dfPreprocess.shape[1]} colunas({dfPreprocess.shape[0] * dfPrepr...
round(np.mean(score)*100, 2 )
Titanic - Machine Learning from Disaster
9,106,511
def generateMetadata(dfInput): data = [] for f in dfInput.columns: if f == 'target': role = 'target' elif f == 'id': role = 'id' else: role = 'input' if f == 'target': level = 'binary' elif 'cat' in f or f == 'id': level = 'nominal' elif dfInput[f].dtype == float or dfInput[f].dtype == np.float64: level = 'interval' el...
svm = SVC() scoring = 'accuracy' score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring) print(score )
Titanic - Machine Learning from Disaster
9,106,511
meta_preprocess = generateMetadata(dfPreprocess )<filter>
round(np.mean(score)*100,2 )
Titanic - Machine Learning from Disaster
9,106,511
print('Metadados categoricos da base pré processada') print(meta_preprocess[(meta_preprocess.level == 'nominal')&(meta_preprocess.keep)].index )<create_dataframe>
svm = SVC() clf.fit(train_data, target) test_data = test_df.drop("PassengerId", axis=1 ).copy() prediction = clf.predict(test_data )
Titanic - Machine Learning from Disaster
9,106,511
print('Tipos e quantidade de features do dataset') display(pd.DataFrame({'count' : meta_preprocess.groupby(['role', 'level'])['role'].size() } ).reset_index() )<count_missing_values>
model = XGBClassifier() model.fit(train_data, target )
Titanic - Machine Learning from Disaster
9,106,511
def getMissingAttributes(dfInput): atributos_missing = [] return_missing = [] for f in dfInput.columns: missings = dfInput[f].isna().sum() if missings > 0: atributos_missing.append(f) missings_perc = missings/dfInput.shape[0] return_missing.append([f, missings, missings_perc]) print('Atributo {} tem {} amostras({:.2%...
y_pred = clf.predict(test_data) predictions = [round(value)for value in y_pred]
Titanic - Machine Learning from Disaster
9,106,511
missing = getMissingAttributes(dfPreprocess[meta_preprocess[(meta_preprocess.role != 'target')].index]) display(missing )<define_variables>
run_gs = False if run_gs: parameter_grid = { 'max_depth' : [4, 6, 8], 'n_estimators': [50, 10], 'max_features': ['sqrt', 'auto', 'log2'], 'min_samples_split': [2, 3, 10], 'min_samples_leaf': [1, 3, 10], 'bootstrap': [True, False], } forest = RandomForestClassifier() cross_validation = StratifiedKFold(n_splits=5) grid_...
Titanic - Machine Learning from Disaster
9,106,511
remove_threshold = 0.425<filter>
output = model.predict(test_data ).astype(int )
Titanic - Machine Learning from Disaster
9,106,511
<feature_engineering><EOS>
submission = pd.DataFrame({ "PassengerId": test_df["PassengerId"], "Survived": output }) submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
5,214,844
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<choose_model_class>
%matplotlib inline rcParams['figure.figsize'] = 12,5
Titanic - Machine Learning from Disaster
5,214,844
def fillNullNumbers(dfInput, dfMetadata, dfMissing, missing_default, label): media_imp = SimpleImputer(missing_values=missing_default, strategy='mean') moda_imp = SimpleImputer(missing_values=missing_default, strategy='most_frequent') for index,row in dfMissing.iterrows() : columnName = row['column_name'] columnType ...
df_train = pd.read_csv(".. /input/titanic/train.csv") df_test = pd.read_csv(".. /input/titanic/test.csv") submission = pd.read_csv(".. /input/titanic/gender_submission.csv", index_col='PassengerId' )
Titanic - Machine Learning from Disaster
5,214,844
dfPreprocess = fillNullNumbers(dfPreprocess, meta_preprocess, missing, -1, 'Pré Processado' )<categorify>
def resumetable(df): print(f"Dataset Shape: {df.shape}") summary = pd.DataFrame(df.dtypes,columns=['dtypes']) summary = summary.reset_index() summary['Name'] = summary['index'] summary = summary[['Name','dtypes']] summary['Missing'] = df.isnull().sum().values summary['Uniques'] = df.nunique().values summary['First Va...
Titanic - Machine Learning from Disaster
5,214,844
def performOneHotEncoding(dfInput, meta_generic, dist_limit): v = meta_generic[(meta_generic.level == 'nominal')&(meta_generic.keep)].index display(v) for f in v: dist_values = dfInput[f].value_counts().shape[0] print('Atributo {} tem {} valores distintos'.format(f, dist_values)) if(dist_values > dist_limit): print('A...
resumetable(df_train )
Titanic - Machine Learning from Disaster
5,214,844
dfPreprocess = performOneHotEncoding(dfPreprocess, meta_preprocess, 200 )<normalization>
df_train['Survived'].replace({0:'No', 1:'Yes'}, inplace=True )
Titanic - Machine Learning from Disaster
5,214,844
min_max_scaler = MinMaxScaler() dfPreprocess[dfPreprocess.columns] = min_max_scaler.fit_transform(dfPreprocess[dfPreprocess.columns] )<import_modules>
df_train["Embarked"] = df_train["Embarked"].fillna('S' )
Titanic - Machine Learning from Disaster
5,214,844
from xgboost import XGBClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV, cross_val_score, ShuffleSplit, KFold, train_test_split, S...
df_train['Fare'].quantile([.01,.1,.25,.5,.75,.9,.99] ).reset_index()
Titanic - Machine Learning from Disaster
5,214,844
def showDistribution(val_classes, targetName): nonUsed, used = pd.DataFrame(val_classes ).groupby(targetName ).size() print('---') print(f'Das {pd.DataFrame(val_classes ).shape[0]} entradas no dataset, {nonUsed} foram de lances não convertidos e {used} foram de lances convertidos.') print(f'Temos assim {round(( used/...
df_train['Fare_log'] = np.log(df_train['Fare'] + 1) df_test['Fare_log'] = np.log(df_test['Fare'] + 1 )
Titanic - Machine Learning from Disaster
5,214,844
def logisticRegression(X_Train, y_Train, X_Val, y_Val): model = LogisticRegression(solver='lbfgs') model.fit(X_Train, y_Train) y_pred_class = model.predict(X_Val) y_pred_proba = model.predict_proba(X_Val) recall = recall_score(y_Val, y_pred_class) accuracy = accuracy_score(y_Val, y_pred_class) logloss = log_loss(...
df_train['Title'] = df_train.Name.apply(lambda x: re.search('([A-Z][a-z]+)\.', x ).group(1)) df_test['Title'] = df_test.Name.apply(lambda x: re.search('([A-Z][a-z]+)\.', x ).group(1)) (df_train['Title'].value_counts(normalize=True)* 100 ).head(5)
Titanic - Machine Learning from Disaster
5,214,844
def xGBClassifier(X_Train, y_Train, X_Val, y_Val, modelName, modelParams): if(modelParams == None): clf = XGBClassifier() else: clf = XGBClassifier(**modelParams) modelName = modelName + ' - Parameters: ' + str(modelParams) clf.fit(X_Train, y_Train) y_pred_class = clf.predict(X_Val) y_pred_proba = clf.predict_proba...
Title_Dictionary = { "Capt": "Officer", "Col": "Officer", "Major": "Officer", "Dr": "Officer", "Rev": "Officer", "Jonkheer": "Royalty", "Don": "Royalty", "Sir" : "Royalty", "the Countess":"Royalty", "Dona": "Royalty", "Lady" : "Royalty", "Mme": "Mrs", "Ms": "Mrs", "Mrs" : "Mrs", "Mlle": "Miss", "Miss" : "Miss", "Mr" : ...
Titanic - Machine Learning from Disaster
5,214,844
def xGB_KFold(X, y, kfoldAmount, modelName, modelParams): if(modelParams == None): clf = XGBClassifier() else: clf = XGBClassifier(**modelParams) modelName = modelName + ' - Parameters: ' + str(modelParams) clf_score = [] iterator = 1 for train_index, test_index in KFold(shuffle=True, n_splits=kfoldAmount, random_sta...
df_train.loc[df_train.Age.isnull() , 'Age'] = df_train.groupby(['Sex','Pclass','Title'] ).Age.transform('median') df_test.loc[df_train.Age.isnull() , 'Age'] = df_test.groupby(['Sex','Pclass','Title'] ).Age.transform('median') print(df_train["Age"].isnull().sum())
Titanic - Machine Learning from Disaster
5,214,844
def decisionTreeClassifier(X_Train, y_Train, X_Val, y_Val): clf = DecisionTreeClassifier() clf.fit(X_Train, y_Train) y_pred_class = clf.predict(X_Val) y_pred_proba = clf.predict_proba(X_Val) recall = recall_score(y_Val, y_pred_class) accuracy = accuracy_score(y_Val, y_pred_class) logloss = log_loss(y_Val, y_pred_p...
interval =(0, 5, 12, 18, 25, 35, 60, 120) cats = ['babies', 'Children', 'Teen', 'Student', 'Young', 'Adult', 'Senior'] df_train["Age_cat"] = pd.cut(df_train.Age, interval, labels=cats) df_test["Age_cat"] = pd.cut(df_test.Age, interval, labels=cats) df_train["Age_cat"].unique()
Titanic - Machine Learning from Disaster
5,214,844
def gridSearchKNN(X_Train, y_Train, X_Val, y_Val, k_range): clf=KNeighborsClassifier() param_grid=dict(n_neighbors=k_range) scores = ['neg_log_loss'] for sc in scores: grid=GridSearchCV(clf,param_grid,cv=2,scoring=sc,n_jobs=-1) print("K-Nearest Neighbors - Tuning hyper-parameters for %s" % sc) grid.fit(X_Train,y_Tra...
df_train["FSize"] = df_train["Parch"] + df_train["SibSp"] + 1 df_test["FSize"] = df_test["Parch"] + df_test["SibSp"] + 1 family_map = {1: 'Alone', 2: 'Small', 3: 'Small', 4: 'Small', 5: 'Medium', 6: 'Medium', 7: 'Large', 8: 'Large', 11: 'Large'} df_train['FSize'] = df_train['FSize'].map(family_map) df_test['FSize'] = ...
Titanic - Machine Learning from Disaster
5,214,844
def gridSearchSVC(X_Train, y_Train, X_Val, y_Val): svc=SVC() param_grid = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4, 1e-5],'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] scores = ['neg_log_loss'] for sc in scores: grid=GridSearchCV(svc,param_grid,cv=4,scoring=sc,n_jobs=-1) print("Support Ve...
df_train['Family'] = extract_surname(df_train['Name']) df_test['Family'] = extract_surname(df_test['Name'] )
Titanic - Machine Learning from Disaster
5,214,844
def predictTestDataset(X_Test, y_Test, clfModel, clfName): y_pred_class = clfModel.predict(X_Test) y_pred_proba = clfModel.predict_proba(X_Test) recall = recall_score(y_Test, y_pred_class) accuracy = accuracy_score(y_Test, y_pred_class) logloss = log_loss(y_Test, y_pred_proba) precision = precision_score(y_Test, y...
df_train['Ticket'].value_counts() [:10]
Titanic - Machine Learning from Disaster
5,214,844
def predictContestDataset(X_Test, clfModel, clfName): print(clfName) print('---') y_pred_class = clfModel.predict(X_Test) y_pred_proba = clfModel.predict_proba(X_Test) pd_prediction = pd.DataFrame(y_pred_class) pd_prediction.columns = ['target'] showDistribution(pd_prediction, 'target') return y_pred_class, y_pre...
df_train['Ticket_Frequency'] = df_train.groupby('Ticket')['Ticket'].transform('count') df_test['Ticket_Frequency'] = df_test.groupby('Ticket')['Ticket'].transform('count' )
Titanic - Machine Learning from Disaster
5,214,844
def performSubSampling(sample_size_target, sample_size_non_target, dfInput, targetValue): target_indices = dfInput[dfInput.target == targetValue].index target_values = dfInput.loc[np.random.choice(activated_indices, sample_size, replace=False)] non_target_indices = dfInput[dfInput.target != targetValue].index non_targe...
def cabin_extract(df): return df['Cabin'].apply(lambda x: str(x)[0] if(pd.notnull(x)) else str('M')) df_train['Cabin'] = cabin_extract(df_train) df_test['Cabin'] = cabin_extract(df_test )
Titanic - Machine Learning from Disaster
5,214,844
dfPredict = dfPreprocess[dfPreprocess['target'].isnull() ] dfPreprocess = dfPreprocess.dropna()<prepare_x_and_y>
df_train['Cabin'] = df_train['Cabin'].replace(['A', 'B', 'C'], 'ABC') df_train['Cabin'] = df_train['Cabin'].replace(['D', 'E'], 'DE') df_train['Cabin'] = df_train['Cabin'].replace(['F', 'G'], 'FG') df_train.loc[df_train['Cabin'] == 'T', 'Cabin'] = 'A' df_test['Cabin'] = df_test['Cabin'].replace(['A', 'B', 'C'], 'ABC...
Titanic - Machine Learning from Disaster
5,214,844
X = dfPreprocess.drop(['target'], axis=1) y = dfPreprocess['target'] y.columns = ['target']<prepare_x_and_y>
family_cats = CategoricalDtype(categories=['Alone', 'Small', 'Medium', 'Large'], ordered=True )
Titanic - Machine Learning from Disaster
5,214,844
X_predict = dfPredict.drop(['target'], axis=1 )<split>
df_train.FSize = df_train.FSize.astype(family_cats) df_test.FSize = df_test.FSize.astype(family_cats )
Titanic - Machine Learning from Disaster
5,214,844
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.30, random_state=42, stratify=y )<compute_train_metric>
df_train.Age_cat = df_train.Age_cat.cat.codes df_train.Fare_cat = df_train.Fare_cat.cat.codes df_test.Age_cat = df_test.Age_cat.cat.codes df_test.Fare_cat = df_test.Fare_cat.cat.codes df_train.FSize = df_train.FSize.cat.codes df_test.FSize = df_test.FSize.cat.codes
Titanic - Machine Learning from Disaster
5,214,844
logRegModel, logRegName = logisticRegression(X_train, y_train, X_val, y_val )<choose_model_class>
df_train.drop([ 'Ticket', 'Name'], axis=1, inplace=True) df_test.drop(['Ticket', 'Name', ], axis=1, inplace=True)
Titanic - Machine Learning from Disaster
5,214,844
xgbPureModel, xgbPureName = xGBClassifier(X_train, y_train, X_val, y_val, 'XGBoost - Base', None) xgbPresetModel, xgbPresetName = xGBClassifier(X_train, y_train, X_val, y_val, 'XGBoost - Preset', {'n_estimator':400, 'learning_rate' : 0.5,'random_state' : 0,'max_depth':70,'objective':"binary:logistic",'subsample':.8,'m...
df_test['Survived'] = 'test' df = pd.concat([df_train, df_test], axis=0, sort=False )
Titanic - Machine Learning from Disaster
5,214,844
<train_on_grid>
le = LabelEncoder() df['Family'] = le.fit_transform(df['Family'].astype(str))
Titanic - Machine Learning from Disaster
5,214,844
showDistribution(y, 'target') xgbGSModel, xgbGSName = xGB_KFold(X, y, 10, 'XGBoost - KFolded', {'colsample_bytree': 0.6, 'gamma': 9, 'learning_rate': 0.01, 'max_depth': 7, 'n_estimators': 500, 'subsample': 0.6, 'random_state': 42 } )<create_dataframe>
df = pd.get_dummies(df, columns=['Sex', 'Cabin', 'Embarked', 'Title'],\ prefix=['Sex', "Cabin", 'Emb', 'Title'], drop_first=True) df_train, df_test = df[df['Survived'] != 'test'], df[df['Survived'] == 'test'].drop('Survived', axis=1) del df
Titanic - Machine Learning from Disaster
5,214,844
contest_prediction, contest_prediction_probability = predictContestDataset(X_predict, xgbGSModel, xgbGSName )<save_to_csv>
df_train['Survived'].replace({'Yes':1, 'No':0}, inplace=True )
Titanic - Machine Learning from Disaster
5,214,844
sample = pd.read_csv('.. /input/kobe-bryant-shot-selection/sample_submission.csv', low_memory=False) sample.shot_made_flag = contest_prediction_probability sample.shot_made_flag = 1 - sample.shot_made_flag sample.to_csv("submission.csv", float_format='%.6f', index=False )<load_from_csv>
print(f'Train shape: {df_train.shape}') print(f'Train shape: {df_test.shape}' )
Titanic - Machine Learning from Disaster
5,214,844
data=pd.read_csv('.. /input/data.csv' )<count_values>
df_train.drop(['Age', 'Fare','Fare_log','Family', 'SibSp', 'Parch'], axis=1, inplace=True) df_test.drop(['Age', 'Fare','Fare_log','Family', 'SibSp', 'Parch'], axis=1, inplace=True )
Titanic - Machine Learning from Disaster
5,214,844
object_vars=[var for var in data if data[var].dtype=='object'] numerical_vars=[var for var in data if data[var].dtype=='float' or data[var].dtype=='int'] for var in object_vars: print(data[var].value_counts() )<drop_column>
X_train = df_train.drop(["Survived","PassengerId"],axis=1) y_train = df_train["Survived"] X_test = df_test.drop(["PassengerId"],axis=1 )
Titanic - Machine Learning from Disaster
5,214,844
data=data.drop(['team_id','team_name'],axis=1) <drop_column>
resumetable(X_train )
Titanic - Machine Learning from Disaster
5,214,844
data['home']=data['matchup'].apply(lambda x: 1 if 'vs' in x else 0) data=data.drop('matchup',axis=1 )<drop_column>
warnings.filterwarnings("ignore")
Titanic - Machine Learning from Disaster
5,214,844
data=data.drop(['lon','lat'],axis=1 )<drop_column>
clfs = [] seed = 3 clfs.append(( "LogReg", Pipeline([("Scaler", StandardScaler()), ("LogReg", LogisticRegression())]))) clfs.append(( "XGBClassifier", Pipeline([("Scaler", StandardScaler()), ("XGB", XGBClassifier())]))) clfs.append(( "KNN", Pipeline([("Scaler", StandardScaler()), ("KNN", KNeighborsClassifier())]))...
Titanic - Machine Learning from Disaster
5,214,844
data['time_remaining_seconds']=data['minutes_remaining']*60+data['seconds_remaining'] data=data.drop(['minutes_remaining','seconds_remaining'],axis=1 )<feature_engineering>
def objective(params): time1 = time.time() params = { 'max_depth': params['max_depth'], 'max_features': params['max_features'], 'n_estimators': params['n_estimators'], 'min_samples_split': params['min_samples_split'], 'criterion': params['criterion'] } print(" print(f"params = {params}") FOLDS = 10 count=1 skf = Strat...
Titanic - Machine Learning from Disaster
5,214,844
data['time_remaining_seconds'] data['last_3_seconds']=data.time_remaining_seconds.apply(lambda x: 1 if x<4 else 0 )<drop_column>
best = fmin(fn=objective, space=rf_space, algo=tpe.suggest, max_evals=40, )
Titanic - Machine Learning from Disaster