kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
8,989,402
def rmse(actual, predicted): return sqrt(mean_squared_error(actual, predicted))<load_from_csv>
from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix,classification_report
Titanic - Machine Learning from Disaster
8,989,402
print('Train') train = pd.read_csv(".. /input/train/train.csv") print(train.shape) print('Test') test = pd.read_csv(".. /input/test/test.csv") print(test.shape) print('Breeds') breeds = pd.read_csv(".. /input/breed_labels.csv") print(breeds.shape) print('Colors') colors = pd.read_csv(".. /input/color_labels.c...
xTrain_small,xTest_small,yTrain_small,yTest_small=train_test_split(xTrain,yTrain )
Titanic - Machine Learning from Disaster
8,989,402
target = train['AdoptionSpeed'] train_id = train['PetID'] test_id = test['PetID'] train.drop(['AdoptionSpeed', 'PetID'], axis=1, inplace=True) test.drop(['PetID'], axis=1, inplace=True )<feature_engineering>
from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV
Titanic - Machine Learning from Disaster
8,989,402
doc_sent_mag = [] doc_sent_score = [] nf_count = 0 for pet in train_id: try: with open('.. /input/train_sentiment/' + pet + '.json', 'r')as f: sentiment = json.load(f) doc_sent_mag.append(sentiment['documentSentiment']['magnitude']) doc_sent_score.append(sentiment['documentSentiment']['score']) except FileNotFoundEr...
clf_best_fit=SVC(kernel='linear' )
Titanic - Machine Learning from Disaster
8,989,402
train_desc = train.Description.fillna("none" ).values test_desc = test.Description.fillna("none" ).values tfv = TfidfVectorizer(min_df=2, max_features=None, strip_accents='unicode', analyzer='word', token_pattern=r'(?u)\b\w+\b', ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, ) tfv.fit(list(train_desc)) ...
clf=SVC(kernel='linear' )
Titanic - Machine Learning from Disaster
8,989,402
train_desc = train.Description.fillna("none" ).values test_desc = test.Description.fillna("none" ).values tfv = TfidfVectorizer(min_df=3, max_features=10000, strip_accents='unicode', analyzer='word', token_pattern=r'\w{1,}', ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, stop_words = 'english') tfv.fit(l...
clf.fit(xTrain_small,yTrain_small )
Titanic - Machine Learning from Disaster
8,989,402
vertex_xs = [] vertex_ys = [] bounding_confidences = [] bounding_importance_fracs = [] dominant_blues = [] dominant_greens = [] dominant_reds = [] dominant_pixel_fracs = [] dominant_scores = [] label_descriptions = [] label_scores = [] nf_count = 0 nl_count = 0 for pet in train_id: try: with open('.. /input/train_metad...
clf.score(xTest_small,yTest_small )
Titanic - Machine Learning from Disaster
8,989,402
train.drop(['Name', 'RescuerID', 'Description'], axis=1, inplace=True) test.drop(['Name', 'RescuerID', 'Description'], axis=1, inplace=True )<data_type_conversions>
yTest_predicted_small=clf.predict(xTest_small )
Titanic - Machine Learning from Disaster
8,989,402
numeric_cols = ['Age', 'Quantity', 'Fee', 'VideoAmt', 'PhotoAmt', 'AdoptionSpeed', 'doc_sent_mag', 'doc_sent_score', 'dominant_score', 'dominant_pixel_frac', 'dominant_red', 'dominant_green', 'dominant_blue', 'bounding_importance', 'bounding_confidence', 'vertex_x', 'vertex_y', 'label_score'] + ['svd_{}'.format(i)for i...
confusion_matrix(yTest_small,yTest_predicted_small )
Titanic - Machine Learning from Disaster
8,989,402
foo = train.dtypes cat_feature_names = foo[foo == "category"] cat_features = [train.columns.get_loc(c)for c in train.columns if c in cat_feature_names]<find_best_model_class>
print(classification_report(yTest_small,yTest_predicted_small))
Titanic - Machine Learning from Disaster
8,989,402
def run_cv_model(train, test, target, model_fn, params={}, eval_fn=None, label='model'): kf = StratifiedKFold(n_splits=5, random_state=42, shuffle=True) fold_splits = kf.split(train, target) cv_scores = [] qwk_scores = [] pred_full_test = 0 pred_train = np.zeros(( train.shape[0], 5)) all_coefficients = np.zeros(( 5, ...
yPredicted=clf.predict(xTest )
Titanic - Machine Learning from Disaster
8,989,402
optR = OptimizedRounder() coefficients_ = np.mean(results['coefficients'], axis=0) print(coefficients_) coefficients_[0] = 1.64 coefficients_[1] = 2.11 coefficients_[3] = 2.85 train_predictions = [r[0] for r in results['train']] train_predictions = optR.predict(train_predictions, coefficients_ ).astype(int) Counter(...
clf = RandomForestClassifier(random_state=0) clf.fit(xTrain_small,yTrain_small )
Titanic - Machine Learning from Disaster
8,989,402
optR = OptimizedRounder() coefficients_ = np.mean(results['coefficients'], axis=0) print(coefficients_) coefficients_[0] = 1.645 coefficients_[1] = 2.115 coefficients_[3] = 2.84 test_predictions = [r[0] for r in results['test']] test_predictions = optR.predict(test_predictions, coefficients_ ).astype(int) Counter(te...
clf.score(xTest_small,yTest_small )
Titanic - Machine Learning from Disaster
8,989,402
print("True Distribution:") print(pd.value_counts(target, normalize=True ).sort_index()) print("Test Predicted Distribution:") print(pd.value_counts(test_predictions, normalize=True ).sort_index()) print("Train Predicted Distribution:") print(pd.value_counts(train_predictions, normalize=True ).sort_index()) <creat...
clf_logistic_regression=LogisticRegression(max_iter=1000) clf_logistic_regression.fit(xTrain_small,yTrain_small )
Titanic - Machine Learning from Disaster
8,989,402
pd.DataFrame(sk_cmatrix(target, train_predictions), index=list(range(5)) , columns=list(range(5)) )<compute_test_metric>
clf.score(xTest_small,yTest_small )
Titanic - Machine Learning from Disaster
8,989,402
quadratic_weighted_kappa(target, train_predictions) rmse(target, [r[0] for r in results['train']]) submission = pd.DataFrame({'PetID': test_id, 'AdoptionSpeed': test_predictions}) submission.head()<save_to_csv>
final_dataFrame=pd.DataFrame() final_dataFrame['PassengerId']=testPIds
Titanic - Machine Learning from Disaster
8,989,402
submission.to_csv('submission.csv', index=False )<save_to_csv>
from sklearn.neural_network import MLPClassifier
Titanic - Machine Learning from Disaster
8,989,402
submission.to_csv('submission.csv', index=False )<set_options>
clf=MLPClassifier(hidden_layer_sizes=(20,10),max_iter=1000,activation='logistic') clf.fit(xTrain_small,yTrain_small )
Titanic - Machine Learning from Disaster
8,989,402
%matplotlib inline plt.style.use('ggplot') py.init_notebook_mode(connected=True) warnings.filterwarnings("ignore") pd.set_option('max_colwidth', 500) pd.set_option('max_columns', 500) pd.set_option('max_rows', 100) def kappa(y_true, y_pred): return cohen_kappa_score(y_true, y_pred, weights='quadratic' )<load_from...
clf.score(xTest_small,yTest_small )
Titanic - Machine Learning from Disaster
8,989,402
breeds = pd.read_csv('.. /input/breed_labels.csv') colors = pd.read_csv('.. /input/color_labels.csv') states = pd.read_csv('.. /input/state_labels.csv') train = pd.read_csv('.. /input/train/train.csv') test = pd.read_csv('.. /input/test/test.csv') sub = pd.read_csv('.. /input/test/sample_submission.csv') train['d...
yPredicted_MLP_Small=clf.predict(xTest_small )
Titanic - Machine Learning from Disaster
8,989,402
ax.patches<count_values>
print(classification_report(yTest_small,yPredicted_MLP_Small))
Titanic - Machine Learning from Disaster
8,989,402
print('Most popular pet names and AdoptionSpeed') for n in train['Name'].value_counts().index[:5]: print(n) print(train.loc[train['Name'] == n, 'AdoptionSpeed'].value_counts().sort_index()) print('' )<feature_engineering>
print(confusion_matrix(yTest_small,yPredicted_MLP_Small))
Titanic - Machine Learning from Disaster
8,989,402
train['Name'] = train['Name'].fillna('Unnamed') test['Name'] = test['Name'].fillna('Unnamed') all_data['Name'] = all_data['Name'].fillna('Unnamed') train['No_name'] = 0 train.loc[train['Name'] == 'Unnamed', 'No_name'] = 1 test['No_name'] = 0 test.loc[test['Name'] == 'Unnamed', 'No_name'] = 1 all_data['No_name'] = 0 ...
yPredicted_MLP=clf.predict(xTest )
Titanic - Machine Learning from Disaster
8,989,402
all_data[all_data['Name'].apply(lambda x: len(str(x)))== 3]['Name'].value_counts().tail()<count_values>
final_dataFrame['Survived']=yPredicted_MLP
Titanic - Machine Learning from Disaster
8,989,402
train['Age'].value_counts().head(10 )<feature_engineering>
final_dataFrame.to_csv('titanic.csv', index=False) print("Your submission was successfully saved!" )
Titanic - Machine Learning from Disaster
6,587,175
train['Pure_breed'] = 0 train.loc[train['Breed2'] == 0, 'Pure_breed'] = 1 test['Pure_breed'] = 0 test.loc[test['Breed2'] == 0, 'Pure_breed'] = 1 all_data['Pure_breed'] = 0 all_data.loc[all_data['Breed2'] == 0, 'Pure_breed'] = 1 print(f"Rate of pure breed pets in train data: {train['Pure_breed'].sum() * 100 / train['Pur...
%pylab inline plt.style.use('seaborn-darkgrid') sns.set(font_scale=2) warnings.filterwarnings(action="ignore") n_arbres = 200 max_depth = 6 noms = [ "Random_Forest", "Ada_Boost", "Gradient_Boosting", "LightGBM", "XGBoost", "CatBoost" ] classifieurs = [ RandomForestClassifier(n_estimators=n_arbres,max_depth=max_depth...
Titanic - Machine Learning from Disaster
6,587,175
breeds_dict = {k: v for k, v in zip(breeds['BreedID'], breeds['BreedName'])}<feature_engineering>
train=pd.read_csv(".. /input/titanic/train.csv") print(train.shape) train.head()
Titanic - Machine Learning from Disaster
6,587,175
train['Breed1_name'] = train['Breed1'].apply(lambda x: '_'.join(breeds_dict[x].split())if x in breeds_dict else 'Unknown') train['Breed2_name'] = train['Breed2'].apply(lambda x: '_'.join(breeds_dict[x])if x in breeds_dict else '-') test['Breed1_name'] = test['Breed1'].apply(lambda x: '_'.join(breeds_dict[x].split())i...
test=pd.read_csv(".. /input/titanic/test.csv") print(test.shape) test.head()
Titanic - Machine Learning from Disaster
6,587,175
( all_data['Breed1_name'] + '__' + all_data['Breed2_name'] ).value_counts().head(15 )<feature_engineering>
donnees = pd.concat([train,test],sort=False) donnees.head()
Titanic - Machine Learning from Disaster
6,587,175
colors_dict = {k: v for k, v in zip(colors['ColorID'], colors['ColorName'])} train['Color1_name'] = train['Color1'].apply(lambda x: colors_dict[x] if x in colors_dict else '') train['Color2_name'] = train['Color2'].apply(lambda x: colors_dict[x] if x in colors_dict else '') train['Color3_name'] = train['Color3'].appl...
donnees['Title'] = donnees.Name.str.extract('([A-Za-z]+)\.', expand=False) pd.crosstab(donnees['Title'], donnees['Sex'] )
Titanic - Machine Learning from Disaster
6,587,175
gender_dict = {1: 'Male', 2: 'Female', 3: 'Mixed'} for i in all_data['Type'].unique() : for j in all_data['Gender'].unique() : df = all_data.loc[(all_data['Type'] == i)&(all_data['Gender'] == j)] top_colors = list(df['full_color'].value_counts().index)[:5] j = gender_dict[j] print(f"Most popular colors of {j} {i}s: {' ...
donnees['Title'] = donnees['Title'].replace(['Capt','Col','Major','Dr','Rev'], 'Autres') donnees['Title'] = donnees['Title'].replace(['Lady', 'Countess', 'Don', 'Sir', 'Jonkheer', 'Dona'], 'Noblesse') donnees['Title'] = donnees['Title'].replace('Mlle', 'Miss') donnees['Title'] = donnees['Title'].replace('Ms', 'Miss'...
Titanic - Machine Learning from Disaster
6,587,175
images = [i.split('-')[0] for i in os.listdir('.. /input/train_images/')] size_dict = {1: 'Small', 2: 'Medium', 3: 'Large', 4: 'Extra Large'} for t in all_data['Type'].unique() : for m in all_data['MaturitySize'].unique() : df = all_data.loc[(all_data['Type'] == t)&(all_data['MaturitySize'] == m)] top_breeds = list(df[...
donnees.Name = donnees.Name.str.extract('([A-Za-z]+)\,', expand=False) donnees.head()
Titanic - Machine Learning from Disaster
6,587,175
c = 0 strange_pets = [] for i, row in all_data[all_data['Breed1_name'].str.contains('air')].iterrows() : if 'Short' in row['Breed1_name'] and row['FurLength'] == 1: pass elif 'Medium' in row['Breed1_name'] and row['FurLength'] == 2: pass elif 'Long' in row['Breed1_name'] and row['FurLength'] == 3: pass else: c += 1 str...
donnees['TailleFamille'] = donnees['Parch'] + donnees['SibSp'] + 1 donnees.TailleFamille = donnees.TailleFamille.astype('int8' )
Titanic - Machine Learning from Disaster
6,587,175
train['health'] = train['Vaccinated'].astype(str)+ '_' + train['Dewormed'].astype(str)+ '_' + train['Sterilized'].astype(str)+ '_' + train['Health'].astype(str) test['health'] = test['Vaccinated'].astype(str)+ '_' + test['Dewormed'].astype(str)+ '_' + test['Sterilized'].astype(str)+ '_' + test['Health'].astype(str) m...
donnees['Pont'] = donnees.Cabin.str.extract('([A-Za-z])', expand=False) donnees.Pont = donnees.Pont.fillna('Na') pd.crosstab(donnees.Pont, np.ones(donnees.shape[0]))
Titanic - Machine Learning from Disaster
6,587,175
train['Quantity'].value_counts().head(10 )<sort_values>
donnees['TicketNum'] = donnees.Ticket.replace(regex=r'([^0-9]+)',value='') donnees.Ticket = donnees.Ticket.replace(regex=r'([^a-zA-Z]+)',value='') donnees.Ticket = donnees.Ticket.replace({r'^(CASOTON|SOTONO|STONO|STONOQ)$':'SOTONOQ', r'^(SC|SCParis)$':'SCPARIS', r'^FCC$':'FC', r'^$':'Vide'}, regex=True )
Titanic - Machine Learning from Disaster
6,587,175
all_data.sort_values('Fee', ascending=False)[['Name', 'Description', 'Fee', 'AdoptionSpeed', 'dataset_type']].head(10 )<feature_engineering>
donnees.rename(columns={"Pclass": "Classe", "Embarked": "Port", "Cabin": "Cabine", "SibSp": "ConjointsOuFratrie", "Parch": "EnfantsOuParents", }, inplace=True )
Titanic - Machine Learning from Disaster
6,587,175
states_dict = {k: v for k, v in zip(states['StateID'], states['StateName'])} train['State_name'] = train['State'].apply(lambda x: '_'.join(states_dict[x].split())if x in states_dict else 'Unknown') test['State_name'] = test['State'].apply(lambda x: '_'.join(states_dict[x].split())if x in states_dict else 'Unknown') a...
donnees.Port = donnees.Port.fillna('Pas') donnees.Cabine = donnees.Cabine.apply(lambda x: 0 if type(x)== float else 1) donnees.head()
Titanic - Machine Learning from Disaster
6,587,175
all_data['State_name'].value_counts(normalize=True ).head()<count_values>
donnees.isnull().sum()
Titanic - Machine Learning from Disaster
6,587,175
all_data['RescuerID'].value_counts().head()<count_values>
donnees[donnees['Fare'].isnull() ]
Titanic - Machine Learning from Disaster
6,587,175
train['VideoAmt'].value_counts()<count_values>
donnees[(donnees['Port'] == 'S')&(donnees['Classe'] == 3)].Fare.median()
Titanic - Machine Learning from Disaster
6,587,175
print(F'Maximum amount of photos in {train["PhotoAmt"].max() }') train['PhotoAmt'].value_counts().head()<train_on_grid>
coefficient = 1.2 ageCalc = donnees[~donnees.Age.isna() ].groupby(['Sex','Classe'] ).agg({'Age':['mean','std']}) ageCalc.columns = ['_'.join(col ).rstrip('_')for col in ageCalc.columns] ageCalc.reset_index(inplace=True) ageCalc['borneMin'] = ageCalc.Age_mean - ageCalc.Age_std*coefficient ageCalc['borneMax'] = ageCalc...
Titanic - Machine Learning from Disaster
6,587,175
tokenizer = TweetTokenizer() vectorizer = TfidfVectorizer(ngram_range=(1, 2), tokenizer=tokenizer.tokenize) vectorizer.fit(all_data['Description'].fillna('' ).values) X_train = vectorizer.transform(train['Description'].fillna('')) rf = RandomForestClassifier(n_estimators=20) rf.fit(X_train, train['AdoptionSpeed'] )<...
ageRand = pd.DataFrame(columns=['Sex','Classe','Age']) for i in [(row.Sex,row.Classe,np.random.randint(round(row.borneMin),round(row.borneMax),size=row.nb)) for indx, row in ageCalc.iterrows() ]: calc = pd.DataFrame(columns=['Sex','Classe','Age']) calc.Age = i[2] calc.Sex = i[0] calc.Classe = i[1] ageRand = pd.concat...
Titanic - Machine Learning from Disaster
6,587,175
train['Description'] = train['Description'].fillna('') test['Description'] = test['Description'].fillna('') all_data['Description'] = all_data['Description'].fillna('') train['desc_length'] = train['Description'].apply(lambda x: len(x)) train['desc_words'] = train['Description'].apply(lambda x: len(x.split())) test[...
donnees.Age01.isna().sum()
Titanic - Machine Learning from Disaster
6,587,175
sentiment_dict = {} for filename in os.listdir('.. /input/train_sentiment/'): with open('.. /input/train_sentiment/' + filename, 'r')as f: sentiment = json.load(f) pet_id = filename.split('.')[0] sentiment_dict[pet_id] = {} sentiment_dict[pet_id]['magnitude'] = sentiment['documentSentiment']['magnitude'] sentiment_dic...
donnees.Age = donnees.Age01.values donnees.drop(columns=['AgeOld','Age01'],inplace=True )
Titanic - Machine Learning from Disaster
6,587,175
train['lang'] = train['PetID'].apply(lambda x: sentiment_dict[x]['language'] if x in sentiment_dict else 'no') train['magnitude'] = train['PetID'].apply(lambda x: sentiment_dict[x]['magnitude'] if x in sentiment_dict else 0) train['score'] = train['PetID'].apply(lambda x: sentiment_dict[x]['score'] if x in sentiment_...
listeVariblesInitiales = donnees.drop(columns=['Name'] ).columns donnees = donnees.set_index('PassengerId' ).sort_index()
Titanic - Machine Learning from Disaster
6,587,175
cols_to_use = ['Type', 'Age', 'Breed1', 'Breed2', 'Gender', 'Color1', 'Color2', 'Color3', 'MaturitySize', 'FurLength', 'Vaccinated', 'Dewormed', 'Sterilized', 'Health', 'Quantity', 'Fee', 'State', 'RescuerID', 'health', 'Free', 'score', 'VideoAmt', 'PhotoAmt', 'AdoptionSpeed', 'No_name', 'Pure_breed', 'desc_length', 'd...
donnees['TitreFamille'] = donnees.apply(lambda ligne : 'Homme' if ligne['Title'] == 'Mr' else 'Femme' if ligne['Sex'] == 'Femme' else 'Garçon' if ligne['Title'] == 'Master' else 'Homme' , axis=1) plt.figure(figsize=(14,12)) plt.title('La distribution du titre calculé pour le groupe famille',size=20) sns.countplot(x='...
Titanic - Machine Learning from Disaster
6,587,175
cat_cols = ['Type', 'Breed1', 'Breed2', 'Gender', 'Color1', 'Color2', 'Color3', 'MaturitySize', 'FurLength', 'Vaccinated', 'Dewormed', 'Sterilized', 'Health', 'State', 'RescuerID', 'No_name', 'Pure_breed', 'health', 'Free']<data_type_conversions>
donnees['GroupFamille'] = donnees.Name+'-'+\ donnees.Classe.apply(lambda x: '%1d' % x)+'-'+\ donnees.Fare.apply(lambda x: '%.3f' % x)+'-'+\ donnees.Port+'-'+donnees.TicketNum donnees.GroupFamille.unique() [:6]
Titanic - Machine Learning from Disaster
6,587,175
more_cols = [] for col1 in cat_cols: for col2 in cat_cols: if col1 != col2 and col1 not in ['RescuerID', 'State'] and col2 not in ['RescuerID', 'State']: train[col1 + '_' + col2] = train[col1].astype(str)+ '_' + train[col2].astype(str) test[col1 + '_' + col2] = test[col1].astype(str)+ '_' + test[col2].astype(str) mor...
donnees['GroupTicket'] = donnees.Classe.apply(lambda x: '%1d' % x)+'-'+\ donnees.Fare.apply(lambda x: '%.3f' % x)+'-'+\ donnees.Port+'-'+donnees.TicketNum donnees.GroupTicket.unique() [:6]
Titanic - Machine Learning from Disaster
6,587,175
%%time indexer = {} for col in cat_cols: _, indexer[col] = pd.factorize(train[col].astype(str)) for col in tqdm_notebook(cat_cols): train[col] = indexer[col].get_indexer(train[col].astype(str)) test[col] = indexer[col].get_indexer(test[col].astype(str)) <prepare_x_and_y>
donnees.drop(columns=['Name','TitreFamille','GroupFamille'], inplace=True) listeVariblesAvecGroups = donnees.columns
Titanic - Machine Learning from Disaster
6,587,175
y = train['AdoptionSpeed'] train = train.drop(['AdoptionSpeed'], axis=1 )<choose_model_class>
def conversionVariableCategorielle(donnees,variable): valeurs = list(donnees[variable].sort_values().unique()) dicoVar = {nom:indx for indx,nom in enumerate(valeurs)} dicoVarRev = {indx:nom for indx,nom in enumerate(valeurs)} donnees[variable] = donnees[variable].apply(lambda x : dicoVar[x]) return dicoVar,dicoVarRev...
Titanic - Machine Learning from Disaster
6,587,175
n_fold = 5 folds = StratifiedKFold(n_splits=n_fold, shuffle=True, random_state=15 )<split>
apprentissage = donnees[~donnees.Survived.isnull() ] apprentissage.Survived = apprentissage.Survived.astype('int8') X = apprentissage.drop(columns='Survived') y = apprentissage.Survived apprentissage.head()
Titanic - Machine Learning from Disaster
6,587,175
def train_model(X=train, X_test=test, y=y, params=None, folds=folds, model_type='lgb', plot_feature_importance=False, averaging='usual', make_oof=False): result_dict = {} if make_oof: oof = np.zeros(( len(X), 5)) prediction = np.zeros(( len(X_test), 5)) scores = [] feature_importance = pd.DataFrame() for fold_n,(train_...
test = donnees[donnees.Survived.isnull() ] test.reset_index().head()
Titanic - Machine Learning from Disaster
6,587,175
params = {'num_leaves': 512, 'objective': 'multiclass', 'max_depth': -1, 'learning_rate': 0.01, "boosting": "gbdt", "feature_fraction": 0.9, "bagging_freq": 3, "bagging_fraction": 0.9, "bagging_seed": 11, "random_state": 42, "verbosity": -1, "num_class": 5}<train_model>
X = apprentissage.drop(columns='Survived') y = apprentissage.Survived X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.112, stratify = y, random_state = 101) print(X_train.shape, y_train.shape) print(X_test.shape, y_test.shape) plt.figure(figsize=(10,6)) plt.hist(y_train,label='apprentissage');...
Titanic - Machine Learning from Disaster
6,587,175
result_dict_lgb = train_model(X=train, X_test=test, y=y, params=params, model_type='lgb', plot_feature_importance=True, make_oof=True )<train_model>
resultats = comparaisonsClassifieurs(classifieursArbresDict, X_train, X_test, y_train, y_test )
Titanic - Machine Learning from Disaster
6,587,175
xgb_params = {'eta': 0.01, 'max_depth': 9, 'subsample': 0.9, 'colsample_bytree': 0.9, 'objective': 'multi:softprob', 'eval_metric': 'merror', 'silent': True, 'nthread': 4, 'num_class': 5} result_dict_xgb = train_model(params=xgb_params, model_type='xgb', make_oof=True )<prepare_output>
classifieur = CatBoostClassifier(iterations=250, depth=3, silent=True )
Titanic - Machine Learning from Disaster
6,587,175
prediction =(result_dict_lgb['prediction'] + result_dict_xgb['prediction'] ).argmax(1) submission = pd.DataFrame({'PetID': sub.PetID, 'AdoptionSpeed': [int(i)for i in prediction]}) submission.head()<save_to_csv>
resultats = controleClassifieur(classifieur, X_train, X_test, y_train, y_test )
Titanic - Machine Learning from Disaster
6,587,175
submission.to_csv('submission.csv', index=False )<save_to_csv>
resultatsFinaux,classifieursCV = effectueValidationCroisee(classifieur, X, y, n_splits = 15 )
Titanic - Machine Learning from Disaster
6,587,175
submission.to_csv('submission.csv', index=False )<set_options>
output = pd.DataFrame({'PassengerId':test.index, 'Survived':np.zeros(test.shape[0])}) for i in range(len(classifieursCV)) : output.Survived += classifieursCV[i].predict_proba(test)[:,1] output.Survived /= len(classifieursCV) output.Survived = output.Survived.round().astype('int8') output.head()
Titanic - Machine Learning from Disaster
6,587,175
<compute_test_metric><EOS>
output.to_csv('submission008.csv',index=False )
Titanic - Machine Learning from Disaster
1,780,981
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_test_metric>
warnings.filterwarnings('ignore', category = DeprecationWarning) warnings.filterwarnings('ignore', category = FutureWarning) sns.set(style='white', context='notebook', palette='deep') plt.style.use('bmh') train=pd.read_csv('.. /input/train.csv') test=pd.read_csv('.. /input/test.csv') IDtest = test["PassengerId"] ...
Titanic - Machine Learning from Disaster
1,780,981
class OptimizedRounder(object): def __init__(self): self.coef_ = 0 def _kappa_loss(self, coef, X, y): X_p = np.copy(X) for i, pred in enumerate(X_p): if pred < coef[0]: X_p[i] = 0 elif pred >= coef[0] and pred < coef[1]: X_p[i] = 1 elif pred >= coef[1] and pred < coef[2]: X_p[i] = 2 elif pred >= coef[2] and pred < coe...
def IQR_outlier(df,n,features): outlier_indices=[] for col in features: Q1=np.percentile(df[col],25) Q3=np.percentile(df[col],75) IQR=Q3-Q1 outlier_step=1.5*IQR outlier_list_col=df[(df[col]<Q1-outlier_step)|(df[col]>Q3+outlier_step)].index print('Total Number Outliers of',col,' : ',len(outlier_list_col)) print('Perce...
Titanic - Machine Learning from Disaster
1,780,981
def rmse(actual, predicted): return sqrt(mean_squared_error(actual, predicted))<load_from_csv>
train.loc[Outliers_to_drop,num_features]
Titanic - Machine Learning from Disaster
1,780,981
%%time print('Train') train = pd.read_csv(".. /input/train/train.csv") print(train.shape) print('Test') test = pd.read_csv(".. /input/test/test.csv") print(test.shape) print('Breeds') breeds = pd.read_csv(".. /input/breed_labels.csv") print(breeds.shape) print('Colors') colors = pd.read_csv(".. /input/color_l...
dataset["Fare"].isnull().sum()
Titanic - Machine Learning from Disaster
1,780,981
target = train['AdoptionSpeed'] train_id = train['PetID'] test_id = test['PetID'] train.drop(['AdoptionSpeed', 'PetID'], axis=1, inplace=True) test.drop(['PetID'], axis=1, inplace=True )<feature_engineering>
dataset["Fare"]=dataset["Fare"].fillna(dataset["Fare"].median() )
Titanic - Machine Learning from Disaster
1,780,981
doc_sent_mag = [] doc_sent_score = [] nf_count = 0 for pet in train_id: try: with open('.. /input/train_sentiment/' + pet + '.json', 'r')as f: sentiment = json.load(f) doc_sent_mag.append(sentiment['documentSentiment']['magnitude']) doc_sent_score.append(sentiment['documentSentiment']['score']) except FileNotFoundEr...
dataset["Fare"] = dataset["Fare"].map(lambda i: np.log(i)if i > 0 else 0 )
Titanic - Machine Learning from Disaster
1,780,981
train_desc = train.Description.fillna("none" ).values test_desc = test.Description.fillna("none" ).values tfv = TfidfVectorizer(min_df=2, max_features=None, strip_accents='unicode', analyzer='word', token_pattern=r'(?u)\b\w+\b', ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, ) tfv.fit(list(train_desc)) ...
dataset['Sex']=dataset['Sex'].map({'male':0,'female':1} )
Titanic - Machine Learning from Disaster
1,780,981
train_desc = train.Description.fillna("none" ).values test_desc = test.Description.fillna("none" ).values tfv = TfidfVectorizer(min_df=3, max_features=10000, strip_accents='unicode', analyzer='word', token_pattern=r'\w{1,}', ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, stop_words = 'english') tfv.fit(l...
print('Number of Null entries: ',dataset['Embarked'].isnull().sum()) print('Most common dock: ',dataset.Embarked.mode() [0] )
Titanic - Machine Learning from Disaster
1,780,981
vertex_xs = [] vertex_ys = [] bounding_confidences = [] bounding_importance_fracs = [] dominant_blues = [] dominant_greens = [] dominant_reds = [] dominant_pixel_fracs = [] dominant_scores = [] label_descriptions = [] label_scores = [] nf_count = 0 nl_count = 0 for pet in train_id: try: with open('.. /input/train_metad...
display(dataset.Cabin.shape) print('Number of null values : ', dataset.Cabin.isnull().sum()) print('Percentage of null values : ', round(dataset.Cabin.isnull().sum() /dataset.Cabin.shape[0]*100),'%' )
Titanic - Machine Learning from Disaster
1,780,981
%%time train.drop(['Name', 'RescuerID', 'Description'], axis=1, inplace=True) test.drop(['Name', 'RescuerID', 'Description'], axis=1, inplace=True )<data_type_conversions>
dataset.isnull().sum()
Titanic - Machine Learning from Disaster
1,780,981
numeric_cols = ['Age', 'Quantity', 'Fee', 'VideoAmt', 'PhotoAmt', 'AdoptionSpeed', 'doc_sent_mag', 'doc_sent_score', 'dominant_score', 'dominant_pixel_frac', 'dominant_red', 'dominant_green', 'dominant_blue', 'bounding_importance', 'bounding_confidence', 'vertex_x', 'vertex_y', 'label_score'] + ['svd_{}'.format(i)for i...
index_NaN_age = dataset["Age"][dataset.Age.isnull() ].index for i in index_NaN_age : age_med = dataset["Age"].median() age_pred = dataset["Age"][(( dataset['SibSp'] == dataset['SibSp'][i])&(dataset['Parch'] == dataset['Parch'][i])&(dataset['Pclass'] == dataset['Pclass'][i])) ].median() if not np.isnan(age_pred): datase...
Titanic - Machine Learning from Disaster
1,780,981
n_repeats = 2 n_splits = 5 def run_cv_model(train, test, target, model_fn, params={}, eval_fn=None, label='model'): kf = RepeatedStratifiedKFold(n_splits=n_splits, random_state=42, n_repeats = n_repeats) fold_splits = kf.split(train, target) cv_scores = [] qwk_scores = [] pred_full_test = 0 pred_train = np.zeros(( tr...
dataset.isnull().sum()
Titanic - Machine Learning from Disaster
1,780,981
optR = OptimizedRounder() coefficients_ = np.mean(results['coefficients'], axis=0) print(coefficients_) train_predictions = [r[0] for r in results['train']] train_predictions = optR.predict(train_predictions, coefficients_ ).astype(int) Counter(train_predictions )<predict_on_test>
print('Mean : ', dataset[['Cabin','Survived']].groupby('Cabin' ).mean()) print('Count : ', dataset[['Cabin','Survived']].groupby('Cabin' ).count() )
Titanic - Machine Learning from Disaster
1,780,981
optR = OptimizedRounder() test_predictions = [r[0] for r in results['test']] test_predictions = optR.predict(test_predictions, coefficients_ ).astype(int) Counter(test_predictions )<create_dataframe>
dataset['Title']=pd.Series([i.split(',')[1].split('.')[0].strip() for i in dataset.Name] )
Titanic - Machine Learning from Disaster
1,780,981
pd.DataFrame(sk_cmatrix(target, train_predictions), index=list(range(5)) , columns=list(range(5)) )<compute_test_metric>
dataset["Title"] = dataset["Title"].replace(['Lady', 'the Countess','Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') dataset["Title"] = dataset["Title"].replace(['Ms', 'Mlle'], 'Miss') dataset["Title"] = dataset["Title"].replace(['Mme'], 'Mrs' )
Titanic - Machine Learning from Disaster
1,780,981
quadratic_weighted_kappa(target, train_predictions )<compute_test_metric>
Ticket=[] for i in list(dataset['Ticket']): if i.isdigit() : Ticket.append('X') else: Ticket.append(i.split(' ')[0]) dataset['Ticket']=Ticket
Titanic - Machine Learning from Disaster
1,780,981
rmse(target, [r[0] for r in results['train']] )<prepare_output>
Ticket = [] for i in list(dataset.Ticket): if not i.isdigit() : Ticket.append(i.replace(".","" ).replace("/","" ).strip()) else: Ticket.append(i) dataset['Ticket']=Ticket
Titanic - Machine Learning from Disaster
1,780,981
submission = pd.DataFrame({'PetID': test_id, 'AdoptionSpeed': test_predictions}) submission.head()<save_to_csv>
dataset = pd.get_dummies(dataset, columns = ["Cabin"], prefix="Cab") dataset = pd.get_dummies(dataset, columns = ["Embarked"], prefix="Em") dataset = pd.get_dummies(dataset, columns = ["Fsize"], prefix="Fam") dataset = pd.get_dummies(dataset, columns = ["Pclass"], prefix="Pc") dataset = pd.get_dummies(dataset, colu...
Titanic - Machine Learning from Disaster
1,780,981
submission.to_csv('submission.csv', index=False )<save_to_csv>
dataset.drop(labels = ['Name','PassengerId'], axis = 1, inplace = True )
Titanic - Machine Learning from Disaster
1,780,981
submission.to_csv('submission.csv', index=False )<set_options>
Y_train=dataset[:train_len]['Survived'] X_train=data[:train_len] test=data[train_len:]
Titanic - Machine Learning from Disaster
1,780,981
warnings.filterwarnings("ignore") %matplotlib inline<define_variables>
Titanic - Machine Learning from Disaster
1,780,981
LABELS = ["isFraud"] all_files = glob.glob(".. /input/lgmodels/*.csv") all_files<load_from_csv>
from sklearn.ensemble import RandomForestClassifier, VotingClassifier 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, Stra...
Titanic - Machine Learning from Disaster
1,780,981
outs = [pd.read_csv(f, index_col=0)for f in all_files] concat_sub = pd.concat(outs, axis=1) cols = list(map(lambda x: "m" + str(x), range(len(concat_sub.columns)))) concat_sub.columns = cols concat_sub.reset_index(inplace=True )<feature_engineering>
kfold = StratifiedKFold(n_splits=10 )
Titanic - Machine Learning from Disaster
1,780,981
rank = np.tril(concat_sub.iloc[:,1:].corr().values,-1) m =(rank>0 ).sum() m_gmean, s = 0, 0 for n in range(min(rank.shape[0],m)) : mx = np.unravel_index(rank.argmin() , rank.shape) w =(m-n)/(m+n) print(w) m_gmean += w*(np.log(concat_sub.iloc[:,mx[0]+1])+np.log(concat_sub.iloc[:,mx[1]+1])) /2 s += w rank[mx] = 1 m_g...
random_state = 42 classifiers = [] classifiers.append(SVC(random_state=random_state)) classifiers.append(DecisionTreeClassifier(random_state=random_state)) classifiers.append(RandomForestClassifier(random_state=random_state)) classifiers.append(KNeighborsClassifier()) classifiers.append(LogisticRegression(random_state...
Titanic - Machine Learning from Disaster
1,780,981
concat_sub['isFraud'] = m_gmean concat_sub[['TransactionID','isFraud']].to_csv('stack_gmean.csv', index=False, float_format='%.4g' )<set_options>
SVMC = SVC(probability=True) svc_param_grid = {'kernel': ['rbf'], 'gamma': [ 0.001, 0.01, 0.1, 1],'C': [1, 10, 50, 100,200,300, 1000]} gsSVMC = GridSearchCV(SVMC,param_grid = svc_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1) gsSVMC.fit(X_train,Y_train) SVMC_best = gsSVMC.best_estimator_ gsSVMC.be...
Titanic - Machine Learning from Disaster
1,780,981
warnings.filterwarnings('ignore' )<define_variables>
DTC = DecisionTreeClassifier() dt_param_grid = {'max_features': ['auto', 'sqrt', 'log2'],'min_samples_split': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 'min_samples_leaf':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],'random_state':[42]} gsDTC = GridSearchCV(DTC,param_grid = dt_param_grid, cv=kfold, scoring="accuracy", n...
Titanic - Machine Learning from Disaster
1,780,981
def seed_everything(seed=0): random.seed(seed) np.random.seed(seed )<define_variables>
RFC = RandomForestClassifier() rf_param_grid = {"max_depth": [None],"max_features": [1, 3, 10],"min_samples_split": [2, 3, 10],"min_samples_leaf": [1, 3, 10], "bootstrap": [False],"n_estimators" :[100,300],"criterion": ["gini"]} gsRFC = GridSearchCV(RFC,param_grid = rf_param_grid, cv=kfold, scoring="accuracy", n_jobs= ...
Titanic - Machine Learning from Disaster
1,780,981
SEED = 42 seed_everything(SEED) TARGET = 'isFraud' START_DATE = datetime.datetime.strptime('2017-11-30', '%Y-%m-%d' )<init_hyperparams>
LRC = LogisticRegression() lr_param_grid = {'penalty':['l1', 'l2'],'C': np.logspace(0, 4, 10)} gsLRC=GridSearchCV(LRC,param_grid=lr_param_grid,cv=kfold,scoring='accuracy', n_jobs= 4, verbose = 1) gsLRC.fit(X_train,Y_train) LRC_best = gsLRC.best_estimator_ gsLRC.best_score_
Titanic - Machine Learning from Disaster
1,780,981
lgb_params = { 'objective':'binary', 'boosting_type':'gbdt', 'metric':'auc', 'n_jobs':-1, 'learning_rate':0.01, 'num_leaves': 2**8, 'max_depth':-1, 'tree_learner':'serial', 'colsample_bytree': 0.7, 'subsample_freq':1, 'subsample':0.7, 'n_estimators':20000, 'max_bin':255, 'verbose':-1, 'seed': SEED, 'early_stopping_roun...
KNNC = KNeighborsClassifier() knn_param_grid = {'n_neighbors':[3, 4, 5, 6, 7, 8],'leaf_size':[1, 2, 3, 5], 'weights':['uniform', 'distance'],'algorithm':['auto', 'ball_tree','kd_tree','brute']} gsKNNC=GridSearchCV(KNNC,param_grid=knn_param_grid,cv=kfold,scoring='accuracy',n_jobs=4,verbose=1) gsKNNC.fit(X_train,Y_train...
Titanic - Machine Learning from Disaster
1,780,981
print('Load Data') train_df = pd.read_pickle('.. /input/ieee-data-minification/train_transaction.pkl') train_df['DT_M'] = train_df['TransactionDT'].apply(lambda x:(START_DATE + datetime.timedelta(seconds = x))) train_df['DT_M'] =(train_df['DT_M'].dt.year-2017)*12 + train_df['DT_M'].dt.month test_df = train_df[train_...
votingC = VotingClassifier(estimators=[('svc', SVMC_best),('rfc', RFC_best),('lrc', LRC_best)], voting='soft', n_jobs=4) votingC = votingC.fit(X_train, Y_train )
Titanic - Machine Learning from Disaster
1,780,981
for col in list(train_df): if train_df[col].dtype=='O': print(col) train_df[col] = train_df[col].fillna('unseen_before_label') test_df[col] = test_df[col].fillna('unseen_before_label') train_df[col] = train_df[col].astype(str) test_df[col] = test_df[col].astype(str) le = LabelEncoder() le.fit(list(train_df[col])+l...
Titanic - Machine Learning from Disaster
1,780,981
rm_cols = [ 'TransactionID','TransactionDT', TARGET, 'DT_M' ] rm_cols += ['V'+str(i)for i in range(1,340)] features_columns = [col for col in list(train_df)if col not in rm_cols] <define_variables>
test_Survived = votingC.predict(test ).astype(int) submission = pd.DataFrame({ "PassengerId": IDtest, "Survived": test_Survived }) submission.to_csv('Titanic_test_prediction_V9.csv', index=False )
Titanic - Machine Learning from Disaster
1,780,981
<train_model><EOS>
accuracy_score(Y_train,votingC.predict(X_train))
Titanic - Machine Learning from Disaster
11,108,910
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<prepare_x_and_y>
import numpy as np import pandas as pd import matplotlib.pyplot as plt
Titanic - Machine Learning from Disaster
11,108,910
print(' print('KFold training...') folds = KFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED) X,y = train_df[features_columns], train_df[TARGET] P = test_df[features_columns] RESULTS['kfold'] = 0 for fold_,(trn_idx, val_idx)in enumerate(folds.split(X, y)) : print('Fold:',fold_+1) tr_x, tr_y = X.iloc[trn_idx,:...
ds = pd.read_csv("/kaggle/input/titanic/train.csv" )
Titanic - Machine Learning from Disaster
11,108,910
print(' print('StratifiedKFold training...') folds = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED) X,y = train_df[features_columns], train_df[TARGET] P = test_df[features_columns] RESULTS['stratifiedkfold'] = 0 for fold_,(trn_idx, val_idx)in enumerate(folds.split(X, y, groups=y)) : print('Fold:'...
Y = ds.Survived X = ds.drop(['PassengerId','Name','Survived'],axis = 1 )
Titanic - Machine Learning from Disaster
11,108,910
print(' print('LBO training...') train_df['DT_M'] = train_df['TransactionDT'].apply(lambda x:(START_DATE + datetime.timedelta(seconds = x))) train_df['DT_M'] =(train_df['DT_M'].dt.year-2017)*12 + train_df['DT_M'].dt.month main_train_set = train_df[train_df['DT_M']<(train_df['DT_M'].max())].reset_index(drop=True) val...
print(X.isnull().sum() )
Titanic - Machine Learning from Disaster
11,108,910
print(' print('GroupKFold timeblocks split training...') folds = GroupKFold(n_splits=N_SPLITS) train_df['groups'] = train_df['TransactionDT'].apply(lambda x:(START_DATE + datetime.timedelta(seconds = x))) train_df['groups'] =(train_df['groups'].dt.year-2017)*12 + train_df['groups'].dt.month X,y = train_df[features_c...
X_temp = X Sex_Embarked = {"Sex":{"male": 1.,"female": 0.}, "Embarked":{"S": 0.,"C": 1.,"Q": 2.}} X_temp = X_temp.replace(Sex_Embarked, inplace=False) CT = ColumnTransformer(transformers = [('encoder',OrdinalEncoder() ,['Ticket'])],remainder = 'passthrough') X_temp = pd.DataFrame(CT.fit_transform(X_temp.drop(['Cabin'...
Titanic - Machine Learning from Disaster
11,108,910
print(' print('GroupKFold uID split training...') folds = GroupKFold(n_splits=N_SPLITS) train_df['groups'] = '' for col in ['card1','card2','card3','card5','addr1','addr2',]: train_df['groups'] = '_' + train_df[col].astype(str) X,y = train_df[features_columns], train_df[TARGET] split_groups = train_df['groups'] P = ...
imputer = SimpleImputer(missing_values=np.nan, strategy = 'mean') ds.Age = imputer.fit_transform(ds.Age.values.reshape(-1,1)) X.Age = imputer.fit_transform(X.Age.values.reshape(-1,1))
Titanic - Machine Learning from Disaster
11,108,910
print(' print('Intermediate results...') final_df = [] for current_strategy in list(RESULTS.iloc[:,2:]): auc_score = metrics.roc_auc_score(RESULTS[TARGET], RESULTS[current_strategy]) final_df.append([current_strategy, auc_score]) final_df = pd.DataFrame(final_df, columns=['Stategy', 'Result']) final_df.sort_values(...
ds.Embarked = SimpleImputer(missing_values=np.nan, strategy = 'most_frequent' ).fit_transform(ds.Embarked.values.reshape(-1,1)) X.Embarked = SimpleImputer(missing_values=np.nan, strategy = 'most_frequent' ).fit_transform(X.Embarked.values.reshape(-1,1))
Titanic - Machine Learning from Disaster
11,108,910
print(' print('LBO full set training...') train_df['DT_M'] = train_df['TransactionDT'].apply(lambda x:(START_DATE + datetime.timedelta(seconds = x))) train_df['DT_M'] =(train_df['DT_M'].dt.year-2017)*12 + train_df['DT_M'].dt.month main_train_set = train_df[train_df['DT_M']<(train_df['DT_M'].max())].reset_index(drop=T...
X_Cabins = X.Cabin.dropna().str.contains('C',regex = False) X_Cabins = X.Cabin[X_Cabins.loc[X_Cabins == True].index] print(X_Cabins )
Titanic - Machine Learning from Disaster