ML Simulation

Machine Learning simulation for neuroplasticity
 avatar
unknown
python
2 months ago
2.6 kB
4
Indexable
import numpy as np
import matplotlib.pyplot as plt
import imageio.v2 as imageio

# initialise neurons with random positions and apply padding
neurons = np.random.rand(100, 2)
neurons[:, 0] = neurons[:, 0] * (1 - 2 * 0.125) + 0.125
neurons[:, 1] = neurons[:, 1] * (1 - 0.125 - 0.2) + 0.2

# links, weights, and activations
links = []
weights = np.zeros((100, 100))
activations = np.random.rand(100)

# load brain image
backgroundImage = imageio.imread('/Users/jackd/Desktop/neuroplasticity/brain.png')

# plot neurons and links
def plotNeurons(neurons, links, weights, f, color='g', sizeMultiplier=1):
    fig, ax = plt.subplots(figsize=(8, 8))
    ax.imshow(backgroundImage, extent=[0, 1, 0, 1], aspect='auto')
    ax.scatter(neurons[:, 0], neurons[:, 1], c='black', s=100 * sizeMultiplier)
    for link in links:
        n1, n2 = link
        weight = weights[n1, n2]
        ax.plot([neurons[n1, 0], neurons[n2, 0]], [neurons[n1, 1], neurons[n2, 1]], f'{color}-', alpha=weight)
    ax.axis('off')
    plt.savefig(f'frames/frame_{f}.png', bbox_inches='tight', pad_inches=0)
    plt.close()

for f in range(15):
    activations = np.random.rand(100)
    for i in range(100):
        for j in range(i + 1, 100):
            if np.random.rand() > 0.9:
                if (i, j) not in links:
                    links.append((i, j))
                weights[i, j] += activations[i] * activations[j] * 0.1
                weights[j, i] = weights[i, j]
    plotNeurons(neurons, links, weights, f, color='g')

# create gif from frames
with imageio.get_writer('/Users/jackd/Desktop/neuroplasticity/neurons.gif', mode='I', duration=1.5, loop=0) as writer:
    for f in range(15):
        image = imageio.imread(f'frames/frame_{f}.png')
        writer.append_data(image)

for f in range(15):
    for i in range(100):
        for j in range(i + 1, 100):
            if (i, j) not in links:
                links.append((i, j))
                weights[i, j] += np.random.rand() * 0.1
                weights[j, i] = weights[i, j]
    sizeMultiplier = 1 + f * 2
    plotNeurons(neurons, links, weights, f + 15, color='r', sizeMultiplier=sizeMultiplier)

# add blank screen to end
plt.figure(figsize=(8, 8))
plt.axis('off')
plt.savefig(f'frames/frame_{15 + 15}.png', bbox_inches='tight', pad_inches=0)
plt.close()

# create gif from exploding brain frames
with imageio.get_writer('/Users/jackd/Desktop/neuroplasticity/neurons_exploding.gif', mode='I', duration=1.5, loop=0) as writer:
    for f in range(15 + 1):
        image = imageio.imread(f'frames/frame_{f + 15}.png')
        writer.append_data(image)
Leave a Comment