kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
5,888,223
glove = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' paragram = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' wiki_news = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def load_embed(file): def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') if file...
df_test["Age"].isnull().sum()
Titanic - Machine Learning from Disaster
5,888,223
glove_embeddings = load_embed(glove) print(len(glove_embeddings))<concatenate>
df_train["Embarked"].isnull().sum()
Titanic - Machine Learning from Disaster
5,888,223
train = df_train['question_text'] test = df_test['question_text'] df = pd.concat([train ,test]) vocab = build_vocab(df )<compute_test_metric>
df_train["Embarked"].fillna("S", inplace = True)
Titanic - Machine Learning from Disaster
5,888,223
print("oov : Glove ") oov = check_coverage(vocab, glove_embeddings) add_lower(glove_embeddings, vocab) print("oov : ") oov = check_coverage(vocab, glove_embeddings) <string_transform>
df_test["Embarked"].isnull().sum()
Titanic - Machine Learning from Disaster
5,888,223
def known_contractions(embed): known = [] for contract in contraction_mapping: if contract in embed: known.append(contract) return known def clean_contractions(text, mapping): specials = ["’", "‘", "´", "`"] for s in specials: text = text.replace(s, "'") text = ' '.join([mapping[t] if t in mapping else t for t in tex...
df_train["Age_Categ"] = 0 df_test["Age_Categ"] = 0
Titanic - Machine Learning from Disaster
5,888,223
def clean_special_chars(text, punct, puncts, mapping): for p in mapping: text = text.replace(p, mapping[p]) for p in punct: text = text.replace(p, f' {p} ') for p in puncts: text = text.replace(p, f' {p} ') specials = {'\u200b': ' ', '…': '...', '\ufeff': '', 'करना': '', 'है': ''} for s in specials: text = text.repl...
def category_age(x): if x < 10: return 0 elif x < 20: return 1 elif x < 30: return 2 elif x < 40: return 3 elif x < 50: return 4 elif x < 60: return 5 elif x < 70: return 6 else: return 7
Titanic - Machine Learning from Disaster
5,888,223
def correct_spelling(x, dic): for word in dic.keys() : x = x.replace(word, dic[word]) return x<categorify>
df_train["Age_Categ"] = df_train["Age"].apply(category_age) df_test["Age_Categ"] = df_test["Age"].apply(category_age)
Titanic - Machine Learning from Disaster
5,888,223
def clean_numbers(x): x = re.sub('[0-9]{5,}', ' x = re.sub('[0-9]{4}', ' x = re.sub('[0-9]{3}', ' x = re.sub('[0-9]{2}', ' return x<feature_engineering>
df_train.drop(["Age"], axis = 1 ,inplace = True) df_test.drop(["Age"], axis = 1, inplace = True )
Titanic - Machine Learning from Disaster
5,888,223
df_train['question_text'] = df_train['question_text'].apply(lambda x: x.lower()) df_train['question_text'] = df_train['question_text'].apply(lambda x: clean_contractions(x, contraction_mapping)) df_train['question_text'] = df_train['question_text'].apply(lambda x: clean_special_chars(x, punct, puncts, punct_mapping)) ...
df_train["Initial"] = df_train["Initial"].map({"Master" : 0, "Miss" : 1, "Mr" : 2, "Mrs" : 3, "Other" : 4}) df_test["Initial"] = df_test["Initial"].map({"Master" : 0, "Miss" : 1, "Mr" : 2, "Mrs" : 3, "Other" : 4} )
Titanic - Machine Learning from Disaster
5,888,223
df_test['question_text'] = df_test['question_text'].apply(lambda x: x.lower()) df_test['question_text'] = df_test['question_text'].apply(lambda x: clean_contractions(x, contraction_mapping)) df_test['question_text'] = df_test['question_text'].apply(lambda x: clean_special_chars(x, punct,puncts, punct_mapping)) df_test...
df_train["Embarked"].value_counts()
Titanic - Machine Learning from Disaster
5,888,223
train = df_train['question_text'] test = df_test['question_text'] df = pd.concat([train ,test]) vocab = build_vocab(df) print("oov : ") oov = check_coverage(vocab, glove_embeddings )<split>
df_train["Embarked"] = df_train["Embarked"].map({"C" : 0, "Q" : 1, "S" : 2}) df_test["Embarked"] = df_test["Embarked"].map({"C" : 0, "Q" : 1, "S" : 2} )
Titanic - Machine Learning from Disaster
5,888,223
train_df, test2_df = train_test_split(df_train, test_size=0.04, random_state=123) train_df, valid_df = train_test_split(train_df, test_size=0.00001, random_state=123) train_df=train_df.reset_index(drop=True) valid_df=valid_df.reset_index(drop=True) test2_df=test2_df.reset_index(drop=True) X_train=train_df['questio...
df_train["Sex"] = df_train["Sex"].map({"female" : 0, "male" : 1}) df_test["Sex"] = df_test["Sex"].map({"female" : 0, "male" : 1} )
Titanic - Machine Learning from Disaster
5,888,223
embedding_dim = 300 max_features = 120000 maxlen = 70 tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(X_train.tolist() + X_valid.tolist() + X_test2.tolist() + X_test.tolist() )<define_variables>
heatmap_data = df_train[["Survived", "Pclass", "Sex", "Fare", "Embarked", "FamilySize", "Initial", "Age_Categ"]]
Titanic - Machine Learning from Disaster
5,888,223
vocab_size = len(tokenizer.word_index)+ 1 print(vocab_size )<feature_engineering>
df_train = pd.get_dummies(df_train, columns = ["Initial"], prefix = "Initial") df_test = pd.get_dummies(df_test, columns = ["Initial"], prefix = "Initial" )
Titanic - Machine Learning from Disaster
5,888,223
def index_to_matrix(embeddings_index,word_index): embedding_matrix = np.zeros(( len(word_index)+ 1, embedding_dim)) for word, i in word_index.items() : embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return(embedding_matrix )<prepare_x_and_y>
df_train = pd.get_dummies(df_train, columns = ["Embarked"], prefix = "Embarked") df_test = pd.get_dummies(df_test, columns = ["Embarked"], prefix = "Embarked" )
Titanic - Machine Learning from Disaster
5,888,223
glove_embedding_matrix=index_to_matrix(glove_embeddings,tokenizer.word_index) embedding_matrix=glove_embedding_matrix<import_modules>
df_train.drop(["PassengerId", "Name", "SibSp", "Parch", "Ticket", "Cabin"], axis = 1, inplace = True) df_test.drop(["PassengerId", "Name", "SibSp", "Parch", "Ticket", "Cabin"], axis = 1, inplace = True )
Titanic - Machine Learning from Disaster
5,888,223
from keras.models import Model from keras.layers import Dense, Embedding, Bidirectional, CuDNNGRU,CuDNNLSTM, GlobalAveragePooling1D, GlobalMaxPooling1D, concatenate, Input, Dropout, Add from keras.optimizers import Adam from keras.models import Sequential from keras import layers import keras.callbacks from keras.optim...
kfold = StratifiedKFold(n_splits=10 )
Titanic - Machine Learning from Disaster
5,888,223
def make_model(embedding_matrix, maxlen, embed_size=300, loss='binary_crossentropy'): inp = Input(shape=(maxlen,)) inp2 = Input(shape=(1,)) x = Embedding(vocab_size, embed_size, weights=[embedding_matrix], trainable=False )(inp) x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x) x = Dropout(0.2 )(x) x = Bid...
df_train["Survived"] = df_train["Survived"].astype(int) Y_train = df_train["Survived"] X_train = df_train.drop(labels = ["Survived"],axis = 1 )
Titanic - Machine Learning from Disaster
5,888,223
model = make_model(embedding_matrix,maxlen=70 )<choose_model_class>
random_state = 2 classifiers = [] classifiers.append(SVC(random_state = random_state)) classifiers.append(DecisionTreeClassifier(random_state = random_state)) classifiers.append(AdaBoostClassifier(DecisionTreeClassifier(random_state = random_state), random_state = random_state, learning_rate = 0.1)) classifiers.append(...
Titanic - Machine Learning from Disaster
5,888,223
seed = 7 n_splits=5 np.random.seed(seed) kfold = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed )<split>
DTC = DecisionTreeClassifier() adaDTC = AdaBoostClassifier(DTC, random_state = 7) ada_param_grid = {"base_estimator__criterion" : ["gini", "entropy"], "base_estimator__splitter": ["best", "random"], "algorithm": ["SAMME", "SAMME.R"], "n_estimators": [1,2], "learning_rate": [0.0001,0.001, 0.01, 0.1, 0.2, 0.3, 1.5]} gsa...
Titanic - Machine Learning from Disaster
5,888,223
i=1 maxlength={} maxl={} for train, valid in kfold.split(X_train, y_train): if i <=n_splits: maxl[i]=X_len_train[train].max() print(X_len_train[train]) maxlength[i]=int(np.quantile(X_len_train[train],0.999)) print("Running Fold", i, "/", n_splits) print("split 99.9 percentile length",maxlength[i],"split max length",m...
ExtC = ExtraTreesClassifier() ex_param_grid = {"max_depth": [None], "max_features": [1,2,10], "min_samples_split": [2, 3, 10], "min_samples_leaf": [1,3,10], "bootstrap": [False], "n_estimators": [100, 300], "criterion": ["gini"]} gsExtC = GridSearchCV(ExtC, param_grid = ex_param_grid, cv = kfold, scoring = "accuracy", ...
Titanic - Machine Learning from Disaster
5,888,223
y_pred={} y_pred_test={} count=0 for i in np.arange(1, n_splits+1, 1): try: model.load_weights(str("Model")+ str(i)) print(str("Model")+ str(i)) x_test2 = tokenizer.texts_to_sequences(X_test2) x_test = tokenizer.texts_to_sequences(X_test) x_test2 = pad_sequences(x_test2, padding='post', maxlen=maxlength[i]) x_test =...
RFC = RandomForestClassifier() rf_param_grid = {"max_depth": [None], "max_features": [1,3,10], "min_samples_split": [2,3,10], "min_samples_leaf": [1,2,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
5,888,223
y_pred_final={} y_pred_test_final={} for i in np.arange(1, count+1, 1): if(i == 1): y_pred_final=y_pred[i] y_pred_test_final=y_pred_test[i] else: y_pred_final=y_pred_final + y_pred[i] y_pred_test_final=y_pred_test_final + y_pred_test[i] y_pred_final=y_pred_final/count y_pred_test_final=y_pred_test_final/count <find_be...
GBC = GradientBoostingClassifier() gb_param_grid = {"loss": ["deviance"], "n_estimators": [100,200,300], "learning_rate": [0.1, 0.05, 0.01], "max_depth": [4, 8], "min_samples_leaf": [100,150], "max_features": [0.3, 0.1]} gsGBC = GridSearchCV(GBC,param_grid = gb_param_grid, cv = kfold, scoring = "accuracy", n_jobs = 4, ...
Titanic - Machine Learning from Disaster
5,888,223
print("Final Model on hold out") model_f1_score={} for thresh in np.arange(0.1, 0.91, 0.01): thresh = np.round(thresh, 2) model_f1_score[thresh]=sklearn.metrics.f1_score(y_test2,(y_pred_final>=thresh ).astype(int)) model_cutoff=max(model_f1_score, key=model_f1_score.get) print("Max F1 score is {1} found at threshold...
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.b...
Titanic - Machine Learning from Disaster
5,888,223
y_pred_test2_final_class =(y_pred_final >= model_cutoff ).astype(int) print(y_test2.sum()) print(y_pred_test2_final_class.sum()) print(sklearn.metrics.f1_score(y_test2, y_pred_test2_final_class)) print('classification report') print(classification_report(y_test2, y_pred_test2_final_class)) print('Confusion matrix')...
votingC = VotingClassifier(estimators = [("rfc", RFC_best),("extc", ExtC_best), ("svc", SVMC_best),("adac", ada_best), ("gbc", GBC_best)], voting = "soft", n_jobs = 4) votingC = votingC.fit(X_train, Y_train )
Titanic - Machine Learning from Disaster
5,888,223
df=pd.DataFrame(columns=['text','y_actual', 'y_pred','y_pred_prob','length'] )<feature_engineering>
submission = pd.read_csv(".. /input/gender_submission.csv" )
Titanic - Machine Learning from Disaster
5,888,223
df['text'] = X_test2 df['y_pred'] =y_pred_test2_final_class df['y_pred_prob'] =y_pred_final df['length'] =X_len_test2 df['y_actual'] =y_test2<filter>
df_test["Fare"].fillna("35.6271", inplace = True) X_test = df_test.values
Titanic - Machine Learning from Disaster
5,888,223
df[(df.y_actual != df.y_pred)&(df.y_pred_prob >=(model_cutoff-0.3)) &(df.y_pred_prob <=(model_cutoff + 0.3)) ]['text'].values<set_options>
prediction = votingC.predict(X_test )
Titanic - Machine Learning from Disaster
5,888,223
wordcloud = WordCloud(width=1600, height=800, max_font_size=200 ).generate(FN_text) plt.figure(figsize=(12,10)) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()<count_values>
submission["Survived"] = prediction
Titanic - Machine Learning from Disaster
5,888,223
counts = Counter(FN_text.split()) print(counts )<count_values>
submission.to_csv("./The_first_submission.csv", index = False )
Titanic - Machine Learning from Disaster
5,267,184
counts = Counter(FP_text.split()) print(counts )<data_type_conversions>
dataset = pd.read_csv(".. /input/train.csv") dataset.head()
Titanic - Machine Learning from Disaster
5,267,184
df_test['prediction']=(y_pred_test_final >= model_cutoff ).astype(int )<drop_column>
dataset.Sex = dataset.Sex.replace("female", 0) dataset.Sex = dataset.Sex.replace("male", 1 )
Titanic - Machine Learning from Disaster
5,267,184
df_test=df_test.drop(['question_text'], axis=1) df_test=df_test.drop(['length'], axis=1 )<save_to_csv>
y = dataset.Survived features = ["Sex", "Age", "Parch", "SibSp"] X = dataset[features]
Titanic - Machine Learning from Disaster
5,267,184
df_test.to_csv(r'submission.csv', index = False )<feature_engineering>
X_tr, X_val, y_tr, y_val = train_test_split(X, y, random_state = 0 )
Titanic - Machine Learning from Disaster
5,267,184
def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True SEED = 999 seed_everything(SEED )<categorify>
my_model = XGBRegressor(n_estimators = 1000, learning_rate = 0.01) my_pipeline = Pipeline(steps=[ ("model", my_model) ] )
Titanic - Machine Learning from Disaster
5,267,184
def _one_sample_positive_class_precisions(scores, truth): num_classes = scores.shape[0] pos_class_indices = np.flatnonzero(truth > 0) if not len(pos_class_indices): return pos_class_indices, np.zeros(0) retrieved_classes = np.argsort(scores)[::-1] class_rankings = np.zeros(num_classes, dtype=np.int) class_rankings...
my_pipeline.fit(X_tr, y_tr, model__early_stopping_rounds = 10, model__eval_set = [(X_val, y_val)], model__verbose = False) preds = my_pipeline.predict(X_val )
Titanic - Machine Learning from Disaster
5,267,184
TRAIN_MODE = False CONTINUOUS_TRAIN = True MIXMATCH_SSL = 0<define_variables>
mean_absolute_error(y_val, preds )
Titanic - Machine Learning from Disaster
5,267,184
DATA = Path('.. /input/freesound-audio-tagging-2019') PREPROCESSED_N1K = Path('.. /input/fat2019_prep_mels1') PREPROCESSED_MP = Path('.. /input/fat2019-multipreprocessed-package') LAST_WEIGHTS = Path('.. /input/fat19-fastai-weights-of-mixup-mp') WORK = Path('work') Path(WORK ).mkdir(exist_ok=True, parents=True) C...
dataset2 = pd.read_csv(".. /input/test.csv") dataset2.Sex = dataset2.Sex.replace("female", 0) dataset2.Sex = dataset2.Sex.replace("male", 1) X = dataset2[features] preds2 = my_pipeline.predict(X )
Titanic - Machine Learning from Disaster
5,267,184
USE_MASK_FREQ = True MASK_FREQ_RANGE = 8 MASK_FREQ_MAX_COUNT = 3 USE_MASK_TIME = True MASK_TIME_RANGE = 8 MASK_TIME_MAX_COUNT = 3 def freq_mask(x, num=1, mask_size=10, mask_value=None, inplace=False): cloned = x.clone() if not inplace else x num_bins = cloned.shape[1] mask_value = cloned.mean() if mask_value is None el...
submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
5,267,184
class AugmentationConfig: padding_scale = 1. whitenoise = True whitenoise_level = 1e-3 pitchshift = True pitchshift_steps = 2. class PreproConfig: sr = 44100 duration = 2. n_out = 128 n_mels = 128 n_fft = n_mels * 20 hop_len = int(sr * duration // n_out) sample_size = int(sr * duration) padding_size = int(sample_s...
submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
6,346,527
class MPLoader: cache = dict() cache_vmem_percent = 45.0 data_type = 'msp' use_augmentation = True max_of_augid = 2 def reset() : MPLoader.cache = dict() def get(fname, augmentation=False, cache=False): if fname in MPLoader.cache: data = MPLoader.cache[fname] else: data = MPLoader.load(fname, cache) if augmentation an...
trainSet = pd.read_csv('/kaggle/input/titanic/train.csv') testSet = pd.read_csv('/kaggle/input/titanic/test.csv') y = trainSet['Survived'] trainSet1 = trainSet.copy() testSet1 = testSet.copy() combineData = list([trainSet1, testSet1]) print(1 )
Titanic - Machine Learning from Disaster
6,346,527
TIME_DIM = 128 def open_fat2019_image(fn, convert_mode, after_open)->Image: fname = '/'.join(fn.split('/')[-2:]) x = MPLoader.get(fname, augmentation=True) base_dim, time_dim = x.shape if time_dim < TIME_DIM: x2 = torch.zeros(( base_dim,TIME_DIM), dtype=x.dtype) crop = random.randint(0, TIME_DIM - time_dim) x2[:, c...
for data in combineData: data.drop(columns = ['PassengerId', 'Name', 'Ticket', 'Fare', 'Cabin'], inplace = True) data['Sex'] = data['Sex'].map({'male':0, 'female':1}) def age(x): if 0<x<=12.0 : return 1 elif 12.0<x<=18.0 : return 2 elif 18.0<x<=40.0 : return 3 elif 40.0<x<=60.0 : return 4 elif 60.0<x : return 5 else:...
Titanic - Machine Learning from Disaster
6,346,527
BATCH_SIZE = 48 tfms = get_transforms(do_flip=True, max_rotate=0, max_lighting=0.1, max_zoom=0, max_warp=0.) src =(ImageList.from_df(df_train, WORK, folder='') .split_none() .label_from_df(label_delim=',') ) data =(src.transform(tfms, size=128) .databunch(bs=BATCH_SIZE ).normalize(imagenet_stats) ) if MIXMATCH_SSL >...
x = trainSet1.drop(columns = ['Survived']) y = trainSet1['Survived'] x.head()
Titanic - Machine Learning from Disaster
6,346,527
if TRAIN_MODE: data.show_batch(3 )<compute_test_metric>
train_x,test_x,train_y,test_y = train_test_split(x, y, test_size = 0.2, random_state = 1 )
Titanic - Machine Learning from Disaster
6,346,527
def lwlrap(y_pred,y_true): score, weight = calculate_per_class_lwlrap(y_true.cpu().numpy() , y_pred.cpu().numpy()) lwlrap =(score * weight ).sum() return torch.from_numpy(np.array(lwlrap))<import_modules>
cv_scores = [] maxDepths = [i for i in range(2,10)] for maxDepth in maxDepths: model = DecisionTreeClassifier(max_depth=maxDepth) scores = cross_val_score(model, train_x, train_y, cv = 5) cv_score = scores.mean() print('maxDepth={},score={:.3f}'.format(maxDepth, cv_score)) cv_scores.append(cv_score )
Titanic - Machine Learning from Disaster
6,346,527
class MixMatchCallback(LearnerCallback): def __init__(self, learn:Learner, unlabeled_dl:DeviceDataLoader, temperature:float=0.5, n_augment:int=2, alpha:float=0.75, lambda_u:float=100, rampup:int=16): super().__init__(learn) self.unlabeled_dl = unlabeled_dl self.T = temperature self.K = n_augment self.beta_distirb = to...
depth = maxDepths[np.argmax(cv_scores)] model = DecisionTreeClassifier(max_depth=depth) model.fit(train_x,train_y) score = model.score(test_x,test_y) print(score )
Titanic - Machine Learning from Disaster
6,346,527
<define_search_model><EOS>
id = testSet['PassengerId'] id = id.as_matrix() result = list(zip(id,model.predict(testSet1))) df = pd.DataFrame(result, columns = ['PassengerId', 'Survived']) df.to_csv('decisionTreeResult.csv', index = False) print(df.shape) df.head()
Titanic - Machine Learning from Disaster
1,919,210
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_test_metric>
input_io_dir=".. /input/titanic/" original_train_data=pd.read_csv(input_io_dir+"train.csv") original_test_data=pd.read_csv(input_io_dir+"test.csv") print('original_train_data',original_train_data.shape) print('original_test_data',original_test_data.shape )
Titanic - Machine Learning from Disaster
1,919,210
labels = df_submission.columns[1:].tolist() label_size = len(labels) def calc_P_R_AP(y_true, y_pred): P = [None] * label_size R = [None] * label_size AP = np.zeros(label_size) for i in range(label_size): P[i], R[i], _ = precision_recall_curve(y_true[:,i], y_pred[:,i]) AP[i] = average_precision_score(y_true[:,i], y_p...
input_io_dir='.. /input/titanic-competition-feature-engineering-1/' def PrepareDataSets() : passengerId=pd.read_csv(input_io_dir+"passengerId.csv",header=None) train_features=pd.read_csv(input_io_dir+"train_features.csv",header=0) train_labels=pd.read_csv(input_io_dir+"train_labels.csv",header=None) test_features=pd...
Titanic - Machine Learning from Disaster
1,919,210
def normalize_predict(y): min_pred = y.min(axis=1 ).reshape(-1,1) max_pred = y.max(axis=1 ).reshape(-1,1) return(y - min_pred)/(max_pred - min_pred )<choose_model_class>
warnings.filterwarnings("ignore", category=DeprecationWarning) def FineTuneLearningModel(learning_model, param_grid, train_features,train_labels,scoring='accuracy'): grid_search = GridSearchCV(learning_model, param_grid, scoring,cv=10) grid_search.fit(train_features.values.astype(float),train_labels.values.ravel().as...
Titanic - Machine Learning from Disaster
1,919,210
def borrowed_model(pretrained=False, **kwargs): return Classifier(**kwargs) if TRAIN_MODE: f_score = partial(fbeta, thresh=0.2) learn = cnn_learner( data, borrowed_model, pretrained=False, metrics=[lwlrap], loss_func=nn.MultiLabelSoftMarginLoss() ) if MIXMATCH_SSL > 0: if CONTINUOUS_TRAIN: learn.mixmatch(noisy_dat...
def TrainModelAndGeneratePredictionsOnTestSet(learning_model,train_features,train_labels,test_features, threshold=-1): learning_model.fit(train_features.values.astype(float),train_labels.values.ravel().astype(float)) if threshold==-1: predictions = learning_model.predict(test_features.values.astype(float)) else: if has...
Titanic - Machine Learning from Disaster
1,919,210
if TRAIN_MODE and CONTINUOUS_TRAIN: df_ap = pd.read_csv(LAST_WEIGHTS/'labels_ap.csv', index_col=0) loss_weights = torch.FloatTensor(( 1/df_ap.AP ).values ** 4 ).cuda() print(loss_weights) learn.loss_func = nn.MultiLabelSoftMarginLoss(weight=loss_weights) else: loss_weights = None<find_best_params>
def GenerateOutputFile(passengerId,predictions): output = pd.DataFrame({ 'PassengerId': passengerId, 'Survived': predictions }) output.to_csv("output.csv", index=False) passengerId = original_test_data['PassengerId'] GenerateOutputFile(passengerId,predictions )
Titanic - Machine Learning from Disaster
1,919,210
if TRAIN_MODE: learn.lr_find() learn.recorder.plot(suggestion=True )<train_model>
training_predictions = pd.DataFrame(learning_model.predict(train_features.values.astype(float))) training_predictions.iloc[:,0]=training_predictions.iloc[:,0].astype(int )
Titanic - Machine Learning from Disaster
1,919,210
if TRAIN_MODE: gc.collect() callbacks = [ SaveModelCallback(learn, every='improvement', monitor='lwlrap', name='best'), ] if CONTINUOUS_TRAIN: learn.fit_one_cycle(50, slice(1e-7,1e-4), callbacks=callbacks) else: learn.fit_one_cycle(300, 2e-2, callbacks=callbacks )<predict_on_test>
result=original_train_data.join(training_predictions!=train_labels)
Titanic - Machine Learning from Disaster
1,919,210
<save_model><EOS>
result.rename(columns={0:'Error'},inplace=True )
Titanic - Machine Learning from Disaster
537,402
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_test_metric>
import numpy as np import pandas as pd import tensorflow as tf from tensorflow.python.framework import ops import matplotlib.pyplot as plt
Titanic - Machine Learning from Disaster
537,402
if TRAIN_MODE: y_true2 = y_true.numpy() y_pred2 = y_pred.numpy() labels = df_submission.columns[1:].tolist() label_size = len(labels) P = [None] * label_size R = [None] * label_size AP = np.zeros(label_size) for i in range(label_size): P[i], R[i], _ = precision_recall_curve(y_true2[:,i], y_pred2[:,i]) AP[i] = averag...
def read_data(file_name): data = pd.read_csv('.. /input/'+file_name+'.csv') return data
Titanic - Machine Learning from Disaster
537,402
MPLoader.reset() MPLoader.full_load(df_test, use_preprocess=False )<load_pretrained>
def prepare_age(data): age = data['Age'] mean_age = age.mean() var_age = age.var() age[age.isnull() ] = mean_age age = age - mean_age age = age / var_age return age.as_matrix()
Titanic - Machine Learning from Disaster
537,402
USE_MASK_FREQ = USE_MASK_TIME = False test = ImageList.from_df(df_test, WORK, folder='') learn = load_learner(WORK, test=test)if TRAIN_MODE else load_learner('.', DEPLOYED_MODEL, test=test) preds, _ = learn.TTA(ds_type=DatasetType.Test, num_pred=50 )<save_to_csv>
def prepare_fare(data): fare = data['Fare'] mean_fare = fare.mean() var_fare = fare.var() fare = fare - mean_fare fare = fare / var_fare return fare.as_matrix()
Titanic - Machine Learning from Disaster
537,402
df_submission[learn.data.classes] = preds df_submission.to_csv('submission.csv', index=False) df_submission.head()<set_options>
def prepare_sex(data): sex = data['Sex'] sex = np.where(sex=='male',0,1) return sex
Titanic - Machine Learning from Disaster
537,402
def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True SEED = 999 seed_everything(SEED )<categorify>
def prepare_embarquation(data): embarked = data['Embarked'] embarked[embarked.isnull() ] = 3 embarked = np.where(embarked=='C', 0, embarked) embarked = np.where(embarked=='Q', 1, embarked) embarked = np.where(embarked=='S', 2, embarked) mean_embarked = embarked.mean() var_embarked = embarked.var() embarked = embar...
Titanic - Machine Learning from Disaster
537,402
def _one_sample_positive_class_precisions(scores, truth): num_classes = scores.shape[0] pos_class_indices = np.flatnonzero(truth > 0) if not len(pos_class_indices): return pos_class_indices, np.zeros(0) retrieved_classes = np.argsort(scores)[::-1] class_rankings = np.zeros(num_classes, dtype=np.int) class_rankings...
def prepare_sibligs(data): sib = data['SibSp'] mean_sib = sib.mean() var_sib = sib.var() sib = sib - mean_sib sib = sib / var_sib return sib
Titanic - Machine Learning from Disaster
537,402
DATA = Path('.. /input/freesound-audio-tagging-2019') PREPROCESSED = Path('.. /input/fat2019_prep_mels1') WORK = Path('work') Path(WORK ).mkdir(exist_ok=True, parents=True) CSV_TRN_CURATED = DATA/'train_curated.csv' CSV_TRN_NOISY = DATA/'train_noisy.csv' CSV_TRN_NOISY_BEST50S = PREPROCESSED/'trn_noisy_best50s.csv' ...
def prepare_parch(data): parch = data['Parch'] mean_parch = parch.mean() var_parch = parch.var() parch = parch - mean_parch parch = parch / var_parch return parch
Titanic - Machine Learning from Disaster
537,402
data.show_batch(3 )<compute_test_metric>
def prepare_family_size(data): parch = data['Parch'] sib = data['SibSp'] family_size = parch + sib mean_family_size = family_size.mean() var_family_size = family_size.var() family_size = family_size - mean_family_size family_size = family_size / var_family_size return family_size
Titanic - Machine Learning from Disaster
537,402
def lwlrap(y_pred,y_true): score, weight = calculate_per_class_lwlrap(y_true.cpu().numpy() , y_pred.cpu().numpy()) lwlrap =(score * weight ).sum() return torch.from_numpy(np.array(lwlrap))<train_model>
def normalize_features(data): age = prepare_age(data) sex = prepare_sex(data) embark = prepare_embarquation(data) fare = prepare_fare(data) sib = prepare_sibligs(data) parch = prepare_parch(data) family_size = prepare_family_size(data) X_train = np.column_stack(( sex, age, family_size, embark)) return X_train....
Titanic - Machine Learning from Disaster
537,402
class MixUpCallback(LearnerCallback): "Callback that creates the mixed-up input and target." def __init__(self, learn:Learner, alpha:float=0.4, stack_x:bool=False, stack_y:bool=True): super().__init__(learn) self.alpha,self.stack_x,self.stack_y = alpha,stack_x,stack_y def on_train_begin(self, **kwargs): if self.stack_...
def prepare_training_data() : pd.set_option('mode.chained_assignment', None) data = read_data('train') X_train = normalize_features(data) Y_train = np.reshape(data['Survived'].as_matrix() ,(X_train.shape[1],1)).T return X_train, Y_train
Titanic - Machine Learning from Disaster
537,402
class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, 1), nn.BatchNorm2d(out_channels), nn.ReLU() , ) self.conv2 = nn.Sequential( nn.Conv2d(out_channels, out_channels, 3, 1, 1), nn.BatchNorm2d(out_channels...
def prepare_test_data() : pd.set_option('mode.chained_assignment', None) data = read_data('test') X_test = normalize_features(data) return X_test
Titanic - Machine Learning from Disaster
537,402
def borrowed_model(pretrained=False, **kwargs): return Classifier(**kwargs) f_score = partial(fbeta, thresh=0.2) learn = cnn_learner(data, borrowed_model, pretrained=False, metrics=[lwlrap] ).mixup(stack_y=False) learn.unfreeze() <train_model>
def initialize_Parameters(nb_features): W1 = tf.get_variable("W1", [5, nb_features], initializer = tf.contrib.layers.xavier_initializer()) b1 = tf.get_variable("b1", [5,1], initializer = tf.zeros_initializer()) W2 = tf.get_variable("W2", [8,5], initializer = tf.contrib.layers.xavier_initializer()) b2 = tf.get_vari...
Titanic - Machine Learning from Disaster
537,402
learn.fit_one_cycle(255, 1e-2,callbacks=[SaveModelCallback(learn, every='improvement', monitor='lwlrap', name='best')] )<train_model>
def forward_propagation(X, parameters): W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] W3 = parameters['W3'] b3 = parameters['b3'] W4 = parameters['W4'] b4 = parameters['b4'] W5 = parameters['W5'] b5 = parameters['b5'] Z1 = tf.add(tf.matmul(W1, X), b1) A1 = tf.nn.relu(Z1) Z2...
Titanic - Machine Learning from Disaster
537,402
learn.lr_find() learn.fit_one_cycle(50, 1e-2,callbacks=[SaveModelCallback(learn, every='improvement', monitor='lwlrap', name='best')] )<load_from_csv>
def create_placeholders(n_x, n_y): X = tf.placeholder(dtype=tf.float32, shape=([n_x, None]), name="X") Y = tf.placeholder(dtype=tf.float32, shape=([n_y, None]), name="Y") return X, Y
Titanic - Machine Learning from Disaster
537,402
del X_train X_test = pickle.load(open(MELS_TEST, 'rb')) CUR_X_FILES, CUR_X = list(test_df.fname.values), X_test test = ImageList.from_csv(WORK, Path('.. ')/CSV_SUBMISSION, folder='test') learn = load_learner(WORK, test=test) preds, _ = learn.TTA(ds_type=DatasetType.Test )<save_to_csv>
def compute_cost(Z, Y): logits = tf.transpose(Z) labels = tf.transpose(Y) cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels)) return cost
Titanic - Machine Learning from Disaster
537,402
test_df[learn.data.classes] = preds test_df.to_csv('submission.csv', index=False) test_df.head()<import_modules>
def train_predict_model(learning_rate, epoch, X_train, Y_train, X_test): X, Y = create_placeholders(X_train.shape[0], Y_train.shape[0]) parameters = initialize_Parameters(X_train.shape[0]) Z4 = forward_propagation(X, parameters) cost = compute_cost(Z4, Y) optimizer = tf.train.AdamOptimizer(learning_rate ).minimiz...
Titanic - Machine Learning from Disaster
537,402
<set_options><EOS>
ops.reset_default_graph() X_train, Y_train = prepare_training_data() X_test = prepare_test_data() prediction_test = train_predict_model(learning_rate=0.0001, epoch=40000, X_train= X_train , Y_train = Y_train, X_test = X_test) prediction_test = np.where(prediction_test < 1, 0, 1) data = read_data('test') submission =...
Titanic - Machine Learning from Disaster
1,306,079
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<set_options>
train = pd.read_csv(".. /input/train.csv") test = pd.read_csv(".. /input/test.csv") train["n"] = 0 test["n"] = 1 global tot tot = pd.concat([train,test],sort = False )
Titanic - Machine Learning from Disaster
1,306,079
def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True SEED = 520 seed_everything(SEED )<feature_engineering>
def check_survive(label): global tot return tot[["Survived",label]].groupby(label ).Survived.mean() def process_Sex() : global tot tot.Sex = tot.Sex.replace({"male": 0, "female": 1}) def process_Name() : global tot tot["Title"] = tot.Name.str.extract("([A-Za-z]+)\.") tot["Title"].replace(['Lady', 'Countess','Sir', 'J...
Titanic - Machine Learning from Disaster
1,306,079
N_JOBS = cpu_count() os.environ['MKL_NUM_THREADS'] = str(N_JOBS) os.environ['OMP_NUM_THREADS'] = str(N_JOBS) DataLoader = partial(DataLoader, num_workers=N_JOBS )<define_variables>
lnames = tot.Name.map(lambda x: x.split(",")[0]) tot.Name = lnames tnum = tot.Ticket.map(lambda x: x.split(" ")[-1]) tot.Ticket = tnum tot["FamSize"] = tot.SibSp + tot.Parch nlist = tot.Name.value_counts().index
Titanic - Machine Learning from Disaster
1,306,079
def _one_sample_positive_class_precisions(scores, truth): num_classes = scores.shape[0] pos_class_indices = np.flatnonzero(truth > 0) if not len(pos_class_indices): return pos_class_indices, np.zeros(0) retrieved_classes = np.argsort(scores)[::-1] class_rankings = np.zeros(num_classes, dtype=np.int) class_rankings...
tot["FamDeath"] = np.nan for i in range(len(tot)) : if tot.iloc[i,:].FamSize > 0: hisname = tot.iloc[i,:].Name hisfam = tot.iloc[i,:].FamSize temp = pd.concat([tot.iloc[:i,:], tot.iloc[i+1:,:]]) family = temp[(temp.Name == hisname)*(temp.FamSize == hisfam)] if len(family)== 0: continue tot.FamDeath.iloc[i] = family.Su...
Titanic - Machine Learning from Disaster
1,306,079
dataset_dir = Path('.. /input/freesound-audio-tagging-2019') preprocessed_dir = Path('.. /input/fat2019_prep_mels1' )<define_variables>
del tot["Ticket"], tot["Cabin"], tot["RT"], tot["LT"] del tot["FamSize"], tot["Name"]
Titanic - Machine Learning from Disaster
1,306,079
csvs = { 'train_curated': dataset_dir / 'train_curated.csv', 'train_noisy': preprocessed_dir / 'trn_noisy_best50s.csv', 'sample_submission': dataset_dir / 'sample_submission.csv', } dataset = { 'train_curated': dataset_dir / 'train_curated', 'train_noisy': dataset_dir / 'train_noisy', 'test': dataset_dir / 'test', } me...
dropped = ["Survived","n","PassengerId","Embarked","Parch","Age","SibSp","Tlen"] parameters = { 'n_estimators' : [100], 'random_state' : [1], 'n_jobs' : [3], 'min_samples_split': np.arange(8,12), 'max_depth' : np.arange(2,6) } clf = grid_search.GridSearchCV(RandomForestClassifier() , parameters) clf.fit(tot[tot.n == ...
Titanic - Machine Learning from Disaster
1,306,079
train_curated = pd.read_csv(csvs['train_curated']) train_noisy = pd.read_csv(csvs['train_noisy']) train_df = pd.concat([train_curated, train_noisy], sort=True, ignore_index=True) train_df.head()<load_from_csv>
data = [] clf = clf.best_estimator_ num_trial = 10 for i in range(num_trial): X_train, X_test, y_train, y_test = train_test_split(tot[tot.n == 0].drop(dropped,axis = 1), tot[tot.n==0].Survived, random_state = i) clf.fit(X_train, y_train) data.append(clf.score(X_test, y_test)) plt.scatter(np.arange(num_trial),data )
Titanic - Machine Learning from Disaster
1,306,079
test_df = pd.read_csv(csvs['sample_submission']) test_df.head()<data_type_conversions>
clf.fit(tot[tot.n == 0].drop(dropped,axis = 1), tot[tot.n == 0].Survived) subm = tot[tot.n == 1].drop(["Survived"], axis = 1 ).join(pd.Series(clf.predict(tot[tot.n == 1].drop(dropped,axis = 1)) ,name="Survived"))
Titanic - Machine Learning from Disaster
1,306,079
<define_variables><EOS>
subm = subm[["PassengerId","Survived"]].set_index("PassengerId") subm.Survived = subm.Survived.map(lambda x: int(x)) subm.to_csv("Submission.csv" )
Titanic - Machine Learning from Disaster
2,692,970
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<prepare_x_and_y>
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns
Titanic - Machine Learning from Disaster
2,692,970
y_train = np.zeros(( len(train_df), num_classes)).astype(int) for i, row in enumerate(train_df['labels'].str.split(',')) : for label in row: idx = labels.index(label) y_train[i, idx] = 1 y_train.shape<load_pretrained>
df=pd.read_csv(".. /input/train.csv") test=pd.read_csv(".. /input/test.csv" )
Titanic - Machine Learning from Disaster
2,692,970
with open(mels['train_curated'], 'rb')as curated, open(mels['train_noisy'], 'rb')as noisy: x_train = pickle.load(curated) x_train.extend(pickle.load(noisy)) with open(mels['test'], 'rb')as test: x_test = pickle.load(test) len(x_train), len(x_test )<categorify>
df=df.drop(['Cabin'],axis=1) test=test.drop(['Cabin'],axis=1) df.columns
Titanic - Machine Learning from Disaster
2,692,970
class FATTestDataset(Dataset): def __init__(self, fnames, mels, transforms, tta=5): super().__init__() self.fnames = fnames self.mels = mels self.transforms = transforms self.tta = tta def __len__(self): return len(self.fnames)* self.tta def __getitem__(self, idx): new_idx = idx % len(self.fnames) image = Image.fromar...
print("Number of people embarking in Southampton(S):") southampton = df[df["Embarked"] == "S"].shape[0] print(southampton) print("Number of people embarking in Cherbourg(C):") cherbourg = df[df["Embarked"] == "C"].shape[0] print(cherbourg) print("Number of people embarking in Queenstown(Q):") queenstown = df[df["E...
Titanic - Machine Learning from Disaster
2,692,970
transforms_dict = { 'train': transforms.Compose([ transforms.RandomHorizontalFlip(0.5), transforms.ToTensor() , ]), 'test': transforms.Compose([ transforms.RandomHorizontalFlip(0.5), transforms.ToTensor() , ]), }<define_search_model>
df=df.drop(['Ticket'],axis=1) test=test.drop(['Ticket'],axis=1) test.columns
Titanic - Machine Learning from Disaster
2,692,970
class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, 1), nn.BatchNorm2d(out_channels), nn.ReLU() , ) self.conv2 = nn.Sequential( nn.Conv2d(out_channels, out_channels, 3, 1, 1), nn.BatchNorm2d(out_channels...
combine = [df, test] for dataset in combine: dataset['Title'] = dataset.Name.str.extract('([A-Za-z]+)\.', expand=False) print(pd.crosstab(df['Title'], df['Sex']))
Titanic - Machine Learning from Disaster
2,692,970
class Classifier(nn.Module): def __init__(self, num_classes): super().__init__() self.conv = nn.Sequential( ConvBlock(in_channels=3, out_channels=64), ConvBlock(in_channels=64, out_channels=128), ConvBlock(in_channels=128, out_channels=256), ConvBlock(in_channels=256, out_channels=512), ) self.fc = nn.Sequential( n...
for dataset in combine: dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col',\ 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['T...
Titanic - Machine Learning from Disaster
2,692,970
Classifier(num_classes=num_classes )<split>
df['Age'] = df.groupby(['Title'])['Age'].transform(lambda x: x.fillna(x.mean())) test['Age'] = test.groupby(['Title'])['Age'].transform(lambda x: x.fillna(x.mean())) df['Age'] = df['Age'].astype(int) test['Age'] = test['Age'].astype(int) df.loc[ df['Age'] <= 16, 'Age'] = 0 df.loc[(df['Age'] > 16)&(df['Age'] <= 32), '...
Titanic - Machine Learning from Disaster
2,692,970
def train_model(x_train, y_train, train_transforms): num_epochs = 118 batch_size = 128 test_batch_size = 256 lr = 1e-3 eta_min = 1e-5 t_max = 5 num_classes = y_train.shape[1] x_trn, x_val, y_trn, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=SEED) train_dataset = FATTrainDataset(x_trn, y_trn, ...
for dataset in combine: dataset['Sex'] = dataset['Sex'].map({'female': 1, 'male': 0} ).astype(int) test.head(5 )
Titanic - Machine Learning from Disaster
2,692,970
result = train_model(x_train, y_train, transforms_dict['train'] )<predict_on_test>
df=df.drop(['Name'],axis=1) test=test.drop(['Name'],axis=1) df.columns
Titanic - Machine Learning from Disaster
2,692,970
test_preds = predict_model(test_df['fname'], x_test, transforms_dict['test'], num_classes, tta=35 )<save_to_csv>
df.drop('AgeGroup',axis=1,inplace=True )
Titanic - Machine Learning from Disaster
2,692,970
test_df[labels] = test_preds.values test_df.to_csv('submission.csv', index=False) test_df.head()<define_search_model>
df = pd.concat([df.drop('Sex', axis=1), pd.get_dummies(df['Sex'])], axis=1) test = pd.concat([test.drop('Sex', axis=1), pd.get_dummies(test['Sex'])], axis=1) test.head(5 )
Titanic - Machine Learning from Disaster
2,692,970
class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, 1), nn.BatchNorm2d(out_channels), nn.ReLU() , ) self.conv2 = nn.Sequential( nn.Conv2d(out_channels, out_channels, 3, 1, 1), nn.BatchNorm2d(out_channels...
df.drop('Class',axis=1,inplace=True) df.head()
Titanic - Machine Learning from Disaster
2,692,970
DATA = Path('.. /input/freesound-audio-tagging-2019') PREPROCESSED = Path('.. /input/fat2019_prep_mels1') WORK = Path('work') Path(WORK ).mkdir(exist_ok=True, parents=True) CSV_TRN_CURATED = DATA/'train_curated.csv' CSV_TRN_NOISY = DATA/'train_noisy.csv' CSV_TRN_NOISY_BEST50S = PREPROCESSED/'trn_noisy_best50s.csv' ...
df['Embarked'].replace({'S':1,'C':2,'Q':3},inplace=True) df['Embarked']=df['Embarked'].fillna(1) test['Embarked'].replace({'S':1,'C':2,'Q':3},inplace=True) test['Embarked']=test['Embarked'].fillna(1) test.head(5 )
Titanic - Machine Learning from Disaster
2,692,970
data.show_batch(3 )<train_model>
df=df.drop(['Title'],axis=1) test=test.drop(['Title'],axis=1) test.columns
Titanic - Machine Learning from Disaster
2,692,970
learn.fit_one_cycle(10, slice(1e-6, 1e-1))<train_model>
predictors=df.drop(['Survived','PassengerId'],axis=1) target=df['Survived'] x_train,x_cv,y_train,y_cv=train_test_split(predictors,target,test_size=0.35,random_state=0 )
Titanic - Machine Learning from Disaster
2,692,970
learn.fit_one_cycle(100, 3e-3 )<save_model>
knn = KNeighborsClassifier() knn.fit(x_train, y_train) y_pred = knn.predict(x_cv) acc_knn = round(accuracy_score(y_pred,y_cv)* 100, 2) print(acc_knn )
Titanic - Machine Learning from Disaster
2,692,970
learn.save('fat2019_fastai_cnn2d_stage-2') learn.export()<load_from_csv>
logreg = LogisticRegression() logreg.fit(x_train, y_train) y_pred = logreg.predict(x_cv) acc_logreg = round(accuracy_score(y_pred, y_cv)* 100, 2) print(acc_logreg )
Titanic - Machine Learning from Disaster