kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
18,588,011 | model = build_model()<train_model> | y_train_ = np_utils.to_categorical(y_train.values)
y_valid_ = np_utils.to_categorical(y_valid.values ) | Natural Language Processing with Disaster Tweets |
18,588,011 | history = model.fit(X_train_norm,
y_train,
batch_size = batch_size,
epochs = num_epochs,
validation_split = 0.1,
shuffle = True,
callbacks = [learning_rate_reduction, early_stopping]
)<save_model> | int_sequences_input = keras.Input(shape=(None,), dtype="int64")
embedded_sequences = embedding_layer(int_sequences_input)
x = layers.Conv1D(64, 5, activation="relu",padding='same' )(embedded_sequences)
x = layers.MaxPooling1D(3 )(x)
x = layers.Conv1D(32, 5, activation="relu",padding='same' )(x)
x = layers.MaxPooli... | Natural Language Processing with Disaster Tweets |
18,588,011 | model.save('model.h5' )<predict_on_test> | early_stopping = callbacks.EarlyStopping(
min_delta=0.001,
patience=20,
restore_best_weights=True,
)
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics ='accuracy'
)
history = model.fit(
x_train, y_train_,
validation_data=(x_valid, y_valid_),
batch_size=128,
epochs=500,
callbacks=[early_st... | Natural Language Processing with Disaster Tweets |
18,588,011 | pred = model.predict(X_test_norm )<prepare_output> | x_test = vectorizer(np.array([[s] for s in test["text"]])).numpy() | Natural Language Processing with Disaster Tweets |
18,588,011 | pred=np.argmax(pred, axis=1 )<prepare_output> | predictions = model.predict(x_test ) | Natural Language Processing with Disaster Tweets |
18,588,011 | sample_submission['label'] = pred<save_to_csv> | sub = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv')
sub.head() | Natural Language Processing with Disaster Tweets |
18,588,011 | <set_options><EOS> | submission = pd.DataFrame({"id": test.iloc[:,0].values,"target": np.argmax(predictions,axis=1)})
submission.to_csv("submission.csv", index=False)
submission.head() | Natural Language Processing with Disaster Tweets |
18,507,165 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<load_from_csv> | !pip install transformers==3.5.1
!pip install pyspellchecker
!pip install -U joblib textblob
!python -m textblob.download_corpora | Natural Language Processing with Disaster Tweets |
18,507,165 | data_train_file = ".. /input/Kannada-MNIST/train.csv"
data_test_file = ".. /input/Kannada-MNIST/test.csv"
df_train = pd.read_csv(data_train_file)
df_test = pd.read_csv(data_test_file)
submissions = pd.read_csv(".. /input/Kannada-MNIST/sample_submission.csv" )<define_variables> | import pandas as pd
import torchtext
from transformers import BertTokenizer, BertForMaskedLM, BertConfig
import transformers
import torch
from torch.utils.data import Dataset, DataLoader
from torch import optim
from torch import cuda
from sklearn.model_selection import train_test_split
import re
import string
from jobl... | Natural Language Processing with Disaster Tweets |
18,507,165 | def get_features_labels(df):
labels = df['label'].values
features = df.values[:, 1:]/255
return features, labels<train_model> | train_val_df = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv")
test_df = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv" ) | Natural Language Processing with Disaster Tweets |
18,507,165 | df_train['label'].value_counts()
print(df_test.shape)
Y_train_1hot = tf.keras.utils.to_categorical(train_labels)
print(Y_train_1hot.shape)
print("
")
X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train_1hot, random_state = 42, test_size = 0.05)
print(X_train.shape)
print(Y_train.shape)
print(X_val... | train_val_df = train_val_df.loc[:,["text","target"]]
test_df = test_df.loc[:,["text"]]
test_df["target"] = [0]*len(test_df["text"] ) | Natural Language Processing with Disaster Tweets |
18,507,165 | model_arch = {}
learning_rate_reduction = ReduceLROnPlateau(monitor = 'val_acc',
patience = 3,
verbose = 1,
factor = 0.3,
min_lr = 0.00001)
<choose_model_class> | check_df = train_val_df | Natural Language Processing with Disaster Tweets |
18,507,165 |
<train_model> | languages = ["de"]
parallel = Parallel(n_jobs=-1, backend="threading", verbose=5 ) | Natural Language Processing with Disaster Tweets |
18,507,165 | generated_data = ImageDataGenerator(
rotation_range = 20,
shear_range = 0.1,
zoom_range = 0.1,
width_shift_range = 0.1,
height_shift_range = 0.1)
generated_data.fit(X_train )<choose_model_class> | def translate_text(comment, language):
if hasattr(comment, "decode"):
comment = comment.decode("utf-8")
text = TextBlob(comment)
try:
text = text.translate(to=language)
sleep(2.0)
text = text.translate(to="en")
sleep(2.0)
except NotTranslated:
pass
return str(text ) | Natural Language Processing with Disaster Tweets |
18,507,165 | model_arch['cnn'] = [
tf.keras.layers.Reshape(input_shape =(28, 28, 1), target_shape =(28, 28, 1)) ,
tf.keras.layers.Conv2D(filters = 32, kernel_size = 5, activation='relu', padding='same'),
tf.keras.layers.Conv2D(filters = 32, kernel_size = 5, activation='relu', padding='same'),
tf.keras.layers.BatchNormalization() ,
... | comments_list = check_df["text"]
for language in languages:
print('Translate comments using "{0}" language'.format(language))
translated_data = parallel(delayed(translate_text )(comment, language)for comment in comments_list)
check_df['text'] = translated_data
result_path = os.path.join("train_val_" + language + ".csv... | Natural Language Processing with Disaster Tweets |
18,507,165 | model = tf.keras.Sequential(model_arch['cnn'])
initial_learningrate=2e-3
user_optimizer = RMSprop(lr=initial_learningrate)
model.compile(loss = 'categorical_crossentropy',
optimizer = user_optimizer,
metrics = ['accuracy'])
model.summary()<define_variables> | train_val_de_df = pd.read_csv("./train_val_de.csv")
train_concat_df = train_val_de_df | Natural Language Processing with Disaster Tweets |
18,507,165 | User_batch_size = 256
EPOCHS = 24<train_model> | print(train_concat_df ) | Natural Language Processing with Disaster Tweets |
18,507,165 | history = model.fit_generator(generated_data.flow(X_train, Y_train, batch_size = User_batch_size),
epochs = EPOCHS, validation_data =(X_val, Y_val),
shuffle = True,
verbose = 1, callbacks = [learning_rate_reduction] )<save_to_csv> | train_val_df = pd.concat([train_val_df,train_concat_df] ) | Natural Language Processing with Disaster Tweets |
18,507,165 | predictions = model.predict(X_test)
predictions = np.argmax(predictions, axis = 1)
submissions['label'] = predictions
submissions.to_csv("submission.csv", index = False, header = True)
<set_options> | tokenizer = BertTokenizer.from_pretrained('bert-base-cased' ) | Natural Language Processing with Disaster Tweets |
18,507,165 | plt.ion()<define_variables> | print(torch.__version__ ) | Natural Language Processing with Disaster Tweets |
18,507,165 | dataset_path = '/kaggle/input/Kannada-MNIST/'
output_path = '/kaggle/working/'<set_options> | def remove_URL(text):
url = re.compile(r'https?://\S+|www\.\S+')
return url.sub(r'', text)
train_val_df['text'] = train_val_df['text'].apply(lambda x : remove_URL(x))
test_df['text'] = test_df['text'].apply(lambda x : remove_URL(x))
def remove_html(text):
html = re.compile(r'<.*?>')
return html.sub(r'',text)
train_... | Natural Language Processing with Disaster Tweets |
18,507,165 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using %r' % device)
batch_size = 1024
num_workers = 4
num_folds = 4
num_epochs = 50<load_from_csv> | test_df.to_csv("test.tsv", sep='\t', index=False, header=None)
print(test_df.shape)
train_val_df.to_csv("train_eval.tsv", sep='\t', index=False, header=None)
print(train_val_df.shape)
| Natural Language Processing with Disaster Tweets |
18,507,165 | csv_cache = {}
def read_csv(path):
if path in csv_cache:
return csv_cache[path]
else:
frame = pd.read_csv(path)
csv_cache[path] = frame
return frame
class MNIST(torch.utils.data.Dataset):
def __init__(self, *paths, train=True, transform=None, split=None):
self.train = train
self.transform = transform
values = pd.conca... | max_length = 100
def tokenizer_100(input_text):
return tokenizer.encode(input_text, max_length=100, return_tensors='pt')[0]
TEXT = torchtext.data.Field(sequential=True, tokenize=tokenizer_100, use_vocab=False, lower=False,
include_lengths=True, batch_first=True, fix_length=max_length, pad_token=0)
LABEL = torchtext.... | Natural Language Processing with Disaster Tweets |
18,507,165 | augmented_transform = transforms.Compose([
transforms.ToPILImage() ,
transforms.RandomAffine(degrees=10, translate=(0.25, 0.25),
scale=(0.9, 1.1), shear=10,
fillcolor=0),
transforms.ToTensor() ,
transforms.Normalize(mean=(128,), std=(128,)) ,
])
transform = transforms.Compose([
transforms.ToTensor() ,
transforms.Norma... | dataset_train_eval, dataset_test = torchtext.data.TabularDataset.splits(
path='.', train='./train_eval.tsv', test='./test.tsv', format='tsv', fields=[('Text', TEXT),('Label', LABEL)] ) | Natural Language Processing with Disaster Tweets |
18,507,165 | class Model(nn.Module):
def __init__(self):
super(Model, self ).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(64, eps=1e-5, momentum=0.1),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(64, eps=1e... | print(tokenizer.convert_ids_to_tokens(item.Text.tolist()))
print(int(item.Label)) | Natural Language Processing with Disaster Tweets |
18,507,165 | models = []
for _ in range(num_folds):
model = Model().to(device)
print(model(iter(trainloader ).next() [0].to(device)).argmax(1 ).tolist())
models.append(model)
models<choose_model_class> | batch_size = 32
dl_train = torchtext.data.Iterator(
dataset_train, batch_size=batch_size, train=True)
dl_eval = torchtext.data.Iterator(
dataset_eval, batch_size=batch_size, train=False, sort=False)
dl_test = torchtext.data.Iterator(
dataset_test, batch_size=batch_size, train=False, sort=False)
dataloaders_dict =... | Natural Language Processing with Disaster Tweets |
18,507,165 | criterion = nn.CrossEntropyLoss()
optimizers = [torch.optim.RMSprop(model.parameters() , lr=0.002,
alpha=0.9, momentum=0.1,
eps=1e-7, centered=True)
for model in models]
schedulers = [torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min',
factor=0.25, patience=2,
verbose=True, min_lr=0.00001)
for optimizer... | print(transformers.__version__ ) | Natural Language Processing with Disaster Tweets |
18,507,165 | histories = []
for k,(optimizer, model)in enumerate(zip(optimizers, models)) :
schedulers[k]
histories.append([])
if k > 0:
print()
print()
print()
print(f'Model fold {k + 1}')
trainsets[k].transform = transform
for epoch in range(num_epochs):
sample = 0
running_total = running_errors = running_loss = 0
epoch_total =... | model = BertModel.from_pretrained('bert-base-cased' ) | Natural Language Processing with Disaster Tweets |
18,507,165 | for i, model in enumerate(models):
torch.save(model.state_dict() , os.path.join(output_path, f'model-{i + 1}.pt'))<prepare_output> | class BertForTwitter(nn.Module):
def __init__(self):
super(BertForTwitter, self ).__init__()
self.bert = model
self.cls = nn.Linear(in_features=768, out_features=9)
nn.init.normal_(self.cls.weight, std=0.02)
nn.init.normal_(self.cls.bias, 0)
def forward(self, input_ids):
result = self.bert(input_ids)
vec_0 = resu... | Natural Language Processing with Disaster Tweets |
18,507,165 | submission = []
for images in testloader:
predictions = sum(model(images.to(device)) for model in models)
submission.extend(predictions.argmax(1 ).tolist())
len(submission )<save_to_csv> | net = BertForTwitter()
net.train()
print('ネットワーク設定完了' ) | Natural Language Processing with Disaster Tweets |
18,507,165 | df = pd.DataFrame.from_records(np.array(submission ).reshape(-1, 1))
df.to_csv(os.path.join(output_path, 'submission.csv'),
index_label='id', header=['label'] )<import_modules> | for param in net.parameters() :
param.requires_grad = False
for param in net.bert.encoder.layer[-1].parameters() :
param.requires_grad = True
for param in net.cls.parameters() :
param.requires_grad = True | Natural Language Processing with Disaster Tweets |
18,507,165 | import numpy as np
import pandas as pd
import os
import struct
import matplotlib.pyplot as plt
import keras
from keras.layers import *
from keras.models import Sequential, load_model
from keras.optimizers import *
from sklearn.preprocessing import MinMaxScaler
from keras.callbacks import CSVLogger, ModelCheckpoint
from... | optimizer = optim.Adam([
{'params': net.bert.encoder.layer[-1].parameters() , 'lr': 5e-5},
{'params': net.cls.parameters() , 'lr': 1e-4}
])
criterion = nn.CrossEntropyLoss()
| Natural Language Processing with Disaster Tweets |
18,507,165 | train = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')
test = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')
valid_part = 10
test_id = test.id
test = test.drop('id', axis=1)
y_train = train.label
x_train = train.drop('label', axis=1)
train_size = int(x_train.shape[0] / valid_part *(valid_part - 1))
x_val... | def train_model(net, dataloaders_dict, criterion, optimizer, num_epochs):
max_acc = 0
Stop_flag = False
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("使用デバイス:", device)
print('-----start-------')
net.to(device)
torch.backends.cudnn.benchmark = True
batch_size = dataloaders_dict["trai... | Natural Language Processing with Disaster Tweets |
18,507,165 | scaler = MinMaxScaler(feature_range=(-1, 1))
rows, cols = 28, 28
x_train = x_train.astype('float32')
test = test.astype('float32')
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_valid = scaler.transform(x_valid)
test = scaler.transform(test)
print(x_train.min() , x_train.max())
x_train = x_train.resha... | num_epochs = 100
net_trained = train_model(net, dataloaders_dict,
criterion, optimizer, num_epochs=num_epochs ) | Natural Language Processing with Disaster Tweets |
18,507,165 | train_datagen = ImageDataGenerator(rotation_range = 10,
shear_range = 0.1,
width_shift_range = 0.25,
height_shift_range = 0.25,
zoom_range = 0.25,
horizontal_flip = False)
epochs = 40
batch_size = 1024
model = Sequential()
model.add(Conv2D(64,
kernel_size=(5, 5),
input_shape=(28, 28, 1),
padding='same'))
model.add(Lea... | sample_submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv")
sample_submission["target"] = ans_list
sample_submission | Natural Language Processing with Disaster Tweets |
18,507,165 | METRICS = {
'accuracy': {
'f': accuracy_score,
'args': {}
},
}
NORM_MEAN = [0.485, 0.456, 0.406]
NORM_STD = [0.229, 0.224, 0.225]
def make_image_label_grid(images, labels=None, class_names=None):
channels = images.shape[1]
if channels not in(3, 1):
raise ValueError("Images must have 1 or 3 channels")
mean = NORM_MEAN ... | sample_submission.to_csv("submission_plus.csv", index=False ) | Natural Language Processing with Disaster Tweets |
18,103,825 | import os
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import torchvision.transforms as transforms
from PIL import Image<define_variables> | !pip install nlpaug | Natural Language Processing with Disaster Tweets |
18,103,825 | CLASS_NAMES =('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
data_root = '.. /input/Kannada-MNIST'
train_file_name = 'train.csv'
val_file_name = 'Dig-MNIST.csv'
test_file_name = 'test.csv'
NORM_MEAN = [0.485, 0.456, 0.406]
NORM_STD = [0.229, 0.224, 0.225]<normalization> | !kaggle datasets download -d rtatman/glove-global-vectors-for-word-representation | Natural Language Processing with Disaster Tweets |
18,103,825 | class KannadaMNISTTransforms(transforms.Compose):
def __init__(self, in_channels=1, out_channels=1, size=(28, 28)) :
if out_channels not in(3, 1)or in_channels not in(3, 1):
raise ValueError("Images must have 1 or 3 channels")
mean = NORM_MEAN if out_channels == 3 else [sum(NORM_MEAN)/ 3]
std = NORM_STD if out_channel... | !pip install nltk
!pip install gensim | Natural Language Processing with Disaster Tweets |
18,103,825 | class KannadaMNISTDataset(torch.utils.data.Dataset):
def __init__(self, images, targets=None, transform=None):
super(KannadaMNISTDataset, self ).__init__()
self.images = [Image.fromarray(image)for image in images]
self.targets = np.zeros(len(images)) if targets is None else targets.astype(int)
self.transform = transfo... | nltk.download('all' ) | Natural Language Processing with Disaster Tweets |
18,103,825 | train_df = pd.read_csv(os.path.join(data_root, train_file_name))
val_df = pd.read_csv(os.path.join(data_root, val_file_name))
test_df = pd.read_csv(os.path.join(data_root, test_file_name))<data_type_conversions> | !wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py | Natural Language Processing with Disaster Tweets |
18,103,825 | train_targets = train_df.label.values.astype(int)
train_images =(train_df.drop('label', axis=1 ).values.astype(float)/ 255 ).reshape(-1, 28, 28)
val_targets = val_df.label.values.astype(int)
val_images =(val_df.drop('label', axis=1 ).values.astype(float)/ 255 ).reshape(-1, 28, 28)
test_ids = test_df.id.values.astyp... | plt.style.use('ggplot')
stop=set(stopwords.words('english'))
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
plt.style.use('ggplot')
stop=set(stopwords.words('english'))
warnings.filterwarnings("ignore")
nltk.download('brown', quiet=True)
nltk... | Natural Language Processing with Disaster Tweets |
18,103,825 | batch_size = 1000
size =(28, 28)
origin_channels = 1
in_channels = 1
train_dataset = KannadaMNISTDataset(train_images, train_targets, transform=KannadaMNISTTransforms(in_channels=origin_channels, out_channels=in_channels, size=size))
val_dataset = KannadaMNISTDataset(val_images, val_targets, transform=Transforms(in_ch... | df_train = pd.read_csv('.. /input/nlp-getting-started/train.csv', dtype={'id': np.int16, 'target': np.int8})
df_test = pd.read_csv('.. /input/nlp-getting-started/test.csv', dtype={'id': np.int16})
print('Training Set Shape = {}'.format(df_train.shape))
print('Training Set Memory Usage = {:.2f} MB'.format(df_train.mem... | Natural Language Processing with Disaster Tweets |
18,103,825 | class Conv2dBNReLU(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=True):
super(Conv2dBNReLU, self ).__init__(
nn.Conv2d(in_channels, out_channels,
kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=bias),
nn.BatchNorm2d(out_cha... | print(f'Number of unique values in keyword = {df_train["keyword"].nunique() }(Training)- {df_test["keyword"].nunique() }(Test)')
print(f'Number of unique values in location = {df_train["location"].nunique() }(Training)- {df_test["location"].nunique() }(Test)' ) | Natural Language Processing with Disaster Tweets |
18,103,825 | device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
net = KannadaMNISTNet(in_channels=in_channels, classes=10)
net = net.to(torch.device(device))
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters() , lr=0.002, weight_decay=0.00005)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, fact... | def create_corpus(target):
corpus=[]
for x in df_train[df_train['target']==target]['text'].str.split() :
for i in x:
corpus.append(i)
return corpus | Natural Language Processing with Disaster Tweets |
18,103,825 | net.eval()
for param in net.parameters() :
param.requires_grad = False<categorify> | counter=Counter(corpus)
most=counter.most_common()
x=[]
y=[]
for word,count in most[:40]:
if(word not in stop):
x.append(word)
y.append(count ) | Natural Language Processing with Disaster Tweets |
18,103,825 | test_predictions = None
for batch in test_dataloader:
inputs = batch[0]
inputs = inputs.to(torch.device(device))
output = net.forward(inputs)
predictions = output.argmax(dim=1 ).data
test_predictions = predictions if test_predictions is None else torch.cat(( test_predictions, predictions))
test_predictions = test_pred... | def get_top_tweet_bigrams(corpus, n=None):
vec = CountVectorizer(ngram_range=(2, 2)).fit(corpus)
bag_of_words = vec.transform(corpus)
sum_words = bag_of_words.sum(axis=0)
words_freq = [(word, sum_words[0, idx])for word, idx in vec.vocabulary_.items() ]
words_freq =sorted(words_freq, key = lambda x: x[1], reverse=Tru... | Natural Language Processing with Disaster Tweets |
18,103,825 | submission_df = pd.DataFrame(np.c_[test_ids[:,None], test_predictions], columns=['id', 'label'])
submission_df.head()<save_to_csv> | df_train['word_count'] = df_train['text'].apply(lambda x: len(str(x ).split()))
df_test['word_count'] = df_test['text'].apply(lambda x: len(str(x ).split()))
df_train['unique_word_count'] = df_train['text'].apply(lambda x: len(set(str(x ).split())))
df_test['unique_word_count'] = df_test['text'].apply(lambda x: len(se... | Natural Language Processing with Disaster Tweets |
18,103,825 | submission_df.to_csv('submission.csv', index=False )<install_modules> | def generate_ngrams(text, n_gram=1):
token = [token for token in text.lower().split(' ')if token != '' if token not in STOPWORDS]
ngrams = zip(*[token[i:] for i in range(n_gram)])
return [' '.join(ngram)for ngram in ngrams]
N = 100
disaster_unigrams = defaultdict(int)
nondisaster_unigrams = defaultdict(int)
for twee... | Natural Language Processing with Disaster Tweets |
18,103,825 | !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<set_options> | sw = stopwords.words('english')
stw = sw + ['lot','frog','ppl','tldr','time','nan','thing', 'subject', 're', 'edu', 'use','good','really','quite','nice','well','little','need','keep','make','important','take','get','very','course','instructor','example']
ps = PorterStemmer()
lemmatizer = nltk.stem.WordNetLemmatizer() | Natural Language Processing with Disaster Tweets |
18,103,825 | SEED = 100
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
seed_everything(SEED )<categorify> | def lower(df):
df['com_token'] = df['text'].str.lower().str.split()
df["com_"] = df["com_token"].apply(' '.join)
return df | Natural Language Processing with Disaster Tweets |
18,103,825 | def collate_fn(batch):
return tuple(zip(*batch))
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)
class BaseWheatTTA:
image_size = 1024
def augment(... | df_train = lower(df_train)
df_train["Orig_comment"] = df_train["text"]
df_train["text"] = df_train["com_"] | Natural Language Processing with Disaster Tweets |
18,103,825 | MODELS_PATHS = ['.. /input/frcnnfold012best/frcnn-fold0-best100.pth',
'.. /input/frcnnfold012best/frcnn_fold1_best50.pth',
'.. /input/frcnnfold012best/frcnn_fold2_best50.pth']
def get_model() :
backbone = resnet_fpn_backbone('resnet101', pretrained=False)
model = FasterRCNN(backbone, num_classes=2)
return model
frcnn... | def decontracted(tweet):
tweet = re.sub(r"won't", "will not", tweet)
tweet = re.sub(r"can't", "can not", tweet)
tweet = re.sub(r"he\ ’ s", "he is", tweet)
tweet = re.sub(r"i\ ’ m", "he is", tweet)
tweet=re.sub("(<.*?>)","",tweet)
tweet=re.sub("(\\W|\\d)"," ",tweet)
tweet = re.sub(r"n't", " not", tweet)
tweet =... | Natural Language Processing with Disaster Tweets |
18,103,825 | class WheatDataset(Dataset):
def __init__(self, dataframe, image_dir, transforms=None):
super().__init__()
self.image_ids = dataframe['image_id'].unique()
self.df = dataframe
self.image_dir = image_dir
self.transforms = transforms
def __len__(self)-> int:
return len(self.image_ids)
def __getitem__(self, idx: int):
ima... | def remove_punct(text):
table=str.maketrans('','',string.punctuation)
return text.translate(table ) | Natural Language Processing with Disaster Tweets |
18,103,825 | def get_train_transform() :
return A.Compose([
A.Flip(0.5),
ToTensorV2(p=1.0)
], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})
def get_valid_transform() :
return A.Compose([
ToTensorV2(p=1.0)
], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})
def get_test_transforms() :
return ... | df_train['text']=df_train['text'].apply(reduce_lengthening, 0)
df_train['text']=df_train['text'].apply(decontracted, 0)
df_train['text']=df_train['text'].apply(lambda x : remove_punct(x)) | Natural Language Processing with Disaster Tweets |
18,103,825 | def make_tta_predictions(images, model, score_threshold=0.40):
with torch.no_grad() :
images = torch.stack(images ).float().to(DEVICE)
predictions = []
for tta_transform in tta_transforms:
result = []
outputs = model(tta_transform.batch_augment(images.clone()))
for i, image in enumerate(images):
boxes = outputs[i]['bo... | def remove_URL(text):
url = re.compile(r'https?://\S+|www\.\S+')
return url.sub(r'',text ) | Natural Language Processing with Disaster Tweets |
18,103,825 | def run_wbf(predictions, image_index, image_size=1024, iou_thr=0.45, skip_box_thr=0.45, weights=None):
boxes = [(prediction[image_index]['boxes']/(image_size-1)).tolist() for prediction in predictions]
scores = [prediction[image_index]['scores'].tolist() for prediction in predictions]
labels = [np.ones(prediction[image... | df_train['text']=df_train['text'].apply(lambda x : remove_URL(x)) | Natural Language Processing with Disaster Tweets |
18,103,825 | DATA_DIR = '.. /input/global-wheat-detection'
device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu')
test_df = pd.read_csv(os.path.join(DATA_DIR, "sample_submission.csv"))
testdf_pseudos = []
for model in frcnn_models:
results = []
testdf_pseudo = []
test_dataset = WheatDataset(test_df, os.... | aug_w2v = naw.WordEmbsAug(
model_type='glove', model_path='.. /input/glove-global-vectors-for-word-representation/glove.6B.100d.txt',
action="substitute")
| Natural Language Processing with Disaster Tweets |
18,103,825 | new_train_dfs = []
for result in testdf_pseudos:
df = pd.DataFrame(result, columns=['image_id', 'width', 'height', 'source', 'x', 'y', 'w', 'h'])
new_train_dfs.append(df )<data_type_conversions> | aug_w2v.aug_p=0.2
print("Augmented Text:")
for ii in range(5):
augmented_text = aug_w2v.augment(text)
print(augmented_text ) | Natural Language Processing with Disaster Tweets |
18,103,825 | train_df = pd.read_csv(f'{DATA_DIR}/train.csv')
train_df['x'] = -1
train_df['y'] = -1
train_df['w'] = -1
train_df['h'] = -1
def expand_bbox(x):
r = np.array(re.findall("([0-9]+[.]?[0-9]*)", x))
if len(r)== 0:
r = [-1, -1, -1, -1]
return r
train_df[['x', 'y', 'w', 'h']] = np.stack(train_df['bbox'].apply(lambda x: expan... | train,valid=train_test_split(df_train,test_size=0.15)
print('Shape of train',train.shape)
print("Shape of Validation ",valid.shape ) | Natural Language Processing with Disaster Tweets |
18,103,825 | class WheatDataset(Dataset):
def __init__(self, dataframe, image_dir=DATA_DIR, transforms=None):
super().__init__()
self.image_ids = dataframe['image_id'].unique()
self.df = dataframe
self.image_dir = image_dir
self.transforms = transforms
def __getitem__(self, index: int):
image_id = self.image_ids[index]
records = se... | def augment_text(df,samples=300,pr=0.2):
aug_w2v.aug_p=pr
new_text=[]
df_n=df[df.target==1].reset_index(drop=True)
for i in tqdm(np.random.randint(0,len(df_n),samples)) :
text = df_n.iloc[i]['text']
augmented_text = aug_w2v.augment(text)
new_text.append(augmented_text)
new=pd.DataFrame({'text':new_text,'target':1})
... | Natural Language Processing with Disaster Tweets |
18,103,825 | class Averager:
def __init__(self):
self.current_total = 0.0
self.iterations = 0.0
def send(self, value):
self.current_total += value
self.iterations += 1
@property
def value(self):
if self.iterations == 0:
return 0
else:
return 1.0 * self.current_total / self.iterations
def reset(self):
self.current_total = 0.0
self.i... | train = augment_text(train,samples=400)
tweet = train.append(valid ).reset_index(drop=True ) | Natural Language Processing with Disaster Tweets |
18,103,825 | frcnn_models_trained = []
for model, train_df in zip(frcnn_models, new_train_dfs):
train_dataset = WheatDataset(train_df, image_dir=DATA_DIR, transforms=get_train_transform())
valid_dataset = WheatDataset(valid_df, image_dir=DATA_DIR, transforms=get_valid_transform())
indices = torch.randperm(len(train_dataset)).toli... | df=pd.concat([tweet,df_test] ) | Natural Language Processing with Disaster Tweets |
18,103,825 | USE_OPTIMIZE = False<load_from_csv> | def create_corpus(df):
corpus=[]
for tweet in tqdm(df['text']):
words=[word.lower() for word in word_tokenize(tweet)if(( word.isalpha() ==1)&(word not in stop)) ]
corpus.append(words)
return corpus
| Natural Language Processing with Disaster Tweets |
18,103,825 | 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 )<feature_engineering> | corpus=create_corpus(df ) | Natural Language Processing with Disaster Tweets |
18,103,825 | skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
df_folds = marking[['image_id']]
df_folds['bbox_count'] = 1
df_folds = df_folds.groupby('image_id' ).count()
df_folds['source'] = marking[['image_id', 'source']].groupby('image_id' ).min() ['source']
df_folds['stratify_group'] = np.char.add(
df_folds['s... | embedding_dict={}
with open('.. /input/glove-global-vectors-for-word-representation/glove.6B.100d.txt','r')as f:
for line in f:
values=line.split()
word=values[0]
vectors=np.asarray(values[1:],'float32')
embedding_dict[word]=vectors
f.close() | Natural Language Processing with Disaster Tweets |
18,103,825 | holdout_dataset = DatasetRetriever(
image_ids=df_holdout.index.values,
marking=marking,
transforms=get_valid_transforms() ,
test=True,
)
holdout_loader = DataLoader(
holdout_dataset,
batch_size=4,
shuffle=False,
num_workers=2,
drop_last=False,
collate_fn=collate_fn
)<choose_model_class> | MAX_LEN=50
tokenizer_obj=Tokenizer()
tokenizer_obj.fit_on_texts(corpus)
sequences=tokenizer_obj.texts_to_sequences(corpus)
tweet_pad=pad_sequences(sequences,maxlen=MAX_LEN,truncating='post',padding='post' ) | Natural Language Processing with Disaster Tweets |
18,103,825 | def load_net(checkpoint_path, version):
config = get_efficientdet_config(f'tf_efficientdet_d{version}')
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))
checkpo... | word_index=tokenizer_obj.word_index
print('Number of unique words:',len(word_index)) | Natural Language Processing with Disaster Tweets |
18,103,825 | 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*2 ).clip(min=0, max=1023 ).astype(int)
indexes = np.where(scores>score_thres... | num_words=len(word_index)+1
embedding_matrix=np.zeros(( num_words,100))
for word,i in tqdm(word_index.items()):
if i > num_words:
continue
emb_vec=embedding_dict.get(word)
if emb_vec is not None:
embedding_matrix[i]=emb_vec
| Natural Language Processing with Disaster Tweets |
18,103,825 | @jit(nopython=True)
def calculate_iou(gt, pr, form='pascal_voc')-> float:
if form == 'coco':
gt = gt.copy()
pr = pr.copy()
gt[2] = gt[0] + gt[2]
gt[3] = gt[1] + gt[3]
pr[2] = pr[0] + pr[2]
pr[3] = pr[1] + pr[3]
dx = min(gt[2], pr[2])- max(gt[0], pr[0])+ 1
if dx < 0:
return 0.0
dy = min(gt[3], pr[3])- max(gt[1], pr[1... | model = Sequential()
embedding=Embedding(num_words,100,embeddings_initializer=Constant(embedding_matrix),
input_length=MAX_LEN,trainable=False)
model.add(embedding)
model.add(SimpleRNN(100))
model.add(Dense(1, activation='sigmoid'))
optimzer=Adam(learning_rate=1e-5)
model.compile(loss='binary_crossentropy',optimizer... | Natural Language Processing with Disaster Tweets |
18,103,825 | def calculate_final_score(
all_predictions,
iou_thr,
skip_box_thr,
method,
sigma=0.5,
):
final_scores = []
for i in range(len(all_predictions)) :
gt_boxes = all_predictions[i]['gt_boxes'].copy()
image_id = all_predictions[i]['image_id']
folds_boxes, folds_scores, folds_labels = [], [], []
for fold_number in range(2):... | train_df=tweet_pad[:tweet.shape[0]]
test_df=tweet_pad[tweet.shape[0]:] | Natural Language Processing with Disaster Tweets |
18,103,825 | if USE_OPTIMIZE:
print('[WBF]: ', calculate_final_score(
all_predictions,
iou_thr=0.55,
skip_box_thr=0.0001,
method='weighted_boxes_fusion',
))
print('[NMS]: ', calculate_final_score(
all_predictions,
iou_thr=0.55,
skip_box_thr=0.0001,
method='nms',
))
print('[SOFT NMS]: ', calculate_final_score(
all_predictions,
... | X_train,y_train = train_df[:train.shape[0]],tweet['target'][:train.shape[0]]
X_test,y_test= train_df[train.shape[0]:],tweet['target'][train.shape[0]:] | Natural Language Processing with Disaster Tweets |
18,103,825 | def log(text):
with open('opt.log', 'a+')as logger:
logger.write(f'{text}
')
def optimize(space, all_predictions, method, n_calls=10):
@use_named_args(space)
def score(**params):
log('-'*5 + f'{method}' + '-'*5)
log(params)
final_score = calculate_final_score(all_predictions, method=method, **params)
log(f'final_s... | history=model.fit(X_train,y_train,batch_size=4,epochs=10,validation_data=(X_test,y_test),verbose=2 ) | Natural Language Processing with Disaster Tweets |
18,103,825 | space = [
Real(0, 1, name='iou_thr'),
Real(0.25, 1, name='skip_box_thr'),
]
if USE_OPTIMIZE:
opt_result = optimize(
space,
all_predictions,
method='weighted_boxes_fusion',
n_calls=50,
)<find_best_params> | y_pre=model.predict(X_test)
y_pre=np.round(y_pre ).astype(int ).reshape(1142 ) | Natural Language Processing with Disaster Tweets |
18,103,825 | if USE_OPTIMIZE:
best_final_score = -opt_result.fun
best_iou_thr = opt_result.x[0]
best_skip_box_thr = opt_result.x[1]
else:
best_final_score = 0.7197
best_iou_thr = 0.450
best_skip_box_thr = 0.450
print('-'*13 + 'WBF' + '-'*14)
print(f'[Best Iou Thr]: {best_iou_thr:.3f}')
print(f'[Best Skip Box Thr]: {best_skip_box_... | print(roc_auc_score(y_pre,y_test)) | Natural Language Processing with Disaster Tweets |
18,103,825 | if USE_OPTIMIZE:
all_predictions = []
for fold_number in range(5):
validation_dataset = DatasetRetriever(
image_ids=df_folds[df_folds['fold'] == fold_number].index.values,
marking=marking,
transforms=get_valid_transforms() ,
test=True,
)
validation_loader = DataLoader(
validation_dataset,
batch_size=4,
shuffle=Fals... | scores_model = [] | Natural Language Processing with Disaster Tweets |
18,103,825 | def calculate_final_score(all_predictions, score_threshold):
final_scores = []
for i in range(len(all_predictions)) :
gt_boxes = all_predictions[i]['gt_boxes'].copy()
pred_boxes = all_predictions[i]['pred_boxes'].copy()
scores = all_predictions[i]['scores'].copy()
image_id = all_predictions[i]['image_id']
indexes = np.... | scores_model.append({'Model': 'SimpleRNN','AUC_Score': roc_auc_score(y_pre,y_test)} ) | Natural Language Processing with Disaster Tweets |
18,103,825 | best_final_score, best_score_threshold = 0, 0
if USE_OPTIMIZE:
for score_threshold in tqdm(np.arange(0, 1, 0.01), total=np.arange(0, 1, 0.01 ).shape[0]):
final_score = calculate_final_score(all_predictions, score_threshold)
if final_score > best_final_score:
best_final_score = final_score
best_score_threshold = score_... | model=Sequential()
embedding=Embedding(num_words,100,embeddings_initializer=Constant(embedding_matrix),
input_length=MAX_LEN,trainable=False)
model.add(embedding)
model.add(SpatialDropout1D(0.2))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))
optimzer=Adam(learning_... | Natural Language Processing with Disaster Tweets |
18,103,825 | print('-'*30)
print(f'[Best Score Threshold]: {best_score_threshold}')
print(f'[OOF Score]: {best_final_score:.4f}')
print('-'*30 )<data_type_conversions> | history=model.fit(X_train,y_train,batch_size=4,epochs=10,validation_data=(X_test,y_test),verbose=2 ) | Natural Language Processing with Disaster Tweets |
18,103,825 | DATA_ROOT_PATH = '.. /input/global-wheat-detection/test'
class TestDatasetRetriever(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_PAT... | y_pre=model.predict(X_test)
y_pre=np.round(y_pre ).astype(int ).reshape(1142 ) | Natural Language Processing with Disaster Tweets |
18,103,825 | def get_valid_transforms512() :
return A.Compose([A.Resize(height=512, width=512, p=1.0), ToTensorV2(p=1.0)], p=1.0)
def get_valid_transforms1024() :
return A.Compose([ToTensorV2(p=1.0)], p=1.0)
dataset512 = TestDatasetRetriever(image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]... | print(roc_auc_score(y_pre,y_test)) | Natural Language Processing with Disaster Tweets |
18,103,825 | def make_frcnn_predictions(images, score_threshold=0.50):
with torch.no_grad() :
images = torch.stack(images ).cuda().float()
predictions = []
for fold_number, model in enumerate(frcnn_models_trained):
for tta_transform in tta_transforms:
result = []
outputs = model(tta_transform.batch_augment(images.clone()))
for i, i... | scores_model.append({'Model': 'LSTM','AUC_Score': roc_auc_score(y_pre,y_test)} ) | Natural Language Processing with Disaster Tweets |
18,103,825 | for i, model in enumerate(models):
print(type(model))<categorify> | model=Sequential()
embedding=Embedding(num_words,100,embeddings_initializer=Constant(embedding_matrix),
input_length=MAX_LEN,trainable=False)
model.add(embedding)
model.add(SpatialDropout1D(0.2))
model.add(GRU(300))
model.add(Dense(1, activation='sigmoid'))
optimzer=Adam(learning_rate=1e-5)
model.compile(loss='binar... | Natural Language Processing with Disaster Tweets |
18,103,825 | 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*2 ).clip(min=0, max=1023 ).astype(int)
indexes = np.where(scores>score_thres... | history=model.fit(X_train,y_train,batch_size=8,epochs=10,validation_data=(X_test,y_test),verbose=2 ) | Natural Language Processing with Disaster Tweets |
18,103,825 | def make_predictions(images, score_threshold=best_score_threshold):
with torch.no_grad() :
images = torch.stack(images ).cuda().float()
predictions = []
for fold_number, net in enumerate(models):
for tta_transform in tta_transforms:
det = net(tta_transform.batch_augment(images.clone()), torch.tensor([1]*images.shape[0]... | y_pre=model.predict(X_test)
y_pre=np.round(y_pre ).astype(int ).reshape(1142)
| Natural Language Processing with Disaster Tweets |
18,103,825 | def run_wbf(predictions, image_index, image_size=512, iou_thr=best_iou_thr, skip_box_thr=best_skip_box_thr, weights=None):
boxes = [(prediction[image_index]['boxes']/(image_size-1)).tolist() for prediction in predictions]
scores = [prediction[image_index]['scores'].tolist() for prediction in predictions]
labels = [np.o... | model=Sequential()
embedding=Embedding(num_words,100,embeddings_initializer=Constant(embedding_matrix),
input_length=MAX_LEN,trainable=False)
model.add(embedding)
model.add(Bidirectional(LSTM(300, dropout=0.3, recurrent_dropout=0.3)))
model.add(Dense(1, activation='sigmoid'))
optimzer=Adam(learning_rate=1e-5)
model... | Natural Language Processing with Disaster Tweets |
18,103,825 | 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 )<predict_on_test> | history=model.fit(X_train,y_train,batch_size=4,epochs=5,validation_data=(X_test,y_test),verbose=2 ) | Natural Language Processing with Disaster Tweets |
18,103,825 | results = []
for(images_effdet, image_ids_effdet),(images_frcnn, image_ids_frcnn)in zip(data_loader512, data_loader1024):
if image_ids_effdet == image_ids_frcnn:
frcnn_predictions = make_frcnn_predictions(images_frcnn)
effdet_predictions = make_effdet_predictions(images_effdet)
images = image_ids_effdet
predictions =... | y_pre=model.predict(X_test)
y_pre=np.round(y_pre ).astype(int ).reshape(1142)
print(roc_auc_score(y_pre,y_test)) | Natural Language Processing with Disaster Tweets |
18,103,825 | test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])
test_df.to_csv('submission.csv', index=False )<choose_model_class> | scores_model.append({'Model': 'Bidirectional-LSTM','AUC_Score': roc_auc_score(y_pre,y_test)} ) | Natural Language Processing with Disaster Tweets |
18,103,825 | def load_net(checkpoint_path, version):
config = get_efficientdet_config(f'tf_efficientdet_d{version}')
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))
checkpo... | !wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py | Natural Language Processing with Disaster Tweets |
18,103,825 | best_score_threshold = 0.40
best_iou_thr = 0.45
best_skip_box_thr = 0.45<categorify> | import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import ModelCheckpoint
import tensorflow_hub as hub
import tokenization | Natural Language Processing with Disaster Tweets |
18,103,825 | 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(self,... | def bert_encode(texts, tokenizer, max_len=512):
all_tokens = []
all_masks = []
all_segments = []
for text in texts:
text = tokenizer.tokenize(text)
text = text[:max_len-2]
input_sequence = ["[CLS]"] + text + ["[SEP]"]
pad_len = max_len - len(input_sequence)
tokens = tokenizer.convert_tokens_to_ids(input_sequence)
to... | Natural Language Processing with Disaster Tweets |
18,103,825 | transform = TTACompose([
TTARotate90() ,
TTAVerticalFlip() ,
] )<data_type_conversions> | def build_model(bert_layer, max_len=512):
input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_word_ids")
input_mask = Input(shape=(max_len,), dtype=tf.int32, name="input_mask")
segment_ids = Input(shape=(max_len,), dtype=tf.int32, name="segment_ids")
_, sequence_output = bert_layer([input_word_ids, ... | Natural Language Processing with Disaster Tweets |
18,103,825 | DATA_ROOT_PATH = '.. /input/global-wheat-detection/test'
class TestDatasetRetriever(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_PAT... | %%time
module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1"
bert_layer = hub.KerasLayer(module_url, trainable=True ) | Natural Language Processing with Disaster Tweets |
18,103,825 | def make_predictions(images, score_threshold=best_score_threshold):
with torch.no_grad() :
images = torch.stack(images ).cuda().float()
predictions = []
for fold_number, net in enumerate(models):
for tta_transform in tta_transforms:
det = net(tta_transform.batch_augment(images.clone()), torch.tensor([1]*images.shape[0]... | train = pd.read_csv(".. /input/nlp-getting-started/train.csv")
test = pd.read_csv(".. /input/nlp-getting-started/test.csv")
submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv")
| Natural Language Processing with Disaster Tweets |
18,103,825 | def run_wbf(predictions, image_index, image_size=512, iou_thr=best_iou_thr, skip_box_thr=best_skip_box_thr, weights=None):
boxes = [(prediction[image_index]['boxes']/(image_size-1)).tolist() for prediction in predictions]
scores = [prediction[image_index]['scores'].tolist() for prediction in predictions]
labels = [np.o... | vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()
do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()
tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case ) | Natural Language Processing with Disaster Tweets |
18,103,825 | 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 )<predict_on_test> | train_input = bert_encode(train.text.values, tokenizer, max_len=160)
test_input = bert_encode(test.text.values, tokenizer, max_len=160)
train_labels = train.target.values | Natural Language Processing with Disaster Tweets |
18,103,825 | results = []
for images, image_ids in data_loader:
predictions = make_predictions(images)
for i, image in enumerate(images):
boxes, scores, labels = run_wbf(predictions, image_index=i)
boxes =(boxes*2 ).astype(np.int32 ).clip(min=0, max=1023)
image_id = image_ids[i]
boxes[:, 2] = boxes[:, 2] - boxes[:, 0]
boxes[:, 3... | checkpoint = ModelCheckpoint('model.h5', monitor='val_loss', save_best_only=True)
train_history = model.fit(
train_input, train_labels,
validation_split=0.2,
epochs=3,
callbacks=[checkpoint],
batch_size=16
) | Natural Language Processing with Disaster Tweets |
18,103,825 | test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])
test_df<define_variables> | model.load_weights('model.h5')
test_pred = model.predict(test_input ) | Natural Language Processing with Disaster Tweets |
18,103,825 | NMS_IOU_THR = 0.6
NMS_CONF_THR = 0.25
best_iou_thr = 0.6
best_skip_box_thr = 0.43
best_final_score = 0
best_score_threshold = 0
SEED = 42
EPO = 15
WEIGHTS = '.. /input/yolov5-k-weights/full-best.pt'
CONFIG = '.. /input/configyolo5/yolov5x.yaml'
DATA = '.. /input/configyolo5/wheat0.yaml'
is_TEST = len(os.listdir('.. /in... | submission['target'] = test_pred.round().astype(int)
submission.to_csv('submission.csv', index=False ) | Natural Language Processing with Disaster Tweets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.