Skip to content

Instantly share code, notes, and snippets.

@steveway
Created November 14, 2017 17:09
Show Gist options
  • Select an option

  • Save steveway/8b5617410a6933efc6f924edf93eac10 to your computer and use it in GitHub Desktop.

Select an option

Save steveway/8b5617410a6933efc6f924edf93eac10 to your computer and use it in GitHub Desktop.
from pybrain.structure import FeedForwardNetwork
from pybrain.structure import LinearLayer, SigmoidLayer
from pybrain.structure import FullConnection
from pybrain.rl.agents import LearningAgent
from PIL import Image, ImageDraw, ImageFont, ImageOps
import numpy as np
import copy
def mse(imageA, imageB):
# the 'Mean Squared Error' between the two images is the
# sum of the squared difference between the two images;
# NOTE: the two images must have the same dimension
err = np.sum((imageA - imageB) ** 2)
err /= float(imageA.shape[0])
# return the MSE, the lower the error, the more "similar"
# the two images are
return err
def render(input_arr):
output = input_arr
out_im = Image.new("RGBA", (128,128), color = (0xFF,0xFF,0xFF,0xFF))
d = ImageDraw.Draw(out_im)
fnt = ImageFont.truetype('unifont-10.0.06.ttf', 8, encoding="utf-32")
for charac, i in zip(output, range(len(output))):
x = 8 * int(i %16)
y = 8 * int(i/16)
try:
d.text((x,y),unichr(max(0,min(0xffffffff,int(charac)))),font=fnt,fill=(0x00,0x00,0x00,0xff))
except:
pass
out_arr = np.array(out_im.convert("L").resize((32,32))).flatten()
return out_arr, out_im
def main():
in_layer = LinearLayer(32*32)
hidden_layer = SigmoidLayer(32*32)
out_layer = LinearLayer(16*16)
n = FeedForwardNetwork()
n.addInputModule(in_layer)
n.addModule(hidden_layer)
n.addOutputModule(out_layer)
in_to_hidden = FullConnection(in_layer, hidden_layer)
hidden_to_out = FullConnection(hidden_layer, out_layer)
n.addConnection(in_to_hidden)
n.addConnection(hidden_to_out)
n.sortModules()
im = Image.open("7ae.jpg").convert("L").resize((32,32))
im_array = np.array(im).flatten()
print(n.activate(im_array))
print(n.activate(im_array))
m = n
n.mutate()
print(n.activate(im_array))
print(m.activate(im_array))
print(n.activate(im_array))
output = n.activate(im_array)
out_arr, out_im = render(output)
old_comp_val = mse(out_arr,im_array)
print(old_comp_val)
curr_out_array = out_arr
curr_out_im = out_im
for i in range(200):
if i % 20 == 0:
print(old_comp_val)
m = n.copy()
m.mutate()
output = m.activate(im_array)
out_arr, out_im = render(output)
comp_val = mse(out_arr,im_array)
#print(comp_val)
if comp_val <= old_comp_val:
n = m.copy()
old_comp_val = comp_val
curr_out_array = out_arr
curr_out_im = out_im
print(comp_val)
# d = ImageDraw.Draw(curr_out_im)
# fnt = ImageFont.truetype('unifont-10.0.06.ttf', 20, encoding="utf-32")
# d.text((0,0),unichr(0x2307),font=fnt,fill=(0x00,0x00,0x00,0xff))
curr_out_im.convert("L").resize((32,32)).show()
im.show()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment