Skip to content

Instantly share code, notes, and snippets.

@tonyroberts
Last active November 29, 2019 16:27
Show Gist options
  • Save tonyroberts/e3b5a8c534fae13373f54779a904d98a to your computer and use it in GitHub Desktop.
Save tonyroberts/e3b5a8c534fae13373f54779a904d98a to your computer and use it in GitHub Desktop.
from pyxll import xl_func, xl_app
import matplotlib.pyplot as plt
import numpy as np
import torch
@xl_func
def nn_Run(net, image_name, scale=1, offset=-0.5, seed=None):
"""Run the neural network with random weights"""
# Set the seed for the RNG
seed = int(seed) if seed is not None else torch.random.initial_seed()
torch.manual_seed(seed)
# Initialize the weights
def init_weights(m):
if isinstance(m, nn.Linear):
nn.init.normal_(m.weight)
net.apply(init_weights)
# Find the Excel image
xl = xl_app()
sheet = xl.Caller.Worksheet
image = sheet.Pictures(image_name)
# Get the image size in pixels
size_x, size_y = get_image_size(image)
# Create the inputs
inputs = np.zeros((size_y, size_x, 2))
for x in np.arange(0, size_x, 1):
for y in np.arange(0, size_y, 1):
scaled_x = scale * ((float(x) / size_x) + offset)
scaled_y = scale * ((float(y) / size_y) + offset)
inputs[y][x] = np.array([scaled_x, scaled_y])
inputs = inputs.reshape(size_x * size_y, 2)
# Compute the results
result = net(torch.tensor(inputs).type(torch.FloatTensor)).detach().numpy()
result = result.reshape((size_y, size_x, 3))
# Create a temporary file to write the result to
file = create_temporary_file(suffix=".png")
# Write the image to the file
plt.imsave(file, result)
file.flush()
# Replace the old image with the new one
new_image = sheet.Shapes.AddPicture(Filename=file.name,
LinkToFile=0, # msoFalse
SaveWithDocument=-1, # msoTrue
Left=image.Left,
Top=image.Top,
Width=image.Width,
Height=image.Height)
image_name = image.Name
image.Delete()
new_image.Name = image_name
return f"[{new_image.Name}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment