kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
7,928,811
z={} for images, image_ids in data_loader: predictions = make_predictions(images,0.4337) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i,iou_thr=0.4637,skip_box_thr=0.12) boxes =(boxes*2) z[image_ids[i]] = [boxes,scores,labels]<define_variables>
X_train, X_val, y_train, y_val = train_test_split(X, df["target"], test_size=0.1, random_state=42) print(X_train.shape) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_va...
Natural Language Processing with Disaster Tweets
7,928,811
def get_valid_transforms() : return A.Compose( [ A.Resize(height=1024, width=1024, p=1.0), ToTensorV2(p=1.0), ], p=1.0, ) dataset = TestDatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms() ) def collate_fn(batch): return tu...
w2v_model = gensim.downloader.load("word2vec-google-news-300") type(w2v_model )
Natural Language Processing with Disaster Tweets
7,928,811
class BaseWheatTTA: image_size = 1024 def augment(self, image): raise NotImplementedError def batch_augment(self, images): raise NotImplementedError def deaugment_boxes(self, boxes): raise NotImplementedError class TTAHorizontalFlip(BaseWheatTTA): def augment(self, image): return image.flip(1) def batch_augment(se...
X_all = pd.concat([df["tokens"], df_test["tokens"]] ).reset_index(drop=True) documents = [TaggedDocument(doc, [i])for i, doc in enumerate(X_all)] del X_all model_d2v = Doc2Vec(documents, vector_size=500, window=2, min_count=1, workers=-1 )
Natural Language Processing with Disaster Tweets
7,928,811
def load_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=1024 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load(ch...
print(len(df["tokens"])) X = [model_d2v.infer_vector(texts)for texts in df["tokens"]] X = np.array(X) print(len(X)) X_test = [model_d2v.infer_vector(texts)for texts in df_test["tokens"]] X_test = np.array(X_test )
Natural Language Processing with Disaster Tweets
7,928,811
l={} for images, image_ids in data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) l[image_ids[i]] = [boxes, scores, labels]<feature_engineering>
X_train, X_val, y_train, y_val = train_test_split(X, df["target"], test_size=0.1, random_state=42) print(X_train.shape) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_va...
Natural Language Processing with Disaster Tweets
21,448,746
all_path = glob('.. /input/global-wheat-detection/test/*') a = {} for row in range(len(all_path)) : image_id = all_path[row].split("/")[-1].split(".")[0] boxes,scores,labels = run_last_wbf(y[image_id],z[image_id]) boxes =(boxes*1023) a[image_id] = [boxes,scores,labels]<categorify>
!pip install git+git://github.com/AndLen/simpletransformers.git --quiet
Natural Language Processing with Disaster Tweets
21,448,746
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings) results = [] for row in range(len(all_path)) : image_id = all_path[row].split("/")[-1].split(".")[0] ...
import csv import os import torch from transformers import pipeline import gc import seaborn as sns from matplotlib import pyplot as plt from scipy.special import softmax from simpletransformers.classification import(ClassificationModel, ClassificationArgs) import sklearn from sklearn.model_selection import train_test...
Natural Language Processing with Disaster Tweets
21,448,746
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv',index=False) test_df<install_modules>
test = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv") training = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv" )
Natural Language Processing with Disaster Tweets
21,448,746
!pip install --no-deps ".. /input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl" !pip install --no-deps ".. /input/resnest/resnest-0.0.5-py3-none-any.whl"<import_modules>
training["text"].isna().sum()
Natural Language Processing with Disaster Tweets
21,448,746
import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision.models.detection import FasterRCNN from torchvision.models.detection.rpn import AnchorGenerator from torch.utils.data.sampler import SequentialSampler from torchvision.models.utils import load_state_dict_from_url ...
training_df = training[["text", "target"]] training_df.columns = ["text", "labels"]
Natural Language Processing with Disaster Tweets
21,448,746
class DatasetRetriever(Dataset): def __init__(self, marking, image_ids, transforms=None, test=False): super().__init__() self.image_ids = image_ids self.marking = marking self.transforms = transforms self.test = test def __getitem__(self, index: int): image_id = self.image_ids[index] if self.test or random.random() > 0...
Natural Language Processing with Disaster Tweets
21,448,746
class TestDatasetRetriever(Dataset): def __init__(self, image_ids, path, transforms=None): super().__init__() self.image_ids = image_ids self.transforms = transforms self.path = path def __getitem__(self, index: int): image_id = self.image_ids[index] image = cv2.imread(f'{self.path}/{image_id}.jpg', cv2.IMREAD_COLOR) ...
gc.collect() torch.cuda.empty_cache()
Natural Language Processing with Disaster Tweets
21,448,746
def get_df_folds(marking): df_folds = marking[['image_id']].copy() df_folds.loc[:, 'bbox_count'] = 1 df_folds = df_folds.groupby('image_id' ).count() df_folds.loc[:, 'source'] = marking[['image_id', 'source']].groupby('image_id' ).min() ['source'] df_folds.loc[:, 'stratify_group'] = np.char.add( df_folds['source'].val...
model_args = ClassificationArgs(num_train_epochs=2, overwrite_output_dir=True) model_args.manual_seed = 42 model_args.best_model_dir = "/kaggle/working/best_model" model_args.output_dir = "/kaggle/temp/output" model_args.normalization = True model_args.reprocess_input_data = True model_args.train_batch_size = 80 model...
Natural Language Processing with Disaster Tweets
21,448,746
class CrossEntropyLabelSmooth(torch.nn.Module): def __init__(self, num_classes, epsilon=0.1, use_gpu=True): super(CrossEntropyLabelSmooth, self ).__init__() self.num_classes = num_classes self.epsilon = epsilon self.use_gpu = use_gpu self.logsoftmax = nn.LogSoftmax(dim=1) def forward(self, inputs, targets): log_pr...
model.train_model(shuffled_training, acc=sklearn.metrics.accuracy_score, f1=sklearn.metrics.f1_score )
Natural Language Processing with Disaster Tweets
21,448,746
def fastrcnn_loss(class_logits, box_regression, labels, regression_targets): labels = torch.cat(labels, dim=0) regression_targets = torch.cat(regression_targets, dim=0) labal_smooth_loss = CrossEntropyLabelSmooth(2) classification_loss = labal_smooth_loss(class_logits, labels) sampled_pos_inds_subset = torch.nonz...
result, model_outputs, wrong_predictions = model.eval_model(shuffled_training, acc=sklearn.metrics.accuracy_score, f1=sklearn.metrics.f1_score )
Natural Language Processing with Disaster Tweets
21,448,746
def resnest_fpn_backbone(pretrained, norm_layer=misc_nn_ops.FrozenBatchNorm2d, trainable_layers=3): backbone = resnest101(pretrained=pretrained) assert trainable_layers <= 5 and trainable_layers >= 0 layers_to_train = ['layer4', 'layer3', 'layer2', 'layer1', 'conv1'][:trainable_layers] for name, parameter in backbone....
result
Natural Language Processing with Disaster Tweets
21,448,746
class WheatDetector(torch.nn.Module): def __init__(self, trainable_layers=3, **kwargs): super(WheatDetector, self ).__init__() backbone = resnest_fpn_backbone(pretrained=False) self.base = FasterRCNN(backbone, num_classes = 2, **kwargs) self.base.roi_heads.fastrcnn_loss = fastrcnn_loss def forward(self, images, targe...
predictions, raw_outputs = model.predict(test["text"].to_list() )
Natural Language Processing with Disaster Tweets
21,448,746
def load_res_net(path, cfg): model = build_model(cfg) checkpoint = torch.load(path) model.load_state_dict(checkpoint['model_state_dict']) model.eval() ; return model.cuda()<choose_model_class>
mypreds = pd.DataFrame(test[["id"]]) mypreds["target"] = predictions
Natural Language Processing with Disaster Tweets
21,448,746
def get_net(level): config = get_efficientdet_config(f'tf_efficientdet_d{level}') net = EfficientDet(config, pretrained_backbone=False) if level == 5: checkpoint = torch.load('.. /input/efficientdet/efficientdet_d5-ef44aea8.pth') elif level == 7: checkpoint = torch.load('.. /input/efficientdet/efficientdet_d7-f05bf7...
mypreds.to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets
21,447,095
class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count<set_options>
! python -m pip install tf-models-nightly --no-deps -q ! python -m pip install tf-models-official==2.4.0 -q ! python -m pip install tensorflow-gpu==2.4.1 -q ! python -m pip install tensorflow-text==2.4.1 -q ! python -m spacy download en_core_web_sm -q ! python -m spacy validate
Natural Language Processing with Disaster Tweets
21,447,095
class RAdam(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) self.buffer = [[None, None, None] for ind in range(10)] super(RAdam, self ).__init__(params, defaults) def __setstate__(self, state): super...
print(f'TensorFlow Version: {tf.__version__}') print(f'Python Version: {python_version() }' )
Natural Language Processing with Disaster Tweets
21,447,095
warnings.filterwarnings("ignore") class Fitter: def __init__(self, model, device, config): self.config = config self.epoch = 0 self.base_dir = f'./{config.folder}' if not os.path.exists(self.base_dir): os.makedirs(self.base_dir) self.log_path = f'{self.base_dir}/log.txt' self.best_summary_loss = 10**5 self.model = mo...
RANDOM_SEED = 123 nlp = spacy.load('en_core_web_sm') pd.set_option('display.max_colwidth', None) rcParams['figure.figsize'] =(10, 6) sns.set_theme(palette='muted', style='whitegrid' )
Natural Language Processing with Disaster Tweets
21,447,095
N_FOLD = 2 USE_TTA = True TRAIN_ROOT_PATH = '.. /input/global-wheat-detection/train' TEST_ROOT_PATH = '.. /input/global-wheat-detection/test' cfg.MODEL.PRETRAIN = False<load_pretrained>
path = '.. /input/nlp-getting-started/train.csv' df = pd.read_csv(path) print(df.shape) df.head()
Natural Language Processing with Disaster Tweets
21,447,095
MODEL = { "effdet": [ load_net_eval('.. /input/effdetd5sourcelee/best-retrain-epoch51.bin', 5), load_net_eval('.. /input/effdetd7/retrains/best-retrain-epoch42.bin', 7) ], "resnest":[ load_res_net(".. /input/resnest-source-weights-andreshuang/checkpoint-60arvalis1.bin", cfg), load_res_net(".. /input/rssnest-source-wei...
path_test = '.. /input/nlp-getting-started/test.csv' df_test = pd.read_csv(path_test) print(df_test.shape) df_test.head()
Natural Language Processing with Disaster Tweets
21,447,095
def to_tensor(images): tmp = [] for img in images: img = img.astype(np.float32) img /= 255.0 img = torch.tensor(img, dtype=torch.float32) tmp.append(img.permute(2,0,1)) return torch.stack(tmp) def get_handout_transforms() : return A.Compose( [ A.Resize(height=512, width=512, p=1.0), ], p=1.0, bbox_params=A.BboxPara...
duplicates = df[df.duplicated(['text', 'target'], keep=False)] print(f'Train Duplicate Entries(text, target): {len(duplicates)}') duplicates.head()
Natural Language Processing with Disaster Tweets
21,447,095
def make_predictions( models, images, score_threshold=0.25, ): predictions = [] for fold_number, net in enumerate(models): with torch.no_grad() : net.eval() det = net(images, torch.tensor([1]*images.shape[0] ).float().cuda()) result = [] for i in range(images.shape[0]): boxes = det[i].detach().cpu().numpy() [:,:4] s...
df.drop_duplicates(['text', 'target'], inplace=True, ignore_index=True) print(df.shape, df_test.shape )
Natural Language Processing with Disaster Tweets
21,447,095
def calculate_final_score( all_predictions, iou_thr, skip_box_thr, resweight, edetweight, sigma=0.5, ): final_scores = [] for predictions in all_predictions: gt_boxes = predictions['gtboxes'].copy() image_id = predictions['image_id'] img_boxes = [] img_scores = [] img_labels = [] for index in range(4): effdet_p = pre...
new_duplicates = df[df.duplicated(['keyword', 'text'], keep=False)] print(f'Train Duplicate Entries(keyword, text): {len(new_duplicates)}') new_duplicates[['text', 'target']].sort_values(by='text' )
Natural Language Processing with Disaster Tweets
21,447,095
USE_OPTIMIZE = False if USE_OPTIMIZE: marking = pd.read_csv('.. /input/global-wheat-detection/train.csv') bboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=','))) for i, column in enumerate(['x', 'y', 'w', 'h']): marking[column] = bboxs[:,i] marking.drop(columns=['bbox'], inplace=True) mark...
df.drop([4253, 4193, 2802, 4554, 4182, 3212, 4249, 4259, 6535, 4319, 4239, 606, 3936, 6018, 5573], inplace=True )
Natural Language Processing with Disaster Tweets
21,447,095
def log(text): with open('opt.log', 'a+')as logger: logger.write(f'{text} ') def optimize(space, all_predictions, n_calls=10): @use_named_args(space) def score(**params): log('-'*5 + 'WBF' + '-'*5) log(params) final_score = calculate_final_score(all_predictions, **params) log(f'final_score = {final_score}') log('...
df = df.reset_index(drop=True) df
Natural Language Processing with Disaster Tweets
21,447,095
if USE_OPTIMIZE: space = [ Real(0.1, 0.7, name='iou_thr'), Real(0.2, 0.7, name='skip_box_thr'), Real(1, 10, name='resweight'), Real(1, 10, name='edetweight'), ] opt_result = optimize( space, all_predictions, n_calls=10, ) best_final_score = -opt_result.fun best_iou_thr = opt_result.x[0] best_skip_box_thr = opt_resul...
df['target'].value_counts() / len(df )
Natural Language Processing with Disaster Tweets
21,447,095
def make_predictions( models, images, score_threshold=0.25, ): predictions = [] for fold_number, net in enumerate(models): with torch.no_grad() : net.eval() det = net(images, torch.tensor([1]*images.shape[0] ).float().cuda()) result = [] for i in range(images.shape[0]): boxes = det[i].detach().cpu().numpy() [:,:4] s...
def null_table(data): null_list = [] for i in data: if data[i].notnull().any() : null_list.append(data[i].notnull().value_counts()) return pd.DataFrame(pd.concat(null_list, axis=1 ).T )
Natural Language Processing with Disaster Tweets
21,447,095
test_dataset = TestDatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{TEST_ROOT_PATH}/*.jpg')]), path=TEST_ROOT_PATH ) test_data_loader = DataLoader( test_dataset, batch_size=1, shuffle=False, num_workers=4, drop_last=False, collate_fn=collate_fn )<load_from_csv>
null_table(df )
Natural Language Processing with Disaster Tweets
21,447,095
if len(os.listdir(TEST_ROOT_PATH)) > 10: marking = pd.read_csv('.. /input/global-wheat-detection/train.csv') bboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=','))) for i, column in enumerate(['x', 'y', 'w', 'h']): marking[column] = bboxs[:,i] marking.drop(columns=['bbox'], inplace=True) m...
null_table(df_test )
Natural Language Processing with Disaster Tweets
21,447,095
N_FOLD = 2 USE_OPTIMIZE = False USE_TTA = True TRAIN_ROOT_PATH = '.. /input/global-wheat-detection/test' TEST_ROOT_PATH = '.. /input/global-wheat-detection/test'<init_hyperparams>
text = df['text'] target = df['target'] test_text = df_test['text'] for i in np.random.randint(500, size=5): print(f'Tweet ' * 2 )
Natural Language Processing with Disaster Tweets
21,447,095
class TrainGlobalConfig: num_workers = 8 batch_size = 4 n_epochs = 5 lr = 0.0002 folder = 'retrains' verbose = True verbose_step = 1 step_scheduler = False validation_scheduler = True SchedulerClass = torch.optim.lr_scheduler.ReduceLROnPlateau scheduler_params = dict( mode='min', factor=0.5, patience=1, verbose=False,...
lookup_dict = { 'abt' : 'about', 'afaik' : 'as far as i know', 'bc' : 'because', 'bfn' : 'bye for now', 'bgd' : 'background', 'bh' : 'blockhead', 'br' : 'best regards', 'btw' : 'by the way', 'cc': 'carbon copy', 'chk' : 'check', 'dam' : 'do not annoy me', 'dd' : 'dear daughter', 'df': 'dear fiance', 'ds' : 'dear son', ...
Natural Language Processing with Disaster Tweets
21,447,095
def re_train(path, marker, level, folder=None): df_folds = get_df_folds(marker) device = torch.device('cuda:0') net = get_net(level) if folder: TrainGlobalConfig.folder = folder train_dataset = DatasetRetriever( image_ids=df_folds[df_folds['fold'] == 0].index.values, marking=marker, transforms=get_train_transforms(...
def lemmatize_text(text, nlp=nlp): doc = nlp(text) lemma_sent = [i.lemma_ for i in doc if not i.is_stop] return ' '.join(lemma_sent) def abbrev_conversion(text): words = text.split() abbrevs_removed = [] for i in words: if i in lookup_dict: i = lookup_dict[i] abbrevs_removed.append(i) return ' '.join(abbrevs_removed...
Natural Language Processing with Disaster Tweets
21,447,095
if len(os.listdir(TEST_ROOT_PATH)) > 10: re_train(".. /input/effdetd5sourcelee/best-retrain-epoch51.bin", marking_p, 5, "retrains") MODEL["effdet"][0] = load_net_eval("retrains/best-retrain.bin", 5) <categorify>
df['clean_text'] = pd.DataFrame(clean_text) df_test['clean_text'] = pd.DataFrame(test_clean_text )
Natural Language Processing with Disaster Tweets
21,447,095
results = [] for images, image_ids in test_data_loader: image = images[0] height, width, _ = image.shape image = cv2.resize(image,(512, 512)) image_res = cv2.resize(image,(1024, 1024)) predictions_tta = { "boxes": [], "scores": [], "labels": [] } for index in range(4): roated = TTAImage(image, index) roated = to_tenso...
df['clean_text'] = df['clean_text'].apply(lambda x: re.sub(pattern_new, '', x)if pd.isna(x)!= True else x) df_test['clean_text'] = df_test['clean_text'].apply(lambda x: re.sub(pattern_new, '', x)if pd.isna(x)!= True else x )
Natural Language Processing with Disaster Tweets
21,447,095
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df<install_modules>
print('Training Counts of 'new': ', len(re.findall(pattern_new, ' '.join(df['clean_text'])))) print('Test Counts of 'new': ', len(re.findall(pattern_new, ' '.join(df_test['clean_text']))))
Natural Language Processing with Disaster Tweets
21,447,095
!pip install --no-deps '.. /input/timm-package/timm-0.1.26-py3-none-any.whl' > /dev/null !pip install --no-deps '.. /input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl' > /dev/null<categorify>
sentence_enc = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4' )
Natural Language Processing with Disaster Tweets
21,447,095
def get_valid_transforms() : return A.Compose([ A.Resize(height=512, width=512, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<data_type_conversions>
def extract_keywords(text, nlp=nlp): potential_keywords = [] TOP_KEYWORD = -1 pos_tag = ['ADJ', 'NOUN', 'PROPN'] doc = nlp(text) for i in doc: if i.pos_ in pos_tag: potential_keywords.append(i.text) document_embed = sentence_enc([text]) potential_embed = sentence_enc(potential_keywords) vector_distances = cosine_si...
Natural Language Processing with Disaster Tweets
21,447,095
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class DatasetRetriever(Dataset): def __init__(self, image_ids, transforms=None): super().__init__() self.image_ids = image_ids self.transforms = transforms def __getitem__(self, index: int): image_id = self.image_ids[index] image = cv2.imread(f'{DATA_ROOT_PATH}/{...
df['keyword_fill'] = pd.DataFrame(list(map(keyword_filler, df['keyword'], df['clean_text'])) ).astype(str) df_test['keyword_fill'] = pd.DataFrame(list(map(keyword_filler, df_test['keyword'], df_test['clean_text'])) ).astype(str) print('Null Training Keywords => ', df['keyword_fill'].isnull().any()) print('Null Test ...
Natural Language Processing with Disaster Tweets
21,447,095
dataset = DatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms() ) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=4, shuffle=False, num_workers=2, drop_last=False, collate_fn=coll...
df['keyword_fill'] = pd.DataFrame(standardize_text(df['keyword_fill'])) df_test['keyword_fill'] = pd.DataFrame(standardize_text(df_test['keyword_fill']))
Natural Language Processing with Disaster Tweets
21,447,095
def load_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=512 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load(che...
keyword_count_0 = pd.DataFrame(df['keyword_fill'][df['target']==0].value_counts().reset_index()) keyword_count_1 = pd.DataFrame(df['keyword_fill'][df['target']==1].value_counts().reset_index() )
Natural Language Processing with Disaster Tweets
21,447,095
class BaseWheatTTA: image_size = 512 def augment(self, image): raise NotImplementedError def batch_augment(self, images): raise NotImplementedError def deaugment_boxes(self, boxes): raise NotImplementedError class TTAHorizontalFlip(BaseWheatTTA): def augment(self, image): return image.flip(1) def batch_augment(sel...
train_features = df[['clean_text','keyword_fill']] test_features = df_test[['clean_text', 'keyword_fill']]
Natural Language Processing with Disaster Tweets
21,447,095
def process_det(index, det, score_threshold=0.25): boxes = det[index].detach().cpu().numpy() [:,:4] scores = det[index].detach().cpu().numpy() [:,4] boxes[:, 2] = boxes[:, 2] + boxes[:, 0] boxes[:, 3] = boxes[:, 3] + boxes[:, 1] boxes =(boxes ).clip(min=0, max=511 ).astype(int) indexes = np.where(scores>score_threshol...
train_x, val_x, train_y, val_y = train_test_split( train_features, target, test_size=0.2, random_state=RANDOM_SEED, ) print(train_x.shape) print(train_y.shape) print(val_x.shape) print(val_y.shape )
Natural Language Processing with Disaster Tweets
21,447,095
tta_transforms = [] for tta_combination in product([TTAHorizontalFlip() , None], [TTAVerticalFlip() , None], [TTARotate90() , None]): tta_transforms.append(TTACompose([tta_transform for tta_transform in tta_combination if tta_transform]))<categorify>
train_ds = tf.data.Dataset.from_tensor_slices(( dict(train_x), train_y)) val_ds = tf.data.Dataset.from_tensor_slices(( dict(val_x), val_y)) test_ds = tf.data.Dataset.from_tensor_slices(dict(test_features))
Natural Language Processing with Disaster Tweets
21,447,095
def make_tta_predictions(images, score_threshold=0.25): with torch.no_grad() : images = torch.stack(images ).float().cuda() predictions = [] for tta_transform in tta_transforms: result = [] det = net(tta_transform.batch_augment(images.clone()), torch.tensor([1]*images.shape[0] ).float().cuda()) for i in range(images.s...
AUTOTUNE = tf.data.experimental.AUTOTUNE BUFFER_SIZE = 1000 BATCH_SIZE = 32 def configure_dataset(dataset, shuffle=False, test=False): if shuffle: dataset = dataset.cache() \ .shuffle(BUFFER_SIZE, seed=RANDOM_SEED, reshuffle_each_iteration=True)\ .batch(BATCH_SIZE, drop_remainder=True ).prefetch(AUTOTUNE) elif test:...
Natural Language Processing with Disaster Tweets
21,447,095
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings )<categorify>
train_ds = configure_dataset(train_ds, shuffle=True) val_ds = configure_dataset(val_ds) test_ds = configure_dataset(test_ds, test=True )
Natural Language Processing with Disaster Tweets
21,447,095
results = [] for images, image_ids in data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) boxes =(boxes*2 ).round().astype(np.int32 ).clip(min=0, max=1023) image_id = image_ids[i] boxes[:, 2] = boxes[:, 2] - boxes[:, 0...
bert_preprocessor = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', name='BERT_preprocesser') bert_encoder = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4', trainable=True, name='BERT_encoder') nnlm_embed = hub.KerasLayer('https://tfhub.dev/google/nnlm-en-d...
Natural Language Processing with Disaster Tweets
21,447,095
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<import_modules>
def build_model() : text_input = layers.Input(shape=() , dtype=tf.string, name='clean_text') encoder_inputs = bert_preprocessor(text_input) encoder_outputs = bert_encoder(encoder_inputs) pooled_output = encoder_outputs["pooled_output"] bert_dropout = layers.Dropout(0.1, name='BERT_dropout' )(pooled_output) key_inpu...
Natural Language Processing with Disaster Tweets
21,447,095
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping from sklearn.model_selection import KFold, StratifiedKFold from sklearn.preprocessing import LabelEncoder from sklearn.metrics import log_loss import tensorflow.keras.backend as K import tensorflow.keras.layers as L import tensorflow.keras.models a...
EPOCHS = 2 LEARNING_RATE = 5e-5 STEPS_PER_EPOCH = int(train_ds.unbatch().cardinality().numpy() / BATCH_SIZE) VAL_STEPS = int(val_ds.unbatch().cardinality().numpy() / BATCH_SIZE) TRAIN_STEPS = STEPS_PER_EPOCH * EPOCHS WARMUP_STEPS = int(TRAIN_STEPS * 0.1) adamw_optimizer = create_optimizer( init_lr=LEARNING_RATE, nu...
Natural Language Processing with Disaster Tweets
21,447,095
test_features = pd.read_csv('/kaggle/input/lish-moa/test_features.csv') train_targets = pd.read_csv('/kaggle/input/lish-moa/train_targets_scored.csv') train_features = pd.read_csv('/kaggle/input/lish-moa/train_features.csv') submission = pd.read_csv('/kaggle/input/lish-moa/sample_submission.csv') del test_features[...
bert_classifier.compile( loss=BinaryCrossentropy(from_logits=True), optimizer= adamw_optimizer, metrics=[BinaryAccuracy(name='accuracy')] ) history = bert_classifier.fit( train_ds, epochs=EPOCHS, steps_per_epoch=STEPS_PER_EPOCH, validation_data= val_ds, validation_steps=VAL_STEPS )
Natural Language Processing with Disaster Tweets
21,447,095
categorical = ['cp_type', 'cp_dose'] for feature in categorical: trans = LabelEncoder() train_features[feature] = trans.fit_transform(train_features[feature]) test_features[feature] = trans.fit_transform(test_features[feature]) time_mapping = {24:1, 48:2, 72:3} train_features['cp_time'] = train_features['cp_time'].ma...
train_loss = history.history['loss'] val_loss = history.history['val_loss'] train_acc = history.history['accuracy'] val_acc = history.history['val_accuracy']
Natural Language Processing with Disaster Tweets
21,447,095
pca = PCA(n_components=800) train_features_pca = pca.fit_transform(train_features) test_features_pca = pca.transform(test_features) train_features_pca = pd.DataFrame(train_features_pca) test_features_pca = pd.DataFrame(test_features_pca) train_features = train_features_pca test_features = test_features_pca<sort_va...
val_target = np.asarray([i[1] for i in list(val_ds.unbatch().as_numpy_iterator())]) print(val_target.shape) val_target[:5]
Natural Language Processing with Disaster Tweets
21,447,095
correlations = train_features.corr().abs().unstack().sort_values(kind='quicksort', ascending=False ).reset_index() correlations = correlations[correlations['level_0'] != correlations['level_1']].reset_index() correlations = correlations[correlations.iloc[:, 3] > 0.92] c = collections.Counter(correlations.iloc[:, 3]) p...
val_predict = bert_classifier.predict(val_ds )
Natural Language Processing with Disaster Tweets
21,447,095
def create_model(num_columns): model = tf.keras.Sequential([ tf.keras.layers.Input(num_columns), tf.keras.layers.BatchNormalization() , tf.keras.layers.Dropout(0.2), tfa.layers.WeightNormalization(tf.keras.layers.Dense(1400, activation="relu")) , tf.keras.layers.BatchNormalization() , tf.keras.layers.Dropout(0.4), tfa....
predictions = bert_classifier.predict(test_ds) print(predictions.shape) print(predictions[:5] )
Natural Language Processing with Disaster Tweets
21,447,095
N_STARTS = 3 tf.random.set_seed(43) res = train_targets.copy() submission.loc[:, train_targets.columns] = 0 res.loc[:, train_targets.columns] = 0 for seed in range(N_STARTS): for n,(tr, te)in enumerate(KFold(n_splits=5, random_state=seed, shuffle=True ).split(train_targets)) : print(f'Fold {n}') model = create_model(...
predictions = np.where(predictions > THRESHOLD, 1, 0) df_predictions = pd.DataFrame(predictions) df_predictions.columns = ['target'] print(df_predictions.shape) df_predictions.head()
Natural Language Processing with Disaster Tweets
21,447,095
metrics = [] for _target in train_targets.columns: metrics.append(log_loss(train_targets.loc[:, _target], res.loc[:, _target])) print(np.mean(metrics))<save_to_csv>
submission = pd.concat([df_test['id'], df_predictions], axis=1) submission.to_csv('submission.csv', index=False )
Natural Language Processing with Disaster Tweets
21,325,840
df = pd.read_csv("/kaggle/input/lish-moa/sample_submission.csv") df_test = pd.read_csv('/kaggle/input/lish-moa/test_features.csv') test_id = df_test['sig_id'].values df_submit = pd.DataFrame(index=test_id, columns=df.columns.drop('sig_id')) df_submit.index.name = 'sig_id' df_submit[:] = 0 df_predict = submission.copy...
train_filepath = '/kaggle/input/nlp-getting-started/train.csv' test_filepath = '/kaggle/input/nlp-getting-started/test.csv' df_train = pd.read_csv(train_filepath) df_test = pd.read_csv(test_filepath) df_train.head()
Natural Language Processing with Disaster Tweets
21,325,840
train = pd.read_csv('/kaggle/input/lish-moa/train_features.csv') train.shape<load_from_csv>
lemmatizer = WordNetLemmatizer() for i in range(0, len(df_train)) : text = re.sub('[^a-zA-Z]', ' ', df_train['text'][i]) text = text.lower() text = re.sub(r'^https?:\/\/.*[\r ]*', '', text) text = text.split() text = [lemmatizer.lemmatize(word)for word in text if word not in stopwords.words('english')] text = ' '.joi...
Natural Language Processing with Disaster Tweets
21,325,840
train_target = pd.read_csv('/kaggle/input/lish-moa/train_targets_scored.csv') train_target.shape<load_from_csv>
for i in range(0, len(df_test)) : text = re.sub('[^a-zA-Z]', ' ', df_test['text'][i]) text = text.lower() text = re.sub(r'^https?:\/\/.*[\r ]*', '', text) text = text.split() text = [lemmatizer.lemmatize(word)for word in text if word not in stopwords.words('english')] text = ' '.join(text) df_test['text'][i] = text ...
Natural Language Processing with Disaster Tweets
21,325,840
test = pd.read_csv('/kaggle/input/lish-moa/test_features.csv') test.shape<feature_engineering>
train_data = df_train.drop(['id','keyword','location'], axis=1) train_data.to_csv('cleaned_train.csv', index=False) test_data = df_test.drop(['keyword','location'], axis=1) test_data.to_csv('cleaned_test.csv', index=False )
Natural Language Processing with Disaster Tweets
21,325,840
train.at[train['cp_type'].str.contains('ctl_vehicle'),train.filter(regex='-.*' ).columns] = 0.0 test.at[test['cp_type'].str.contains('ctl_vehicle'),test.filter(regex='-.*' ).columns] = 0.0<categorify>
train_data = pd.read_csv('cleaned_train.csv') len(train_data)
Natural Language Processing with Disaster Tweets
21,325,840
train_size = train.shape[0] traintest = pd.concat([train, test]) traintest = pd.concat([traintest, pd.get_dummies(traintest['cp_type'], prefix='cp_type')], axis=1) traintest = pd.concat([traintest, pd.get_dummies(traintest['cp_time'], prefix='cp_time')], axis=1) traintest = pd.concat([traintest, pd.get_dummies(train...
SEED = 1234 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.backends.cudnn.deterministic = True
Natural Language Processing with Disaster Tweets
21,325,840
g_columns = [ c for c in train.columns if 'g-' in c ] scaler = StandardScaler() train[g_columns] = scaler.fit_transform(train[g_columns]) test[g_columns] = scaler.transform(test[g_columns] )<prepare_x_and_y>
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased' )
Natural Language Processing with Disaster Tweets
21,325,840
x_train = train.drop('sig_id', axis=1) y_train = train_target.drop('sig_id', axis=1) x_test = test.drop('sig_id', axis=1 )<define_variables>
init_token = tokenizer.cls_token eos_token = tokenizer.sep_token pad_token = tokenizer.pad_token unk_token = tokenizer.unk_token
Natural Language Processing with Disaster Tweets
21,325,840
options = { 'default': { 'features': list(x_train.columns) } }<categorify>
init_token_idx = tokenizer.convert_tokens_to_ids(init_token) eos_token_idx = tokenizer.convert_tokens_to_ids(eos_token) pad_token_idx = tokenizer.convert_tokens_to_ids(pad_token) unk_token_idx = tokenizer.convert_tokens_to_ids(unk_token) print(init_token_idx, eos_token_idx, pad_token_idx, unk_token_idx )
Natural Language Processing with Disaster Tweets
21,325,840
def make_x(option): features = options[option]['features'] return x_train[features], x_test[features]<import_modules>
max_input_length = tokenizer.max_model_input_sizes['bert-base-uncased'] print(max_input_length )
Natural Language Processing with Disaster Tweets
21,325,840
from sklearn.feature_selection import RFECV import lightgbm as lgb<init_hyperparams>
def tokenize_and_cut(sentence): tokens = tokenizer.tokenize(sentence) tokens = tokens[:max_input_length-2] return tokens
Natural Language Processing with Disaster Tweets
21,325,840
params = { 'objective': 'binary', 'learning_rate': 0.05, 'max_depth': -1, 'num_leaves': 31, 'num_threads': 4, 'random_state': 42 }<define_variables>
TEXT = data.Field(batch_first = True, use_vocab = False, tokenize = tokenize_and_cut, preprocessing = tokenizer.convert_tokens_to_ids, init_token = init_token_idx, eos_token = eos_token_idx, pad_token = pad_token_idx, unk_token = unk_token_idx) LABEL = data.LabelField(dtype = torch.float )
Natural Language Processing with Disaster Tweets
21,325,840
options['500'] = { 'features': ['g-0', 'g-1', 'g-2', 'g-3', 'g-4', 'g-5', 'g-6', 'g-7', 'g-8', 'g-9', 'g-10', 'g-11', 'g-12', 'g-13', 'g-14', 'g-15', 'g-16', 'g-17', 'g-18', 'g-19', 'g-20', 'g-21', 'g-22', 'g-23', 'g-24', 'g-25', 'g-26', 'g-27', 'g-28', 'g-29', 'g-30', 'g-31', 'g-32', 'g-33', 'g-34', 'g-35', 'g-36', 'g...
fields = [('text', TEXT),('target', LABEL)] datasets = torchtext.legacy.data.TabularDataset( path='cleaned_train.csv',format='csv',skip_header=True,fields=fields) train_data, test_data = datasets.split(split_ratio=[0.95, 0.05]) train_data, valid_data = train_data.split(random_state = random.seed(SEED))
Natural Language Processing with Disaster Tweets
21,325,840
options['600'] = { 'features': ['g-0', 'g-1', 'g-2', 'g-3', 'g-4', 'g-5', 'g-6', 'g-7', 'g-8', 'g-9', 'g-10', 'g-11', 'g-12', 'g-13', 'g-14', 'g-15', 'g-16', 'g-17', 'g-18', 'g-19', 'g-20', 'g-21', 'g-22', 'g-23', 'g-24', 'g-25', 'g-26', 'g-27', 'g-28', 'g-29', 'g-30', 'g-31', 'g-32', 'g-33', 'g-34', 'g-35', 'g-36', 'g...
LABEL.build_vocab(train_data )
Natural Language Processing with Disaster Tweets
21,325,840
options['700'] = { 'features': ['g-0', 'g-1', 'g-2', 'g-3', 'g-4', 'g-5', 'g-6', 'g-7', 'g-8', 'g-9', 'g-10', 'g-11', 'g-12', 'g-13', 'g-14', 'g-15', 'g-16', 'g-17', 'g-18', 'g-19', 'g-20', 'g-21', 'g-22', 'g-23', 'g-24', 'g-25', 'g-26', 'g-27', 'g-28', 'g-29', 'g-30', 'g-31', 'g-32', 'g-33', 'g-34', 'g-35', 'g-36', 'g...
BATCH_SIZE = 128 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(device) train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits( (train_data, valid_data, test_data), batch_size = BATCH_SIZE, device = device )
Natural Language Processing with Disaster Tweets
21,325,840
import tensorflow as tf import tensorflow_addons as tfa from sklearn.model_selection import StratifiedKFold, KFold from sklearn.metrics import accuracy_score import tensorflow.keras.backend as K<choose_model_class>
train_data, valid_data = train_data.split( split_ratio=[0.85, 0.15], random_state=random.seed(123)) print('Num Train: {}'.format(len(train_data))) print('Num Validation: {}'.format(len(valid_data)) )
Natural Language Processing with Disaster Tweets
21,325,840
def make_layer(x, units, dropout_rate): t = tfa.layers.WeightNormalization(tf.keras.layers.Dense(units))(x) t = tf.keras.layers.BatchNormalization()(t) t = tf.keras.layers.Activation('relu' )(t) t = tf.keras.layers.Dropout(dropout_rate )(t) return t def make_model(data, units, dropout_rates): inputs = tf.keras.laye...
bert = BertModel.from_pretrained('bert-base-uncased' )
Natural Language Processing with Disaster Tweets
21,325,840
def fit_predict(n_splits, x_train, y_train, units, dropout_rates, epochs, x_test, verbose, random_state): histories = [] scores = [] y_preds = [] cv = KFold(n_splits=n_splits, shuffle=True, random_state=random_state) for train_idx, valid_idx in cv.split(x_train, y_train): x_train_train = x_train.iloc[train_idx] y_trai...
class BERTGRUDisaster(nn.Module): def __init__(self, bert, hidden_dim, output_dim, n_layers, bidirectional, dropout): super().__init__() self.bert = bert embedding_dim = bert.config.to_dict() ['hidden_size'] self.rnn = nn.GRU(embedding_dim, hidden_dim, num_layers = n_layers, bidirectional = bidirectional, batch_first =...
Natural Language Processing with Disaster Tweets
21,325,840
optuna.logging.set_verbosity(CRITICAL )<find_best_params>
HIDDEN_DIM = 256 OUTPUT_DIM = 1 N_LAYERS = 2 BIDIRECTIONAL = True DROPOUT = 0.25 model = BERTGRUDisaster(bert, HIDDEN_DIM, OUTPUT_DIM, N_LAYERS, BIDIRECTIONAL, DROPOUT )
Natural Language Processing with Disaster Tweets
21,325,840
def objective(trial): n_layers = trial.suggest_int('n_layers', 1, 5) units = [] dropout_rates = [] for i in range(n_layers): u = trial.suggest_categorical('units_{}'.format(i+1), [1024, 512, 256, 128]) units.append(u) r = trial.suggest_loguniform('dropout_rate_{}'.format(i+1), 0.1, 0.5) dropout_rates.append(r) pri...
for name, param in model.named_parameters() : if name.startswith('bert'): param.requires_grad = False
Natural Language Processing with Disaster Tweets
21,325,840
params = { 'n_layers': 5, 'units_1': 128, 'units_2': 256, 'units_3': 512, 'units_4': 256, 'units_5': 1024, 'dropout_rate_1': 0.3478936880741539, 'dropout_rate_2': 0.3478936880741539, 'dropout_rate_3': 0.3478936880741539, 'dropout_rate_4': 0.3478936880741539, 'dropout_rate_5': 0.3478936880741539 } options['default']['pa...
optimizer = optim.Adam(model.parameters()) criterion = nn.BCEWithLogitsLoss()
Natural Language Processing with Disaster Tweets
21,325,840
params = { 'n_layers': 3, 'units_1': 1024, 'units_2': 512, 'units_3': 256, 'dropout_rate_1': 0.4501813451502177, 'dropout_rate_2': 0.4501813451502177, 'dropout_rate_3': 0.4501813451502177 } options['500']['params'] = params options['600']['params'] = params options['700']['params'] = params<predict_on_test>
model = model.to(device) criterion = criterion.to(device )
Natural Language Processing with Disaster Tweets
21,325,840
def fit_predict_option(option, random_state): print('Option:', option) params = options[option]['params'] n_layers = params['n_layers'] units = [] dropout_rates = [] for i in range(n_layers): u = params['units_{}'.format(i+1)] units.append(u) d = params['dropout_rate_{}'.format(i+1)] dropout_rates.append(d) x_train_...
def binary_accuracy(preds, y): rounded_preds = torch.round(torch.sigmoid(preds)) correct =(rounded_preds == y ).float() acc = correct.sum() / len(correct) return acc
Natural Language Processing with Disaster Tweets
21,325,840
y_preds = [] for option in options: y_pred, histories, score = fit_predict_option(option, 42) y_preds.append(y_pred) <save_to_csv>
def train(model, iterator, optimizer, criterion): epoch_loss = 0 epoch_acc = 0 model.train() for batch in iterator: optimizer.zero_grad() predictions = model(batch.text ).squeeze(1) loss = criterion(predictions, batch.target) acc = binary_accuracy(predictions, batch.target) loss.backward() optimizer.step() epoch_los...
Natural Language Processing with Disaster Tweets
21,325,840
submission = pd.read_csv('/kaggle/input/lish-moa/sample_submission.csv') columns = list(submission.columns) columns.remove('sig_id') for i in range(len(columns)) : submission[columns[i]] = y_pred[:,i] submission.to_csv('submission.csv', index=False )<import_modules>
def epoch_time(start_time, end_time): elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time -(elapsed_mins * 60)) return elapsed_mins, elapsed_secs
Natural Language Processing with Disaster Tweets
21,325,840
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from matplotlib.pyplot import xticks from nltk.corpus import stopwords import nltk import re from nltk.stem import WordNetLemmatizer import string from nltk.tokenize import word_tokenize from nltk.util import ngrams from collec...
def binary_accuracy(preds, y): rounded_preds = torch.round(torch.sigmoid(preds)) correct =(rounded_preds == y ).float() acc = correct.sum() / len(correct) return acc
Natural Language Processing with Disaster Tweets
21,325,840
train= pd.read_csv('.. /input/nlp-getting-started/train.csv') test=pd.read_csv('.. /input/nlp-getting-started/test.csv' )<count_missing_values>
N_EPOCHS = 5 best_valid_loss = float('inf') for epoch in range(N_EPOCHS): start_time = time.time() train_loss, train_acc = train(model, train_iterator, optimizer, criterion) end_time = time.time() epoch_mins, epoch_secs = epoch_time(start_time, end_time) print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch...
Natural Language Processing with Disaster Tweets
21,325,840
train.isnull().sum().sort_values(ascending = False )<define_variables>
torch.save(model.state_dict() , 'disaster-model.pt' )
Natural Language Processing with Disaster Tweets
21,325,840
print("No.of Real Disaster Tweets(Target = 1):",len(train[train["target"]==1])) print("No.of Fake Disaster Tweets(Target = 0):",len(train[train["target"]==0]))<feature_engineering>
def predict_disaster(model, tokenizer, sentence): model.eval() tokens = tokenizer.tokenize(sentence) tokens = tokens[:max_input_length-2] indexed = [init_token_idx] + tokenizer.convert_tokens_to_ids(tokens)+ [eos_token_idx] tensor = torch.LongTensor(indexed ).to(device) tensor = tensor.unsqueeze(0) prediction = torc...
Natural Language Processing with Disaster Tweets
21,325,840
def length(text): return len(text) train["length"]= train.text.apply(length )<drop_column>
predict_disaster(model, tokenizer, "Our Deeds are the Reason of this
Natural Language Processing with Disaster Tweets
21,325,840
train.drop("length",1,inplace=True )<string_transform>
test_data = pd.read_csv('cleaned_test.csv') test_data.head(10 )
Natural Language Processing with Disaster Tweets
21,325,840
stop = list(stopwords.words("english"))<string_transform>
test_data = test_data.fillna('nan') test_data.isna().sum()
Natural Language Processing with Disaster Tweets
21,325,840
sw = [] for message in train.text: for word in message.split() : if word in stop: sw.append(word) wordlist = nltk.FreqDist(sw) top10 = wordlist.most_common(10 )<define_variables>
submission_dict = {'id' : [], 'target' : []} for data in test_data.iterrows() : idx = data[1].id text = data[1].text target = predict_disaster(model, tokenizer, text) target = 0 if target < 0.5 else 1 submission_dict['id'].append(idx) submission_dict['target'].append(target)
Natural Language Processing with Disaster Tweets
21,325,840
punctuation = list(string.punctuation )<string_transform>
sample_df = pd.DataFrame(submission_dict) sample_df
Natural Language Processing with Disaster Tweets
21,325,840
pun = [] for message in train.text: for word in message.split() : if word in punctuation: pun.append(word) wordlist = nltk.FreqDist(pun) top10 = wordlist.most_common(10 )<string_transform>
sample_df.to_csv('sample_submission_01.csv', index=False )
Natural Language Processing with Disaster Tweets
21,325,840
<string_transform><EOS>
x = pd.read_csv('sample_submission_01.csv') x.head()
Natural Language Processing with Disaster Tweets
21,301,029
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<choose_model_class>
warnings.filterwarnings('ignore')
Natural Language Processing with Disaster Tweets
21,301,029
lemma = WordNetLemmatizer()<define_variables>
train = pd.read_csv('.. /input/nlp-getting-started/train.csv', usecols=['id','text','target']) test = pd.read_csv('.. /input/nlp-getting-started/test.csv', usecols=['id','text']) sample = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv' )
Natural Language Processing with Disaster Tweets
21,301,029
sw_pun = stop + punctuation<categorify>
%%time def clean(tweet): tweet = re.sub(r"\x89Û_", "", tweet) tweet = re.sub(r"\x89ÛÒ", "", tweet) tweet = re.sub(r"\x89ÛÓ", "", tweet) tweet = re.sub(r"\x89ÛÏWhen", "When", tweet) tweet = re.sub(r"\x89ÛÏ", "", tweet) tweet = re.sub(r"China\x89Ûªs", "China's", tweet) tweet = re.sub(r"let\x89Ûªs", "let's", tweet) ...
Natural Language Processing with Disaster Tweets
21,301,029
def preprocess(tweet): tweet = re.sub(r"https?:\/\/t.co\/[A-Za-z0-9]+", "", tweet) tweet = re.sub('[^\w]',' ',tweet) tweet = re.sub('[\d]','',tweet) tweet = tweet.lower() words = tweet.split() sentence = "" for word in words: if word not in(sw_pun): word = lemma.lemmatize(word,pos = 'v') if len(word)> 3: sentence =...
train['text'] = train['text'].apply(lambda s : clean(s))
Natural Language Processing with Disaster Tweets
21,301,029
train['text'] = train['text'].apply(lambda s : preprocess(s)) test ['text'] = test ['text'].apply(lambda s : preprocess(s))<drop_column>
train[train.target == 0]
Natural Language Processing with Disaster Tweets