You're working on a really interesting problem! You want to place four apples (agents) in a 2D space such that each apple tries to be the closest to as many of the user-placed dots as possible. And you want them to compete — so they should partition the space and "own" regions, ideally dividing the dots evenly among themselves.
You’re using gradient descent, which means you need a differentiable loss function for each apple that encourages it to move toward areas with lots of unclaimed dots, while also avoiding overlapping with other apples.
Let’s break this down and suggest a continuous, differentiable, competitive objective function per apple that does what you want without manual balancing.
🧠 Key Concepts
- Each dot will belong to the nearest apple.
- Apples are competing — if two apples are near the same dot, only one gets credit.
- Goal: Maximize number of dots closest to each apple → equivalent to minimizing a loss based on how far away an apple is from its claimed dots, plus a repulsion term from other apples.
But how do we make this differentiable?
✅ Solution: Softmax Approximation of Nearest Apple
We can use a soft approximation of "which apple is closest to a dot" via softmax or exponentials. This gives us a differentiable proxy for competition.
Let:
- xi∈R2 be the position of apple i
- dj∈R2 be the position of dot j
For each dot dj, define a responsibility weight for each apple:
wij=∑
Where:
- wij is the "soft" assignment weight of apple i to dot j
- β controls how sharp the softmax is (higher = more like argmin)
This assigns most weight to the apple closest to the dot.
Now define the loss for apple i as:
Li=j=1
Explanation:
- First term: Encourages apple i to stay close to the dots it's responsible for (weighted by soft assignment).
- Second term: Repels apple i from other apples — inverse squared distance ensures strong gradients when apples get too close.
- No manual balancing needed because both terms are about relative distances; the repulsive force naturally prevents clustering.
🔁 Gradient Descent Update
Each apple updates via gradient descent:
xi←xi−η∇
Where η is the learning rate.
The gradient ∇xiLi includes:
- Pulling toward the weighted center of its assigned dots
- Pushing away from other apples
This leads to natural competition, without needing to manually tune weights between attraction/repulsion.
📈 Behavior Over Time
- Initially, apples spread out due to repulsion.
- Then they settle into positions where each attracts ~25% of the dots.
- If there's an uneven distribution of dots, the apples will still adjust accordingly.
- The softmax weighting allows smooth transitions and avoids hard thresholds.
🧪 Optional Enhancements
- Use temperature scaling β to control softness over time (start soft, get harder).
- Add momentum or Adam optimizer to stabilize movement.
- For visualization, color each dot by the dominant apple (i.e., highest wij).
🧮 Python Pseudocode (PyTorch-like)
import torch
dots = torch.randn(100, 2, requires_grad=False)
apples = torch.randn(4, 2, requires_grad=True)
beta = 10.0
lambda_repulsion = 0.1
optimizer = torch.optim.Adam([apples], lr=0.01)
for _ in range(1000):
optimizer.zero_grad()
losses = []
for i in range(4):
dists = torch.sum((apples[i] - dots) ** 2, dim=1)
all_dists = torch.stack([torch.sum((a - dots) ** 2, dim=1) for a in apples])
weights = torch.softmax(-beta * all_dists, dim=0)[i]
# Attraction term
attraction = torch.sum(weights * dists)
# Repulsion term
repulsion = 0
for j in range(4):
if i != j:
repulsion += 1.0 / torch.sum((apples[i] - apples[j]) ** 2)
loss_i = attraction + lambda_repulsion * repulsion
losses.append(loss_i)
total_loss = sum(losses)
total_loss.backward()
optimizer.step()
Note: You could compute this more efficiently using broadcasting instead of loops.
✅ Summary
Use a softmax-based responsibility weight combined with inverse-square repulsion to create a continuous, differentiable, competitive loss function for your apples. This setup:
- Naturally partitions the space
- Prevents apples from overlapping
- Doesn't require manual balancing
- Scales well with more dots or agents
Let me know if you'd like help visualizing this or turning it into a full interactive game!