Download Data¶
In [ ]:
!git clone https://github.com/Franck-Dernoncourt/pubmed-rct
Cloning into 'pubmed-rct'... remote: Enumerating objects: 33, done. remote: Counting objects: 100% (8/8), done. remote: Compressing objects: 100% (3/3), done. remote: Total 33 (delta 5), reused 5 (delta 5), pack-reused 25 Unpacking objects: 100% (33/33), 177.08 MiB | 9.80 MiB/s, done. Updating files: 100% (13/13), done.
Preprocessing¶
In [ ]:
data_dir = "/content/pubmed-rct/PubMed_20k_RCT_numbers_replaced_with_at_sign/"
In [ ]:
import os
filenames = [data_dir + filename for filename in os.listdir(data_dir)]
In [ ]:
def get_lines(filename):
with open(filename, "r") as f:
return f.readlines()
In [ ]:
train_lines = get_lines(data_dir+"train.txt")
train_lines[:20]
Out[ ]:
['###24293578\n', 'OBJECTIVE\tTo investigate the efficacy of @ weeks of daily low-dose oral prednisolone in improving pain , mobility , and systemic low-grade inflammation in the short term and whether the effect would be sustained at @ weeks in older adults with moderate to severe knee osteoarthritis ( OA ) .\n', 'METHODS\tA total of @ patients with primary knee OA were randomized @:@ ; @ received @ mg/day of prednisolone and @ received placebo for @ weeks .\n', 'METHODS\tOutcome measures included pain reduction and improvement in function scores and systemic inflammation markers .\n', 'METHODS\tPain was assessed using the visual analog pain scale ( @-@ mm ) .\n', 'METHODS\tSecondary outcome measures included the Western Ontario and McMaster Universities Osteoarthritis Index scores , patient global assessment ( PGA ) of the severity of knee OA , and @-min walk distance ( @MWD ) .\n', 'METHODS\tSerum levels of interleukin @ ( IL-@ ) , IL-@ , tumor necrosis factor ( TNF ) - , and high-sensitivity C-reactive protein ( hsCRP ) were measured .\n', 'RESULTS\tThere was a clinically relevant reduction in the intervention group compared to the placebo group for knee pain , physical function , PGA , and @MWD at @ weeks .\n', 'RESULTS\tThe mean difference between treatment arms ( @ % CI ) was @ ( @-@ @ ) , p < @ ; @ ( @-@ @ ) , p < @ ; @ ( @-@ @ ) , p < @ ; and @ ( @-@ @ ) , p < @ , respectively .\n', 'RESULTS\tFurther , there was a clinically relevant reduction in the serum levels of IL-@ , IL-@ , TNF - , and hsCRP at @ weeks in the intervention group when compared to the placebo group .\n', 'RESULTS\tThese differences remained significant at @ weeks .\n', 'RESULTS\tThe Outcome Measures in Rheumatology Clinical Trials-Osteoarthritis Research Society International responder rate was @ % in the intervention group and @ % in the placebo group ( p < @ ) .\n', 'CONCLUSIONS\tLow-dose oral prednisolone had both a short-term and a longer sustained effect resulting in less knee pain , better physical function , and attenuation of systemic inflammation in older patients with knee OA ( ClinicalTrials.gov identifier NCT@ ) .\n', '\n', '###24854809\n', 'BACKGROUND\tEmotional eating is associated with overeating and the development of obesity .\n', 'BACKGROUND\tYet , empirical evidence for individual ( trait ) differences in emotional eating and cognitive mechanisms that contribute to eating during sad mood remain equivocal .\n', 'OBJECTIVE\tThe aim of this study was to test if attention bias for food moderates the effect of self-reported emotional eating during sad mood ( vs neutral mood ) on actual food intake .\n', 'OBJECTIVE\tIt was expected that emotional eating is predictive of elevated attention for food and higher food intake after an experimentally induced sad mood and that attentional maintenance on food predicts food intake during a sad versus a neutral mood .\n', 'METHODS\tParticipants ( N = @ ) were randomly assigned to one of the two experimental mood induction conditions ( sad/neutral ) .\n']
In [ ]:
def preprocess_text_with_line_numbers(filename):
"""Returns a list of dictionaries of abstract line data.
Takes in filename, reads its contents and sorts through each line,
extracting things like the target label, the text of the sentence,
how many sentences are in the current abstract and what sentence number
the target line is.
Args:
filename: a string of the target text file to read and extract line data
from.
Returns:
A list of dictionaries each containing a line from an abstract,
the lines label, the lines position in the abstract and the total number
of lines in the abstract where the line is from. For example:
[{"target": 'CONCLUSION',
"text": The study couldn't have gone better, turns out people are kinder than you think",
"line_number": 8,
"total_lines": 8}]
"""
input_lines = get_lines(filename)
abstract_lines = ""
abstract_samples = []
for line in input_lines:
if line.startswith("###"):
abstract_id = line
abstract_lines = ""
elif line.isspace():
abstract_line_split = abstract_lines.splitlines()
for abstract_line_number, abstract_line in enumerate(abstract_line_split):
line_data = {}
target_text_split = abstract_line.split("\t")
line_data["target"] = target_text_split[0]
line_data["text"] = target_text_split[1].lower()
line_data["line_number"] = abstract_line_number
line_data["total_lines"] = len(abstract_line_split) - 1
abstract_samples.append(line_data)
else:
abstract_lines += line
return abstract_samples
In [ ]:
train_samples = preprocess_text_with_line_numbers(data_dir + "train.txt")
val_samples = preprocess_text_with_line_numbers(data_dir + "dev.txt")
test_samples = preprocess_text_with_line_numbers(data_dir + "test.txt")
In [ ]:
import pandas as pd
train_df = pd.DataFrame(train_samples)
val_df = pd.DataFrame(val_samples)
test_df = pd.DataFrame(test_samples)
In [ ]:
train_sentences = train_df["text"].tolist()
val_sentences = val_df["text"].tolist()
test_sentences = test_df["text"].tolist()
In [ ]:
from sklearn.preprocessing import OneHotEncoder
one_hot_encoder = OneHotEncoder(sparse=False)
train_labels_one_hot = one_hot_encoder.fit_transform(train_df["target"].to_numpy().reshape(-1,1))
val_labels_one_hot = one_hot_encoder.transform(val_df["target"].to_numpy().reshape(-1,1))
test_labels_one_hot = one_hot_encoder.transform(test_df["target"].to_numpy().reshape(-1,1))
In [ ]:
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
train_labels_encoded = label_encoder.fit_transform(train_df["target"].to_numpy())
val_labels_encoded = label_encoder.fit_transform(val_df["target"].to_numpy())
test_labels_encoded = label_encoder.fit_transform(test_df["target"].to_numpy())
In [ ]:
num_classes = len(label_encoder.classes_)
class_anmes = label_encoder.classes_
Model 0¶
In [ ]:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
model_0 = Pipeline([
("tf-idf", TfidfVectorizer()),
("clf", MultinomialNB())
])
model_0.fit(X=train_sentences,
y=train_labels_encoded)
Out[ ]:
Pipeline(steps=[('tf-idf', TfidfVectorizer()), ('clf', MultinomialNB())])In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Pipeline(steps=[('tf-idf', TfidfVectorizer()), ('clf', MultinomialNB())])TfidfVectorizer()
MultinomialNB()
In [ ]:
model_0.score(X=val_sentences,
y=val_labels_encoded)
Out[ ]:
0.7218323844829869
In [ ]:
baseline_preds = model_0.predict(val_sentences)
In [ ]:
!wget https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/extras/helper_functions.py
from helper_functions import calculate_results
--2023-03-12 13:27:06-- https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/extras/helper_functions.py Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.108.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 10246 (10K) [text/plain] Saving to: ‘helper_functions.py’ helper_functions.py 0%[ ] 0 --.-KB/s helper_functions.py 100%[===================>] 10.01K --.-KB/s in 0s 2023-03-12 13:27:06 (88.5 MB/s) - ‘helper_functions.py’ saved [10246/10246]
In [ ]:
baseline_results = calculate_results(y_true=val_labels_encoded,
y_pred=baseline_preds)
baseline_results
Out[ ]:
{'accuracy': 72.1832384482987,
'precision': 0.7186466952323352,
'recall': 0.7218323844829869,
'f1': 0.6989250353450294} Preparing the data for deep sequence models¶
- Vectorize
- embedding layers
In [ ]:
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
In [ ]:
# How long is each sentence on average
sent_lens = [len(sentence.split()) for sentence in train_sentences]
avg_sent_len = np.mean(sent_lens)
In [ ]:
# Whats the distribution?
import matplotlib.pyplot as plt
plt.hist(sent_lens, bins=20)
Out[ ]:
(array([4.2075e+04, 8.3771e+04, 3.6877e+04, 1.0945e+04, 3.9310e+03,
1.4450e+03, 5.6000e+02, 2.2600e+02, 1.0100e+02, 4.5000e+01,
2.0000e+01, 1.2000e+01, 9.0000e+00, 1.0000e+01, 6.0000e+00,
2.0000e+00, 3.0000e+00, 0.0000e+00, 1.0000e+00, 1.0000e+00]),
array([ 1. , 15.75, 30.5 , 45.25, 60. , 74.75, 89.5 , 104.25,
119. , 133.75, 148.5 , 163.25, 178. , 192.75, 207.5 , 222.25,
237. , 251.75, 266.5 , 281.25, 296. ]),
<BarContainer object of 20 artists>) In [ ]:
output_seq_len = int(np.percentile(sent_lens, 95))
In [ ]:
max_tokens = 68000
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
text_vectorizer = TextVectorization(max_tokens=max_tokens,
output_sequence_length=output_seq_len)
In [ ]:
text_vectorizer.adapt(train_sentences)
In [ ]:
import random
target_sentence = random.choice(train_sentences)
print(f"Text: \n {target_sentence}")
print(f"\n length of text: {len(target_sentence.split())}")
print(f"\nVectorized text: {text_vectorizer([target_sentence])}")
Text:
to compare effectiveness , satisfaction level , and safety of rimabotulinumtoxinb with onabotulinumtoxina at a conversion ratio of @:@ for the treatment of pah .
length of text: 25
Vectorized text: [[ 6 226 257 428 204 3 136 4 19701 7 5120 15
8 2514 166 4 11 2 19 4 6066 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0]]
In [ ]:
rct_20k_text_vocab = text_vectorizer.get_vocabulary()
print(f"Number of words in vocab: {len(rct_20k_text_vocab)}")
print(f"Most common words in the vocab: {rct_20k_text_vocab[:5]}")
print(f"Least common words in the vocab: {rct_20k_text_vocab[-5:]}")
Number of words in vocab: 64841 Most common words in the vocab: ['', '[UNK]', 'the', 'and', 'of'] Least common words in the vocab: ['aainduced', 'aaigroup', 'aachener', 'aachen', 'aaacp']
In [ ]:
text_vectorizer.get_config()
Out[ ]:
{'name': 'text_vectorization',
'trainable': True,
'dtype': 'string',
'batch_input_shape': (None,),
'max_tokens': 68000,
'standardize': 'lower_and_strip_punctuation',
'split': 'whitespace',
'ngrams': None,
'output_mode': 'int',
'output_sequence_length': 55,
'pad_to_max_tokens': False,
'sparse': False,
'ragged': False,
'vocabulary': None,
'idf_weights': None,
'encoding': 'utf-8'} Create Custom text embedding¶
In [ ]:
token_embed = layers.Embedding(input_dim=len(rct_20k_text_vocab),
output_dim=128,
mask_zero=True,
name="token_embedding")
In [ ]:
print(f"Sentence before vectorization: \n {target_sentence}")
vectorized_sentence = text_vectorizer([target_sentence])
print(f"Sentence after vectorization (before embedding): \n {vectorized_sentence}\n")
embedded_sentence = token_embed(vectorized_sentence)
print(f"Sentence after embedding: \n {embedded_sentence}\n")
print(f"Embedded sentence shape: {embedded_sentence.shape}")
Sentence before vectorization:
to compare effectiveness , satisfaction level , and safety of rimabotulinumtoxinb with onabotulinumtoxina at a conversion ratio of @:@ for the treatment of pah .
Sentence after vectorization (before embedding):
[[ 6 226 257 428 204 3 136 4 19701 7 5120 15
8 2514 166 4 11 2 19 4 6066 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0]]
Sentence after embedding:
[[[-0.04615562 0.00117009 0.02937986 ... 0.03927759 0.01864533
0.04511062]
[ 0.00486338 0.03399055 -0.03318892 ... 0.04185674 0.03627844
0.04440106]
[-0.04915943 0.02695758 -0.02553362 ... 0.01127566 -0.02087184
-0.0264936 ]
...
[-0.02976215 -0.03697643 0.03576532 ... 0.03214028 0.03322096
0.01136223]
[-0.02976215 -0.03697643 0.03576532 ... 0.03214028 0.03322096
0.01136223]
[-0.02976215 -0.03697643 0.03576532 ... 0.03214028 0.03322096
0.01136223]]]
Embedded sentence shape: (1, 55, 128)
Creating datasets¶
(making sure the data loads fast)
In [ ]:
# Turn our data into Tensorflow Datasets
train_dataset = tf.data.Dataset.from_tensor_slices((train_sentences, train_labels_one_hot))
valid_dataset = tf.data.Dataset.from_tensor_slices((val_sentences, val_labels_one_hot))
test_dataset= tf.data.Dataset.from_tensor_slices((test_sentences, test_labels_one_hot))
In [ ]:
# prefetching
train_dataset = train_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
valid_dataset = valid_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
test_dataset = test_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
Model 1 Conv1D with token embeddings¶
In [ ]:
inputs = layers.Input(shape=(1,), dtype = tf.string)
text_vectors = text_vectorizer(inputs)
embeddings = token_embed(text_vectors)
x = layers.Conv1D(64, kernel_size=5, padding = "same", activation="relu")(embeddings)
x = layers.GlobalAveragePooling1D()(x)
outputs = layers.Dense(num_classes, activation="softmax")(x)
model_1 = tf.keras.Model(inputs,outputs)
model_1.compile(loss="categorical_crossentropy",
optimizer = tf.keras.optimizers.Adam(),
metrics=["accuracy"])
In [ ]:
# Fit the model
history_model_1 = model_1.fit(train_dataset,
steps_per_epoch=int(0.1*len(train_dataset)),
epochs=3,
validation_data=valid_dataset,
validation_steps = int(0.1*len(valid_dataset)))
Epoch 1/3 562/562 [==============================] - 47s 81ms/step - loss: 0.9156 - accuracy: 0.6383 - val_loss: 0.6835 - val_accuracy: 0.7360 Epoch 2/3 562/562 [==============================] - 43s 76ms/step - loss: 0.6535 - accuracy: 0.7587 - val_loss: 0.6301 - val_accuracy: 0.7739 Epoch 3/3 562/562 [==============================] - 46s 82ms/step - loss: 0.6134 - accuracy: 0.7768 - val_loss: 0.5945 - val_accuracy: 0.7866
In [ ]:
model_1.evaluate(valid_dataset)
945/945 [==============================] - 4s 4ms/step - loss: 0.5954 - accuracy: 0.7882
Out[ ]:
[0.5953881144523621, 0.7881636619567871]
In [ ]:
model_1_pred_probs = model_1.predict(valid_dataset)
model_1_pred_probs, model_1_pred_probs.shape
945/945 [==============================] - 4s 4ms/step
Out[ ]:
(array([[4.4913521e-01, 1.4943682e-01, 5.8230158e-02, 3.1496683e-01,
2.8230978e-02],
[4.1630343e-01, 2.8261870e-01, 1.4050441e-02, 2.7627426e-01,
1.0753191e-02],
[1.5990542e-01, 7.8024538e-03, 1.5261150e-03, 8.3073562e-01,
3.0455089e-05],
...,
[7.3449455e-06, 4.9260329e-04, 5.8223313e-04, 3.7533027e-06,
9.9891412e-01],
[5.2310899e-02, 4.6858320e-01, 8.6061850e-02, 6.2505171e-02,
3.3053893e-01],
[1.3006426e-01, 7.3356968e-01, 4.1837540e-02, 4.5270838e-02,
4.9257640e-02]], dtype=float32), (30212, 5)) In [ ]:
model_1_preds = tf.argmax(model_1_pred_probs, axis=1)
In [ ]:
model_1_results = calculate_results(y_true = val_labels_encoded,
y_pred=model_1_preds)
model_1_results
Out[ ]:
{'accuracy': 78.81636435853304,
'precision': 0.7853731338152676,
'recall': 0.7881636435853303,
'f1': 0.78610395895878} Model 2: Feature Extraction with pretrained token embeddings¶
In [ ]:
import tensorflow_hub as hub
tf_hub_embedding_layer = hub.KerasLayer("https://tfhub.dev/google/universal-sentence-encoder/4",
trainable=False,
name="universal_sentence_encoder")
WARNING:tensorflow:Please fix your imports. Module tensorflow.python.training.tracking.data_structures has been moved to tensorflow.python.trackable.data_structures. The old module will be deleted in version 2.11.
In [ ]:
random_train_sentence = random.choice(train_sentences)
use_embedded_sentence = tf_hub_embedding_layer([random_train_sentence])
random_train_sentence, use_embedded_sentence
Out[ ]:
('analyses will be conducted on an intention-to-treat basis .',
<tf.Tensor: shape=(1, 512), dtype=float32, numpy=
array([[ 5.41769899e-02, 6.85121045e-02, -1.97337829e-02,
-2.71293093e-02, -2.46561170e-02, -6.20791651e-02,
2.77688131e-02, -5.92896864e-02, 3.14862430e-02,
4.16138954e-02, -3.02800047e-03, 2.17585228e-02,
1.01269092e-02, -5.48334373e-03, 2.09440999e-02,
-5.14813662e-02, 5.91339171e-02, 4.36047688e-02,
-5.85279940e-03, 2.67846566e-02, -3.59719316e-03,
7.62034804e-02, -9.29302573e-02, 1.03161251e-02,
1.39192734e-02, 7.13577420e-02, 2.13499218e-02,
2.09671631e-02, 6.06491230e-02, -4.93837753e-03,
2.24815533e-02, -6.72427118e-02, 5.25027066e-02,
3.94310392e-02, -4.33514267e-02, 9.07592103e-02,
-8.33318830e-02, -6.91916794e-02, -2.54493188e-02,
1.05001573e-02, 2.48978585e-02, -3.66998799e-02,
-3.76719632e-03, 5.26765212e-02, 3.99820060e-02,
2.11374704e-02, -1.12461234e-02, 6.64851367e-02,
8.19315016e-02, -2.37073228e-02, -8.03255197e-03,
-8.62722397e-02, -4.36456539e-02, -4.41965349e-02,
-8.10302235e-03, -3.61844897e-02, 4.85097244e-02,
1.90611072e-02, 2.04119310e-02, 9.33368504e-03,
2.71877926e-02, -3.88585292e-02, 4.61865701e-02,
-9.98182893e-02, -7.04697007e-03, 4.97108400e-02,
-4.09163386e-02, -1.77793633e-02, 7.19153602e-03,
4.45474982e-02, -1.48710040e-02, -4.55137603e-02,
-2.69450359e-02, -4.02350686e-02, -2.43155323e-02,
2.36777347e-02, 1.34653095e-02, 2.90642437e-02,
-7.79701546e-02, 1.81702385e-03, -1.34981703e-02,
-2.42671687e-02, 7.35932514e-02, -4.77389693e-02,
-1.24485428e-02, -4.64066342e-02, 1.71145573e-02,
-7.43141025e-03, -2.59080268e-02, -5.62477931e-02,
-3.10932975e-02, 2.58315615e-02, -3.17879394e-02,
4.95374687e-02, 4.16821055e-03, -5.40344371e-03,
-4.97619994e-02, -4.94528599e-02, -4.09436487e-02,
7.45099261e-02, 4.42609526e-02, -5.86041547e-02,
6.48119226e-02, -1.97321381e-02, -1.88390240e-02,
-3.58499773e-02, 6.32653758e-03, 3.37988371e-04,
-3.97118442e-02, 2.09295601e-02, 1.21130394e-02,
-1.95414051e-02, 2.02017743e-02, -1.49461422e-02,
-2.85514817e-02, -7.27298437e-03, -4.27073054e-03,
2.79297717e-02, -1.65433530e-02, -4.73657213e-02,
1.63632333e-02, 2.38527753e-03, -1.20506529e-02,
-6.69352338e-02, -7.90493861e-02, 3.18825878e-02,
-6.49456233e-02, 3.96221839e-02, 5.25661632e-02,
8.21119454e-03, 3.36499885e-02, 5.12244329e-02,
-2.64160298e-02, 2.18374804e-02, -1.53795816e-03,
-8.14673863e-03, -1.28064156e-02, 2.71155331e-02,
7.98988491e-02, 1.54410647e-02, 2.23963857e-02,
-1.00569867e-01, 5.05035184e-02, 1.86636820e-02,
3.22627202e-02, 5.98084815e-02, -1.15718469e-02,
2.52593625e-02, 2.12452165e-03, 4.92301024e-02,
2.85224039e-02, -4.95857606e-03, -5.75496489e-03,
-1.95090994e-02, 1.05697419e-02, 3.52181904e-02,
2.91097015e-02, -7.55607858e-02, 4.22972254e-02,
3.32232490e-02, 4.58932854e-02, 5.19337654e-02,
1.05310436e-02, -5.30605391e-02, 3.75159793e-02,
-7.40301386e-02, -2.30544489e-02, 4.39651194e-05,
-1.41062429e-02, -3.06235012e-02, -1.02461511e-02,
8.76369849e-02, -3.57935689e-02, -6.21532872e-02,
2.29002652e-03, 1.62718259e-02, 4.90576997e-02,
1.61037706e-02, 4.84057656e-03, -2.79588019e-03,
3.65805882e-03, -2.22743303e-02, 1.67572293e-02,
2.26518270e-02, -1.20921060e-02, 1.95237156e-02,
-4.24436182e-02, -5.52234463e-02, -4.48931158e-02,
5.13798818e-02, 1.09393619e-01, -5.75249568e-02,
-6.52355477e-02, 2.87160054e-02, -4.49910294e-03,
2.81930566e-02, -2.38570496e-02, 3.42058986e-02,
-1.89184106e-03, -3.40972072e-03, -2.91907741e-03,
-1.18258530e-02, -5.02918810e-02, 6.22775145e-02,
5.06235436e-02, -1.04283229e-01, -5.61349280e-02,
-2.94085909e-02, 2.62823366e-02, 7.43368790e-02,
-1.23906014e-02, 7.61542544e-02, -4.89045754e-02,
-4.70578112e-02, 2.65578050e-02, -5.38873635e-02,
1.88133493e-02, 9.44997296e-02, 1.96114499e-02,
1.07541885e-02, 1.87394116e-02, -7.37989098e-02,
1.01518277e-02, 5.54478765e-02, 3.03884316e-02,
3.10574602e-02, 4.60066535e-02, -4.05254476e-02,
-4.94135767e-02, 3.86776701e-02, -2.52481271e-03,
1.21861193e-02, -5.19880876e-02, 1.69068389e-02,
6.20773435e-02, -4.61942367e-02, -4.52577621e-02,
-2.07789266e-03, 3.99699211e-02, -4.55209352e-02,
-6.73647672e-02, -2.28201263e-02, 1.62466355e-02,
-2.33424697e-02, -5.09627685e-02, -5.44366017e-02,
-2.47714762e-02, -8.39014128e-02, -5.52052520e-02,
1.24008150e-03, 1.39654120e-02, -7.50936493e-02,
2.69338079e-02, 1.23280915e-03, -8.13831091e-02,
-1.35691008e-02, -6.25651926e-02, -7.29754567e-02,
1.74153745e-02, -2.97953549e-04, -7.96233714e-02,
-1.51625229e-02, -3.97345498e-02, 8.88538659e-02,
2.81431861e-02, -4.63039055e-02, -2.20563188e-02,
2.10575126e-02, 9.41112885e-05, 3.89783308e-02,
-7.44736195e-02, -7.89573975e-03, 4.72804308e-02,
-4.29070555e-03, -5.62218241e-02, 2.30080597e-02,
-5.83499484e-02, -1.72146708e-02, -6.66682348e-02,
5.83180711e-02, -1.02799654e-01, 1.74054876e-02,
-4.81643826e-02, 6.44899532e-02, -4.30284888e-02,
4.88880202e-02, -1.37489997e-02, 2.86133699e-02,
-1.10195670e-02, -1.73850525e-02, -3.04242200e-03,
2.61848662e-02, 1.23166749e-02, 3.30810174e-02,
-5.89205660e-02, 4.21574526e-02, -1.47786839e-02,
2.72259787e-02, -1.93727156e-03, -6.27199784e-02,
5.99831045e-02, 5.22752479e-02, 2.34762169e-02,
-4.30853851e-02, -9.05911624e-02, 3.40395235e-02,
2.91523505e-02, 1.13885887e-02, -9.18283127e-03,
-2.24336213e-03, 5.69259096e-03, 3.62607390e-02,
8.14057663e-02, 2.11009178e-02, 2.83522941e-02,
-6.37010112e-02, 3.87104191e-02, -8.55180714e-03,
-5.63042052e-02, -2.95193680e-02, -4.90278453e-02,
-7.19809532e-02, 3.15540060e-02, -4.05083634e-02,
7.57393800e-03, -2.13194434e-02, -5.99832125e-02,
-4.65853587e-02, -2.50532124e-02, -3.79797816e-02,
-5.51727638e-02, -2.05941368e-02, 8.39191601e-02,
3.04834843e-02, 2.43312195e-02, 5.79514094e-02,
5.14389239e-02, -1.98319908e-02, 1.20929359e-02,
6.88277856e-02, 3.47612947e-02, 5.85059859e-02,
6.52113184e-02, 5.68570346e-02, -4.60844524e-02,
2.64836978e-02, -4.83212359e-02, 7.19936863e-02,
-4.85145040e-02, 3.40022743e-02, -1.28139807e-02,
3.26976217e-02, -1.44883739e-02, -2.22725607e-02,
7.03397393e-02, -4.12113369e-02, -1.20540243e-02,
2.46189795e-02, 7.90591389e-02, -6.36300221e-02,
-1.93651579e-02, -1.66282803e-02, -7.83990547e-02,
-4.55431268e-02, -1.99750811e-02, -4.21770327e-02,
-1.33130476e-02, 1.04715228e-02, -8.56391117e-02,
-4.04927805e-02, 3.00680883e-02, -1.70136131e-02,
6.48661554e-02, 2.57216278e-03, -1.43680600e-02,
-7.24774152e-02, -6.40890300e-02, 3.35440636e-02,
-5.29739447e-02, 6.09223396e-02, -3.09869442e-02,
-1.64638367e-02, -8.08690339e-02, 4.96226884e-02,
-8.44427496e-02, -5.06896898e-02, 3.78946103e-02,
-2.81247441e-02, 8.79235845e-03, -2.16286094e-03,
-9.72675160e-02, 3.73124629e-02, 4.64987149e-03,
2.55259555e-02, 6.81776367e-03, 1.81871094e-02,
4.18572947e-02, -8.91360641e-02, -2.60793953e-03,
1.03334703e-01, -6.87756687e-02, -1.89606193e-02,
-1.55966906e-02, 8.17129835e-02, 3.38522755e-02,
4.85860109e-02, 3.75147499e-02, 7.52271563e-02,
-2.37569474e-02, 2.13962495e-02, 6.87193573e-02,
-4.81286980e-02, -2.50914544e-02, -8.37529171e-03,
-3.98030095e-02, -3.92174460e-02, -5.66637926e-02,
-1.05696462e-01, 1.00404053e-04, 4.61555959e-04,
8.66785645e-02, -3.62860598e-02, -4.99757305e-02,
2.06314567e-02, 5.84754720e-02, -4.85269688e-02,
-6.58846051e-02, -8.31431672e-02, -1.15644941e-02,
-6.06129766e-02, -2.08098870e-02, -6.20683394e-02,
-2.43185554e-02, 1.63780898e-02, -6.99614827e-03,
1.59969814e-02, -1.43313790e-02, -8.46194103e-03,
2.30382625e-02, 2.85958964e-02, 2.46286727e-02,
3.68446261e-02, -1.37822609e-02, -9.63478163e-02,
-5.52764051e-02, 5.28007150e-02, 6.42283931e-02,
-4.76174243e-02, 3.77857505e-04, 3.79880570e-04,
7.15163127e-02, 9.77399796e-02, 9.46934801e-03,
1.30267544e-02, 2.84411339e-03, -9.55114216e-02,
-1.70047767e-02, 7.71037266e-02, -2.43180338e-02,
6.29994199e-02, 2.63760961e-03, 4.02163677e-02,
1.11770313e-02, 4.12749872e-02, -7.34309107e-02,
8.82321037e-03, 4.44065407e-02, 1.90395974e-02,
9.02021900e-02, -3.15936282e-02, -3.43958773e-02,
5.31076640e-02, -1.40632009e-02, -1.80716291e-02,
-2.76954044e-02, 4.63634767e-02, -4.69581187e-02,
3.95714864e-02, -6.41763881e-02, 8.11897665e-02,
4.65169065e-02, -1.18751246e-02, -2.89300252e-02,
2.65923664e-02, 1.92345828e-02, 1.75444048e-03,
-6.93337619e-02, -4.17684466e-02, 3.05270478e-02,
-1.50266159e-02, 5.73386587e-02, 7.89662376e-02,
-4.64550555e-02, -7.18940096e-03, -3.60006257e-03,
-1.40314754e-02, -4.09012958e-02, 2.77883615e-02,
-4.03469428e-02, -2.20058579e-02, 3.18237282e-02,
-2.52268165e-02, 3.82014527e-03, 4.63144854e-02,
-6.70162775e-03, -5.54545596e-02, 2.14021727e-02,
-6.57858467e-03, 6.02435693e-03, 9.75138508e-03,
-9.91258398e-03, -3.26796109e-03]], dtype=float32)>) In [ ]:
inputs = layers.Input(shape=[], dtype=tf.string)
pretrained_embedding = tf_hub_embedding_layer(inputs)
x = layers.Dense(128, activation = "relu")(pretrained_embedding)
outputs = layers.Dense(num_classes, activation="softmax")(x)
model_2 = tf.keras.Model(inputs, outputs,
name="model_2_USE_feature_extractor")
model_2.compile(loss="categorical_crossentropy",
optimizer= tf.keras.optimizers.Adam(),
metrics= ["accuracy"])
model_2.summary()
WARNING:tensorflow:From /usr/local/lib/python3.9/dist-packages/tensorflow/python/autograph/pyct/static_analysis/liveness.py:83: Analyzer.lamba_check (from tensorflow.python.autograph.pyct.static_analysis.liveness) is deprecated and will be removed after 2023-09-23. Instructions for updating: Lambda fuctions will be no more assumed to be used in the statement where they are used, or at least in the same block. https://github.com/tensorflow/tensorflow/issues/56089
Model: "model_2_USE_feature_extractor"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) [(None,)] 0
universal_sentence_encoder (None, 512) 256797824
(KerasLayer)
dense_1 (Dense) (None, 128) 65664
dense_2 (Dense) (None, 5) 645
=================================================================
Total params: 256,864,133
Trainable params: 66,309
Non-trainable params: 256,797,824
_________________________________________________________________
In [ ]:
history_model_2 = model_2.fit(train_dataset,
epochs=3,
steps_per_epoch = int(0.1*len(train_dataset)),
validation_data = valid_dataset,
validation_steps=int(0.1 * len(valid_dataset)))
Epoch 1/3 562/562 [==============================] - 10s 13ms/step - loss: 0.9221 - accuracy: 0.6486 - val_loss: 0.7982 - val_accuracy: 0.6912 Epoch 2/3 562/562 [==============================] - 6s 11ms/step - loss: 0.7714 - accuracy: 0.7003 - val_loss: 0.7583 - val_accuracy: 0.7008 Epoch 3/3 562/562 [==============================] - 6s 11ms/step - loss: 0.7563 - accuracy: 0.7111 - val_loss: 0.7434 - val_accuracy: 0.7098
In [ ]:
model_2.evaluate(valid_dataset)
945/945 [==============================] - 8s 8ms/step - loss: 0.7458 - accuracy: 0.7111
Out[ ]:
[0.7458107471466064, 0.7111412882804871]
In [ ]:
model_2_pred_probs = model_2.predict(valid_dataset)
model_2_pred_probs
945/945 [==============================] - 8s 8ms/step
Out[ ]:
array([[4.3422687e-01, 3.6142790e-01, 2.1149786e-03, 1.9464298e-01,
7.5872596e-03],
[3.4780338e-01, 4.8940066e-01, 3.7401854e-03, 1.5517540e-01,
3.8803599e-03],
[2.1420549e-01, 1.4800373e-01, 2.0897944e-02, 5.7757407e-01,
3.9318770e-02],
...,
[2.0430745e-03, 6.3805967e-03, 5.4795228e-02, 8.2456123e-04,
9.3595654e-01],
[4.0250774e-03, 4.0663589e-02, 2.2689721e-01, 1.4827074e-03,
7.2693145e-01],
[1.5657867e-01, 2.4246831e-01, 5.1643497e-01, 8.0781700e-03,
7.6439850e-02]], dtype=float32) In [ ]:
model_2_preds = tf.argmax(model_2_pred_probs, axis=1)
model_2_preds
Out[ ]:
<tf.Tensor: shape=(30212,), dtype=int64, numpy=array([0, 1, 3, ..., 4, 4, 2])>
In [ ]:
model_2_results= calculate_results(y_true = val_labels_encoded,
y_pred = model_2_preds)
model_2_results
Out[ ]:
{'accuracy': 71.1141268370184,
'precision': 0.7109563735989716,
'recall': 0.711141268370184,
'f1': 0.7082515457833648} Model 3: Conv1d with character embeddings¶
In [ ]:
train_sentences[:5]
Out[ ]:
['to investigate the efficacy of @ weeks of daily low-dose oral prednisolone in improving pain , mobility , and systemic low-grade inflammation in the short term and whether the effect would be sustained at @ weeks in older adults with moderate to severe knee osteoarthritis ( oa ) .', 'a total of @ patients with primary knee oa were randomized @:@ ; @ received @ mg/day of prednisolone and @ received placebo for @ weeks .', 'outcome measures included pain reduction and improvement in function scores and systemic inflammation markers .', 'pain was assessed using the visual analog pain scale ( @-@ mm ) .', 'secondary outcome measures included the western ontario and mcmaster universities osteoarthritis index scores , patient global assessment ( pga ) of the severity of knee oa , and @-min walk distance ( @mwd ) .']
In [ ]:
def split_chars(text):
return " ".join(list(text))
In [ ]:
split_chars(random_train_sentence)
Out[ ]:
'a n a l y s e s w i l l b e c o n d u c t e d o n a n i n t e n t i o n - t o - t r e a t b a s i s .'
In [ ]:
train_chars = [split_chars(sentence) for sentence in train_sentences]
val_chars = [split_chars(sentence) for sentence in val_sentences]
test_chars = [split_chars(sentence) for sentence in test_sentences]
In [ ]:
char_lens = [len(sentence) for sentence in train_sentences]
mean_char_len = np.mean(char_lens)
mean_char_len
Out[ ]:
149.3662574983337
In [ ]:
import matplotlib.pyplot as plt
plt.hist(char_lens, bins=7)
Out[ ]:
(array([1.41175e+05, 3.71110e+04, 1.60000e+03, 1.27000e+02, 2.10000e+01,
5.00000e+00, 1.00000e+00]),
array([1.00000000e+00, 1.98857143e+02, 3.96714286e+02, 5.94571429e+02,
7.92428571e+02, 9.90285714e+02, 1.18814286e+03, 1.38600000e+03]),
<BarContainer object of 7 artists>) In [ ]:
output_seq_char_len = int(np.percentile(char_lens, 95))
output_seq_char_len
Out[ ]:
290
In [ ]:
import string
alphabet = string.ascii_lowercase + string.digits + string.punctuation
NUM_CHAR_TOKENS = len(alphabet) + 2
char_vectorizer = TextVectorization(max_tokens=NUM_CHAR_TOKENS,
output_sequence_length=output_seq_char_len,
standardize='lower_and_strip_punctuation',
name="char_vetorizer")
In [ ]:
char_vectorizer.adapt(train_chars)
char_vocab = char_vectorizer.get_vocabulary()
In [ ]:
char_embed = layers.Embedding(input_dim=len(char_vocab),
output_dim=25,
mask_zero=True,
name="char_embed")
In [ ]:
inputs = layers.Input(shape=(1,), dtype="string")
text_vectors = char_vectorizer(inputs)
char_em = char_embed(text_vectors)
x = layers.Conv1D(64, kernel_size=5, padding="same", activation = "relu")(char_em)
x = layers.GlobalMaxPool1D()(x)
outputs = layers.Dense(num_classes, activation="softmax")(x)
model_3 = tf.keras.Model(inputs, outputs, name="model_3_conv1d_char_embeddings")
model_3.compile(loss = "categorical_crossentropy",
optimizer = tf.keras.optimizers.Adam(),
metrics = ["accuracy"])
model_3.summary()
Model: "model_3_conv1d_char_embeddings"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_5 (InputLayer) [(None, 1)] 0
char_vetorizer (TextVectori (None, 290) 0
zation)
char_embed (Embedding) (None, 290, 25) 700
conv1d_2 (Conv1D) (None, 290, 64) 8064
global_max_pooling1d (Globa (None, 64) 0
lMaxPooling1D)
dense_4 (Dense) (None, 5) 325
=================================================================
Total params: 9,089
Trainable params: 9,089
Non-trainable params: 0
_________________________________________________________________
In [ ]:
train_char_dataset = tf.data.Dataset.from_tensor_slices((train_chars, train_labels_one_hot)).batch(32).prefetch(tf.data.AUTOTUNE)
val_char_dataset = tf.data.Dataset.from_tensor_slices((val_chars, val_labels_one_hot)).batch(32).prefetch(tf.data.AUTOTUNE)
test_char_dataset = tf.data.Dataset.from_tensor_slices((test_chars, test_labels_one_hot)).batch(32).prefetch(tf.data.AUTOTUNE)
In [ ]:
model_3_history = model_3.fit(train_char_dataset,
steps_per_epoch=int(0.1*len(train_char_dataset)),
epochs=3,
validation_data=val_char_dataset,
validation_steps=int(0.1*len(val_char_dataset)))
Epoch 1/3 562/562 [==============================] - 11s 19ms/step - loss: 1.2565 - accuracy: 0.4813 - val_loss: 1.1184 - val_accuracy: 0.5532 Epoch 2/3 562/562 [==============================] - 13s 23ms/step - loss: 1.0829 - accuracy: 0.5644 - val_loss: 1.0160 - val_accuracy: 0.5918 Epoch 3/3 562/562 [==============================] - 13s 23ms/step - loss: 0.9950 - accuracy: 0.6071 - val_loss: 0.9505 - val_accuracy: 0.6263
In [ ]:
model_3_pred_probs = model_3.predict(val_char_dataset)
model_3_pred_probs
945/945 [==============================] - 5s 5ms/step
Out[ ]:
array([[0.09065318, 0.33763337, 0.26869836, 0.23524268, 0.0677723 ],
[0.15873677, 0.43171608, 0.01322432, 0.36395332, 0.03236937],
[0.10995094, 0.24631527, 0.07298288, 0.5433485 , 0.02740242],
...,
[0.04478712, 0.11457787, 0.17656954, 0.03246031, 0.6316052 ],
[0.03226728, 0.23586535, 0.48869738, 0.08628745, 0.15688252],
[0.31787407, 0.31050932, 0.21858568, 0.12196248, 0.03106844]],
dtype=float32) In [ ]:
model_3_preds = tf.argmax(model_3_pred_probs, axis=1)
model_3_preds
Out[ ]:
<tf.Tensor: shape=(30212,), dtype=int64, numpy=array([1, 1, 3, ..., 4, 2, 0])>
In [ ]:
model_3_results = calculate_results(y_true=val_labels_encoded,
y_pred=model_3_preds)
model_3_results
Out[ ]:
{'accuracy': 62.23354958294718,
'precision': 0.6364670583530218,
'recall': 0.6223354958294718,
'f1': 0.612028535717401} In [ ]:
Model 4: Combining pretrained token embeddings + charactes embeddings (hybrid)¶
- Create a token-level model (similar to model_1)
- Create a character-level model (similar to model_3 with a slight modification to reflect the paper)
- Combine (using layers.Concatenate) the outputs of 1 and 2
- Build a series of output layers on top of 3 similar to Figure 1 and section 4.2 of [*Neural Networks for Joint Sentence Classification
In [ ]:
token_inputs = layers.Input(shape=[], dtype=tf.string, name="token_input")
token_embeddings = tf_hub_embedding_layer(token_inputs)
token_output = layers.Dense(128, activation="relu")(token_embeddings)
token_model = tf.keras.Model(inputs=token_inputs,
outputs=token_output)
char_inputs = layers.Input(shape=(1,), dtype=tf.string, name="char_input")
char_vectors = char_vectorizer(char_inputs)
char_embeddings = char_embed(char_vectors)
char_bi_lstm = layers.Bidirectional(layers.LSTM(25))(char_embeddings)
char_model = tf.keras.Model(inputs=char_inputs,
outputs=char_bi_lstm)
token_char_concat = layers.Concatenate(name="token_char_hybrid")([token_model.output,
char_model.output])
combined_dropout = layers.Dropout(0.5)(token_char_concat)
combined_dense = layers.Dense(200, activation="relu")(combined_dropout)
final_dropout = layers.Dropout(0.5)(combined_dense)
output_layer = layers.Dense(num_classes, activation="softmax")(final_dropout)
model_4 = tf.keras.Model(inputs=[token_model.input, char_model.input],
outputs=output_layer,
name="model_4_token_and_char_embeddings")
In [ ]:
model_4.summary()
Model: "model_4_token_and_char_embeddings"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
char_input (InputLayer) [(None, 1)] 0 []
token_input (InputLayer) [(None,)] 0 []
char_vetorizer (TextVectorizat (None, 290) 0 ['char_input[0][0]']
ion)
universal_sentence_encoder (Ke (None, 512) 256797824 ['token_input[0][0]']
rasLayer)
char_embed (Embedding) (None, 290, 25) 700 ['char_vetorizer[2][0]']
dense_5 (Dense) (None, 128) 65664 ['universal_sentence_encoder[1][0
]']
bidirectional (Bidirectional) (None, 50) 10200 ['char_embed[2][0]']
token_char_hybrid (Concatenate (None, 178) 0 ['dense_5[0][0]',
) 'bidirectional[0][0]']
dropout (Dropout) (None, 178) 0 ['token_char_hybrid[0][0]']
dense_6 (Dense) (None, 200) 35800 ['dropout[0][0]']
dropout_1 (Dropout) (None, 200) 0 ['dense_6[0][0]']
dense_7 (Dense) (None, 5) 1005 ['dropout_1[0][0]']
==================================================================================================
Total params: 256,911,193
Trainable params: 113,369
Non-trainable params: 256,797,824
__________________________________________________________________________________________________
In [ ]:
from keras.utils import plot_model
plot_model(model_4, show_shapes=True)
Out[ ]:
In [ ]:
model_4.compile(loss="categorical_crossentropy",
optimizer =tf.keras.optimizers.Adam(),
metrics=["accuracy"])
In [ ]:
train_char_token_data = tf.data.Dataset.from_tensor_slices((train_sentences, train_chars))
train_char_token_labels = tf.data.Dataset.from_tensor_slices(train_labels_one_hot)
train_char_token_dataset = tf.data.Dataset.zip((train_char_token_data, train_char_token_labels))
train_char_token_dataset = train_char_token_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
val_char_token_data = tf.data.Dataset.from_tensor_slices((val_sentences, val_chars))
val_char_token_labels = tf.data.Dataset.from_tensor_slices(val_labels_one_hot)
val_char_token_dataset = tf.data.Dataset.zip((val_char_token_data, val_char_token_labels))
val_char_token_dataset = val_char_token_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
In [ ]:
history_model_4 = model_4.fit(train_char_token_dataset,
epochs = 3,
steps_per_epoch=int(0.1*len(train_char_token_dataset)),
validation_data=val_char_token_dataset,
validation_steps = int(0.1*len(val_char_token_dataset)))
Epoch 1/3 562/562 [==============================] - 133s 219ms/step - loss: 0.9638 - accuracy: 0.6170 - val_loss: 0.7695 - val_accuracy: 0.7038 Epoch 2/3 562/562 [==============================] - 116s 207ms/step - loss: 0.7905 - accuracy: 0.6945 - val_loss: 0.7083 - val_accuracy: 0.7340 Epoch 3/3 562/562 [==============================] - 117s 208ms/step - loss: 0.7646 - accuracy: 0.7062 - val_loss: 0.6808 - val_accuracy: 0.7453
In [ ]:
model_4_pred_probs = model_4.predict(val_char_token_dataset)
model_4_pred_probs
945/945 [==============================] - 57s 56ms/step
Out[ ]:
array([[4.28928614e-01, 3.92034113e-01, 2.97186244e-03, 1.71171516e-01,
4.89383237e-03],
[3.37443858e-01, 5.02291143e-01, 1.85330119e-03, 1.56881139e-01,
1.53058418e-03],
[3.52816373e-01, 1.07717074e-01, 6.34969696e-02, 4.43023264e-01,
3.29463109e-02],
...,
[1.09098945e-03, 1.00437822e-02, 5.89296520e-02, 3.93304974e-04,
9.29542303e-01],
[8.91150348e-03, 7.10064322e-02, 2.05754831e-01, 3.54606635e-03,
7.10781157e-01],
[2.59739161e-01, 4.06385779e-01, 2.38856733e-01, 3.17684337e-02,
6.32498339e-02]], dtype=float32) In [ ]:
model_4_preds = tf.argmax(model_4_pred_probs, axis=1)
model_4_preds
Out[ ]:
<tf.Tensor: shape=(30212,), dtype=int64, numpy=array([0, 1, 3, ..., 4, 4, 1])>
In [ ]:
model_4_results = calculate_results(y_true=val_labels_encoded,
y_pred=model_4_preds)
model_4_results
Out[ ]:
{'accuracy': 73.75877134913279,
'precision': 0.7374610987378799,
'recall': 0.7375877134913279,
'f1': 0.7351158173574258} Model 5: Transfer Learning with pretrained token embeddings + character embeddings + positional embeddings¶
- Create a token-level model (similar to model_1)
- Create a character-level model (similar to model_3 with a slight modification to reflect the paper)
- Create a "line_number" model (takes in one-hot-encoded "line_number" tensor and passes it through a non-linear layer)
- Create a "total_lines" model (takes in one-hot-encoded "total_lines" tensor and passes it through a non-linear layer)
- Combine (using layers.Concatenate) the outputs of 1 and 2 into a token-character-hybrid embedding and pass it series of output to Figure 1 and section 4.2 of [*Neural Networks for Joint Sentence Classification
In [ ]:
train_df["line_number"].value_counts()
Out[ ]:
0 15000 1 15000 2 15000 3 15000 4 14992 5 14949 6 14758 7 14279 8 13346 9 11981 10 10041 11 7892 12 5853 13 4152 14 2835 15 1861 16 1188 17 751 18 462 19 286 20 162 21 101 22 66 23 33 24 22 25 14 26 7 27 4 28 3 29 1 30 1 Name: line_number, dtype: int64
In [ ]:
train_line_numbers_one_hot = tf.one_hot(train_df["line_number"].to_numpy(), depth=15)
val_line_numbers_one_hot = tf.one_hot(val_df["line_number"].to_numpy(), depth=15)
test_line_numbers_one_hot = tf.one_hot(test_df["line_number"].to_numpy(), depth=15)
In [ ]:
train_total_lines_one_hot = tf.one_hot(train_df["total_lines"].to_numpy(), depth=20)
val_total_lines_one_hot = tf.one_hot(val_df["total_lines"].to_numpy(), depth=20)
test_total_lines_one_hot = tf.one_hot(test_df["total_lines"].to_numpy(), depth=20)
train_total_lines_one_hot.shape, train_total_lines_one_hot[:10]
Out[ ]:
(TensorShape([180040, 20]), <tf.Tensor: shape=(10, 20), dtype=float32, numpy=
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0.]], dtype=float32)>) In [ ]:
token_inputs = layers.Input(shape=[], dtype="string", name="token_inputs")
token_embeddings = tf_hub_embedding_layer(token_inputs)
token_outputs = layers.Dense(128, activation="relu")(token_embeddings)
token_model = tf.keras.Model(inputs=token_inputs,
outputs=token_outputs)
char_inputs = layers.Input(shape=(1,), dtype="string", name="char_inputs")
char_vectors = char_vectorizer(char_inputs)
char_embeddings = char_embed(char_vectors)
char_bi_lstm = layers.Bidirectional(layers.LSTM(32))(char_embeddings)
char_model = tf.keras.Model(inputs=char_inputs,
outputs=char_bi_lstm)
line_number_inputs = layers.Input(shape=(15,), dtype=tf.int32, name="line_number_input")
x = layers.Dense(32, activation="relu")(line_number_inputs)
line_number_model = tf.keras.Model(inputs=line_number_inputs,
outputs=x)
total_lines_inputs = layers.Input(shape=(20,), dtype=tf.int32, name="total_lines_input")
y = layers.Dense(32, activation="relu")(total_lines_inputs)
total_line_model = tf.keras.Model(inputs=total_lines_inputs,
outputs=y)
combined_embeddings = layers.Concatenate(name="token_char_hybrid_embedding")([token_model.output,
char_model.output])
z = layers.Dense(256, activation="relu")(combined_embeddings)
z = layers.Dropout(0.5)(z)
z = layers.Concatenate(name="token_char_positional_embedding")([line_number_model.output,
total_line_model.output,
z])
output_layer = layers.Dense(num_classes, activation="softmax", name="output_layer")(z)
model_5 = tf.keras.Model(inputs=[line_number_model.input,
total_line_model.input,
token_model.input,
char_model.input],
outputs=output_layer)
In [ ]:
from keras.utils import plot_model
plot_model(model_5)
Out[ ]:
In [ ]:
model_5.compile(loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.2),
optimizer=tf.keras.optimizers.Adam(),
metrics=["accuracy"])
In [ ]:
train_pos_char_token_data = tf.data.Dataset.from_tensor_slices((train_line_numbers_one_hot,
train_total_lines_one_hot,
train_sentences,
train_chars))
train_pos_char_token_labels = tf.data.Dataset.from_tensor_slices(train_labels_one_hot)
train_pos_char_token_dataset = tf.data.Dataset.zip((train_pos_char_token_data, train_pos_char_token_labels))
train_pos_char_token_dataset = train_pos_char_token_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
val_pos_char_token_data = tf.data.Dataset.from_tensor_slices((val_line_numbers_one_hot,
val_total_lines_one_hot,
val_sentences,
val_chars))
val_pos_char_token_labels = tf.data.Dataset.from_tensor_slices(val_labels_one_hot)
val_pos_char_token_dataset = tf.data.Dataset.zip((val_pos_char_token_data, val_pos_char_token_labels))
val_pos_char_token_dataset = val_pos_char_token_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
train_pos_char_token_dataset, val_pos_char_token_dataset
Out[ ]:
(<PrefetchDataset element_spec=((TensorSpec(shape=(None, 15), dtype=tf.float32, name=None), TensorSpec(shape=(None, 20), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.string, name=None), TensorSpec(shape=(None,), dtype=tf.string, name=None)), TensorSpec(shape=(None, 5), dtype=tf.float64, name=None))>, <PrefetchDataset element_spec=((TensorSpec(shape=(None, 15), dtype=tf.float32, name=None), TensorSpec(shape=(None, 20), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.string, name=None), TensorSpec(shape=(None,), dtype=tf.string, name=None)), TensorSpec(shape=(None, 5), dtype=tf.float64, name=None))>)
In [ ]:
history_model_5 = model_5.fit(train_pos_char_token_dataset,
steps_per_epoch=int(0.1 * len(train_pos_char_token_dataset)),
epochs=3,
validation_data=val_pos_char_token_dataset,
validation_steps=int(0.1 * len(val_pos_char_token_dataset)))
Epoch 1/3 562/562 [==============================] - 144s 237ms/step - loss: 1.1012 - accuracy: 0.7169 - val_loss: 0.9835 - val_accuracy: 0.8015 Epoch 2/3 562/562 [==============================] - 124s 222ms/step - loss: 0.9682 - accuracy: 0.8151 - val_loss: 0.9520 - val_accuracy: 0.8298 Epoch 3/3 562/562 [==============================] - 124s 221ms/step - loss: 0.9507 - accuracy: 0.8221 - val_loss: 0.9411 - val_accuracy: 0.8281
In [ ]:
model_5_pred_probs = model_5.predict(val_pos_char_token_dataset, verbose=1)
model_5_pred_probs
945/945 [==============================] - 55s 55ms/step
Out[ ]:
array([[0.52218175, 0.1071113 , 0.01011305, 0.34516218, 0.0154317 ],
[0.53147495, 0.07347722, 0.03215399, 0.35457075, 0.00832312],
[0.2998657 , 0.10310975, 0.12004947, 0.4131333 , 0.06384192],
...,
[0.04159614, 0.09939624, 0.04067647, 0.03122656, 0.7871046 ],
[0.02915285, 0.29524153, 0.07637534, 0.02588103, 0.5733492 ],
[0.21659288, 0.5568623 , 0.12053229, 0.03691146, 0.06910107]],
dtype=float32) In [ ]:
model_5_preds = tf.argmax(model_5_pred_probs, axis=1)
model_5_preds
Out[ ]:
<tf.Tensor: shape=(30212,), dtype=int64, numpy=array([0, 0, 3, ..., 4, 4, 1])>
In [ ]:
model_5_results = calculate_results(y_true=val_labels_encoded,
y_pred=model_5_preds)
model_5_results
Out[ ]:
{'accuracy': 83.12591023434396,
'precision': 0.8303595117294587,
'recall': 0.8312591023434397,
'f1': 0.8305670126223899} Compare results¶
In [ ]:
all_model_results = pd.DataFrame({"baseline": baseline_results,
"custom_token_embed_conv1d": model_1_results,
"pretrained_token_embed": model_2_results,
"custom_char_embed_conv1d": model_3_results,
"hybrid_char_token_embed": model_4_results,
"tribrid_pos_char_token_embed": model_5_results})
all_model_results = all_model_results.transpose()
all_model_results
Out[ ]:
| accuracy | precision | recall | f1 | |
|---|---|---|---|---|
| baseline | 72.183238 | 0.718647 | 0.721832 | 0.698925 |
| custom_token_embed_conv1d | 78.816364 | 0.785373 | 0.788164 | 0.786104 |
| pretrained_token_embed | 71.114127 | 0.710956 | 0.711141 | 0.708252 |
| custom_char_embed_conv1d | 62.233550 | 0.636467 | 0.622335 | 0.612029 |
| hybrid_char_token_embed | 73.758771 | 0.737461 | 0.737588 | 0.735116 |
| tribrid_pos_char_token_embed | 83.125910 | 0.830360 | 0.831259 | 0.830567 |
In [ ]:
all_model_results["accuracy"] = all_model_results["accuracy"]/100
In [ ]:
all_model_results.plot(kind="bar", figsize=(10, 7)).legend(bbox_to_anchor=(1.0, 1.0));
In [ ]:
all_model_results.sort_values("f1", ascending=False)["f1"].plot(kind="bar", figsize=(10, 7));
In [ ]:
model_5.save("skimlit_tribrid_model")
WARNING:absl:Found untraced functions such as _update_step_xla, lstm_cell_7_layer_call_fn, lstm_cell_7_layer_call_and_return_conditional_losses, lstm_cell_8_layer_call_fn, lstm_cell_8_layer_call_and_return_conditional_losses while saving (showing 5 of 5). These functions will not be directly callable after loading.
In [ ]:
!wget https://storage.googleapis.com/ztm_tf_course/skimlit/skimlit_tribrid_model.zip
!mkdir skimlit_gs_model
!unzip skimlit_tribrid_model.zip -d skimlit_gs_model
In [ ]:
import tensorflow_hub as hub
import tensorflow as tf
from tensorflow.keras.layers import TextVectorization
model_path = "skimlit_gs_model/skimlit_tribrid_model"
loaded_model = tf.keras.models.load_model(model_path)