text
stringlengths
1
93.6k
return dy.transpose(exp) * params
def linear_layer(exp, weights, biases=None):
""" Linear layer with weights and biases.
Inputs:
exp (dy.Expression): A Dynet tensor.
params (dy.Parameters): Dynet parameters representing weights (a matrix).
biases (dy.Parameters, optional): Dynet parameters representing biases
(a vector).
Returns:
dy.Expression representing exp * weights + biases
"""
if biases:
return dy.affine_transform([add_dim(biases),
add_dim(exp) if is_vector(exp) else exp,
weights])
else:
return linear_transform(exp, weights)
def compute_loss(gold_seq,
scores,
index_to_token_maps,
gold_tok_to_id,
noise=0.00000001):
""" Computes the loss of a gold sequence given scores.
Inputs:
gold_seq (list of str): A sequence of gold tokens.
scores (list of dy.Expression): Expressions representing the scores of
potential output tokens for each token in gold_seq.
index_to_tok_maps (list of dict str->list of int): Maps from index in the
sequence to a dictionary mapping from a string to a set of integers.
gold_tok_to_id (lambda (str, str)->list of int): Maps from the gold token
and some lookup function to the indices in the probability distribution
where the gold token occurs.
noise (float, optional): The amount of noise to add to the loss.
Returns:
dy.Expression representing the sum of losses over the sequence.
"""
assert len(gold_seq) == len(scores)
assert len(index_to_token_maps) == len(scores)
losses = []
for i, gold_tok in enumerate(gold_seq):
score = scores[i]
token_map = index_to_token_maps[i]
gold_indices = gold_tok_to_id(gold_tok, token_map)
assert len(gold_indices) > 0
if len(gold_indices) == 1:
losses.append(dy.pickneglogsoftmax(score, gold_indices[0]))
else:
prob_of_tok = dy.zeroes(1)
probdist = dy.softmax(score)
for index in gold_indices:
prob_of_tok += probdist[index]
prob_of_tok += noise
losses.append(-dy.log(prob_of_tok))
return dy.esum(losses)
def get_seq_from_scores(scores, index_to_token_maps):
"""Gets the argmax sequence from a set of scores.
Inputs:
scores (list of dy.Expression): Sequences of output scores.
index_to_token_maps (list of list of str): For each output token, maps
the index in the probability distribution to a string.
Returns:
list of str, representing the argmax sequence.
"""
seq = []
for score, tok_map in zip(scores, index_to_token_maps):
assert score.dim()[0][0] == len(tok_map)
seq.append(tok_map[np.argmax(score.npvalue())])
return seq
def per_token_accuracy(gold_seq, pred_seq):
""" Returns the per-token accuracy comparing two strings (recall).
Inputs:
gold_seq (list of str): A list of gold tokens.
pred_seq (list of str): A list of predicted tokens.
Returns:
float, representing the accuracy.
"""
num_correct = 0
for i, gold_token in enumerate(gold_seq):
if i < len(pred_seq) and pred_seq[i] == gold_token:
num_correct += 1