Academic year: 2026-2027¶
This mini project is an example and a warm-up for exercise 2.4 of Practicals 2. It is not graded and is not to be submitted: only the project is graded.
Mini Project: Understanding the Translation of Wikidata Properties¶
Goals¶
Load and clean a real dataset of events with pandas.
Observe translation patterns with plots.
Mine frequent sets of languages and association rules (
mlxtend).Visualise the flow of translation as a graph (
networkx,holoviews).Predict the next language of a translation sequence: simple baselines, then a recurrent network and a Transformer written with Keras 3.
Inspect the learned language embeddings and add a symbolic constraint to the neural model (a bridge towards the bonus of the project).
Diagnose what limits the accuracy, then improve the inputs (time, all translation types) and the target (the next set of languages) of the model.
Each exercise ends with questions: write your answers as markdown cells in your copy of the notebook.
Estimated time: exercises 1.1–1.4 about 1h30, exercise 1.5 about 2h, exercise 1.6 about 1h30.
Setup¶
The libraries below are listed in the requirements.txt of the course. If one of them is missing, uncomment the corresponding line.
The notebook uses Keras 3 (import keras), which is the version shipped with TensorFlow ≥ 2.16. The code is the same as tf.keras, but written in the backend-independent way now recommended by the documentation.
# %pip install pandas numpy matplotlib scikit-learn mlxtend networkx holoviews bokeh tensorflow
import hashlib
import os
import urllib.request
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import keras
SEED = 42
keras.utils.set_random_seed(SEED)
print("Keras", keras.__version__, "- backend:", keras.backend.backend())Exercise 1.1¶
Download¶
The data come from https://
Note that this dataset is a snapshot taken in July 2019: it describes the first translations of Wikidata properties between 2013 and 2019. Wikidata has changed a lot since then (about twice as many properties today), so keep this in mind when interpreting the results.
DATA_URL = "https://zenodo.org/records/3271358/files/multilingual_wikidata_translation_flow.csv?download=1"
DATA_FILE = "multilingual_wikidata_translation_flow.csv"
DATA_MD5 = "7a6fa0bc0f6b335d521c67d87debacbf"
if not os.path.exists(DATA_FILE):
urllib.request.urlretrieve(DATA_URL, DATA_FILE)
with open(DATA_FILE, "rb") as f:
print("checksum OK:", hashlib.md5(f.read()).hexdigest() == DATA_MD5)The data¶
View the data contents. As you can see in the output, there are four columns: timestamp, property, language and type.
Taking an example line from this dataset,
2013-09-10T22:43:54Z,P856,en,labelcorresponds to the action that an English label of Property P856 was added for the first time at 2013-09-10T22:43:54Z.
Following is a description of each column.
timestamp: the time at which an action was made. For example, 2013-09-10T22:43:54Z
property: Wikidata property identifier. It uses the P-number, for example, P856
language: the language in which a label/description/alias was first translated
type: it could be one of the following values: label, description and alias
Creation of the dataframe¶
Three details matter when loading the file:
the header line appears a second time in the middle of the file (the dataset was built by concatenating several exports), so we drop it;
the timestamps are strings: we convert them to real dates once and for all (
pd.to_datetime) instead of parsing each line by hand;everything that follows depends on the chronological order of the rows within a property. The file happens to be sorted, but we sort it explicitly so that the sequences do not depend on the file layout.
dataframe = pd.read_csv(DATA_FILE)
# the header line is repeated inside the file: drop it
dataframe = dataframe[dataframe["timestamp"] != "timestamp"]
# remove duplicates and rows with missing values
dataframe = dataframe.drop_duplicates().dropna()
# parse the dates once, then make the chronological order explicit
dataframe["timestamp"] = pd.to_datetime(dataframe["timestamp"], utc=True)
dataframe = dataframe.sort_values("timestamp", kind="stable").reset_index(drop=True)
print(dataframe)Get a detailed information of the given dataframe. describe(include="all") also summarises the categorical columns (number of distinct values, most frequent value).
display(dataframe.describe(include="all"))
print("properties:", dataframe["property"].nunique())
print("languages:", dataframe["language"].nunique())
print("period:", dataframe["timestamp"].min().date(), "to", dataframe["timestamp"].max().date())
print(dataframe["type"].value_counts())Let us now take a look at the translation of labels in different languages for a given property.
dataframe.loc[(dataframe["property"] == "P856") & (dataframe["type"] == "label")]We will check the data available for a property like P856.
ptranslation = dataframe.loc[(dataframe["property"] == "P856")]
print(ptranslation)You can also add additional conditions to filter out any information. The code below filters out the translation of labels of property P856. Test it with different properties and look at the translation of descriptions and aliases.
Questions. What are your first observations? Which language comes first? How long does it take before the first translations appear?
ptranslation = dataframe.loc[
(dataframe["property"] == "P856") & (dataframe["type"] == "label")
]
print(ptranslation)Visualization of translation¶
Our next goal is to plot the translation of a property and see whether we can observe any translation pattern. Rather than copying the same plotting code for each property, we write one function plot_property with parameters:
pid: the property identifier;y: what to put on the y-axis,"type"(label/description/alias) or"language";languages: an optional list of languages to keep.
Time is always on the x-axis and the colour gives the translation type.
TYPE_COLORS = {"label": "tab:blue", "description": "tab:orange", "alias": "tab:green"}
def plot_property(pid, y="type", languages=None, annotate=True, figsize=None, filename=None):
"""Scatter plot of the translation events of property `pid`: time on x, `y` on the y-axis."""
data = dataframe[dataframe["property"] == pid]
if languages is not None:
data = data[data["language"].isin(languages)]
if figsize is None:
figsize = (14, 4) if y == "type" else (14, 0.25 * data["language"].nunique() + 2)
fig, ax = plt.subplots(figsize=figsize)
for kind, color in TYPE_COLORS.items():
part = data[data["type"] == kind]
ax.scatter(part["timestamp"], part[y], s=30, color=color, label=kind)
# annotate the points with the language code
if annotate and y == "type":
for _, row in data.iterrows():
ax.annotate(row["language"], (row["timestamp"], row["type"]), fontsize=7, rotation=45)
ax.set_xlabel("Time")
ax.set_ylabel(y.capitalize())
ax.set_title(f"Translation of {pid}")
ax.legend(loc="upper right")
if filename:
fig.savefig(filename, bbox_inches="tight")
plt.show()
plot_property("P856", y="type")Now, we plot another graph, this time, language on the y-axis and time on the x-axis.
plot_property("P279", y="language", filename="translation.png")Check the plots concerning properties: P31, P279 and P856 respectively. You can also see that some translations can be even made in a single edit: look for vertical columns of points in the figure of P31.
Questions. What are your observations on the values on the y-axis? Are the languages translated in the same order for the three properties? What could explain the vertical columns?



