2017年 03月 14日
そのexeconce()を呼び出して脳内情報を得て、matplot
libを利用して図示しよう。plt.figure(figsize=(16,12))
figure()により、図に関するさまざまな事を指定できる。for idx in range(9):
print("exec ",idx)
ans = execonce()
ansx1 = ans[0:50,0]
ansy1 = ans[0:50,1]
ansx2 = ans[50:100,0]
ansy2 = ans[50:100,1]
ansx3 = ans[100:150,0]
ansy3 = ans[100:150,1]
plt.subplot(3,3,idx+1)
plt.scatter(ansx1,ansy1,c="r",alpha=0.5,linewidth=0)
plt.scatter(ansx2,ansy2,c="g",alpha=0.5,linewidth=0)
plt.scatter(ansx3,ansy3,c="b",alpha=0.5,linewidth=0)
ansx1,ansy1,…の部分は、3種類のIrisに合わせて、3つのx座標、y座標に分けているだけ。#!/usr/bin/env python
# from http://nlp.dse.ibaraki.ac.jp/~shinnou/book/chainer.tgz
import numpy as np
import chainer
from chainer import cuda, Function, gradient_check, Variable
from chainer import optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
import matplotlib.pyplot as plt
# Set data
from sklearn import datasets
iris = datasets.load_iris()
xtrain = iris.data.astype(np.float32)
# Define model
class MyAE(Chain):
def __init__(self):
super(MyAE, self).__init__(
l1=L.Linear(4,2),
l2=L.Linear(2,4),
)
def __call__(self,x):
bv = self.fwd(x)
return F.mean_squared_error(bv, x)
def fwd(self,x):
fv = F.sigmoid(self.l1(x))
bv = self.l2(fv)
return bv
def execonce():
# Initialize model
model = MyAE()
optimizer = optimizers.SGD()
optimizer.setup(model)
# Learn
n = 150
for j in range(3000):
x = Variable(xtrain)
model.cleargrads() # model.zerograds()
loss = model(x)
loss.backward()
optimizer.update()
# get middle layer data
x = Variable(xtrain, volatile='on')
yt = F.sigmoid(model.l1(x))
ans = yt.data
return ans
# 本体:9回実行し、グラフ出力
plt.figure(figsize=(16,12))
for idx in range(9):
print("exec ",idx)
ans = execonce()
ansx1 = ans[0:50,0]
ansy1 = ans[0:50,1]
ansx2 = ans[50:100,0]
ansy2 = ans[50:100,1]
ansx3 = ans[100:150,0]
ansy3 = ans[100:150,1]
plt.subplot(3,3,idx+1)
plt.scatter(ansx1,ansy1,c="r",alpha=0.5,linewidth=0)
plt.scatter(ansx2,ansy2,c="g",alpha=0.5,linewidth=0)
plt.scatter(ansx3,ansy3,c="b",alpha=0.5,linewidth=0)
plt.savefig("irisautoencode.png")
plt.show()