# XAI Experiment 9: CBOW Word Embeddings and Gradient × Input  [lab notebook version]
# Requires: exam: none (math, random) | lab: tensorflow
# ===========================================================================

import math

vocab = ["the", "movie", "was", "good", "bad"]
weights = [0.1, 0.2, 0.1, 2.0, -2.0]
bias = 0

x = [1, 1, 1, 1, 0]

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

def prediction(x):
    w = 0

    for i in range(len(weights)):
        w += weights[i]*x[i]

    return sigmoid(w)

def gradient_input(x):
    predict = prediction(x)
    attributions = []

    for i in range(len(x)):
        grad = predict * (1-predict) * weights[i]

        attributions.append(grad*x[i])

    return attributions

gradient_input(x)

import tensorflow as tf
import numpy as np

# Vocabulary
vocabulary = ["the", "movie", "was", "good", "bad"]

word_to_index = {}

for i in range(len(vocabulary)):
    word_to_index[vocabulary[i]] = i

vocab_size = len(vocabulary)
embedding_dim = 2

# Corpus
sentences = [
    "the movie was good",
    "the movie was bad"
]

# Create training data
X = []
Y = []

for sentence in sentences:
    words = sentence.split()

    for i in range(1, len(words) - 1):

        context = [
            word_to_index[words[i-1]],
            word_to_index[words[i+1]]
        ]

        target = word_to_index[words[i]]

        X.append(context)
        Y.append(target)

X = np.array(X)
Y = np.array(Y)

print("Training Data:")
print(X)
print(Y)


# CBOW Model
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(
        input_dim=vocab_size,
        output_dim=embedding_dim,
        input_length=2
    ),

    tf.keras.layers.GlobalAveragePooling1D(),

    tf.keras.layers.Dense(vocab_size, activation="softmax")
])


# Compile model
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.05),
    loss="sparse_categorical_crossentropy"
)


history = model.fit(
    X,
    Y,
    epochs=1000,
    verbose=0
)


# Display loss
for i in range(0, 1000, 100):
    print("Epoch:", i, "Loss:", history.history["loss"][i])


W = model.layers[0].get_weights()[0]

print("\nLearned Word Embeddings:")

for i in range(vocab_size):
    print(vocabulary[i], W[i])

import tensorflow as tf
import numpy as np

# Select input context
context = np.array([[0, 2]])  # the, was

# Select target word
target_word = 1  # movie

# Get embedding layer
embedding_layer = model.layers[0]

# Calculate Gradient x Input
with tf.GradientTape() as tape:

    # Convert context words into embeddings
    embeddings = embedding_layer(context)

    # Watch the embeddings
    tape.watch(embeddings)

    # Average the context embeddings
    h = tf.reduce_mean(embeddings, axis=1)

    # Pass through output layer
    prediction = model.layers[2](h)

    # Select probability of target word
    output = prediction[0][target_word]

# Calculate gradients
gradients = tape.gradient(output, embeddings)

# Gradient x Input
attributions = gradients * embeddings

# Display results
print("Predicted Probability:", output.numpy())

print("\nGradient x Input:")

for i in range(len(context[0])):

    word_index = context[0][i]

    word = vocabulary[word_index]

    score = tf.reduce_sum(attributions[0][i]).numpy()

    print(word, ":", round(float(score), 5))
