import numpy as np
import chainer
import chainer.links as L
from chainer import Chain, Variable
from chainer import datasets

class SOM(Chain):
    def __init__(self, width):
        self.width = width
        super(SOM,self).__init__(
            competitive = L.Linear(None,self.width*self.width, nobias=True)
        )
    def predict(self,x):
        ip = self.competitive(x)
        pos = np.argmax(ip.data)
        return pos/self.width, pos%self.width
    def __neighbor(self, center, var):
        y = np.abs(np.arange(-center[0], self.width - center[0]))
        x = np.abs(np.arange(-center[1], self.width - center[1]))
        xx, yy = np.meshgrid(x,y)
        d2 = xx**2 + yy**2
        return np.exp(-d2/(2*(var**2)))

    def incr_learn(self, x, lr=0.1, var=4.0, reinforce=True):
        pos = self.predict(x)
        delta_x = (lr * self.__neighbor(pos, var).reshape(1, -1)).T.dot(x.data)

def main():
    pass

if __name__ == '__main__':
    main()

@@ -901,29 +901,1319 @@
 ta)%0A
-%0Adef main():%0A    pass
+        delta_w = (lr * self.__neighbor(pos, var).reshape(1, -1)).T * self.competitive.W.data%0A        self.competitive.W.data += delta_x if reinforce else - delta_x%0A        self.competitive.W.data += delta_w if reinforce else - delta_w%0A%0A    def weight_show(self, in_width, ch):%0A        show_array = np.zeros((in_width * self.width, in_width*self.width, ch),dtype=float32)%0A        for i, c in enumerate(self.competitive.W.data):%0A            y = i / self.width%0A            x = i %25 self.width%0A            if ch == 3:%0A                show_array%5By*in_width:(y+1)*in_width, x*in_width:(x+1)*in_width%5D = cv2.cvtColor(np.rollaxis(c.reshape(ch, in_width, in_width), 0, 3), cv2.COLOR_RGB2BGR)%0A            else:%0A                show_array%5By*in_width:(y+1)*in_width, x*in_width:(x+1)*in_width%5D = c.reshape(in_width, in_width)%0A        cv2.imshow('win', show_array)%0A        cv2.waitKey(1)%0A%0A%0Adef main():%0A    som = SOM(width=10)%0A    train, test = datasets.get_mnist()%0A%0A    for it, tr in enumerate(train):%0A        if it %25 5000 == 0:%0A            print('Iteration: %7B0%7D'.format(it))%0A%0A        x = Variable(np.array(%5Btr%5B0%5D%5D, dtype=np.float32))%0A%0A        lr = 0.05 * (1.0 - float(it) / len(train))%0A        lr = 2.0 * (1.0 - float(it) / len(train))%0A%0A        som.incr_learn(x, lr=lr, var=var)%0A%0A        som.weight_show(in_width=28, ch =1)
 %0A%0Aif

Add main function.