In the code given below, we select some languages and see the order of translation. Plot the graphs for different properties and note your observations.
# list of languages under consideration
langlist = ["fr", "es", "en", "de", "it", "pt", "ja"]
plot_property("P18", y="language", languages=langlist, figsize=(10, 4))Exercise 1.2¶
We used plotting techniques to manually detect some patterns of translation. Now we use other algorithms to see whether groups of languages are always present together.
We first prepare the language dataset. We will focus on the translation of property labels: for every property, we build the chronological list of the languages in which its label was translated. The function translation_sequences will be reused in the following exercises with kind="description" or kind="alias".
def translation_sequences(dataframe, kind="label"):
"""One chronological list of languages per property, for the given translation type."""
subset = dataframe[dataframe["type"] == kind]
# the dataframe is sorted by time, so each group is already in chronological order
return subset.groupby("property", sort=False)["language"].apply(list)
languageorder = translation_sequences(dataframe, kind="label")
print(languageorder.head())
print(languageorder.loc["P856"])Now we calculate the frequent itemsets using the apriori algorithm. TransactionEncoder turns the list of sequences into a boolean table (one row per property, one column per language). Uncomment the display line to see this intermediate dataframe.
from mlxtend.frequent_patterns import apriori
from mlxtend.preprocessing import TransactionEncoder
te = TransactionEncoder()
te_ary = te.fit(languageorder.tolist()).transform(languageorder.tolist())
df = pd.DataFrame(te_ary, columns=te.columns_)
# display(df)
frequent_itemsets = apriori(df, min_support=0.75, use_colnames=True)
frequent_itemsets.sort_values("support", ascending=False)The program uses a minimum support of 0.75: an itemset is kept if it is present in at least 75% of the properties. English labels are present for all the properties, whereas French labels are only available for about 93% of them. On considering pairs of languages, we see combinations such as (en, ar) or (nl, uk) that are almost always present together. As we go further down, we see combinations of 3, 4, 5 languages.
Questions.
Change the minimum support between 0 and 1 and look at the output. What happens to the number of itemsets and to the computation time when the support decreases?
Repeat the experiment for descriptions and aliases (
translation_sequences(dataframe, kind="description")). Are the same languages present?
Exercise 1.3¶
Our next goal is to generate the association rules, i.e., rules of the form A → C, where A is the antecedent and C is the consequent.
from mlxtend.frequent_patterns import association_rules
association_rules(frequent_itemsets, metric="confidence", min_threshold=0.95)Let’s take a look at one of the association rules, for example (de, fr) → (en): when the French and German translations are available, the English translation is also available, with a confidence close to 1. Note that a high confidence does not mean that the rule is interesting: English is present almost everywhere, so any rule X → (en) has a high confidence. The lift column corrects for this (a lift close to 1 means that A and C are independent).
You can change the metric to "lift" and test.
We will now add two columns that will contain the length of antecedents and consequents. As you may have noticed, association rules are dataframes. So we can easily write filter conditions to get antecedents and consequents of length more than 1.
arules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.95)
arules["antecedent_len"] = arules["antecedents"].apply(len)
arules["consequent_len"] = arules["consequents"].apply(len)
arules.loc[(arules["antecedent_len"] > 1) & (arules["consequent_len"] > 1)]Questions. Repeat the above experiment for the translation of descriptions and aliases. Which rules have the highest lift? Do you find rules between languages that are linguistically or geographically close?
Exercise 1.4¶
Our next goal is to visualize the flow of translation. First, we count, over all the label sequences, how many times a language is directly followed by another one: each consecutive pair (source, target) is one edge of a directed graph, and the number of occurrences is its weight.
def language_pairs(sequences):
"""Count the consecutive (source, target) language pairs of the sequences."""
pairs = [(seq[i], seq[i + 1]) for seq in sequences for i in range(len(seq) - 1)]
flows = pd.DataFrame(pairs, columns=["source", "target"])
return flows.value_counts().reset_index(name="count")
flows = language_pairs(languageorder)
print(flows)Next we visualize them using a circular layout. The graph is directed and the width of an edge is proportional to its weight. We only keep the TOP_EDGES most frequent pairs so that the figure remains readable.
import networkx as nx
TOP_EDGES = 60
top_flows = flows.head(TOP_EDGES)
G = nx.from_pandas_edgelist(top_flows, "source", "target", edge_attr="count", create_using=nx.DiGraph)
pos = nx.circular_layout(G)
widths = [8 * G[u][v]["count"] / top_flows["count"].max() for u, v in G.edges]
plt.figure(figsize=(12, 12))
nx.draw(
G, pos, with_labels=True, width=widths, node_color="lightblue", node_size=1200,
edge_color="gray", arrowsize=15, connectionstyle="arc3,rad=0.1",
)
plt.show()Check the flow of translations for languages of your choice (number of languages > 20): filter flows on source and target, or increase TOP_EDGES.
The chord diagram of Holoviews/Bokeh shows the weights more clearly: the thickness of a ribbon is the number of transitions between the two languages. Hover over a ribbon to read its value.
import holoviews as hv
hv.extension("bokeh")
chord = hv.Chord(top_flows).opts(
width=650, height=650, labels="index", node_color="index", edge_color="source",
cmap="Category20", edge_cmap="Category20", title=f"{TOP_EDGES} most frequent transitions (labels)",
)
chordQuestions. Which language is the main source of the flow? Which languages are mostly targets? Do the transitions found here agree with the association rules of exercise 1.3? Note that an association rule ignores the order, whereas a transition keeps it.
Exercise 1.5: predicting the next language¶
Our final goal is to predict the next language(s) that will be translated, given a sequence of available translations.
Take for example, let’s assume we have seen the following sequences of translation.
[['en', 'it', 'fi', 'fr', 'de', 'nl', 'pt', 'pl', 'ca', 'cs'],
['en', 'it', 'fi', 'fr', 'de', 'ilo', 'zh', 'nb'],
['ru', 'hu', 'he', 'nl', 'pt', 'pl', 'ca', 'cs'],
...]Once your model has been trained using this data, it may be able to predict the next possible translation(s).
Example 1: if the user enters the sequence ['pt'], your model may return ['pl'].
Example 2: if the user enters the sequence ['it', 'fi'], your model may return ['fr'].
Example 3: if the user enters the sequence ['nl', 'pt', 'pl'], your model may return ['ca', 'cs'].
1.5.1 From sequences to a prediction problem¶
Look at the problem again: given the previous “tokens” of a sequence, predict the next one, where a token is a language code. This is exactly the task solved by a language model — the same one that is behind the large language models of today — except that our vocabulary has a few hundred language codes instead of tens of thousands of word pieces. We will therefore follow the same recipe:
build a vocabulary and encode each language as an integer;
cut each sequence into training examples (context → next language);
compare models of increasing complexity on the same test set: counting baselines, a recurrent network, a Transformer.
Two important details:
Splitting: we split the properties (whole sequences) into train / validation / test sets, never the examples. Two examples cut from the same sequence share most of their context, so splitting the examples would leak information from the test set into the training set. The variable
SPLITalso lets you try a temporal split (train on the oldest properties, test on the most recent ones), which is closer to the real use of such a model.Vocabulary: it is built from the training sequences only. A language which only appears in the test set is unknown to the model and is encoded as
<unk>; index 0 is reserved for padding.
The variable KIND selects labels, descriptions or aliases: the exercise must be done for the three types.
from sklearn.model_selection import train_test_split
KIND = "label" # "label", "description" or "alias"
SPLIT = "random" # "random" or "temporal"
MAX_LEN = 20 # number of previous languages given to the model
sequences = translation_sequences(dataframe, kind=KIND)
sequences = sequences[sequences.str.len() >= 2] # a sequence of length 1 gives no example
if SPLIT == "random":
property_ids = sequences.index.to_numpy()
train_ids, test_ids = train_test_split(property_ids, test_size=0.2, random_state=SEED)
val_ids, test_ids = train_test_split(test_ids, test_size=0.5, random_state=SEED)
else:
# order the properties by the date of their first translation
first_seen = dataframe[dataframe["type"] == KIND].groupby("property")["timestamp"].min()
ordered = first_seen.loc[sequences.index].sort_values().index
n = len(ordered)
train_ids, val_ids, test_ids = ordered[: int(0.8 * n)], ordered[int(0.8 * n) : int(0.9 * n)], ordered[int(0.9 * n) :]
print(f"{len(sequences)} sequences: {len(train_ids)} train, {len(val_ids)} validation, {len(test_ids)} test")PAD, UNK = 0, 1
vocab = ["<pad>", "<unk>"] + sorted({lang for pid in train_ids for lang in sequences[pid]})
lang2id = {lang: i for i, lang in enumerate(vocab)}
V = len(vocab)
print("vocabulary size:", V)
def encode(languages):
return [lang2id.get(lang, UNK) for lang in languages]
def make_examples(ids):
"""Cut the sequences into (context of at most MAX_LEN languages, next language) pairs."""
X, y = [], []
for pid in ids:
seq = encode(sequences[pid])
for t in range(1, len(seq)):
if seq[t] == UNK: # an unknown language cannot be predicted: skip
continue
X.append(seq[max(0, t - MAX_LEN) : t])
y.append(seq[t])
# pad on the left so that the most recent language is always in the last column
X = keras.utils.pad_sequences(X, maxlen=MAX_LEN, padding="pre", value=PAD)
return X, np.array(y)
X_train, y_train = make_examples(train_ids)
X_val, y_val = make_examples(val_ids)
X_test, y_test = make_examples(test_ids)
print("examples:", len(X_train), "train,", len(X_val), "validation,", len(X_test), "test")
print("example:", [vocab[i] for i in X_train[5] if i != PAD], "->", vocab[y_train[5]])Metrics¶
Several next languages are often equally plausible, so the exact accuracy (top-1) is a harsh criterion. We also report:
top-5 accuracy: the true language is among the 5 highest scores;
MRR (mean reciprocal rank): the average of 1 / rank of the true language, which rewards a model that puts the right answer high in its ranking.
evaluate takes a matrix of scores (one row per example, one column per language) so that it can be used for all the models below, neural or not.
def evaluate(scores, y, k=5):
"""Ranking metrics from a (n_examples, V) score matrix; higher score = more likely."""
ranking = np.argsort(-scores, axis=1)
rank = np.argmax(ranking == y[:, None], axis=1) + 1 # position of the true language
return {"top-1": np.mean(rank == 1), f"top-{k}": np.mean(rank <= k), "MRR": np.mean(1 / rank)}
results = {}1.5.2 Baselines without learning¶
Before training a neural network, we need to know what a trivial model achieves — otherwise, how would we know that the network has learned something?
Frequency: always predict the most frequent next languages of the training set, whatever the context.
Bigram: predict from the last language only, using the transition counts of exercise 1.4 (with a small additive smoothing so that unseen transitions do not get a zero score). This is a Markov chain.
Association rules: reuse exercise 1.3. For an input sequence, every rule whose antecedent is included in the input votes for its consequent with its confidence. The rules are mined on the training sequences only.
# frequency baseline
frequency = np.bincount(y_train, minlength=V).astype(float)
scores_frequency = np.tile(frequency, (len(X_test), 1))
results["frequency"] = evaluate(scores_frequency, y_test)
# bigram (Markov chain) baseline
ALPHA = 0.1
transitions = np.full((V, V), ALPHA)
np.add.at(transitions, (X_train[:, -1], y_train), 1)
transitions /= transitions.sum(axis=1, keepdims=True)
results["bigram"] = evaluate(transitions[X_test[:, -1]], y_test)
pd.DataFrame(results).T# association rules baseline: mine the rules on the training sequences only
train_sets = [sequences[pid] for pid in train_ids]
te_train = TransactionEncoder()
df_train = pd.DataFrame(te_train.fit(train_sets).transform(train_sets), columns=te_train.columns_)
itemsets_train = apriori(df_train, min_support=0.05, use_colnames=True, max_len=3)
rules = association_rules(itemsets_train, metric="confidence", min_threshold=0.5)
rules = rules[rules["consequents"].apply(len) == 1]
print(len(itemsets_train), "itemsets,", len(rules), "rules")
def rules_scores(X):
"""Each applicable rule votes for its consequent with its confidence."""
present = np.zeros((len(X), V), dtype=bool)
np.put_along_axis(present, X, True, axis=1)
present[:, PAD] = False
scores = np.tile(frequency / frequency.sum(), (len(X), 1)) * 1e-3 # tie-breaker when no rule applies
for antecedent, consequent, confidence in zip(rules["antecedents"], rules["consequents"], rules["confidence"]):
applies = present[:, encode(antecedent)].all(axis=1)
scores[applies, encode(consequent)[0]] += confidence
return scores
results["association rules"] = evaluate(rules_scores(X_test), y_test)
pd.DataFrame(results).T1.5.3 Recurrent neural network¶
The first neural model is the one suggested in the original version of this exercise: an Embedding layer turns each language into a vector of EMBEDDING_DIM numbers, an LSTM reads the sequence of vectors and summarises it, and a Dense layer with a softmax activation gives a probability to each language of the vocabulary. mask_zero=True tells the LSTM to skip the padding (use_cudnn=False is needed on a GPU because the fast cuDNN kernel only supports padding on the right, whereas we pad on the left).
The loss is sparse_categorical_crossentropy because the target is an integer (the index of the next language). We stop the training when the validation loss stops improving (EarlyStopping). Ten epochs take a few minutes on a CPU; increase epochs if the validation curve is still going down.
EMBEDDING_DIM = 32
def build_rnn(units=64):
inputs = keras.Input(shape=(MAX_LEN,), dtype="int32")
x = keras.layers.Embedding(V, EMBEDDING_DIM, mask_zero=True, name="language_embedding")(inputs)
# the cuDNN kernel only accepts right-padded masks; our sequences are left-padded
x = keras.layers.LSTM(units, use_cudnn=False)(x)
x = keras.layers.Dropout(0.2)(x)
outputs = keras.layers.Dense(V, activation="softmax")(x)
return keras.Model(inputs, outputs, name="lstm")
def train(model, x=None, y=None, validation_data=None, epochs=10, batch_size=128,
loss="sparse_categorical_crossentropy", metrics=None):
if x is None: # default: the next-language examples
x, y, validation_data = X_train, y_train, (X_val, y_val)
if metrics is None:
metrics = ["accuracy", keras.metrics.SparseTopKCategoricalAccuracy(k=5, name="top5")]
model.compile(optimizer="adam", loss=loss, metrics=metrics)
early_stopping = keras.callbacks.EarlyStopping(patience=2, restore_best_weights=True)
return model.fit(
x, y, validation_data=validation_data,
epochs=epochs, batch_size=batch_size, callbacks=[early_stopping], verbose=2,
)
def plot_history(history, title, metric="accuracy"):
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
for ax, metric in zip(axes, ["loss", metric]):
ax.plot(history.history[metric], label="train")
ax.plot(history.history["val_" + metric], label="validation")
ax.set_xlabel("epoch")
ax.set_ylabel(metric)
ax.legend()
fig.suptitle(title)
plt.show()
rnn = build_rnn()
rnn.summary()
history_rnn = train(rnn)
plot_history(history_rnn, "LSTM")
results["LSTM"] = evaluate(rnn.predict(X_test, verbose=0), y_test)
pd.DataFrame(results).T1.5.4 Transformer¶
Recurrent networks read the sequence one language at a time. The Transformer (Vaswani et al., 2017) replaces the recurrence by self-attention: every position looks at all the previous positions at once and learns which ones matter for the prediction. It is the architecture of all the current large language models. Two ingredients are needed:
since attention has no notion of order, we add a position embedding to the language embedding (
TokenAndPositionEmbedding);a causal mask so that a position can only attend to the positions before it, combined with a padding mask that hides the padding on the left of the short sequences.
keras.layers.MultiHeadAttention does the heavy lifting: with use_causal_mask=True, it builds the causal mask itself, and we give it the padding mask as attention_mask. The decoder block below is the standard “attention → add & normalise → feed-forward → add & normalise” block. We stack NUM_BLOCKS of them and keep the output of the last position to predict the next language.
class TokenAndPositionEmbedding(keras.layers.Layer):
"""Language embedding + learned position embedding."""
def __init__(self, vocab_size, max_len, d_model, **kwargs):
super().__init__(**kwargs)
self.token_embedding = keras.layers.Embedding(vocab_size, d_model)
self.position_embedding = keras.layers.Embedding(max_len, d_model)
def call(self, x):
positions = keras.ops.arange(0, keras.ops.shape(x)[-1])
return self.token_embedding(x) + self.position_embedding(positions)
class TransformerBlock(keras.layers.Layer):
"""Causal self-attention followed by a feed-forward network, each with a residual connection."""
def __init__(self, d_model, num_heads, ff_dim, dropout=0.1, **kwargs):
super().__init__(**kwargs)
self.attention = keras.layers.MultiHeadAttention(num_heads, d_model // num_heads, dropout=dropout)
self.ffn = keras.Sequential([keras.layers.Dense(ff_dim, activation="relu"), keras.layers.Dense(d_model)])
self.norm1 = keras.layers.LayerNormalization()
self.norm2 = keras.layers.LayerNormalization()
self.dropout = keras.layers.Dropout(dropout)
def call(self, x, padding_mask=None):
attention = self.attention(x, x, attention_mask=padding_mask, use_causal_mask=True)
x = self.norm1(x + self.dropout(attention))
return self.norm2(x + self.dropout(self.ffn(x)))
def build_transformer(d_model=32, num_heads=4, ff_dim=64, num_blocks=2):
inputs = keras.Input(shape=(MAX_LEN,), dtype="int32")
# (batch, 1, MAX_LEN): which keys may be attended to
padding_mask = keras.ops.expand_dims(keras.ops.not_equal(inputs, PAD), 1)
x = TokenAndPositionEmbedding(V, MAX_LEN, d_model, name="language_embedding")(inputs)
for _ in range(num_blocks):
x = TransformerBlock(d_model, num_heads, ff_dim)(x, padding_mask=padding_mask)
x = x[:, -1, :] # representation of the last position
outputs = keras.layers.Dense(V, activation="softmax")(x)
return keras.Model(inputs, outputs, name="transformer")
transformer = build_transformer()
transformer.summary()
history_transformer = train(transformer)
plot_history(history_transformer, "Transformer")
results["Transformer"] = evaluate(transformer.predict(X_test, verbose=0), y_test)
pd.DataFrame(results).T1.5.5 Comparison¶
All the models were evaluated on the same test examples, so the table can be compared line by line.
Questions.
Which baseline is the hardest to beat? Why does the bigram model do so well on this dataset (think about the vertical columns of exercise 1.1)?
Compare the LSTM and the Transformer: accuracy, number of parameters, training time. Change
MAX_LEN(5, 10, 40): which model benefits from a longer context?Is the ranking of the models the same with
SPLIT = "temporal"? Which split do you think is the most honest estimate of the performance on new properties?Repeat with
KIND = "description"andKIND = "alias". Are the sequences as predictable?
comparison = pd.DataFrame(results).T
display(comparison)
comparison.plot.bar(figsize=(10, 4), rot=0, title=f"Next-language prediction ({KIND}, {SPLIT} split)")
plt.ylabel("score on the test set")
plt.show()1.5.6 Using the model¶
predict_next returns the k most probable next languages with their probability. Test the three examples given at the beginning of the exercise.
Question. The model answers en to ['pt'] rather than pl. Why? (Look at which language starts almost every sequence, and think about what the model has seen just before a pt that is not preceded by en.)
def predict_next(model, languages, k=3):
x = keras.utils.pad_sequences([encode(languages)[-MAX_LEN:]], maxlen=MAX_LEN, value=PAD)
probabilities = model.predict(x, verbose=0)[0]
top = np.argsort(-probabilities)[:k]
return [(vocab[i], round(float(probabilities[i]), 3)) for i in top]
for example in [["pt"], ["it", "fi"], ["nl", "pt", "pl"], ["en"], ["en", "fr", "de"]]:
print(example, "->", predict_next(transformer, example))1.5.7 What did the model learn? Language embeddings¶
The Embedding layer has learned one vector per language. Languages that play a similar role in the sequences should end up with similar vectors. We project the vectors of the most frequent languages on two dimensions with a PCA and colour them by language family (obtained from Wikidata, see below). The vectors are normalised first, otherwise the first axis mostly reflects how frequent a language is.
from sklearn.decomposition import PCA
# language family of the most frequent languages, obtained from Wikidata (see 1.5.8)
FAMILY = {
"en": "Germanic", "de": "Germanic", "nl": "Germanic", "sv": "Germanic", "da": "Germanic", "nb": "Germanic",
"nn": "Germanic", "sco": "Germanic", "fr": "Romance", "es": "Romance", "it": "Romance", "pt": "Romance",
"ca": "Romance", "ro": "Romance", "gl": "Romance", "ast": "Romance", "oc": "Romance", "scn": "Romance",
"uk": "Slavic", "ru": "Slavic", "pl": "Slavic", "cs": "Slavic", "sk": "Slavic", "sl": "Slavic", "bg": "Slavic",
"mk": "Slavic", "sr": "Slavic", "bs": "Slavic", "be": "Slavic", "lv": "Baltic", "el": "Hellenic", "cy": "Celtic",
"fa": "Iranian", "bn": "Indo-Aryan", "sq": "Albanian", "hu": "Uralic", "fi": "Uralic", "et": "Uralic",
"tr": "Turkic", "ar": "Semitic", "he": "Semitic", "zh": "Sino-Tibetan", "ja": "Japonic", "ko": "Koreanic",
"id": "Austronesian", "ms": "Austronesian", "vi": "Austroasiatic", "eu": "Basque", "eo": "constructed",
}
def family_of(code):
# "zh-hans", "pt-br", "be-tarask"... share the family of their base language
return FAMILY.get(code, FAMILY.get(code.split("-")[0], "other"))
def plot_embeddings(embeddings, languages, title, min_family_size=2):
# normalise the vectors so that the projection reflects their direction, not the frequency of the language
embeddings = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
points = PCA(n_components=2, random_state=SEED).fit_transform(embeddings)
# only colour the families with several languages in the plot
families = pd.Series([family_of(lang) for lang in languages])
counts = families.value_counts()
families = families.where(families.map(counts) >= min_family_size, "other")
palette = dict(zip(sorted(families.unique()), plt.cm.tab10(np.linspace(0, 1, families.nunique()))))
fig, ax = plt.subplots(figsize=(12, 9))
for family, color in palette.items():
idx = np.where(families == family)[0]
ax.scatter(points[idx, 0], points[idx, 1], color=color, label=family, s=60)
for i, lang in enumerate(languages):
ax.annotate(lang, (points[i, 0], points[i, 1]), fontsize=9, xytext=(3, 3), textcoords="offset points")
ax.set_title(title)
ax.legend(loc="best")
plt.show()
TOP_LANGUAGES = 50
frequent_ids = np.argsort(-frequency)[:TOP_LANGUAGES]
embeddings = rnn.get_layer("language_embedding").get_weights()[0]
plot_embeddings(embeddings[frequent_ids], [vocab[i] for i in frequent_ids], "LSTM language embeddings (PCA)")Questions.
Do languages of the same family end up close to each other? Are the variants of a language (
zh,zh-hans,zh-hant;pt,pt-br;sr,sr-ec,sr-el) close?Which other factor could explain the proximity of two languages in this plot? (Think about who translates the properties: a few very active contributors and bots.)
Plot the embeddings of the Transformer (
transformer.get_layer("language_embedding").token_embedding.get_weights()[0]) and compare.
1.5.8 Adding a symbolic constraint¶
The project rewards the integration of a symbolic component. Here is the simplest possible one: a language that is already in the sequence has already been translated, so it cannot be the next one. A neural network has to learn this rule from the data (and it never learns it perfectly), whereas we can simply enforce it: we set the score of the languages present in the input to zero before ranking. This is a rule applied after the model, so it works with every model of this notebook.
def forbid_seen_languages(scores, X):
"""Rule: a language already present in the input cannot be the next translation."""
scores = scores.copy()
np.put_along_axis(scores, X, -np.inf, axis=1)
scores[:, PAD] = -np.inf
return scores
constrained = {
"frequency": scores_frequency,
"bigram": transitions[X_test[:, -1]],
"association rules": rules_scores(X_test),
"LSTM": rnn.predict(X_test, verbose=0),
"Transformer": transformer.predict(X_test, verbose=0),
}
for name, scores in constrained.items():
results[name + " + rule"] = evaluate(forbid_seen_languages(scores, X_test), y_test)
pd.DataFrame(results).T.sort_values("MRR", ascending=False)Questions.
Which models benefit the most from the rule? Why does the Transformer or the LSTM benefit less than the frequency baseline?
The rule only sees the
MAX_LENlast languages. How would you give it the full sequence?(Bonus) Wikidata knows the family and the script of each language. The query below fetches them with SPARQL (it needs an internet connection: set
USE_WIKIDATA = True). Use them to build a second rule or an additional input feature — for example, “a language of the same family as the last one is more likely” — and measure whether it helps. Whether it helps or not, explain why: the answer tells you something about how Wikidata is really translated.
USE_WIKIDATA = False
SPARQL = """
SELECT ?code (GROUP_CONCAT(DISTINCT ?familyLabel; separator="|") AS ?families)
(GROUP_CONCAT(DISTINCT ?scriptLabel; separator="|") AS ?scripts) WHERE {
VALUES ?code { %s }
?lang wdt:P424 ?code . # Wikimedia language code
?lang wdt:P1394 ?glottolog . # keep languages (not language variants)
OPTIONAL { ?lang wdt:P279+ ?family . ?family wdt:P31 wd:Q25295 .
?family rdfs:label ?familyLabel FILTER(LANG(?familyLabel) = "en") }
OPTIONAL { ?lang wdt:P282 ?script . ?script rdfs:label ?scriptLabel FILTER(LANG(?scriptLabel) = "en") }
} GROUP BY ?code
"""
if USE_WIKIDATA:
import io
import requests
codes = " ".join(f'"{vocab[i]}"' for i in frequent_ids)
response = requests.get(
"https://query.wikidata.org/sparql",
params={"query": SPARQL % codes},
headers={"Accept": "text/csv", "User-Agent": "IA-DeepLearning-miniproject/1.0"},
)
language_info = pd.read_csv(io.StringIO(response.text))
display(language_info)1.5.9 To go further¶
Sequence → set. Example 3 expects two languages. Turn the problem into a multi-label one: predict the set of the next
klanguages with a sigmoid output and abinary_crossentropyloss, and evaluate with precision@k.Attention weights. Call
MultiHeadAttentionwithreturn_attention_scores=Trueand display, for a given input, which previous languages the last position attends to.Large language models. Ask an LLM (zero-shot) to predict the next language of a few test sequences and compare its answers with those of your models. Which one knows the habits of the Wikidata community? Remember that the use of AI assistants must be cited in the project report.
Please comment your code and write down your observations: what is the maximum length of the input sequence? What are the metrics of each model? Why did you choose a given architecture and hyperparameters?
Exercise 1.6: why is the accuracy so low, and what can be done about it?¶
A top-1 accuracy of about 23% looks poor. Before trying bigger models, a data scientist asks two questions: is the task actually predictable from these inputs? and what information is the model missing? This exercise answers both, then changes the inputs and the target of the model accordingly. It trains three more Transformers: about 3 minutes on a GPU, 15 on a CPU.
1.6.1 Diagnosis¶
Three things to look at:
How much time passes between two consecutive translations? If the next translation arrives months later, it is made by whoever happens to visit the property, and the sequence tells us little about it.
Does the answer change over the years? The Wikidata community, its tools and its bots changed a lot between 2013 and 2019. If the most likely language after
enis different every year, a model that does not know the year has to average over all of them.How uncertain is the next language, at best? The conditional entropy H(next | previous) measures the uncertainty that remains once the previous language is known. 2^H is the number of equally likely languages it corresponds to: this is the ceiling that any model using only the previous language can reach.
We also compare the training and validation accuracy of the Transformer: if they are equal, the model is not overfitting; it is limited by its inputs, not by its size.
events = dataframe[dataframe["type"] == KIND].copy()
by_property = events.groupby("property", sort=False)
events["previous_language"] = by_property["language"].shift()
events["gap"] = (events["timestamp"] - by_property["timestamp"].shift()).dt.total_seconds()
events = events.dropna(subset=["previous_language"]) # keep the events that are prediction targets
# 1. time between consecutive translations
gap = events["gap"]
print(f"same second as the previous translation: {(gap == 0).mean():.1%}")
print(f"within one hour: {(gap <= 3600).mean():.1%}")
print(f"more than 30 days later: {(gap > 30 * 86400).mean():.1%}")
# 2. the most frequent language after "en", year by year
after_en = events[events["previous_language"] == "en"]
most_common = lambda s: f"{s.mode()[0]} ({s.value_counts(normalize=True).iloc[0]:.0%})"
print("\nmost frequent language after 'en':")
print(after_en.groupby(after_en["timestamp"].dt.year)["language"].agg(most_common).to_string())
# 3. conditional entropy of the next language given the previous one
p = events.groupby("previous_language")["language"].value_counts(normalize=True)
entropy = -(p * np.log2(p)).groupby(level=0).sum()
weights = events["previous_language"].value_counts(normalize=True)
H = (entropy * weights.reindex(entropy.index)).sum()
print(f"\nH(next | previous) = {H:.2f} bits: as uncertain as a choice among {2 ** H:.0f} equally likely languages")
# 4. is the Transformer overfitting?
print(f"\nTransformer accuracy - train: {history_transformer.history['accuracy'][-1]:.3f}, "
f"validation: {history_transformer.history['val_accuracy'][-1]:.3f}")Questions.
What fraction of the targets are “independent visits” (more than a month after the previous translation)? What can a sequence model say about them?
Read the table year by year: which language dominates in 2017? What does this suggest about who (or which bot) was translating that year?
With a conditional entropy of about 5 bits, what top-1 accuracy would you expect from a bigram model? Compare with the value obtained in exercise 1.5. Is the Transformer far from the ceiling of its inputs?
Since the models do not overfit, the way forward is to give them better inputs (1.6.2, 1.6.3) or to ask them a better question (1.6.4).
1.6.2 Giving the model time¶
The models of exercise 1.5 only see language codes. We add two features that are known at prediction time:
the year of the last known translation;
the time elapsed between the two last known translations, on a logarithmic scale (0: same second, 2: minutes, 5: a day, 7: months), as a proxy for the activity around the property.
Each feature gets its own small embedding, concatenated to the representation of the sequence produced by the Transformer. transformer_features rebuilds the body of the Transformer of 1.5.4 so that the same architecture can be reused with different inputs and outputs.
timestamps = dataframe[dataframe["type"] == KIND].groupby("property", sort=False)["timestamp"].apply(list)
YEARS = sorted(dataframe["timestamp"].dt.year.unique())
GAP_BUCKETS = 10
def make_examples_with_time(ids):
X, years, gaps, y = [], [], [], []
for pid in ids:
seq, times = encode(sequences[pid]), timestamps[pid]
for t in range(1, len(seq)):
if seq[t] == UNK:
continue
X.append(seq[max(0, t - MAX_LEN) : t])
y.append(seq[t])
years.append(times[t - 1].year - YEARS[0]) # year of the last known translation
seconds = (times[t - 1] - times[t - 2]).total_seconds() if t >= 2 else 0
gaps.append(min(int(np.log10(seconds + 1)), GAP_BUCKETS - 1))
X = keras.utils.pad_sequences(X, maxlen=MAX_LEN, padding="pre", value=PAD)
return [X, np.array(years), np.array(gaps)], np.array(y)
def transformer_features(inputs, vocab_size, d_model=32, num_heads=4, ff_dim=64, num_blocks=2):
"""The Transformer of 1.5.4 without its output layer: returns the representation of the last position."""
padding_mask = keras.ops.expand_dims(keras.ops.not_equal(inputs, PAD), 1)
x = TokenAndPositionEmbedding(vocab_size, MAX_LEN, d_model)(inputs)
for _ in range(num_blocks):
x = TransformerBlock(d_model, num_heads, ff_dim)(x, padding_mask=padding_mask)
return x[:, -1, :]
def build_transformer_with_time():
languages = keras.Input(shape=(MAX_LEN,), dtype="int32", name="languages")
year = keras.Input(shape=(), dtype="int32", name="year")
gap = keras.Input(shape=(), dtype="int32", name="gap")
x = keras.layers.Concatenate()([
transformer_features(languages, V),
keras.layers.Embedding(len(YEARS), 8)(year),
keras.layers.Embedding(GAP_BUCKETS, 8)(gap),
])
outputs = keras.layers.Dense(V, activation="softmax")(x)
return keras.Model([languages, year, gap], outputs, name="transformer_with_time")
Xt_train, yt_train = make_examples_with_time(train_ids)
Xt_val, yt_val = make_examples_with_time(val_ids)
Xt_test, yt_test = make_examples_with_time(test_ids)
print("same targets as in 1.5:", np.array_equal(yt_test, y_test))
transformer_time = build_transformer_with_time()
history_time = train(transformer_time, Xt_train, yt_train, (Xt_val, yt_val))
plot_history(history_time, "Transformer + time")
results["Transformer + time"] = evaluate(transformer_time.predict(Xt_test, verbose=0), y_test)
pd.DataFrame(results).T.loc[["bigram", "LSTM", "Transformer", "Transformer + time"]]Questions.
How many points does the time information bring? Which of the two features matters most? (Train a model with only one of them.)
With
SPLIT = "temporal", the test properties are all from 2019, a year the model has hardly seen. What happens to the gain? Is this a limitation of the feature or of the evaluation?
1.6.3 One stream for labels, descriptions and aliases¶
Until now, the label model never sees the descriptions and aliases, although they are added by the same people at the same moments: a French description that just arrived is a strong hint that a French label is coming. We rebuild the context as the stream of all events of the property, each encoded as a type:language token, while the target remains the next label language. The targets are exactly the same as before, so the results are comparable.
all_events = dataframe[dataframe["property"].isin(sequences.index)]
stream = (all_events["type"] + ":" + all_events["language"]).groupby(all_events["property"], sort=False).apply(list)
stream_types = all_events.groupby("property", sort=False)["type"].apply(list)
stream_languages = all_events.groupby("property", sort=False)["language"].apply(list)
stream_vocab = ["<pad>", "<unk>"] + sorted({token for pid in train_ids for token in stream[pid]})
token2id = {token: i for i, token in enumerate(stream_vocab)}
print("stream vocabulary size:", len(stream_vocab))
def make_stream_examples(ids):
X, y = [], []
for pid in ids:
tokens = [token2id.get(token, UNK) for token in stream[pid]]
labels_seen = 0
for i, kind in enumerate(stream_types[pid]):
if kind != KIND:
continue
target = lang2id.get(stream_languages[pid][i], UNK)
if labels_seen >= 1 and target != UNK: # same condition as make_examples
X.append(tokens[max(0, i - MAX_LEN) : i])
y.append(target)
labels_seen += 1
X = keras.utils.pad_sequences(X, maxlen=MAX_LEN, padding="pre", value=PAD)
return X, np.array(y)
Xs_train, ys_train = make_stream_examples(train_ids)
Xs_val, ys_val = make_stream_examples(val_ids)
Xs_test, ys_test = make_stream_examples(test_ids)
print("same targets as in 1.5:", np.array_equal(ys_test, y_test))
inputs = keras.Input(shape=(MAX_LEN,), dtype="int32")
outputs = keras.layers.Dense(V, activation="softmax")(transformer_features(inputs, len(stream_vocab)))
transformer_stream = keras.Model(inputs, outputs, name="transformer_all_types")
history_stream = train(transformer_stream, Xs_train, ys_train, (Xs_val, ys_val))
plot_history(history_stream, "Transformer on all types")
results["Transformer + all types"] = evaluate(transformer_stream.predict(Xs_test, verbose=0), y_test)
pd.DataFrame(results).T.loc[["Transformer", "Transformer + time", "Transformer + all types"]]Questions.
Does the extra context help? Note that with
MAX_LEN = 20, the window now covers fewer labels than before: tryMAX_LEN = 40.Combine the two improvements (all types + time) in a single model.
1.6.4 Asking a better question: the next set of languages¶
Example 3 of exercise 1.5 already hinted at it: what we really want to know is which languages will come next, not in which exact order. When five people translate a property in the same week, the order among them is arbitrary, and a model predicting “the next one” is penalised for a mistake that nobody cares about.
We therefore change the target: for each position, the set of languages among the next K = 5 translations. This is a multi-label classification: the output layer uses a sigmoid per language and the loss is binary_crossentropy. The metrics are precision@5 (how many of the 5 predicted languages are in the true set) and recall@5 (how many of the true set are among the 5 predicted).
The models of 1.5 can be scored on this new target too, by taking their 5 most probable languages: this shows how much comes from the new formulation itself and how much from training for it.
K = 5
def make_set_targets(ids):
"""Multi-hot target: the languages among the next K translations (aligned with make_examples)."""
Y = []
for pid in ids:
seq = encode(sequences[pid])
for t in range(1, len(seq)):
if seq[t] == UNK:
continue
target = np.zeros(V, dtype="float32")
target[[s for s in seq[t : t + K] if s != UNK]] = 1
Y.append(target)
return np.array(Y)
def evaluate_set(scores, Y, k=K):
top = np.argsort(-scores, axis=1)[:, :k]
hits = np.take_along_axis(Y, top, axis=1)
return {f"precision@{k}": hits.mean(), f"recall@{k}": (hits.sum(axis=1) / Y.sum(axis=1)).mean()}
Y_train, Y_val, Y_test = make_set_targets(train_ids), make_set_targets(val_ids), make_set_targets(test_ids)
print("average size of the target set:", Y_test.sum(axis=1).mean().round(2))
inputs = keras.Input(shape=(MAX_LEN,), dtype="int32")
outputs = keras.layers.Dense(V, activation="sigmoid")(transformer_features(inputs, V))
transformer_set = keras.Model(inputs, outputs, name="transformer_next_set")
history_set = train(
transformer_set, X_train, Y_train, (X_val, Y_val),
loss="binary_crossentropy", metrics=[keras.metrics.Precision(top_k=K, name="precision")],
)
plot_history(history_set, "Transformer, next set of languages", metric="precision")
set_results = {
"frequency": evaluate_set(scores_frequency, Y_test),
"bigram": evaluate_set(transitions[X_test[:, -1]], Y_test),
"Transformer (next one)": evaluate_set(transformer.predict(X_test, verbose=0), Y_test),
"Transformer (next set)": evaluate_set(transformer_set.predict(X_test, verbose=0), Y_test),
}
pd.DataFrame(set_results).TFinally, the symbolic rule of 1.5.8 applies to any of these models: it only needs the scores and the input sequence. We add it on top of the best model.
results["Transformer + time + rule"] = evaluate(
forbid_seen_languages(transformer_time.predict(Xt_test, verbose=0), X_test), y_test
)
pd.DataFrame(results).T.loc[["Transformer", "Transformer + rule", "Transformer + time", "Transformer + time + rule"]]1.6.5 Taking stock¶
Questions.
Summarise in a table what each change brought: time features, all types, next-set target. Which one would you recommend to someone who wants to use such a model on Wikidata, and why?
The neural models are not overfitting. Which hyperparameters would you nevertheless try (
d_model,num_blocks,epochs, learning rate, label smoothing), and what gain do you expect, given the diagnosis of 1.6.1? Try one of them and report.Apply the symbolic rule of 1.5.8 to the next-set model:
forbid_seen_languagesworks on its scores too. Does the gain differ from the one obtained on the next-language model?Which piece of information, absent from this dataset, would most likely change the picture? What would be the ethical and practical implications of collecting it?