def sigmoid(x):
return 1 / (1 + np.exp(-x)) if x >= 0 else np.exp(x) / (1 + np.exp(x))
# re-initialisation propre pour le modele negative-sampling
W = rng.normal(0, 0.1, (V, D)); Wp = rng.normal(0, 0.1, (V, D))
b = np.zeros(D); bp = np.zeros(V)
def negsample_loss_grad(tgt, pos, negs):
"""1 positif (pos) + k negatives (negs), tout en sigmoïdes."""
h = W[tgt] + b
x = Wp[pos] @ h + bp[pos]
loss = np.logaddexp(0.0, -x)
dWp = np.zeros_like(Wp); dbp = np.zeros(V); dh = np.zeros(D)
g = sigmoid(x) - 1.0 # positif : pousse x vers +inf
dWp[pos] += g * h; dbp[pos] += g; dh += g * Wp[pos]
for n in negs: # negatif : pousse x vers -inf
xn = Wp[n] @ h + bp[n]
loss += np.logaddexp(0.0, xn)
g = sigmoid(xn)
dWp[n] += g * h; dbp[n] += g; dh += g * Wp[n]
return loss, (dh, dWp, dh, dbp)
def sample_negatives(vocab_size, pos, tgt, k, generator):
"""Tire exactement k indices admissibles, avec remplacement."""
if k < 0:
raise ValueError("k doit être positif ou nul")
pool = np.array([i for i in range(vocab_size) if i != pos and i != tgt], dtype=int)
if k and not len(pool):
raise ValueError("aucun indice négatif admissible")
return generator.choice(pool, size=k, replace=True) if k else np.array([], dtype=int)
# Une fixture sans aléa fragile : un seul négatif admissible et répétitions.
assert np.array_equal(sample_negatives(3, 0, 1, 5, np.random.default_rng(80)), [2]*5)
assert len(sample_negatives(2, 0, 1, 0, np.random.default_rng(1))) == 0
try:
sample_negatives(2, 0, 1, 1, np.random.default_rng(1))
except ValueError:
print("sampler : cardinalité et domaine validés")
else:
raise AssertionError("le domaine vide doit être refusé")
# Les doublons contribuent chacun au gradient ; vérifier leur somme par différence finie.
_saved = (W.copy(), Wp.copy(), b.copy(), bp.copy())
W[:] = 0; Wp[:] = 0; b[:] = 0; bp[:] = 0
W[0, 0] = 1; Wp[1, 0] = -30; Wp[2, 0] = 30
_loss, (_dwt, _dwp, _db, _dbp) = negsample_loss_grad(0, 1, [2, 2])
for row in (1, 2):
old = Wp[row, 0]; Wp[row, 0] = old + 1e-5; plus = negsample_loss_grad(0, 1, [2, 2])[0]
Wp[row, 0] = old - 1e-5; minus = negsample_loss_grad(0, 1, [2, 2])[0]; Wp[row, 0] = old
assert np.isclose(_dwp[row, 0], (plus-minus)/2e-5, atol=1e-7)
W[:], Wp[:], b[:], bp[:] = _saved
print("SGNS extrême et négatifs répétés : différences finies validées")
# Différences finies à l'initialisation, avant mise à jour de W ou W'.
def check_sgns_initial(tgt, pos, negs, eps=1e-5):
_, (dwt, dwp, db, dbp) = negsample_loss_grad(tgt, pos, negs)
max_error = 0.0
for param, analytic in ((W[tgt], dwt), (Wp, dwp), (b, db), (bp, dbp)):
for index in np.ndindex(param.shape):
original = param[index]
param[index] = original + eps; plus = negsample_loss_grad(tgt, pos, negs)[0]
param[index] = original - eps; minus = negsample_loss_grad(tgt, pos, negs)[0]
param[index] = original
max_error = max(max_error, abs(analytic[index] - (plus-minus)/(2*eps)))
return max_error
err_sgns = check_sgns_initial(0, 1, [2, 2, 3, 4, 5])
assert err_sgns < 1e-4
print(f"SGNS initial avec doublon : erreur maximale {err_sgns:.2e}")
def train_negsample(epochs=60, lr=0.05, k=5):
global W, Wp, b, bp
losses = []
for e in range(epochs):
tl = 0.0
for i in rng.permutation(len(pairs)):
ctx, tgt = pairs[i]
pos = ctx[0]
# Tirage uniforme avec remplacement dans le domaine admissible.
negs = sample_negatives(V, pos, tgt, k, rng)
loss, (dWt, dWp, db, dbp) = negsample_loss_grad(tgt, pos, negs)
W[tgt] -= lr*dWt; Wp -= lr*dWp; b -= lr*db; bp -= lr*dbp
tl += loss
losses.append(tl / len(pairs))
return losses
ns_losses = train_negsample()
print(f"echantillonnage negatif — perte : {ns_losses[0]:.3f} -> {ns_losses[-1]:.3f}")