kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
11,792,393 | checkpoint = torch.load("/kaggle/input/deepfakes-inference-demo/resnext.pth", map_location=gpu)
model = MyResNeXt().to(gpu)
model.load_state_dict(checkpoint)
_ = model.eval()
del checkpoint<predict_on_test> | def flat_accuracy(preds, labels):
pred_flat = np.argmax(preds, axis=1 ).flatten()
labels_flat = labels.flatten()
return np.sum(pred_flat == labels_flat)/ len(labels_flat ) | Natural Language Processing with Disaster Tweets |
11,792,393 | def predict_on_video(video_path, batch_size):
try:
faces = face_extractor.process_video(video_path)
face_extractor.keep_only_best_face(faces)
if len(faces)> 0:
x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8)
n = 0
for frame_data in faces:
for face in frame_data["faces"]:
resized_face = isotrop... | def format_time(elapsed):
elapsed_rounded = int(round(( elapsed)))
return str(datetime.timedelta(seconds=elapsed_rounded)) | Natural Language Processing with Disaster Tweets |
11,792,393 | def predict_on_video_set(videos, num_workers):
def process_file(i):
filename = videos[i]
y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video)
return y_pred
with ThreadPoolExecutor(max_workers=num_workers)as ex:
predictions = ex.map(process_file, range(len(videos)))
return list(pred... | seed_val = 42
random.seed(seed_val)
np.random.seed(seed_val)
torch.manual_seed(seed_val)
torch.cuda.manual_seed_all(seed_val)
loss_values = []
for epoch_i in range(0, epochs):
print("")
print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, epochs))
print('Training...')
t0 = time.time()
total_loss = 0
mode... | Natural Language Processing with Disaster Tweets |
11,792,393 | predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv> | print("")
print("Running Validation...")
t0 = time.time()
model.eval()
preds=[]
true=[]
eval_loss, eval_accuracy = 0, 0
nb_eval_steps, nb_eval_examples = 0, 0
for batch in validation_dataloader:
batch = tuple(t.to(device)for t in batch)
b_input_ids, b_input_mask, b_labels = batch
with torch.no_grad() :
outputs = mod... | Natural Language Processing with Disaster Tweets |
11,792,393 | submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions})
submission_df_resnext.to_csv("submission_resnext.csv", index=False )<install_modules> | flat_predictions = [item for sublist in preds for item in sublist]
flat_predictions = np.argmax(flat_predictions, axis=1 ).flatten()
flat_true_labels = [item for sublist in true for item in sublist] | Natural Language Processing with Disaster Tweets |
11,792,393 | !pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet<set_options> | print(classification_report(flat_predictions,flat_true_labels)) | Natural Language Processing with Disaster Tweets |
11,792,393 | %matplotlib inline
warnings.filterwarnings("ignore" )<define_variables> | comments1 = df_test.text.values
indices1=tokenizer.batch_encode_plus(comments1,max_length=128,add_special_tokens=True, return_attention_mask=True,pad_to_max_length=True,truncation=True)
input_ids1=indices1["input_ids"]
attention_masks1=indices1["attention_mask"]
prediction_inputs1= torch.tensor(input_ids1)
prediction... | Natural Language Processing with Disaster Tweets |
11,792,393 | test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/"
test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"])
len(test_videos )<set_options> | print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
model.eval()
predictions = []
for batch in prediction_dataloader1:
batch = tuple(t.to(device)for t in batch)
b_input_ids1, b_input_mask1 = batch
with torch.no_grad() :
outputs1 = model(b_input_ids1, token_type_ids=None,
attention_ma... | Natural Language Processing with Disaster Tweets |
11,792,393 | gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )<load_pretrained> | sample_sub=pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv')
submit=pd.DataFrame({'id':sample_sub['id'].values.tolist() ,'target':flat_predictions})
| Natural Language Processing with Disaster Tweets |
11,792,393 | <load_pretrained><EOS> | df_leak = pd.read_csv('/kaggle/input/disasters-on-social-media/socialmedia-disaster-tweets-DFE.csv', encoding ='ISO-8859-1')[['choose_one', 'text']]
df_leak['target'] =(df_leak['choose_one'] == 'Relevant' ).astype(np.int8)
df_leak['id'] = df_leak.index.astype(np.int16)
df_leak.drop(columns=['choose_one', 'text'], inp... | Natural Language Processing with Disaster Tweets |
11,449,263 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<define_variables> | %matplotlib inline
| Natural Language Processing with Disaster Tweets |
11,449,263 | input_size = 150<normalization> | train_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 |
11,449,263 | mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
normalize_transform = Normalize(mean, std )<choose_model_class> | train_df['char'] = train_df['text'].str.len()
train_df['words'] = train_df['text'].str.split().map(lambda x: len(x))
train_df.head(3 ) | Natural Language Processing with Disaster Tweets |
11,449,263 | model = get_model("xception", pretrained=False)
model = nn.Sequential(*list(model.children())[:-1])
class Pooling(nn.Module):
def __init__(self):
super(Pooling, self ).__init__()
self.p1 = nn.AdaptiveAvgPool2d(( 1,1))
self.p2 = nn.AdaptiveMaxPool2d(( 1,1))
def forward(self, x):
x1 = self.p1(x)
x2 = self.p2(x)
retur... | print('There are {} tweets in total and {} tweets with keyword'.format(train_df['keyword'].shape[0], train_df['keyword'].notna().sum())) | Natural Language Processing with Disaster Tweets |
11,449,263 | def predict_on_video(video_path, batch_size):
try:
faces = face_extractor.process_video(video_path)
face_extractor.keep_only_best_face(faces)
if len(faces)> 0:
x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8)
n = 0
for frame_data in faces:
for face in frame_data["faces"]:
resized_face = isotrop... | train_df['text'] = train_df['text'].str.replace("http\S+", " ")
test_df['text'] = test_df['text'].str.replace("http\S+", " " ) | Natural Language Processing with Disaster Tweets |
11,449,263 | def predict_on_video_set(videos, num_workers):
def process_file(i):
filename = videos[i]
y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video)
return y_pred
with ThreadPoolExecutor(max_workers=num_workers)as ex:
predictions = ex.map(process_file, range(len(videos)))
return list(pred... | train_df = train_df[['text', 'target']]
tweets = train_df.groupby('text' ).mean().reset_index()
print('There are {} tweets with different label in duplicates.'.format(tweets[(tweets['target']!=1)&(tweets['target']!=0)].shape[0]))
df_diff = tweets[(tweets['target']!=1)&(tweets['target']!=0)].reset_index(drop=True)
twee... | Natural Language Processing with Disaster Tweets |
11,449,263 | %%time
model.eval()
predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv> | for i in range(64):
print(train_df[train_df['text']==df_diff.loc[i]['text']] ) | Natural Language Processing with Disaster Tweets |
11,449,263 | submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions})
submission_df_xception.to_csv("submission_xception.csv", index=False )<create_dataframe> | nlp = spacy.load('en_core_web_lg' ) | Natural Language Processing with Disaster Tweets |
11,449,263 | submission_df = pd.DataFrame({"filename": test_videos} )<feature_engineering> | X_train, X_valid, y_train, y_valid = train_test_split(vectors, tweets.target, test_size=0.2,
random_state=52, stratify = tweets.target)
model = LinearSVC(random_state=1, dual=False)
model.fit(X_train, y_train)
print(f'Model test accuracy: {model.score(X_valid, y_valid)*100:.3f}%' ) | Natural Language Processing with Disaster Tweets |
11,449,263 | submission_df["label"] = 0.70*submission_df_resnext["label"] + 0.30*submission_df_xception["label"]<save_to_csv> | second_model = LogisticRegression(solver='saga')
second_model.fit(X_train, y_train)
print(f'Model test accuracy: {second_model.score(X_valid, y_valid)*100:.3f}%' ) | Natural Language Processing with Disaster Tweets |
11,449,263 | submission_df.to_csv("submission.csv", index=False )<define_variables> | third_model = linear_model.RidgeClassifier()
third_model.fit(X_train, y_train)
print(f'Model test accuracy: {third_model.score(X_valid, y_valid)*100:.3f}%' ) | Natural Language Processing with Disaster Tweets |
11,449,263 | TEST_DIR = "/kaggle/input/deepfake-detection-challenge/test_videos/"
CHECKPOINT = '/kaggle/input/kha-deepfake-dataset/checkpoint_mobilev3_alldata_1903_withfaceforensics_3epochs_.pth'
CHECKPOINT2 = '/kaggle/input/kha-deepfake-dataset/cpt_mbn_sqrimg_2503)2epochs_.pth'
CHECKPOINT3 = '/kaggle/input/kha-deepfake-dataset/che... | lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
params = {
'task' : 'train',
'boosting_type' : 'gbdt',
'objective' : 'binary',
'metric' : {'binary_logloss'},
'num_leaves' : 51,
'learning_rate' : 0.01,
'max_bin': 397,
'feature_fraction' : 0.9,
'bagging_fraction' ... | Natural Language Processing with Disaster Tweets |
11,449,263 | package_path = '.. /input/kha-efficientnet/EfficientNet-PyTorch/'
sys.path.append(package_path)
<install_modules> | print('SVM f1 score {}'.format(f1_score(y_valid, np.round(model.predict(X_valid), 0 ).astype(int))))
print('Logistic Regression f1 score {}'.format(f1_score(y_valid, np.round(second_model.predict(X_valid), 0 ).astype(int))))
print('Ridge Classifier f1 score {}'.format(f1_score(y_valid, np.round(third_model.predict(X_va... | Natural Language Processing with Disaster Tweets |
11,449,263 | %%capture
!pip install /kaggle/input/khafacenet/facenet_pytorch-2.2.7-py3-none-any.whl
!pip install /kaggle/input/imutils/imutils-0.5.3<install_modules> | X_train = pd.DataFrame(vectors)
y_train = tweets['target']
X_test = pd.DataFrame(vectors_pred)
y_preds = []
models = []
oof_train = np.zeros(( len(X_train),))
cv = KFold(n_splits=5, shuffle=True, random_state=100892)
params = {
'task' : 'train',
'boosting_type' : 'gbdt',
'objective' : 'binary',
'metric' : {'binary_l... | Natural Language Processing with Disaster Tweets |
11,449,263 |
<load_from_zip> | print('===CV scores===')
print(scores)
print(score ) | Natural Language Processing with Disaster Tweets |
11,449,263 |
<set_options> | pred = pd.DataFrame(np.round(y_preds, 0)).astype('int8' ).T | Natural Language Processing with Disaster Tweets |
11,449,263 | %matplotlib inline
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
<categorify> | np.round(pred.mean(axis=1),0 ).astype(int ) | Natural Language Processing with Disaster Tweets |
11,449,263 | def conv_bn(inp, oup, stride, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return nn.Sequential(
conv_layer(inp, oup, 3, stride, 1, bias=False),
norm_layer(oup),
nlin_layer(inplace=True)
)
def conv_1x1_bn(inp, oup, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return n... | Natural Language Processing with Disaster Tweets | |
11,449,263 | net = mobilenetv3(mode='small', pretrained=False)
net.classifier[1] = torch.nn.Linear(in_features=1280, out_features=1)
net = net.to(device)
state_dict = torch.load(CHECKPOINT)
net.load_state_dict(state_dict)
net.cuda()
net.eval()<find_best_params> | sample_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv")
sample_submission | Natural Language Processing with Disaster Tweets |
11,449,263 | net2 = mobilenetv3(mode='small', pretrained=False)
net2.classifier[1] = torch.nn.Linear(in_features=1280, out_features=1)
net2 = net2.to(device)
state_dict = torch.load(CHECKPOINT2)
net2.load_state_dict(state_dict)
net2.cuda()
net2.eval()<set_options> | sample_submission["target"] = np.round(pred.mean(axis=1),0 ).astype(int)
sample_submission["target"] = sample_submission["target"].astype('int8' ) | Natural Language Processing with Disaster Tweets |
11,449,263 | <set_options><EOS> | sample_submission.to_csv("submission.csv", index=False ) | Natural Language Processing with Disaster Tweets |
11,373,963 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<define_search_model> | !pip install -q keras-bert keras-rectified-adam
!wget -q https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip
!unzip -o uncased_L-12_H-768_A-12.zip | Natural Language Processing with Disaster Tweets |
11,373,963 | class SeparableConv2d(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False):
super(SeparableConv2d,self ).__init__()
self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dilation,groups=in_channels,bias=bias)
self.pointwise = nn.Conv2d(in_ch... | SEQ_LEN = 128
BATCH_SIZE = 1024
EPOCHS = 15
LR = 1e-4 | Natural Language Processing with Disaster Tweets |
11,373,963 | class MaxPoolPad(nn.Module):
def __init__(self):
super(MaxPoolPad, self ).__init__()
self.pad = nn.ZeroPad2d(( 1, 0, 1, 0))
self.pool = nn.MaxPool2d(3, stride=2, padding=1)
def forward(self, x):
x = self.pad(x)
x = self.pool(x)
x = x[:, :, 1:, 1:].contiguous()
return x
class AvgPoolPad(nn.Module):
def __init__(self,... | pretrained_path = 'uncased_L-12_H-768_A-12'
config_path = os.path.join(pretrained_path, 'bert_config.json')
checkpoint_path = os.path.join(pretrained_path, 'bert_model.ckpt')
vocab_path = os.path.join(pretrained_path, 'vocab.txt')
os.environ['TF_KERAS'] = '1' | Natural Language Processing with Disaster Tweets |
11,373,963 | class CFG:
seq_len=10
lstm_in = 16
lstm_out = 16
class LSTM_Model(nn.Module):
def __init__(self):
super(LSTM_Model, self ).__init__()
self.cnn_net = mobilenetv3(mode='small', pretrained=False)
self.cnn_net.classifier[1] = nn.Linear(in_features=1280, out_features=1)
self.cnn_net.classifier[1] = nn.Linear(in_features=1... | tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
tpu_strategy = tf.distribute.experimental.TPUStrategy(tpu ) | Natural Language Processing with Disaster Tweets |
11,373,963 |
<find_best_params> | token_dict = {}
with codecs.open(vocab_path, 'r', 'utf8')as reader:
for line in reader:
token = line.strip()
token_dict[token] = len(token_dict)
with tpu_strategy.scope() :
model = load_trained_model_from_checkpoint(
config_path,
checkpoint_path,
training=True,
trainable=True,
seq_len=SEQ_LEN,
) | Natural Language Processing with Disaster Tweets |
11,373,963 | net11 = torchvision.models.resnet18(pretrained=False)
net11.fc = nn.Linear(in_features=512, out_features=1, bias=True)
net11.load_state_dict(torch.load(CHECKPOINT11))
net11 = net11.to(device)
net11.cuda()
net11.eval()<import_modules> | train_df = pd.read_csv('.. /input/nlp-getting-started/train.csv', index_col='id')
test_df = pd.read_csv('.. /input/nlp-getting-started/test.csv', index_col='id' ) | Natural Language Processing with Disaster Tweets |
11,373,963 | import albumentations
from albumentations.augmentations.transforms import ShiftScaleRotate, HorizontalFlip, RandomBrightnessContrast, MotionBlur, Blur, GaussNoise, JpegCompression
<define_variables> | def strip_html(text):
soup = BeautifulSoup(text, "html.parser")
return soup.get_text()
def remove_between_square_brackets(text):
return re.sub('\[[^]]*\]', '', text)
def remove_url(text):
return re.sub(r'http\S+', '', text)
def add_space(text):
return re.sub('%20', ' ', text)
def remove_hashtags(text):
return re.su... | Natural Language Processing with Disaster Tweets |
11,373,963 | def predict_on_video(model, model2, model3, model4, model5, model6, model7, model8, model9, model10, model11, video_path):
try:
x, x_sqr, x_299_sqr, x_lstm, frame_skip = extract_frames(video_path)
if x is None or x_sqr is None: return 0.5
else:
with torch.no_grad() :
y_pred = model(x.to(device))
y_pred = torch.sigmoid... | def preprocess_df(df):
df = df.fillna("")
df['text'] = df['keyword'] + " " + df['text']
del df['keyword']
df['location'] = df['location'].astype('category')
df['location'] = df['location'].cat.codes
df['text'] = df['text'].apply(denoise_text)
return df
train_df = preprocess_df(train_df)
test_df = preprocess_df(test... | Natural Language Processing with Disaster Tweets |
11,373,963 | class FastMTCNN(object):
def __init__(self, resize=1, *args, **kwargs):
self.resize = resize
self.mtcnn = MTCNN(*args, **kwargs)
def __call__(self, frames):
if self.resize != 1:
frames = [f.resize([int(d * self.resize)for d in f.size])for f in frames]
boxes, probs = self.mtcnn.detect(frames)
boxes = [b.astype(int ).t... | np.random.seed(1)
msk = np.random.rand(len(train_df)) < 0.8
train_df, dev_df = train_df[msk], train_df[~msk] | Natural Language Processing with Disaster Tweets |
11,373,963 | test_videos = sorted([x for x in os.listdir(TEST_DIR)if x[-4:] == ".mp4"])
len(test_videos )<predict_on_test> | tokenizer = Tokenizer(token_dict)
def tokenize(df):
X, y = [], []
for i, index in enumerate(tqdm(df.index.values)) :
ids, segments = tokenizer.encode(df.text.values[i], max_len=SEQ_LEN)
X.append(ids)
try:
label = df.target.values[i]
y.append(label)
except:
y.append(0)
items = list(zip(X, y))
np.random.shuffle(item... | Natural Language Processing with Disaster Tweets |
11,373,963 | def predict_on_video_set(model, model2, model3, model4, model5, model6, model7, model8, model9, model10, model11, videos, num_workers):
def process_file(i):
filename = videos[i]
y_pred = predict_on_video(model, model2, model3, model4, model5, model6, model7, model8, model9, model10, model11, os.path.join(TEST_DIR, file... | X_test = []
for i, index in enumerate(tqdm(test_df.index.values)) :
ids, segments = tokenizer.encode(test_df.text.values[i], max_len=SEQ_LEN)
X_test.append(ids)
X_test = [np.array(X_test), np.zeros_like(X_test)] | Natural Language Processing with Disaster Tweets |
11,373,963 | predictions = np.clip(predictions, 0.005, 0.995)
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions})
submission_df.to_csv("submission.csv", index=False )<import_modules> | with tpu_strategy.scope() :
inputs = model.inputs[:2]
dense = model.get_layer('NSP-Dense' ).output
outputs = keras.layers.Dense(units=2, activation='softmax' )(dense)
model = keras.models.Model(inputs, outputs)
model.compile(
RAdam(lr=LR),
loss='sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy... | Natural Language Processing with Disaster Tweets |
11,373,963 | import random
import re
from copy import deepcopy
from typing import Union, List, Tuple, Optional, Callable
from collections import OrderedDict, defaultdict
import math
import cv2
import torch
import torch.nn as nn
from torch.utils.data import Dataset,DataLoader
from torch.utils.data.sampler import SequentialSampler, R... | learning_rate_reduction = keras.callbacks.ReduceLROnPlateau(monitor='val_sparse_categorical_accuracy', patience=2, verbose=1,factor=0.5, min_lr=1e-5 ) | Natural Language Processing with Disaster Tweets |
11,373,963 | TARGET_H, TARGET_W = 224, 224
FRAMES_PER_VIDEO = 30
TEST_VIDEOS_PATH = '.. /input/deepfake-detection-challenge/test_videos'
NN_MODEL_PATHS = [
'.. /input/kdold-deepfake-effb2/fold0-effb2-000epoch.pt',
'.. /input/kdold-deepfake-effb2/fold0-effb2-001epoch.pt',
'.. /input/kdold-deepfake-effb2/fold0-effb2-002epoch.pt',
'..... | hist = model.fit(X_train, y_train, validation_data=(X_dev, y_dev), epochs=EPOCHS, batch_size=BATCH_SIZE, callbacks=[learning_rate_reduction] ) | Natural Language Processing with Disaster Tweets |
11,373,963 | SEED = 42
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 = False
torch.backends.cudnn.benchmark = True
seed_everything(SEED )<choose_model_class> | print("Accuracy of the model on Training Data is - {} %".format(model.evaluate(X_train,y_train)[1]*100))
print("Accuracy of the model on Dev Data is - {} %".format(model.evaluate(X_dev,y_dev)[1]*100)) | Natural Language Processing with Disaster Tweets |
11,373,963 | !pip install.. /input/pytorchefficientnet/EfficientNet-PyTorch-master > /dev/null
def get_net() :
net = EfficientNet.from_name('efficientnet-b2')
net._fc = nn.Linear(in_features=net._fc.in_features, out_features=2, bias=True)
return net<feature_engineering> | classes = model.predict(X_test)[:, 0] | Natural Language Processing with Disaster Tweets |
11,373,963 | class DatasetRetriever(Dataset):
def __init__(self, df):
self.video_paths = df['video_path']
self.filenames = df.index
self.face_dr = FaceDetector(frames_per_video=FRAMES_PER_VIDEO)
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
self.normalize_transform = Normalize(mean, std)
self.video_reader = VideoReader... | submission = pd.DataFrame(
{'id': list(test_df.index.values),
'target': list(( classes < 0.5 ).astype(int)) ,
} ).set_index('id' ) | Natural Language Processing with Disaster Tweets |
11,373,963 | class DeepFakePredictor:
def __init__(self):
self.models = [self.prepare_model(get_net() , path)for path in NN_MODEL_PATHS]
self.models_count = len(self.models)
def predict(self, dataset):
result = []
with torch.no_grad() :
for filename, video in dataset:
video = video.to(self.device, dtype=torch.float32)
try:
label ... | submission.to_csv('submission.csv' ) | Natural Language Processing with Disaster Tweets |
12,182,973 | deep_fake_predictor = DeepFakePredictor()<predict_on_test> | !pip install -q tf-models-official==2.3.0
| Natural Language Processing with Disaster Tweets |
12,182,973 | def process_dfs(df, num_workers=2):
def process_df(sub_df):
dataset = DatasetRetriever(sub_df)
result = deep_fake_predictor.predict(dataset)
return result
with ThreadPoolExecutor(max_workers=num_workers)as ex:
results = ex.map(process_df, np.split(df, num_workers))
return results<save_to_csv> | 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 |
12,182,973 | result.to_csv('submission.csv' )<install_modules> | train['words'] = train['text'].str.split()
train['word_len'] = train['words'].map(lambda x: len(x))
train['word_len'].max() | Natural Language Processing with Disaster Tweets |
12,182,973 | !pip install.. /input/pytorchcv/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet<import_modules> | test['words'] = test['text'].str.split()
test['word_len'] = test['words'].map(lambda x: len(x))
test['word_len'].max() | Natural Language Processing with Disaster Tweets |
12,182,973 | device = 'cuda' if torch.cuda.is_available() else 'cpu'<normalization> | ids_with_target_error = [328,443,513,2619,3640,3900,4342,5781,6552,6554,6570,6701,6702,6729,6861,7226]
train.loc[train['id'].isin(ids_with_target_error),'target'] = 0
train[train['id'].isin(ids_with_target_error)] | Natural Language Processing with Disaster Tweets |
12,182,973 | def gem(x, p=3, eps=1e-6):
return F.avg_pool2d(x.clamp(min=eps ).pow(p),(x.size(-2), x.size(-1)) ).pow(1./p)
class GeM(nn.Module):
def __init__(self, p=3, eps=1e-6):
super(GeM,self ).__init__()
self.p = Parameter(torch.ones(1)*p)
self.eps = eps
def forward(self, x):
return gem(x, p=self.p, eps=self.eps)
def __repr__... | df_all = pd.concat([train,test])
df_all.shape | Natural Language Processing with Disaster Tweets |
12,182,973 |
<normalization> | df_all['text'] = df_all['text'].str.lower()
df_all['text'].head(2 ) | Natural Language Processing with Disaster Tweets |
12,182,973 | mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
normalize_transform = Normalize(mean, std )<set_options> | def remove_breaklines(text):
return re.sub('
','',text)
df_all['text'] = df_all['text'].apply(lambda x: remove_breaklines(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | detection_graph = tf.Graph()
with detection_graph.as_default() :
od_graph_def = tf.compat.v1.GraphDef()
with tf.io.gfile.GFile('.. /input/mobilenet-face/frozen_inference_graph_face.pb', 'rb')as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
... | def remove_numbers(text):
return re.sub('\w*\d\w*', '', text)
df_all['text'] = df_all['text'].apply(lambda x: remove_numbers(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | probs = np.asarray(probs)
probs[probs!=probs] = 0.5
plt.hist(probs, 40)
filenames = [os.path.basename(f)for f in filenames]
submission = pd.DataFrame({'filename': filenames, 'label': probs})
submission.to_csv('submission.csv', index=False)
submission<import_modules> | def remove_URL(text):
url = re.compile(r'https?://\S+|www\.\S+')
return url.sub(r'',text)
df_all['text'] = df_all['text'].apply(lambda x: remove_URL(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | from fastai.vision import *<load_from_disk> | def remove_html(text):
html=re.compile(r'<.*?>')
return html.sub(r'',text)
df_all['text']=df_all['text'].apply(lambda x : remove_html(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | train_sample_metadata = pd.read_json('.. /input/deepfake-detection-challenge/train_sample_videos/metadata.json' ).T.reset_index()
train_sample_metadata.columns = ['fname','label','split','original']
train_sample_metadata.head()<filter> | def remove_emoji(text):
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F"
u"\U0001F300-\U0001F5FF"
u"\U0001F680-\U0001F6FF"
u"\U0001F1E0-\U0001F1FF"
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE)
return emoji_pattern.sub(r'', text)
df_all['text']=df_all['text'].apply(lambda x: remove_... | Natural Language Processing with Disaster Tweets |
12,182,973 | fake_sample_df = train_sample_metadata[train_sample_metadata.label == 'FAKE']
real_sample_df = train_sample_metadata[train_sample_metadata.label == 'REAL']<define_variables> | def remove_punct(text):
table=str.maketrans('','',string.punctuation)
return text.translate(table)
df_all['text']=df_all['text'].apply(lambda x : remove_punct(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | train_dir = Path('/kaggle/input/deepfake-detection-challenge/train_sample_videos/')
test_dir = Path('/kaggle/input/deepfake-detection-challenge/test_videos/')
train_video_files = get_files(train_dir, extensions=['.mp4'])
test_video_files = get_files(test_dir, extensions=['.mp4'] )<define_variables> | abbreviations = {
"$" : " dollar ",
"€" : " euro ",
"4ao" : "for adults only",
"a.m" : "before midday",
"a3" : "anytime anywhere anyplace",
"aamof" : "as a matter of fact",
"acct" : "account",
"adih" : "another day in hell",
"afaic" : "as far as i am concerned",
"afaict" : "as far as i can tell",
"afaik" : "as far as i... | Natural Language Processing with Disaster Tweets |
12,182,973 | dummy_video_file = train_video_files[0]<set_options> | def convert_abbrev_in_text(text):
tokens = word_tokenize(text)
tokens = [convert_abbrev(word)for word in tokens]
text = ' '.join(tokens)
return text
df_all['text']=df_all['text'].apply(lambda x : convert_abbrev_in_text(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | sys.path.insert(0,'/kaggle/working/reader/python')
set_bridge('torch')
device = torch.device("cuda" )<categorify> | df_all['text']=df_all['text'].apply(lambda x : word_tokenize(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | retinaface_stats = tensor([123,117,104] ).to(device)
def decord_cpu_video_reader(path, freq=None):
video = VideoReader(str(path), ctx=cpu())
len_video = len(video)
if freq: t = video.get_batch(range(0, len(video), freq)).permute(0,3,1,2)
else: t = video.get_batch(range(len_video))
return t, len_video
def get_decord... | stop = set(stopwords.words('english'))
def remove_stopwords(text):
words = [w for w in text if w not in stop]
return ' '.join(words)
df_all['text']=df_all['text'].apply(lambda x : remove_stopwords(x)) | Natural Language Processing with Disaster Tweets |
12,182,973 | sys.path.insert(0,"/kaggle/input/retina-face-2/Pytorch_Retinaface_2/" )<import_modules> | cl_ch_len = df_all['text'].apply(lambda x: len(x))
cl_wd_len = df_all['text'].str.split().map(lambda x: len(x))
print('Max words length for cleaned tweets: {}'.format(max(cl_wd_len)))
print('Max characters length for cleaned tweets: {}'.format(max(cl_ch_len)))
MAX_LEN = max(cl_wd_len ) | Natural Language Processing with Disaster Tweets |
12,182,973 | import os
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from data import cfg_mnet, cfg_re50
from layers.functions.prior_box import PriorBox
from utils.nms.py_cpu_nms import py_cpu_nms
import cv2
from models.retinaface import RetinaFace
from utils.box_utils import decode, decode_landm
import time<... | def create_corpus(df):
corpus=[]
for tweet in tqdm(df_all['text']):
words=[word.lower() for word in word_tokenize(tweet)if(( word.isalpha() ==1)&(word not in stop)) ]
corpus.append(words)
return corpus
corpus = create_corpus(df_all)
corpus[0] | Natural Language Processing with Disaster Tweets |
12,182,973 | def check_keys(model, pretrained_state_dict):
ckpt_keys = set(pretrained_state_dict.keys())
model_keys = set(model.state_dict().keys())
used_pretrained_keys = model_keys & ckpt_keys
unused_pretrained_keys = ckpt_keys - model_keys
missing_keys = model_keys - ckpt_keys
print('Missing keys:{}'.format(len(missing_keys)))... | glove_embedding_dict={}
with open('.. /input/glove-global-vectors-for-word-representation/glove.6B.200d.txt','r')as f:
for line in tqdm(f):
values=line.split()
word=values[0]
vectors=np.asarray(values[1:],'float32')
glove_embedding_dict[word]=vectors | Natural Language Processing with Disaster Tweets |
12,182,973 | cudnn.benchmark = True<define_variables> | W_E_DIM = 200 | Natural Language Processing with Disaster Tweets |
12,182,973 | def get_model(modelname="mobilenet"):
torch.set_grad_enabled(False)
cfg = None
cfg_mnet['pretrain'] = False
cfg_re50['pretrain'] = False
if modelname == "mobilenet":
pretrained_path = ".. /input/retina-face-2/Pytorch_Retinaface_2/weights/mobilenet0.25_Final.pth"
cfg = cfg_mnet
if modelname == "resnet50":
pretrained_pa... | 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 |
12,182,973 | def predict(model, t, sz, cfg,
confidence_threshold = 0.5, top_k = 5, nms_threshold = 0.5, keep_top_k = 5):
"get prediction for a batch t by model with image sz"
resize = 1
scale_rate = 1
im_height, im_width = sz, sz
scale = torch.Tensor([sz, sz, sz, sz])
scale = scale.to(device)
locs, confs, landmss = torch.Tensor([... | word_index=tokenizer_obj.word_index
print('Number of unique words:',len(word_index)) | Natural Language Processing with Disaster Tweets |
12,182,973 | %%time
model, cfg = get_model("mobilenet" )<categorify> | num_words=len(word_index)+1
embedding_matrix=np.zeros(( num_words,W_E_DIM))
for word,i in tqdm(word_index.items()):
if i < num_words:
emb_vec=glove_embedding_dict.get(word)
if emb_vec is not None:
embedding_matrix[i]=emb_vec | Natural Language Processing with Disaster Tweets |
12,182,973 | def bboxes_to_original_scale(bboxes, H, W, sz):
res = []
for bb in bboxes:
h_scale, w_scale = H/sz, W/sz
orig_bboxes =(bb*array([w_scale, h_scale, w_scale, h_scale])[None,...] ).astype(int)
res.append(orig_bboxes)
return res<categorify> | train_text = tweet_pad[:train.shape[0]]
test_text = tweet_pad[train.shape[0]:]
X_train,X_dev,Y_train,Y_dev=train_test_split(train_text,train['target'].values,test_size=0.2)
print('Shape of train',X_train.shape)
print("Shape of Validation ",X_dev.shape ) | Natural Language Processing with Disaster Tweets |
12,182,973 | def landmarks_to_original_scale(landmarks, H, W, sz):
res = []
for landms in landmarks:
h_scale, w_scale = H/sz, W/sz
orig_landms =(landms*array([w_scale, h_scale]*5)[None,...] ).astype(int)
res.append(orig_landms)
return res<import_modules> | model=Sequential()
embedding=Embedding(num_words,W_E_DIM,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(learn... | Natural Language Processing with Disaster Tweets |
12,182,973 | from tqdm import tqdm<init_hyperparams> | history=model.fit(X_train,Y_train,batch_size=4,
epochs=10,validation_data=(X_dev,Y_dev),verbose=2)
| Natural Language Processing with Disaster Tweets |
12,182,973 | freq = 5
model_args = dict(confidence_threshold = 0.5, top_k = 5, nms_threshold = 0.5, keep_top_k = 5)
sz = cfg['image_size']
imgnet_stats = [tensor(o)for o in imagenet_stats]
rescale_param = 1.3<install_modules> | pred = model.predict(test_text)
pred = pred.round().astype('int' ) | Natural Language Processing with Disaster Tweets |
12,182,973 | !pip install -q.. /input/efficientnetpytorchpip/efficientnet_pytorch-0.6.3/<import_modules> | df_sub = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv')
df_sub['target'] = pred
df_sub = df_sub[['id', 'target']]
df_sub.to_csv('lstm_submission.csv', index=False, header=True)
df_sub.head(10 ) | Natural Language Processing with Disaster Tweets |
12,182,973 | from fastai.vision.models.efficientnet import *<categorify> | %%time
bert_url = 'https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/2'
bert_layer = hub.KerasLayer(bert_url, trainable=True, name='Bert_layer' ) | Natural Language Processing with Disaster Tweets |
12,182,973 | class DummyDatabunch:
c = 2
path = '.'
device = defaults.device
loss_func = None
data = DummyDatabunch()<load_pretrained> | def bert_encode(texts, tokenizer, max_len=512):
input_tokens = []
input_masks = []
input_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_sequenc... | Natural Language Processing with Disaster Tweets |
12,182,973 | effnet_model = EfficientNet.from_name("efficientnet-b5", override_params={'num_classes': 2})
learner = Learner(data, effnet_model); learner.model_dir = '.'
learner.load('.. /input/deepfakerandmergeaugmodels/single_frame_effnetb5_randmerge')
effnetb5_inference_model = learner.model.eval()<load_pretrained> | 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")
pooled_output, sequence_output = bert_layer([inpu... | Natural Language Processing with Disaster Tweets |
12,182,973 | effnet_model = EfficientNet.from_name("efficientnet-b7", override_params={'num_classes': 2})
learner = Learner(data, effnet_model); learner.model_dir = '.'
learner.load('.. /input/deepfakerandmergeaugmodels/single_frame_effnetb7_randmerge_fp16')
effnetb7_inference_model = learner.model.float().eval()<load_pretrained> | 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 |
12,182,973 | learner = cnn_learner(data, models.resnet34, pretrained=False); learner.model_dir = '.'
learner.load('.. /input/deepfakerandmergeaugmodels/single_frame_resnet34_randmerge')
resnet_inference_model = learner.model.eval()<define_variables> | train_text = df_all[:train.shape[0]].text
test_text = df_all[train.shape[0]:].text
train_input = bert_encode(train_text, tokenizer, max_len=160)
test_input = bert_encode(test_text, tokenizer, max_len = 160)
train_labels = train.target.values | Natural Language Processing with Disaster Tweets |
12,182,973 | predictions = []
video_fnames = []<define_variables> | checkpoint = ModelCheckpoint('model.h5', monitor='val_loss', save_best_only=True)
train_history = model.fit(
train_input, train_labels,
validation_split=0.2,
epochs=5,
callbacks=[checkpoint],
batch_size=16
) | Natural Language Processing with Disaster Tweets |
12,182,973 | fname2pred = dict(zip(video_fnames, predictions))<load_from_csv> | model.load_weights('model.h5')
test_pred = model.predict(test_input ) | Natural Language Processing with Disaster Tweets |
12,182,973 | submission_df = pd.read_csv("/kaggle/input/deepfake-detection-challenge/sample_submission.csv" )<categorify> | submission['target'] = test_pred.round().astype(int)
submission.to_csv('bert_submission.csv', index=False ) | Natural Language Processing with Disaster Tweets |
12,165,368 | submission_df.label = submission_df.filename.map(fname2pred )<feature_engineering> | test_set = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv")
train_set = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv" ) | Natural Language Processing with Disaster Tweets |
12,165,368 | submission_df['label'] = np.clip(submission_df['label'], 0.01, 0.99 )<save_to_csv> | import seaborn as sns
from matplotlib import pyplot as plt | Natural Language Processing with Disaster Tweets |
12,165,368 | submission_df.to_csv("submission.csv",index=False )<install_modules> | print("train set")
print(train_set.count())
print("test set")
print(test_set.count() ) | Natural Language Processing with Disaster Tweets |
12,165,368 | !pip install fastai==0.7.0 --no-deps
!pip install torch==0.4.1 torchvision==0.2.1
!pip install torchtext==0.2.3<define_variables> | !pip install emoji | Natural Language Processing with Disaster Tweets |
12,165,368 | MODEL_NAME = 'Densenet201'
TRAIN = '.. /input/train/'
TEST = '.. /input/test/'
LABELS = '.. /input/train.csv'
SAMPLE_SUB = '.. /input/sample_submission.csv'
arch = resnet50
num_workers = 8<feature_engineering> | def strip_emoji(text: str)-> str:
return re.sub(emoji.get_emoji_regexp() , r"", text ) | Natural Language Processing with Disaster Tweets |
12,165,368 | df = pd.read_csv(LABELS ).set_index('Image')
new_whale_df = df[df.Id == "new_whale"]
train_df = df[~(df.Id == "new_whale")]
unique_labels = np.unique(train_df.Id.values)
labels_dict = dict()
labels_list = []
for i in range(len(unique_labels)) :
labels_dict[unique_labels[i]] = i
labels_list.append(unique_labels[i])
p... | train_set["text"] = train_set.text.str.strip().str.replace("
", "")
train_set["text"] = train_set.text.str.strip().str.replace("\r", "")
train_set["text"] = train_set.text.apply(strip_emoji)
train_set["text"] = train_set.text.str.strip().str.replace("
train_set["text"] = train_set.text.str.lower() | Natural Language Processing with Disaster Tweets |
12,165,368 | train_df['image_name'] = train_df.index
rs = np.random.RandomState(42)
perm = rs.permutation(len(train_df))
tr_n = train_df['image_name'].values
val_n = train_df['image_name'].values[perm][:1000]
print('Train/val:', len(tr_n), len(val_n))
print('Train classes', len(train_df.loc[tr_n].Id.unique()))
print('Val classes',... | test_set["text"] = test_set.text.str.strip().str.replace("
", "")
test_set["text"] = test_set.text.str.strip().str.replace("\r", "")
test_set["text"] = test_set.text.apply(strip_emoji)
test_set["text"] = test_set.text.str.strip().str.replace("
test_set["text"] = test_set.text.str.lower() | Natural Language Processing with Disaster Tweets |
12,165,368 | class HWIDataset(FilesDataset):
def __init__(self, fnames, path, transform):
self.train_df = train_df
super().__init__(fnames, transform, path)
def get_x(self, i):
img = open_image(os.path.join(self.path, self.fnames[i]))
img = cv2.resize(img,(self.sz, self.sz))
return img
def get_y(self, i):
if(self.path == TEST): re... | !pip install torch>=1.6.0 transformers==3.3.1 | Natural Language Processing with Disaster Tweets |
12,165,368 | class RandomLighting(Transform):
def __init__(self, b, c, tfm_y=TfmType.NO):
super().__init__(tfm_y)
self.b, self.c = b, c
def set_state(self):
self.store.b_rand = rand0(self.b)
self.store.c_rand = rand0(self.c)
def do_transform(self, x, is_y):
if is_y and self.tfm_y != TfmType.PIXEL: return x
b = self.store.b_rand
... | import random
from typing import Sequence
from transformers import BertForMaskedLM, BertTokenizer
import torch | Natural Language Processing with Disaster Tweets |
12,165,368 | image_size = 224
batch_size = 48
md = get_data(image_size, batch_size)
extra_fc_layers_size = []
learn = ConvLearner.pretrained(arch, md, xtra_fc=extra_fc_layers_size)
learn.opt_fn = optim.Adam<init_hyperparams> | tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
text = train_set.text[0]
tokenized_text = tokenizer.tokenize(text)
print(tokenized_text ) | Natural Language Processing with Disaster Tweets |
12,165,368 | print('Number of layer groups:', len(learn.get_layer_groups()), '\t(first 2 groups is pretrained backbone)')
print('This is our extra thin on top of the backbone Resnet50 architecture:')
learn.get_layer_groups() [2]<train_model> | index = 4
tokenized_text.insert(index, "[MASK]")
print("Text Tokens")
print(tokenized_text)
tokenized_text_ids = torch.LongTensor(tokenizer.encode(tokenized_text, max_length=512, truncation=True))
print("Text Tokens ids")
print(tokenized_text_ids ) | Natural Language Processing with Disaster Tweets |
12,165,368 | base_lr = 5e-4
fc_lr = 5e-3
lrs = [base_lr, base_lr, fc_lr]
learn.fit(lrs=lrs, n_cycle=2, cycle_len=None)
learn.unfreeze()
learn.fit(lrs, n_cycle=3, cycle_len=1, cycle_mult=2)
learn.save('weights' )<define_variables> | model = BertForMaskedLM.from_pretrained("bert-base-uncased")
model.eval()
with torch.no_grad() :
predictions = model(tokenized_text_ids.unsqueeze(0)) [0]
predicted_word = tokenizer.convert_ids_to_tokens([torch.argmax(predictions[0, index+1] ).item() ])[0]
print(predicted_word ) | Natural Language Processing with Disaster Tweets |
12,165,368 | image_size = 448
batch_size = 24
md = get_data(image_size, batch_size)
learn.set_data(md )<train_model> | tokenized_text[index] = predicted_word
augmented_text = " ".join(tokenized_text)
print(augmented_text ) | Natural Language Processing with Disaster Tweets |
12,165,368 | base_lr = 1e-5
fc_lr = 1e-3
lrs = [base_lr, base_lr, fc_lr]
learn.fit(lrs, n_cycle=6, cycle_len=1)
learn.save('weights_v2' )<prepare_output> | class WordAugmentation:
_mask_token: str = "[MASK]"
def __init__(self,
model_path: str="bert-base-uncased",
device: str="cuda"):
self._tokenizer = BertTokenizer.from_pretrained(model_path)
self._device = device
self._model = BertForMaskedLM.from_pretrained(model_path ).to(self._device)
def _predict(self,
inputs_i... | 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.