kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
14,631,065
nlp_train_df = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') nlp_test_df = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv') def callback(operation_future): result = operation_future.result()<filter>
model.load_weights(checkpoint_filepath )
Contradictory, My Dear Watson
14,631,065
nlp_train_df.loc[nlp_train_df['text'].str.contains('fire', na=False, case=False)]<count_values>
test_input = encode(test, tokenizer=tokenizer, max_len=MAX_LEN )
Contradictory, My Dear Watson
14,631,065
nlp_train_df.loc[nlp_train_df['text'].str.contains('fire', na=False, case=False)].target.value_counts()<load_pretrained>
predictions = [np.argmax(i)for i in model.predict(test_input)]
Contradictory, My Dear Watson
14,631,065
def upload_blob(bucket_name, source_file_name, destination_blob_name): bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print('File {} uploaded to {}'.format( source_file_name, 'gs://' + bucket_name + '/' + destination_blob_name)) def download_to_kaggle(bucket_name,destination_directory,file_name,prefix=None): os.makedirs(destination_directory, exist_ok = True) full_file_path = os.path.join(destination_directory, file_name) blobs = storage_client.list_blobs(bucket_name,prefix=prefix) for blob in blobs: blob.download_to_filename(full_file_path )<prepare_output>
submission = test.id.copy().to_frame() submission['prediction'] = predictions submission.head()
Contradictory, My Dear Watson
14,631,065
bucket = storage.Bucket(storage_client, name=bucket_name) if not bucket.exists() : bucket.create(location=region )<save_to_csv>
submission.to_csv("submission.csv", index = False )
Contradictory, My Dear Watson
13,825,770
nlp_train_df[['text','target']].to_csv('train.csv', index=False, header=False )<load_from_csv>
!pip install --upgrade pip !pip install --upgrade allennlp !pip install transformers==4.0.1
Contradictory, My Dear Watson
13,825,770
training_gcs_path = 'uploads/kaggle_getstarted/full_train.csv' upload_blob(bucket_name, 'train.csv', training_gcs_path )<choose_model_class>
!curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py !python pytorch-xla-env-setup.py --apt-packages libomp5 libopenblas-dev
Contradictory, My Dear Watson
13,825,770
amw = AutoMLWrapper(client=client, project_id=PROJECT_ID, bucket_name=bucket_name, region='us-central1', dataset_display_name=dataset_display_name, model_display_name=model_display_name) <prepare_x_and_y>
import transformers import pandas as pd import torch
Contradictory, My Dear Watson
13,825,770
print(f'Getting dataset ready at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') if not amw.get_dataset_by_display_name(dataset_display_name): print('dataset not found') amw.create_dataset() amw.import_gcs_data(training_gcs_path) amw.dataset print(f'Dataset ready at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') <train_model>
import torch_xla import torch_xla.core.xla_model as xm
Contradictory, My Dear Watson
13,825,770
print(f'Getting model trained at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') if not amw.get_model_by_display_name() : print(f'Training model at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') amw.train_model() print(f'Model trained.Ensuring model is deployed at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') amw.deploy_model() amw.model print(f'Model trained and deployed at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') <find_best_params>
print('Transformers version: ', transformers.__version__) print('Pytorch version: ', torch.__version__ )
Contradictory, My Dear Watson
13,825,770
amw.model_full_path<predict_on_test>
data_dir = '/kaggle/input/contradictory-my-dear-watson/' train_df = pd.read_csv(data_dir+'train.csv' ).sample(frac=1, random_state=100) test_df = pd.read_csv(data_dir+'test.csv') print(train_df['label'].value_counts()) train_df.head(5 )
Contradictory, My Dear Watson
13,825,770
print(f'Begin getting predictions at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') prediction_client = automl.PredictionServiceClient() amw.set_prediction_client(prediction_client) predictions_df = amw.get_predictions(nlp_test_df, input_col_name='text', limit=None, threshold=0.5, verbose=False) print(f'Finished getting predictions at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}' )<concatenate>
PRE_TRAINED_MODEL = 'xlm-roberta-large' tokenizer = transformers.AutoTokenizer.from_pretrained(PRE_TRAINED_MODEL )
Contradictory, My Dear Watson
13,825,770
submission_df = pd.concat([nlp_test_df['id'], predictions_df['class']], axis=1) submission_df.head()<rename_columns>
MAX_LEN = 84 split_idx = int(train_df.shape[0] * 0.8 )
Contradictory, My Dear Watson
13,825,770
submission_df = submission_df.rename(columns={'class':'target'}) submission_df.head()<save_to_csv>
def get_encode(data): tokenized_data=tokenizer( text=list(data['premise']), text_pair=list(data['hypothesis']), max_length=MAX_LEN, pad_to_max_length=True, add_special_tokens=True, truncation=True, return_attention_mask=True, return_token_type_ids=True, return_tensors='pt') return tokenized_data
Contradictory, My Dear Watson
13,825,770
submission_df.to_csv("submission.csv", index=False, header=True )<load_from_csv>
seed=2 tokenized_train=get_encode(train_df[:split_idx]) labels_train=torch.tensor(train_df.label.values[:split_idx]) tokenized_valid=get_encode(train_df[split_idx:]) labels_valid=torch.tensor(train_df.label.values[split_idx:]) tokenized_test=get_encode(test_df )
Contradictory, My Dear Watson
13,825,770
train, test = pd.read_csv('.. /input/train.csv'), pd.read_csv('.. /input/test.csv') train['Boy'], test['Boy'] = [(df.Name.str.split().str[1] == 'Master.' ).astype('int')for df in [train, test]] train['Surname'], test['Surname'] = [df.Name.str.split(',' ).str[0] for df in [train, test]] model = catboost.CatBoostClassifier(one_hot_max_size=4, iterations=100, random_seed=0, verbose=False) model.fit(train[['Sex', 'Pclass', 'Embarked', 'Boy', 'Surname']].fillna(''), train['Survived'], cat_features=[0, 2, 4]) pred = model.predict(test[['Sex', 'Pclass', 'Embarked', 'Boy', 'Surname']].fillna('')).astype('int') pd.concat([test['PassengerId'], pd.DataFrame(pred, columns=['Survived'])], axis=1 ).to_csv('submission.csv', index=False )<train_on_grid>
batch_size=64 train_data=TensorDataset(torch.tensor(tokenized_train['input_ids']), torch.tensor(tokenized_train['token_type_ids']),torch.tensor(tokenized_train['attention_mask']) ,labels_train) train_sampler=RandomSampler(train_data) train_dataloader=DataLoader(train_data, sampler=train_sampler, batch_size=batch_size) valid_data=TensorDataset(torch.tensor(tokenized_valid['input_ids']), torch.tensor(tokenized_valid['token_type_ids']), torch.tensor(tokenized_valid['attention_mask']) ,labels_valid) valid_sampler=SequentialSampler(valid_data) valid_dataloader=DataLoader(valid_data, sampler=valid_sampler, batch_size=batch_size) test_data=TensorDataset(torch.tensor(tokenized_test['input_ids']), torch.tensor(tokenized_test['token_type_ids']), torch.tensor(tokenized_test['attention_mask'])) test_dataloader=DataLoader(test_data, batch_size=batch_size )
Contradictory, My Dear Watson
13,825,770
features = ['Sex', 'Pclass', 'Embarked'] X_train = train[features].fillna('') y_train = train['Survived'] X_test = test[features].fillna('') model = catboost.CatBoostClassifier( one_hot_max_size=4, iterations=100, random_seed=0, verbose=False, eval_metric='Accuracy' ) pool = catboost.Pool(X_train, y_train, cat_features=[0, 2]) print('To see the Catboost plots, fork this kernel and run it in the editing mode.') cv_scores = catboost.cv(pool, model.get_params() , fold_count=10, plot=True) print('CV score: {:.5f}'.format(cv_scores['test-Accuracy-mean'].values[-1]))<save_to_csv>
model = AutoModelForSequenceClassification.from_pretrained(PRE_TRAINED_MODEL, num_labels = 3, output_attentions = False, output_hidden_states = False)
Contradictory, My Dear Watson
13,825,770
model.fit(pool) pred = model.predict(X_test ).astype('int') output = pd.concat([test['PassengerId'], pd.DataFrame(pred, columns=['Survived'])], axis=1) output.to_csv('submission2.csv', index=False )<train_on_grid>
device = xm.xla_device() torch.set_default_tensor_type('torch.FloatTensor') print(model.to(device)) print('TPU available')
Contradictory, My Dear Watson
13,825,770
features = ['Sex', 'Pclass', 'Embarked', 'Boy'] X_train = train[features].fillna('') y_train = train['Survived'] X_test = test[features].fillna('') model = catboost.CatBoostClassifier( one_hot_max_size=4, iterations=100, random_seed=0, verbose=False, eval_metric='Accuracy' ) pool = catboost.Pool(X_train, y_train, cat_features=[0, 2]) print('To see the Catboost plots, fork this kernel and run it in the editing mode.') cv_scores = catboost.cv(pool, model.get_params() , fold_count=10, plot=True) print('CV score: {:.5f}'.format(cv_scores['test-Accuracy-mean'].values[-1]))<save_to_csv>
def accuracy(predictions, labels): prediction_flat = np.argmax(predictions, axis=1 ).flatten() labels_flat = labels.flatten() return np.sum(prediction_flat == labels_flat)/ len(labels_flat )
Contradictory, My Dear Watson
13,825,770
model.fit(pool) pred = model.predict(X_test ).astype('int') output = pd.concat([test['PassengerId'], pd.DataFrame(pred, columns=['Survived'])], axis=1) output.to_csv('submission3.csv', index=False )<train_on_grid>
optimizer = AdamW(model.parameters() , lr = 2e-5 ) epochs = 20 total_steps = len(train_dataloader)* epochs scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps = 0, num_training_steps = total_steps )
Contradictory, My Dear Watson
13,825,770
features = ['Sex', 'Pclass', 'Embarked', 'Boy', 'Surname'] X_train = train[features].fillna('') y_train = train['Survived'] X_test = test[features].fillna('') model = catboost.CatBoostClassifier( one_hot_max_size=4, iterations=100, random_seed=0, verbose=False, eval_metric='Accuracy' ) pool = catboost.Pool(X_train, y_train, cat_features=[0, 2, 4]) print('To see the Catboost plots, fork this kernel and run it in the editing mode.') cv_scores = catboost.cv(pool, model.get_params() , fold_count=10, plot=True) print('CV score: {:.5f}'.format(cv_scores['test-Accuracy-mean'].values[-1]))<save_to_csv>
random.seed(10) np.random.seed(10) torch.manual_seed(10) torch.cuda.manual_seed_all(10) losses = [] for i in range(0, epochs): print('Epoch {:} of {:} Training...'.format(i+1, epochs)) total_loss = 0 model.train() for step, batch in enumerate(train_dataloader): if step % 10 == 0 and step != 0: print('[{}] Batch {:>5,} of {:>5,}' .format(datetime.datetime.now().strftime('%H:%M:%S'), step, len(train_dataloader))) train_batch_input = batch[0].to(device) train_batch_input_types = batch[1].to(device) train_batch_mask = batch[2].to(device) train_batch_label = batch[3].to(device) model.zero_grad() outputs = model(train_batch_input, token_type_ids = train_batch_input_types, attention_mask = train_batch_mask, labels = train_batch_label) loss = outputs[0] total_loss += loss.item() loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters() , 1.0) xm.optimizer_step(optimizer, barrier=True) scheduler.step() average_train_loss = total_loss / len(train_dataloader) losses.append(average_train_loss) print('Training loss={:.2f}'.format(average_train_loss)) model.eval() eval_accuracy = 0 eval_count = 0 for batch in valid_dataloader: valid_batch_input = batch[0].to(device) valid_batch_input_types = batch[1].to(device) valid_batch_mask = batch[2].to(device) valid_batch_labels = batch[3].to(device) with torch.no_grad() : outputs = model(valid_batch_input, token_type_ids = valid_batch_input_types, attention_mask = valid_batch_mask) logits = outputs[0] logits = logits.detach().cpu().numpy() label_ids = valid_batch_labels.to('cpu' ).numpy() batch_accuracy = accuracy(logits, label_ids) eval_accuracy += batch_accuracy eval_count += 1 print('Validation accuracy={:.2f}'.format(eval_accuracy / eval_count)) print('') if i == 4: break print("Training done")
Contradictory, My Dear Watson
13,825,770
model.fit(pool) pred = model.predict(X_test ).astype('int') output = pd.concat([test['PassengerId'], pd.DataFrame(pred, columns=['Survived'])], axis=1) output.to_csv('submission4.csv', index=False )<set_options>
model.eval() submissions = [] for batch in test_dataloader: test_batch_input = batch[0].to(device) test_batch_input_types = batch[1].to(device) test_batch_mask = batch[2].to(device) with torch.no_grad() : outputs = model(test_batch_input, token_type_ids = test_batch_input_types, attention_mask = test_batch_mask) logits = outputs[0] submissions.extend(np.argmax(logits.detach().cpu().numpy() , axis=1 ).flatten())
Contradictory, My Dear Watson
13,825,770
%matplotlib inline color = sns.color_palette() sns.set_style('darkgrid') def ignore_warn(*args, **kwargs): pass warnings.warn = ignore_warn <load_from_csv>
output = pd.DataFrame({'id': test_df.id, 'prediction': submissions}) output.to_csv('submission.csv', index=False )
Contradictory, My Dear Watson
13,380,346
train = pd.read_csv('.. /input/train.csv') test = pd.read_csv('.. /input/test.csv') train.describe()<drop_column>
!pip install datasets !pip install --upgrade seaborn
Contradictory, My Dear Watson
13,380,346
train_ID = train['Id'] test_ID = test['Id'] train.drop("Id", axis = 1, inplace = True) test.drop("Id", axis = 1, inplace = True )<drop_column>
import os import seaborn as sns import numpy as np import random from sklearn.utils import shuffle import matplotlib.pyplot as plt import pandas as pd from collections import namedtuple import plotly.express as px import transformers import tokenizers import datetime import time from sklearn.metrics import accuracy_score, precision_recall_fscore_support, matthews_corrcoef import tensorflow from datasets import load_dataset import torch from torch import nn from transformers import BertTokenizer, AutoTokenizer, TrainingArguments, AutoModel, AutoModelForSequenceClassification from torch.utils.data import TensorDataset, random_split from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from transformers import BertForSequenceClassification, AdamW, BertConfig from transformers import get_linear_schedule_with_warmup from transformers import RobertaTokenizer, RobertaForSequenceClassification, XLMRobertaModel
Contradictory, My Dear Watson
13,380,346
train = train.drop(train[(train['GrLivArea']>4000)&(train['SalePrice']<300000)].index )<feature_engineering>
mnli = load_dataset('glue', 'mnli') len(mnli )
Contradictory, My Dear Watson
13,380,346
train["SalePrice"] = np.log1p(train["SalePrice"]) check_skewness('SalePrice' )<prepare_x_and_y>
xnli = load_dataset('xnli', 'all_languages') len(xnli )
Contradictory, My Dear Watson
13,380,346
ntrain = train.shape[0] ntest = test.shape[0] y_train = train.SalePrice.values all_data = pd.concat(( train, test)).reset_index(drop=True) all_data.drop(['SalePrice'], axis=1, inplace=True) print("all_data size is : {}".format(all_data.shape))<create_dataframe>
original_train_df = pd.read_csv(".. /input/contradictory-my-dear-watson/train.csv") original_train_df = shuffle(original_train_df) print(original_train_df.shape) original_valid_df = original_train_df[:len(original_train_df)//2] original_train_df = original_train_df[(len(original_train_df)//2):] print(original_train_df.shape, original_valid_df.shape) original_train_df.head()
Contradictory, My Dear Watson
13,380,346
all_data_na =(all_data.isnull().sum() / len(all_data)) * 100 all_data_na = all_data_na.drop(all_data_na[all_data_na == 0].index ).sort_values(ascending=False)[:30] missing_data = pd.DataFrame({'Missing Ratio' :all_data_na} )<filter>
original_test_df = pd.read_csv(".. /input/contradictory-my-dear-watson/test.csv") original_test_df.shape
Contradictory, My Dear Watson
13,380,346
all_data.PoolQC.loc[all_data.PoolQC.notnull() ]<data_type_conversions>
bert_model_name = 'joeddav/xlm-roberta-large-xnli' max_len = 128 tokenizer = AutoTokenizer.from_pretrained(bert_model_name )
Contradictory, My Dear Watson
13,380,346
all_data["PoolQC"] = all_data["PoolQC"].fillna("None" )<data_type_conversions>
def encode(premise, hypothesis, label): encoded_dict = tokenizer( premise, hypothesis, add_special_tokens = True, truncation=True, max_length = max_len, padding='max_length', return_attention_mask = True, return_tensors = 'pt', ) for k in encoded_dict: encoded_dict[k] = torch.squeeze(encoded_dict[k]) encoded_dict['labels'] = label return encoded_dict
Contradictory, My Dear Watson
13,380,346
all_data["MiscFeature"] = all_data["MiscFeature"].fillna("None" )<data_type_conversions>
raw_ds_mapping = { 'original train':(_get_raw_datasets_from_dataframe, original_train_df, len(original_train_df)) , 'original valid':(_get_raw_datasets_from_dataframe, original_valid_df, len(original_valid_df)) , 'mnli train' :(_get_raw_datasets_from_nlp, mnli['train'], mnli['train'].num_rows), 'mnli valid 1' :(_get_raw_datasets_from_nlp, mnli['validation_matched'], mnli['validation_matched'].num_rows), 'mnli valid 2' :(_get_raw_datasets_from_nlp, mnli['validation_mismatched'], mnli['validation_mismatched'].num_rows), 'xnli valid' :(_get_raw_datasets_from_nlp, xnli['validation'], xnli['validation'].num_rows * 15), 'xnli test' :(_get_raw_datasets_from_nlp, xnli['test'], xnli['test'].num_rows * 15), 'original test' :(_get_raw_datasets_from_dataframe, original_test_df, len(original_test_df)) , } def get_raw_dataset(ds_name): fn, ds, nb_examples = raw_ds_mapping[ds_name] for x in fn(ds): yield x return
Contradictory, My Dear Watson
13,380,346
all_data["Alley"] = all_data["Alley"].fillna("None" )<data_type_conversions>
train_ds_names = ['original train', 'mnli train', 'mnli valid 1', 'mnli valid 2', 'xnli valid', 'xnli test'] eval_ds_names = ['original valid'] test_ds_names = ['original test']
Contradictory, My Dear Watson
13,380,346
all_data["Fence"] = all_data["Fence"].fillna("None" )<data_type_conversions>
class MyIterableDataset(torch.utils.data.IterableDataset): def __init__(self, ds_names, isLabeledDataset=False): super(MyIterableDataset ).__init__() self.ds_names = ds_names self.length = self.getLen() self.isLabeledDataset = isLabeledDataset return def getLen(self): length = 0 for ds_name in self.ds_names: fn, ds, nb_examples = raw_ds_mapping[ds_name] length += nb_examples return length def __iter__(self): for ds_name in self.ds_names: fn, ds, nb_examples = raw_ds_mapping[ds_name] for x in fn(ds): if self.isLabeledDataset and x['labels'] == -1: continue yield x return def __len__(self): return self.length
Contradictory, My Dear Watson
13,380,346
all_data["FireplaceQu"] = all_data["FireplaceQu"].fillna("None" )<groupby>
train_dataset = MyIterableDataset(train_ds_names, True) for i, d in enumerate(train_dataset): if i==0: print(d) break
Contradictory, My Dear Watson
13,380,346
grouped_df = all_data.groupby('Neighborhood')['LotFrontage'] for key, item in grouped_df: print(key," ") print(grouped_df.get_group(key)) break<categorify>
def get_dataLoaders(train_dataset, per_device_train_batch_size=64, epochs=1): if isinstance(train_dataset, torch.utils.data.IterableDataset): train_sampler = None else: train_sampler = SequentialSampler(train_dataset) train_dataloader = DataLoader( train_dataset, sampler = train_sampler, batch_size = per_device_train_batch_size ) return train_dataloader def test_iterate_dataloader(train_dataloader): for step, batch in enumerate(train_dataloader): print(step, batch) return
Contradictory, My Dear Watson
13,380,346
all_data["LotFrontage"] = all_data.groupby("Neighborhood")["LotFrontage"].transform( lambda x: x.fillna(x.median()))<data_type_conversions>
class My_Dataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labels return def __getitem__(self, idx): item = {key: torch.tensor(val[idx])for key, val in self.encodings.items() } if self.labels is not None and len(self.labels)>0: item['labels'] = self.labels[idx] return item def __len__(self): return len(self.labels )
Contradictory, My Dear Watson
13,380,346
for col in ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']: all_data[col] = all_data[col].fillna('None' )<groupby>
def get_mapType_Dataset(ds_names, isLabeledDataset): input_ids = [] attention_mask = [] labels = [] lang = [] dataset_iter = MyIterableDataset(ds_names, isLabeledDataset) for encoded_dict in dataset_iter: input_ids.append(encoded_dict['input_ids']) attention_mask.append(encoded_dict['attention_mask']) labels.append(encoded_dict['labels']) encodings = {'input_ids':input_ids, 'attention_mask':attention_mask} my_dataset = My_Dataset(encodings, labels) return my_dataset
Contradictory, My Dear Watson
13,380,346
abc = ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond','GarageYrBlt', 'GarageArea', 'GarageCars'] all_data.groupby('GarageType')[abc].count()<data_type_conversions>
eval_dataset = get_mapType_Dataset(eval_ds_names, True) test_dataset = get_mapType_Dataset(test_ds_names, False )
Contradictory, My Dear Watson
13,380,346
for col in('GarageYrBlt', 'GarageArea', 'GarageCars'): all_data[col] = all_data[col].fillna(0 )<data_type_conversions>
def save_my_model_and_tokenizer(model, tokenizer=None, output_dir='./model_save/'): model_state_file = output_dir + 'my_model.bin' if not os.path.exists(output_dir): os.makedirs(output_dir) print("Saving model to %s" % model_state_file) model.cpu() state = model.state_dict() torch.save(state, model_state_file) if tokenizer is not None: tokenizer.save_pretrained(output_dir) model.cuda() return
Contradictory, My Dear Watson
13,380,346
for col in('BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath'): all_data[col] = all_data[col].fillna(0 )<data_type_conversions>
def load_model(bert_model_name, output_dir='./model_save/'): model_state_file = output_dir + 'my_model.bin' model = MyGAPModelForSeqClf(bert_model_name) state = torch.load(model_state_file) model.load_state_dict(state) return model
Contradictory, My Dear Watson
13,380,346
for col in('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'): all_data[col] = all_data[col].fillna('None' )<data_type_conversions>
def format_time(elapsed): elapsed_rounded = int(round(( elapsed))) return str(datetime.timedelta(seconds=elapsed_rounded))
Contradictory, My Dear Watson
13,380,346
all_data["MasVnrType"] = all_data["MasVnrType"].fillna("None") all_data["MasVnrArea"] = all_data["MasVnrArea"].fillna(0 )<count_values>
def compute_metrics(labels, pred_logits): preds = pred_logits.argmax(-1) precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='macro') acc = accuracy_score(labels, preds) mcc = matthews_corrcoef(labels, preds) metrics = { 'mcc': mcc, 'accuracy': acc, 'f1': f1, 'precision': precision, 'recall': recall } return metrics
Contradictory, My Dear Watson
13,380,346
all_data['MSZoning'].value_counts()<data_type_conversions>
class MyTrainer: def __init__(self, model, args, train_dataset, eval_dataset, tokenizer, compute_metrics=compute_metrics): self.model = model self.args = args self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.tokenizer = tokenizer self.compute_metrics = compute_metrics self.isTrained = False self.device = self.get_device_type() self.optimizer = AdamW(model.parameters() , lr = args.learning_rate, eps = args.adam_epsilon ) self.epochs = self.args.num_train_epochs self.train_dataloader, self.validation_dataloader, self.lr_scheduler, self.num_training_steps = self.get_dataLoaders() return def get_device_type(self): if torch.cuda.is_available() : device = torch.device("cuda") print('There are %d GPU(s)available.' % torch.cuda.device_count()) print('We will use the GPU:', torch.cuda.get_device_name(0)) else: print('No GPU available, using the CPU instead.') device = torch.device("cpu") return device def get_dataLoaders(self): if isinstance(self.train_dataset, torch.utils.data.IterableDataset): train_sampler = None else: train_sampler = SequentialSampler(self.train_dataset) train_dataloader = DataLoader( self.train_dataset, sampler = train_sampler, batch_size = self.args.per_device_train_batch_size ) validation_dataloader = DataLoader( self.eval_dataset, sampler = SequentialSampler(self.eval_dataset), batch_size = self.args.per_device_eval_batch_size ) num_training_steps = len(train_dataloader)* self.epochs lr_scheduler = get_linear_schedule_with_warmup(self.optimizer, num_warmup_steps = self.args.warmup_steps, num_training_steps = num_training_steps) return train_dataloader, validation_dataloader, lr_scheduler, num_training_steps def test_iterate_dataloader() : for step, batch in enumerate(self.train_dataloader): print(step, batch) return def train(self, is_train_base_encoding_model=True): if is_train_base_encoding_model: self.model.unfreez() else: self.model.freez() seed_val = 42 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(seed_val) training_stats = [] total_t0 = time.time() min_val_loss = 99999999 for epoch_i in range(0, self.epochs): print("") print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, self.epochs)) print('Training...') t0 = time.time() total_train_loss = 0 self.model.train() for step, batch in enumerate(self.train_dataloader): if step % 50 == 0 and not step == 0: elapsed = format_time(time.time() - t0) print(' Batch {:>5,} of {:>5,}.Elapsed: {:}.'.format(step, len(self.train_dataloader), elapsed)) if(self.args.max_steps > 0 and self.args.max_steps < step)or \ (is_train_base_encoding_model and self.args.eval_steps>0 and step % self.args.eval_steps==0 and step>0): avg_train_loss = total_train_loss / step training_time = format_time(time.time() - t0) print("Running Validation...") avg_val_loss, avg_val_f1, avg_val_mcc, avg_val_precision, avg_val_recall, avg_val_accuracy, validation_time = self.evaluate() training_stats.append({ 'epoch' : epoch_i + 1, 'training_loss' : avg_train_loss, 'eval_loss' : avg_val_loss, 'eval_f1' : avg_val_f1, 'eval_mcc' : avg_val_mcc, 'eval_precision': avg_val_precision, 'eval_recall' : avg_val_recall, 'eval_accuracy' : avg_val_accuracy, 'training_time' : training_time, 'eval_time' : validation_time }) if avg_val_loss < min_val_loss: min_val_loss = avg_val_loss save_my_model_and_tokenizer(self.model, self.tokenizer, output_dir='./model_save/') if self.args.max_steps > 0 and self.args.max_steps < step: return training_stats self.model.zero_grad() for k in batch: batch[k] = batch[k].to(self.device) output = self.model(**batch) loss = output.loss logits = output.logits total_train_loss += loss.item() loss.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters() , 1.0) self.optimizer.step() self.lr_scheduler.step() avg_train_loss = total_train_loss / len(self.train_dataloader) training_time = format_time(time.time() - t0) print(" Average training loss: {0:.2f}".format(avg_train_loss)) print(" Training epcoh took: {:}".format(training_time)) print(" Running Validation...") avg_val_loss, avg_val_f1, avg_val_mcc, avg_val_precision, avg_val_recall, avg_val_accuracy, validation_time = self.evaluate() training_stats.append({ 'epoch' : epoch_i + 1, 'training_loss' : avg_train_loss, 'eval_loss' : avg_val_loss, 'eval_f1' : avg_val_f1, 'eval_mcc' : avg_val_mcc, 'eval_precision': avg_val_precision, 'eval_recall' : avg_val_recall, 'eval_accuracy' : avg_val_accuracy, 'training_time' : training_time, 'eval_time' : validation_time }) if avg_val_loss < min_val_loss: min_val_loss = avg_val_loss save_my_model_and_tokenizer(self.model, self.tokenizer, output_dir='./model_save/') print("") print("Training complete!") print("Total training took {:}(h:mm:ss)".format(format_time(time.time() -total_t0))) self.isTrained = True self.plot_train_stats(training_stats) return training_stats def evaluate(self): t0 = time.time() self.model.eval() total_eval_mcc = 0 total_eval_f1 = 0 total_eval_precision = 0 total_eval_recall = 0 total_eval_accuracy = 0 total_eval_loss = 0 nb_eval_steps = 0 for batch in self.validation_dataloader: with torch.no_grad() : for k in batch: batch[k] = batch[k].to(self.device) output = self.model(**batch) loss = output.loss logits = output.logits total_eval_loss += loss.item() logits = logits.detach().cpu().numpy() label_ids = batch['labels'].to('cpu' ).numpy() metrics = self.compute_metrics(label_ids, logits) total_eval_mcc += metrics['mcc'] total_eval_f1 += metrics['f1'] total_eval_precision += metrics['precision'] total_eval_recall += metrics['recall'] total_eval_accuracy += metrics['accuracy'] avg_val_f1 = total_eval_f1 / len(self.validation_dataloader) print(" F1: {0:.3f}".format(avg_val_f1)) avg_val_mcc = total_eval_mcc / len(self.validation_dataloader) print(" MCC: {0:.3f}".format(avg_val_mcc)) avg_val_precision = total_eval_precision / len(self.validation_dataloader) print(" Precision: {0:.3f}".format(avg_val_precision)) avg_val_recall = total_eval_recall / len(self.validation_dataloader) print(" Recall: {0:.3f}".format(avg_val_recall)) avg_val_accuracy = total_eval_accuracy / len(self.validation_dataloader) print(" Accuracy: {0:.3f}".format(avg_val_accuracy)) avg_val_loss = total_eval_loss / len(self.validation_dataloader) validation_time = format_time(time.time() - t0) print(" Validation Loss: {0:.2f}".format(avg_val_loss)) print(" Validation took: {:}".format(validation_time)) return avg_val_loss, avg_val_f1, avg_val_mcc, avg_val_precision, avg_val_recall, avg_val_accuracy, validation_time def plot_train_stats(self, training_stats): mccs = [e['eval_mcc'] for e in training_stats] accuracies = [e['eval_accuracy'] for e in training_stats] f1_scores = [e['eval_f1'] for e in training_stats] precisions = [e['eval_precision'] for e in training_stats] recalls = [e['eval_recall'] for e in training_stats] losses = [e['eval_loss'] for e in training_stats] epochs = training_stats[-1]['epoch'] print('mccs:', mccs) print('accuracies:', accuracies) print('precisions:', precisions) print('recalls:', recalls) print('f1_scores:', f1_scores) print('losses:', losses) sns.lineplot(x=np.arange(1, epochs + 1), y=mccs, label='val_mcc') sns.lineplot(x=np.arange(1, epochs + 1), y=accuracies, label='val_accuracy') sns.lineplot(x=np.arange(1, epochs + 1), y=precisions, label='val_precision') sns.lineplot(x=np.arange(1, epochs + 1), y=recalls, label='val_recall') sns.lineplot(x=np.arange(1, epochs + 1), y=f1_scores, label='val_f1') plt.show() return def getTrainedModel(self): if self.isTrained: return self.model return None def predict(self, prediction_dataset, isRemoveLabels=True): prediction_sampler = SequentialSampler(prediction_dataset) prediction_dataloader = DataLoader(prediction_dataset, sampler=prediction_sampler, batch_size=self.args.per_device_eval_batch_size) print('Predicting labels for {:,} test sentences...'.format(len(prediction_dataset))) self.model.eval() predictions = [] for batch in prediction_dataloader: batch = {t:batch[t].to(self.device)for t in batch} with torch.no_grad() : if isRemoveLabels: batch.pop('labels') for k in batch: batch[k] = batch[k].to(self.device) outputs = model(**batch) logits = outputs[0] logits = logits.detach().cpu().numpy() predictions.append(logits) print('Done predictions for ', len(predictions), '/', len(prediction_dataloader), 'batches') print('Done prediction') pred_logits = np.concatenate(predictions, axis=0) return pred_logits, None, None
Contradictory, My Dear Watson
13,380,346
all_data['MSZoning'] = all_data['MSZoning'].fillna(all_data['MSZoning'].mode() [0] )<count_values>
class MyGAPModelForSeqClf(nn.Module): def __init__(self, bert_model_name, outputCount=3, drop_prob=0.1, nonlin=nn.ReLU()): super(MyGAPModelForSeqClf, self ).__init__() self.model = AutoModelForSequenceClassification.from_pretrained(bert_model_name ).base_model self.drop_prob = drop_prob self.nonlin = nonlin self.outputCount = outputCount hidden_size = self.model.config.hidden_size self.dense = nn.Linear(hidden_size, hidden_size) self.batchnorm = nn.BatchNorm1d(hidden_size) self.outDense = nn.Linear(hidden_size, outputCount) self.dropout = nn.Dropout(drop_prob) self.outActivtn = nn.LogSoftmax(dim=1) self.NLLLoss = nn.NLLLoss() return def freez(self): for param in self.model.base_model.parameters() : param.requires_grad = False return def unfreez(self): for param in self.model.base_model.parameters() : param.requires_grad = True return def forward(self, input_ids, attention_mask, token_type_ids=None, labels=None, **kwargs): last_hidden_states = None if token_type_ids is None: moutput = self.model(input_ids=input_ids, attention_mask=attention_mask) last_hidden_states = moutput[0] else: moutput = self.model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids) last_hidden_states = moutput[0] last_hidden_states = torch.mean(last_hidden_states, 1) X = self.dropout(self.nonlin(self.batchnorm(self.dense(last_hidden_states)))) out_logits = self.outDense(X) if labels is None: Logits = namedtuple('Logits',['logits']) out_logits = Logits(out_logits) return out_logits log_ps = self.outActivtn(out_logits) batchLoss = self.NLLLoss(log_ps, labels) Loss_Logits = namedtuple('Loss_Logits',['loss','logits']) loss_logits = Loss_Logits(batchLoss, out_logits) return loss_logits
Contradictory, My Dear Watson
13,380,346
all_data['Utilities'].value_counts()<drop_column>
model = MyGAPModelForSeqClf(bert_model_name) try: model.load_state_dict(torch.load(".. /input/robertagapxnlimnlirishi/roberta-gap-xnli-mnli-rishi/my_model.bin")) except: model.load_state_dict(torch.load(".. /input/robertagapxnlimnlirishi/roberta-gap-xnli-mnli-rishi/my_model.bin", map_location='cpu')) warnings.filterwarnings("ignore") model.cuda()
Contradictory, My Dear Watson
13,380,346
all_data = all_data.drop(['Utilities'], axis=1 )<data_type_conversions>
training_args = TrainingArguments( output_dir='./results', num_train_epochs=1, warmup_steps=1000, eval_steps=5000, max_steps=5000, learning_rate=5e-4, per_device_train_batch_size=16, per_device_eval_batch_size=16, ) trainer = MyTrainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, tokenizer=tokenizer, compute_metrics=compute_metrics, )
Contradictory, My Dear Watson
13,380,346
all_data["Functional"] = all_data["Functional"].fillna("Typ" )<categorify>
training_args = TrainingArguments( output_dir='./results', num_train_epochs=1, warmup_steps=1000, eval_steps=5000, learning_rate=1e-5, per_device_train_batch_size=24, per_device_eval_batch_size=24, ) trainer = MyTrainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, tokenizer=tokenizer, compute_metrics=compute_metrics, ) training_stats = trainer.train()
Contradictory, My Dear Watson
13,380,346
mode_col = ['Electrical','KitchenQual', 'Exterior1st', 'Exterior2nd', 'SaleType'] for col in mode_col: all_data[col] = all_data[col].fillna(all_data[col].mode() [0] )<data_type_conversions>
predictions, true_labels, metrics_dummy = trainer.predict(test_dataset) pred_labels = np.argmax(predictions, axis=1) pred_labels
Contradictory, My Dear Watson
13,380,346
<sort_values><EOS>
submitDF = original_test_df[['id']] submitDF['prediction'] = pred_labels submitDF.prediction = submitDF.prediction.astype(int) submitDF.to_csv('submission.csv', index=False) submitDF.head()
Contradictory, My Dear Watson
12,093,149
<SOS> metric: categorizationaccuracy Kaggle data source: contradictory,-my-dear-watson<count_values>
!pip install transformers
Contradictory, My Dear Watson
12,093,149
all_data['OverallCond'].value_counts()<data_type_conversions>
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') tokenizer = AutoTokenizer.from_pretrained("joeddav/xlm-roberta-large-xnli", padding=True) model = AutoModelForSequenceClassification.from_pretrained("joeddav/xlm-roberta-large-xnli" ).to(device) model.config
Contradictory, My Dear Watson
12,093,149
all_data['MSSubClass'] = all_data['MSSubClass'].apply(str) all_data['OverallCond'] = all_data['OverallCond'].astype(str) all_data['YrSold'] = all_data['YrSold'].astype(str) all_data['MoSold'] = all_data['MoSold'].astype(str )<categorify>
train_data = pd.read_csv('.. /input/contradictory-my-dear-watson/train.csv', encoding='utf8') test_data = pd.read_csv('.. /input/contradictory-my-dear-watson/test.csv', encoding='utf8') train_data.head()
Contradictory, My Dear Watson
12,093,149
cols =('FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual', 'GarageCond', 'ExterQual', 'ExterCond','HeatingQC', 'PoolQC', 'KitchenQual', 'BsmtFinType1', 'BsmtFinType2', 'Functional', 'Fence', 'BsmtExposure', 'GarageFinish', 'LandSlope', 'LotShape', 'PavedDrive', 'Street', 'Alley', 'CentralAir', 'MSSubClass', 'OverallCond', 'YrSold', 'MoSold') for c in cols: lbl = LabelEncoder() lbl.fit(list(all_data[c].values)) all_data[c] = lbl.transform(list(all_data[c].values)) print('Shape all_data: {}'.format(all_data.shape))<feature_engineering>
train_data['label'] = train_data['label'].replace([0, 2], [2, 0]) train_data.head()
Contradictory, My Dear Watson
12,093,149
all_data['TotalSF'] = all_data['TotalBsmtSF'] + all_data['1stFlrSF'] + all_data['2ndFlrSF']<feature_engineering>
class MyDataset(Dataset): def __init__(self, df, tokenizer, labels = False): self.inputs = df.loc[:,['premise', 'hypothesis']].values self.tokenizer = tokenizer self.labels = labels if self.labels: self.tgt = df['label'].values def __len__(self): return len(self.inputs) def __getitem__(self, idx): inputs = tokenizer(self.inputs[idx].tolist() , add_special_tokens=True, padding=True, return_tensors='pt') if self.labels: inputs['labels'] = self.tgt[idx] return inputs return inputs
Contradictory, My Dear Watson
12,093,149
skewness = skewness[abs(skewness)> 0.75] print("There are {} skewed numerical features to Box Cox transform".format(skewness.shape[0])) skewed_features = skewness.index lam = 0.15 for feat in skewed_features: all_data[feat] = boxcox1p(all_data[feat], lam )<categorify>
def eval_model(model, dataloader, device): correct = 0 eval_loss = 0 model.eval() for i, batch in enumerate(dataloader): out = model(input_ids=batch['input_ids'].squeeze().to(device), attention_mask=batch['attention_mask'].squeeze().to(device), labels=batch['labels'].squeeze().to(device)) eval_loss += out[0].item() correct +=(out[1].argmax(dim=1)==batch['labels'].squeeze().to(device)).float().sum() accu = correct / train_dataloader.dataset.__len__() eval_loss /= len(dataloader) return eval_loss, accu
Contradictory, My Dear Watson
12,093,149
all_data = pd.get_dummies(all_data) all_data.shape<prepare_x_and_y>
train_dataset = MyDataset(train_data.loc[0:1000], tokenizer, labels=True) train_dataloader = DataLoader(dataset=train_dataset, sampler=BatchSampler( SequentialSampler(train_dataset), batch_size=8, drop_last=True)) loss, accuracy = eval_model(model, train_dataloader, device) print("Loss: {}, Accuracy: {}".format(loss, accuracy))
Contradictory, My Dear Watson
12,093,149
train = all_data[:ntrain] test = all_data[ntrain:] train.shape<import_modules>
def submission_predict(model, dataloader, device): model.eval() predicts = np.array([]) for i, batch in enumerate(dataloader): inp_ids = batch['input_ids'].squeeze().to(device) mask = batch['attention_mask'].squeeze().to(device) out = model(input_ids=inp_ids, attention_mask=mask) batch_preds = out[0].argmax(dim=1) predicts = np.concatenate(( predicts, batch_preds.cpu().detach().numpy())) return predicts
Contradictory, My Dear Watson
12,093,149
from sklearn.linear_model import ElasticNet, Lasso, BayesianRidge, LassoLarsIC from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.kernel_ridge import KernelRidge from sklearn.pipeline import make_pipeline from sklearn.preprocessing import RobustScaler from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone from sklearn.model_selection import KFold, cross_val_score, train_test_split from sklearn.metrics import mean_squared_error import xgboost as xgb import lightgbm as lgb<compute_train_metric>
test_dataset = MyDataset(test_data, tokenizer, labels=False) test_dataloader = DataLoader(dataset=test_dataset, sampler=BatchSampler( SequentialSampler(test_dataset), batch_size=8, drop_last=False), shuffle=False) test_preds = submission_predict(model, test_dataloader, device )
Contradictory, My Dear Watson
12,093,149
n_folds = 5 def rmsle_cv(model): kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(train.values) rmse= np.sqrt(-cross_val_score(model, train.values, y_train, scoring="neg_mean_squared_error", cv = kf)) return(rmse )<compute_train_metric>
submission = np.concatenate(( test_data['id'].values.reshape(-1,1), np.int32(test_preds.reshape(-1,1))), axis=1) submission = pd.DataFrame(submission, columns=['id', 'prediction']) submission['prediction'] = submission['prediction'].astype(np.int32 ).replace([0,2], [2,0]) submission.to_csv('submission.csv', index=False) model.save_pretrained('./model.pt') tokenizer.save_pretrained('.. /tokenizer' )
Contradictory, My Dear Watson
11,089,925
KRR = KernelRidge(alpha=0.6, kernel='polynomial', degree=2, coef0=2.5) score = rmsle_cv(KRR) print("Kernel Ridge score: {:.4f}({:.4f}) ".format(score.mean() , score.std()))<compute_test_metric>
!pip install googletrans textAugment
Contradictory, My Dear Watson
11,089,925
lasso = make_pipeline(RobustScaler() , Lasso(alpha =0.0005, random_state=1)) score = rmsle_cv(lasso) print("Lasso score: {:.4f}({:.4f}) ".format(score.mean() , score.std()))<compute_train_metric>
try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) print('Running on TPU ', tpu.master()) except ValueError: strategy = tf.distribute.get_strategy() print("REPLICAS: ", strategy.num_replicas_in_sync )
Contradictory, My Dear Watson
11,089,925
ENet = make_pipeline(RobustScaler() , ElasticNet(alpha=0.0005, l1_ratio=.9, random_state=3)) score = rmsle_cv(ENet) print("ElasticNet score: {:.4f}({:.4f}) ".format(score.mean() , score.std()))<compute_train_metric>
df_train = pd.read_csv('/kaggle/input/contradictory-my-dear-watson/train.csv') df_test = pd.read_csv('/kaggle/input/contradictory-my-dear-watson/test.csv' )
Contradictory, My Dear Watson
11,089,925
GBoost = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05, max_depth=4, max_features='sqrt', min_samples_leaf=15, min_samples_split=10, loss='huber', random_state =5) score = rmsle_cv(GBoost) print("Gradient Boosting score: {:.4f}({:.4f}) ".format(score.mean() , score.std()))<train_model>
from textaugment import EDA from googletrans import Translator
Contradictory, My Dear Watson
11,089,925
LassoMd = lasso.fit(train.values,y_train) ENetMd = ENet.fit(train.values,y_train) KRRMd = KRR.fit(train.values,y_train) GBoostMd = GBoost.fit(train.values,y_train )<predict_on_test>
for lang in df_train['language'].unique() : number_of_training_samples = df_train[df_train['language'] == lang].shape[0] / df_train.shape[0] number_of_testing_samples = df_test[df_test['language'] == lang].shape[0] / df_test.shape[0] print('distribution of {} in training samples: {} and in testing samples {}'.format(lang, number_of_training_samples, number_of_testing_samples))
Contradictory, My Dear Watson
11,089,925
finalMd =(np.expm1(LassoMd.predict(test.values)) + np.expm1(ENetMd.predict(test.values)) + np.expm1(KRRMd.predict(test.values)) + np.expm1(GBoostMd.predict(test.values)))/ 4 finalMd<save_to_csv>
idx2label = {0: 'entailment', 1 :'neutral', 2: 'contradiction'} for label in df_train['label'].unique() : number_of_training_samples = df_train[df_train['label'] == label].shape[0] / df_train.shape[0] print('distribution of {} in training samples: {}'.format(idx2label[label], number_of_training_samples))
Contradictory, My Dear Watson
11,089,925
sub = pd.DataFrame() sub['Id'] = test_ID sub['SalePrice'] = finalMd sub.to_csv('submission.csv',index=False )<define_search_space>
tf.random.set_seed(seed )
Contradictory, My Dear Watson
11,089,925
%%writefile main.cpp using namespace std; using namespace std::chrono; constexpr array<uint8_t, 12> DISTRIBUTION{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 5}; // You can setup how many families you need for swaps and what best choice use for each family // {2, 5} it's mean the first random family will brute force for choices 1-2 and the second random family will brute force for choices 1-5 constexpr int MAX_OCCUPANCY = 300; constexpr int MIN_OCCUPANCY = 125; constexpr int NUMBER_FAMILIES = 6000; constexpr int NUMBER_DAYS = 100; constexpr int BEST_N = 10; array<uint8_t, NUMBER_FAMILIES> n_people; array<array<uint8_t, 10>, NUMBER_FAMILIES> choices; array<array<uint16_t, 10>, NUMBER_FAMILIES> PCOSTM; array<array<array<double, 5>, 176>, 176> ACOSTM; void init_data() { ifstream in(".. /input/santa-2019-revenge-of-the-accountants/family_data.csv"); assert(in && "family_data.csv"); string header; int n,x; char comma; getline(in, header); for(int j = 0; j < choices.size() ; ++j){ in >> x >> comma; for(int i = 0; i < 10; ++i){ in >> x >> comma; choices[j][i] = x-1; } in >> n; n_people[j] = n; } array<int, 10> pc{0, 50, 50, 100, 200, 200, 300, 300, 400, 500}; array<int, 10> pn{0, 0, 9, 9, 9, 18, 18, 36, 36, 235}; for(int j = 0; j < PCOSTM.size() ; ++j) for(int i = 0; i < 10; ++i) PCOSTM[j][i] = pc[i] + pn[i] * n_people[j]; for(int i = 0; i < 176; ++i) for(int j = 0; j < 176; ++j) for(int k = 1; k <= 5; ++k) ACOSTM[i][j][k-1] = i * pow(i+MIN_OCCUPANCY, 0.5 + abs(i-j)/ 50.0)/ 400.0 / k / k; } array<uint8_t, NUMBER_FAMILIES> read_submission(string filename){ ifstream in(filename); assert(in && "submission.csv"); array<uint8_t, NUMBER_FAMILIES> assigned_day{}; string header; int id, x; char comma; getline(in, header); for(int j = 0; j < choices.size() ; ++j){ in >> id >> comma >> x; assigned_day[j] = x-1; auto it = find(begin(choices[j]), end(choices[j]), assigned_day[j]); if(it != end(choices[j])) assigned_day[j] = distance(begin(choices[j]), it); } return assigned_day; } struct Index { Index(array<uint8_t, NUMBER_FAMILIES> assigned_days_): assigned_days(assigned_days_){ setup() ; } array<uint8_t, NUMBER_FAMILIES> assigned_days; array<uint16_t, NUMBER_DAYS> daily_occupancy_{}; int preference_cost_ = 0; void setup() { preference_cost_ = 0; daily_occupancy_.fill(0); for(int j = 0; j < assigned_days.size() ; ++j){ daily_occupancy_[choices[j][assigned_days[j]]] += n_people[j]; preference_cost_ += PCOSTM[j][assigned_days[j]]; } } double calc(const array<uint16_t, NUMBER_FAMILIES>& indices, const array<uint8_t, DISTRIBUTION.size() >& change){ double accounting_penalty = 0.0; auto daily_occupancy = daily_occupancy_; int preference_cost = preference_cost_; for(int i = 0; i < DISTRIBUTION.size() ; ++i){ int j = indices[i]; daily_occupancy[choices[j][assigned_days[j]]] -= n_people[j]; daily_occupancy[choices[j][ change[i]]] += n_people[j]; preference_cost += PCOSTM[j][change[i]] - PCOSTM[j][assigned_days[j]]; } for(auto occupancy : daily_occupancy) if(occupancy < MIN_OCCUPANCY) return 1e12*(MIN_OCCUPANCY-occupancy); else if(occupancy > MAX_OCCUPANCY) return 1e12*(occupancy - MAX_OCCUPANCY); for(int day = 0; day < NUMBER_DAYS; ++day) for(int j = 0; j < 5; ++j) accounting_penalty += ACOSTM[daily_occupancy[day]-MIN_OCCUPANCY][daily_occupancy[min(NUMBER_DAYS-1, day+j+1)]-MIN_OCCUPANCY][j]; return preference_cost + accounting_penalty; } void reindex(const array<uint16_t, DISTRIBUTION.size() >& indices, const array<uint8_t, DISTRIBUTION.size() >& change){ for(int i = 0; i < DISTRIBUTION.size() ; ++i){ assigned_days[indices[i]] = change[i]; } setup() ; } }; double calc(const array<uint8_t, NUMBER_FAMILIES>& assigned_days, bool print=false){ int preference_cost = 0; double accounting_penalty = 0.0; array<uint16_t, NUMBER_DAYS> daily_occupancy{}; for(int j = 0; j < assigned_days.size() ; ++j){ preference_cost += PCOSTM[j][assigned_days[j]]; daily_occupancy[choices[j][assigned_days[j]]] += n_people[j]; } for(auto occupancy : daily_occupancy) if(occupancy < MIN_OCCUPANCY) return 1e12*(MIN_OCCUPANCY-occupancy); else if(occupancy > MAX_OCCUPANCY) return 1e12*(occupancy - MAX_OCCUPANCY); for(int day = 0; day < NUMBER_DAYS; ++day) for(int j = 0; j < 5; ++j) accounting_penalty += ACOSTM[daily_occupancy[day]-MIN_OCCUPANCY][daily_occupancy[min(99, day+j+1)]-MIN_OCCUPANCY][j]; if(print){ cout << preference_cost << " " << accounting_penalty << " " << preference_cost+accounting_penalty << endl; } return preference_cost + accounting_penalty; } void save_sub(const array<uint8_t, NUMBER_FAMILIES>& assigned_day){ ofstream out("submission.csv"); out << "family_id,assigned_day" << endl; for(int i = 0; i < assigned_day.size() ; ++i) out << i << "," << choices[i][assigned_day[i]]+1 << endl; } const vector<array<uint8_t, DISTRIBUTION.size() >> changes = []() { vector<array<uint8_t, DISTRIBUTION.size() >> arr; array<uint8_t, DISTRIBUTION.size() > tmp{}; for(int i = 0; true; ++i){ arr.push_back(tmp); tmp[0] += 1; for(int j = 0; j < DISTRIBUTION.size() ; ++j) if(tmp[j] >= DISTRIBUTION[j]){ if(j >= DISTRIBUTION.size() -1) return arr; tmp[j] = 0; ++tmp[j+1]; } } return arr; }() ; template<class ExitFunction> void stochastic_product_search(Index index, ExitFunction fn){ double best_local_score = calc(index.assigned_days); thread_local std::mt19937 gen(std::random_device{}()); uniform_int_distribution<> dis(0, NUMBER_FAMILIES-1); array<uint16_t, NUMBER_FAMILIES> indices; iota(begin(indices), end(indices), 0); array<uint16_t, DISTRIBUTION.size() > best_indices{}; array<uint8_t, DISTRIBUTION.size() > best_change{}; bool need_save = false; for(; fn() ;){ bool found_better = false; for(int k = 0; k < BEST_N; ++k){ for(int i = 0; i < DISTRIBUTION.size() ; ++i)//random swap swap(indices[i], indices[dis(gen)]); for(const auto& change : changes){ auto score = index.calc(indices, change); if(score < best_local_score){ found_better = true; best_local_score = score; best_change = change; copy_n(begin(indices), DISTRIBUTION.size() , begin(best_indices)) ; } } } if(found_better){ // reindex from N best if found better need_save = true; index.reindex(best_indices, best_change); // save_sub(index.assigned_days); calc(index.assigned_days, true); } } if(need_save) save_sub(index.assigned_days); } int main() { init_data() ; auto assigned_day = read_submission(".. /input/mip-optimization-preference-cost-santa2019revenge/submission.csv"); Index index(assigned_day); calc(index.assigned_days, true); // auto forever = []() { return true; }; // auto count_exit = [start = 0]() mutable { return(++start <= 1000); }; auto time_exit = [start = high_resolution_clock::now() ]() { return duration_cast<minutes>(high_resolution_clock::now() -start ).count() < 355; //5h55 }; stochastic_product_search(index, time_exit); return 0; }<set_options>
model_name = 'jplu/tf-xlm-roberta-large' tokenizer = XLMRobertaTokenizer.from_pretrained(model_name )
Contradictory, My Dear Watson
11,089,925
!g++ -pthread -lpthread -O3 -std=c++17 -o main main.cpp<set_options>
def clean_word(value): language = value[0] word = value[1] if language != 'English': word = word.lower() return word word = word.lower() word = re.sub(r'\?\?', 'e', word) word = re.sub('\.\.\.', '.', word) word = re.sub('\/', ' ', word) word = re.sub('--', ' ', word) word = re.sub('/\xad', '', word) word = word.strip(' ') return word df_train['premise'] = df_train[['language', 'premise']].apply(lambda v: clean_word(v), axis=1) df_train['hypothesis'] = df_train[['language', 'hypothesis']].apply(lambda v: clean_word(v), axis=1) df_test['premise'] = df_test[['language', 'premise']].apply(lambda v: clean_word(v), axis=1) df_test['hypothesis'] = df_test[['language', 'hypothesis']].apply(lambda v: clean_word(v), axis=1 )
Contradictory, My Dear Watson
11,089,925
sns.set_style('whitegrid') %matplotlib inline <load_from_csv>
def build_model() : with strategy.scope() : bert_encoder = TFXLMRobertaModel.from_pretrained(model_name) input_word_ids = tf.keras.Input(shape=(None,), dtype=tf.int32, name="input_word_ids") input_mask = tf.keras.Input(shape=(None,), dtype=tf.int32, name="input_mask") embedding = bert_encoder([input_word_ids, input_mask])[0] output_layer = tf.keras.layers.Dropout(0.25 )(embedding) output_layer = tf.keras.layers.GlobalAveragePooling1D()(output_layer) output_dense_layer = tf.keras.layers.Dense(64, activation='relu' )(output_layer) output_dense_layer = tf.keras.layers.Dense(32, activation='relu' )(output_dense_layer) output = tf.keras.layers.Dense(3, activation='softmax' )(output_dense_layer) model = tf.keras.Model(inputs=[input_word_ids, input_mask], outputs=output) model.compile(tf.keras.optimizers.Adam(lr=1e-5), loss='sparse_categorical_crossentropy', metrics=['accuracy']) return model
Contradictory, My Dear Watson
11,089,925
titanic_df = pd.read_csv(".. /input/train.csv") test_df = pd.read_csv(".. /input/test.csv") titanic_df.head()<categorify>
batch_size = 8 * strategy.num_replicas_in_sync num_splits = 5 test_input = None
Contradictory, My Dear Watson
11,089,925
def get_title(name): if '.' in name: return name.split(',')[1].split('.')[0].strip() else: return 'Unknown' def title_map(title): if title in ['Mr']: return 1 elif title in ['Master']: return 3 elif title in ['Ms','Mlle','Miss']: return 4 elif title in ['Mme','Mrs']: return 5 else: return 2 titanic_df['title'] = titanic_df['Name'].apply(get_title ).apply(title_map) test_df['title'] = test_df['Name'].apply(get_title ).apply(title_map) title_xt = pd.crosstab(titanic_df['title'], titanic_df['Survived']) title_xt_pct = title_xt.div(title_xt.sum(1 ).astype(float), axis=0) title_xt_pct.plot(kind='bar', stacked=True, title='Survival Rate by title') plt.xlabel('title') plt.ylabel('Survival Rate' )<drop_column>
auto = tf.data.experimental.AUTOTUNE languages = [ 'zh-cn' if lang == 'zh' else lang for lang in df_train['lang_abv'].unique() ] def make_dataset(train_input, train_label): dataset = tf.data.Dataset.from_tensor_slices( ( train_input, train_label ) ).repeat().shuffle(batch_size ).batch(batch_size ).prefetch(auto) return dataset
Contradictory, My Dear Watson
11,089,925
titanic_df = titanic_df.drop(['PassengerId','Name','Ticket'], axis=1) test_df = test_df.drop(['Name','Ticket'], axis=1 )<feature_engineering>
def xlm_roberta_encode(hypotheses, premises, src_langs, augmentation=False): num_examples = len(hypotheses) sentence_1 = [tokenizer.encode(s)for s in premises] sentence_2 = [tokenizer.encode(s)for s in hypotheses] input_word_ids = list(map(lambda x: x[0]+x[1], list(zip(sentence_1,sentence_2)))) input_mask = [np.ones_like(x)for x in input_word_ids] inputs = { 'input_word_ids': tf.keras.preprocessing.sequence.pad_sequences(input_word_ids, padding='post'), 'input_mask': tf.keras.preprocessing.sequence.pad_sequences(input_mask, padding='post') } return inputs
Contradictory, My Dear Watson
11,089,925
test_df["Fare"].fillna(test_df["Fare"].median() , inplace=True) titanic_df.loc[ titanic_df['Fare'] <= 7.91, 'Fare'] = 0 titanic_df.loc[(titanic_df['Fare'] > 7.91)&(titanic_df['Fare'] <= 14.454), 'Fare'] = 1 titanic_df.loc[(titanic_df['Fare'] > 14.454)&(titanic_df['Fare'] <= 31), 'Fare'] = 2 titanic_df.loc[ titanic_df['Fare'] > 31, 'Fare'] = 3 test_df.loc[ test_df['Fare'] <= 7.91, 'Fare'] = 0 test_df.loc[(test_df['Fare'] > 7.91)&(test_df['Fare'] <= 14.454), 'Fare'] = 1 test_df.loc[(test_df['Fare'] > 14.454)&(test_df['Fare'] <= 31), 'Fare'] = 2 test_df.loc[test_df['Fare'] > 31, 'Fare'] = 3 titanic_df['Fare'] = titanic_df['Fare'].astype(int) test_df['Fare'] = test_df['Fare'].astype(int) <categorify>
train_df, validation_df = train_test_split(df_train, test_size=0.1) if test_input is None: test_input = xlm_roberta_encode(df_test.hypothesis.values, df_test.premise.values, df_test.lang_abv.values,augmentation=False) df_train['prediction'] = 0 num_augmentation = 1 train_input = xlm_roberta_encode(train_df.hypothesis.values,train_df.premise.values, train_df.lang_abv.values, augmentation=False) train_label = train_df.label.values train_sequence = make_dataset(train_input, train_label) n_steps =(len(train_label)) // batch_size validation_input = xlm_roberta_encode(validation_df.hypothesis.values, validation_df.premise.values,validation_df.lang_abv.values, augmentation=False) validation_label = validation_df.label.values tf.keras.backend.clear_session() with strategy.scope() : model = build_model() history = model.fit( train_sequence, shuffle=True, steps_per_epoch=n_steps, validation_data =(validation_input, validation_label), epochs=50, verbose=1, callbacks=[ tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=10), tf.keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', factor=0.1, patience=5), tf.keras.callbacks.ModelCheckpoint( 'model.h5', monitor='val_accuracy', save_best_only=True,save_weights_only=True) ] ) model.load_weights('model.h5') validation_predictions = model.predict(validation_input) validation_predictions = np.argmax(validation_predictions, axis=-1) validation_df['predictions'] = validation_predictions acc = accuracy_score(validation_label, validation_predictions) print('Accuracy: {}'.format(acc)) test_split_predictions = model.predict(test_input) del train_input, train_label, validation_input, validation_label, model, train_sequence gc.collect()
Contradictory, My Dear Watson
11,089,925
titanic_df['Age'] = titanic_df.groupby(['Pclass'])['Age'].transform(lambda x: x.fillna(x.mean())) test_df['Age'] = test_df.groupby(['Pclass'])['Age'].transform(lambda x: x.fillna(x.mean()))<drop_column>
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) labels = list(idx2label.values()) for ax,language in zip(axes.flatten() [:validation_df['language'].nunique() ],validation_df['language'].unique()): y_pred = validation_df[validation_df['language'] == language]['prediction'].values y_true = validation_df[validation_df['language'] == language]['label'].values lang_acc = accuracy_score(y_true, y_pred) print('Language {} has accuracy {}'.format(language, lang_acc)) cm = confusion_matrix(np.array([idx2label[v] for v in y_true]), np.array([idx2label[v] for v in y_pred]), labels=labels) cax = ConfusionMatrixDisplay(cm, display_labels=labels) cax.plot(ax=ax) ax.set_title(language) ax.set_xticklabels([''] + labels) ax.set_yticklabels([''] + labels) plt.title('Confusion matrix of the classifier') plt.xlabel('Predicted') plt.ylabel('True') plt.tight_layout() plt.show()
Contradictory, My Dear Watson
11,089,925
titanic_df.drop("Cabin",axis=1,inplace=True) test_df.drop("Cabin",axis=1,inplace=True )<feature_engineering>
predictions = np.argmax(test_split_predictions, axis=-1) submission = df_test.id.copy().to_frame() submission['prediction'] = predictions
Contradictory, My Dear Watson
11,089,925
<categorify><EOS>
submission.head() submission.to_csv("submission.csv", index = False )
Contradictory, My Dear Watson
11,148,955
<SOS> metric: categorizationaccuracy Kaggle data source: contradictory,-my-dear-watson<categorify>
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import tensorflow as tf from transformers import AutoTokenizer, TFAutoModel from tqdm.notebook import tqdm
Contradictory, My Dear Watson
11,148,955
titanic_df['age_class'] = titanic_df['Age'] * titanic_df['Pclass'] test_df['age_class'] = test_df['Age'] * test_df['Pclass']<prepare_x_and_y>
!pip install nlp
Contradictory, My Dear Watson
11,148,955
X_train = titanic_df.drop("Survived",axis=1) Y_train = titanic_df["Survived"] X_test = test_df.drop("PassengerId",axis=1 ).copy()<compute_train_metric>
MODEL_NAME = 'jplu/tf-xlm-roberta-large' EPOCHS = 10 MAX_LEN = 80 RATE = 1e-5 BATCH_SIZE = 64 * strategy.num_replicas_in_sync
Contradictory, My Dear Watson
11,148,955
<train_on_grid>
train = pd.read_csv('/kaggle/input/contradictory-my-dear-watson/train.csv') test = pd.read_csv('/kaggle/input/contradictory-my-dear-watson/test.csv') submission = pd.read_csv('/kaggle/input/contradictory-my-dear-watson/sample_submission.csv' )
Contradictory, My Dear Watson
11,148,955
<train_model>
train = train[['premise', 'hypothesis', 'label']]
Contradictory, My Dear Watson
11,148,955
random_forest = RandomForestClassifier(n_estimators=100) random_forest.fit(X_train, Y_train) Y_pred_1 = random_forest.predict(X_test) random_forest.score(X_train, Y_train )<train_on_grid>
multigenre_data = nlp.load_dataset(path='glue', name='mnli' )
Contradictory, My Dear Watson
11,148,955
<train_on_grid>
index = [] premise = [] hypothesis = [] label = [] for example in multigenre_data['train']: premise.append(example['premise']) hypothesis.append(example['hypothesis']) label.append(example['label'] )
Contradictory, My Dear Watson
11,148,955
<data_type_conversions>
multigenre_df = pd.DataFrame(data={ 'premise': premise, 'hypothesis': hypothesis, 'label': label } )
Contradictory, My Dear Watson
11,148,955
Y_pred = Y_pred_1<save_to_csv>
adversarial_data = nlp.load_dataset(path='anli' )
Contradictory, My Dear Watson
11,148,955
submission = pd.DataFrame({ "PassengerId": test_df["PassengerId"], "Survived": Y_pred }) submission.to_csv('titanic.csv', index=False )<load_from_csv>
index = [] premise = [] hypothesis = [] label = [] for example in adversarial_data['train_r1']: premise.append(example['premise']) hypothesis.append(example['hypothesis']) label.append(example['label']) for example in adversarial_data['train_r2']: premise.append(example['premise']) hypothesis.append(example['hypothesis']) label.append(example['label']) for example in adversarial_data['train_r3']: premise.append(example['premise']) hypothesis.append(example['hypothesis']) label.append(example['label'] )
Contradictory, My Dear Watson
11,148,955
train_df = pd.read_csv("/kaggle/input/titanic/train.csv") test_df = pd.read_csv("/kaggle/input/titanic/test.csv" )<count_missing_values>
adversarial_df = pd.DataFrame(data={ 'premise': premise, 'hypothesis': hypothesis, 'label': label } )
Contradictory, My Dear Watson
11,148,955
train_df.isnull().sum()<count_missing_values>
train = pd.concat([train, multigenre_df, adversarial_df] )
Contradictory, My Dear Watson
11,148,955
test_df.isnull().sum()<count_missing_values>
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME )
Contradictory, My Dear Watson
11,148,955
train_df.isnull().sum()<count_missing_values>
train_text = train[['premise', 'hypothesis']].values.tolist() test_text = test[['premise', 'hypothesis']].values.tolist()
Contradictory, My Dear Watson
11,148,955
train_df.drop('Cabin', axis=1, inplace=True) train_df.isnull().sum()<count_missing_values>
train_encoded = tokenizer.batch_encode_plus( train_text, pad_to_max_length=True, max_length=MAX_LEN )
Contradictory, My Dear Watson
11,148,955
train_df.dropna(subset=['Embarked'], inplace=True) train_df.isnull().sum()<data_type_conversions>
test_encoded = tokenizer.batch_encode_plus( test_text, pad_to_max_length=True, max_length=MAX_LEN )
Contradictory, My Dear Watson
11,148,955
train_df['Age'].fillna(train_df['Age'].mean() , inplace=True) train_df.isnull().sum()<count_missing_values>
vocab = tokenizer.get_vocab() print(vocab['<s>']) print(vocab['▁and']) print(vocab['▁these']) print(vocab['▁comments']) print(vocab['▁were']) print(vocab['▁considered']) print(vocab['▁in']) print(vocab['▁formula']) print(vocab['ting']) print(vocab['▁the']) print(vocab['▁inter']) print(vocab['im']) print(vocab['▁rules']) print(vocab['.'] )
Contradictory, My Dear Watson
11,148,955
test_df.isnull().sum()<count_missing_values>
x_train, x_valid, y_train, y_valid = train_test_split( train_encoded['input_ids'], train.label.values, test_size=0.2, random_state=2020 )
Contradictory, My Dear Watson
11,148,955
test_df.drop('Cabin', axis=1, inplace=True) test_df.isnull().sum()<feature_engineering>
x_test = test_encoded['input_ids']
Contradictory, My Dear Watson
11,148,955
test_df['Fare'] = test_df['Fare'].fillna(train_df['Fare'].median()) test_df.isnull().sum()<count_missing_values>
auto = tf.data.experimental.AUTOTUNE train_dataset =( tf.data.Dataset .from_tensor_slices(( x_train, y_train)) .repeat() .shuffle(2048) .batch(BATCH_SIZE) .prefetch(auto) )
Contradictory, My Dear Watson
11,148,955
test_df['Age'].fillna(train_df['Age'].mean() , inplace=True) test_df.isnull().sum()<prepare_x_and_y>
valid_dataset =( tf.data.Dataset .from_tensor_slices(( x_valid, y_valid)) .batch(BATCH_SIZE) .cache() .prefetch(auto) )
Contradictory, My Dear Watson
11,148,955
X = train_df.drop(['PassengerId', 'Survived', 'Name', 'Ticket', 'Fare'], axis=1) y = train_df['Survived'] n_test_df = test_df.drop(['PassengerId', 'Name', 'Ticket', 'Fare'], axis=1 )<categorify>
test_dataset =( tf.data.Dataset .from_tensor_slices(x_test) .batch(BATCH_SIZE) )
Contradictory, My Dear Watson
11,148,955
X = pd.get_dummies(X, drop_first=True )<categorify>
with strategy.scope() : backbone = TFAutoModel.from_pretrained(MODEL_NAME )
Contradictory, My Dear Watson