Last active
February 14, 2017 04:09
-
-
Save paraya3636/ac1ba5c43faa01bcc14405648f172fac to your computer and use it in GitHub Desktop.
与えられた値を2倍にする by Python3.5 & Chainer1.12
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env/ python | |
# coding:utf-8 | |
import numpy as np | |
import chainer.links as L | |
from chainer import functions as F | |
from chainer import Variable, optimizers, Chain | |
class Model(Chain): | |
def __init__(self): | |
super(Model, self).__init__( | |
l1=L.Linear(1, 1), | |
) | |
def __call__(self, x): | |
h = self.l1(x) | |
return h | |
# モデル定義 | |
model = Model() | |
optimizer = optimizers.SGD() | |
optimizer.setup(model) | |
# 学習させる回数 | |
times = 50 | |
# 学習用データ | |
x = Variable(np.atleast_2d(np.array([[1], [2], [7]], dtype=np.float32))) | |
# 正解データ(入力されたデータを2倍にしたい) | |
t = Variable(np.atleast_2d(np.array([[2], [4], [14]], dtype=np.float32))) | |
# 学習ループ | |
for i in range(0, times): | |
# 勾配を初期化 | |
optimizer.zero_grads() | |
# ここでモデルに予測させている | |
y = model(x) | |
# モデルが出した答えを表示 | |
print(y.data) | |
# 損失を計算する | |
loss = F.MeanSquaredError()(y, t) | |
# 逆伝播する | |
loss.backward() | |
# optimizerを更新する | |
optimizer.update() | |
# 学習済みモデルに対してデータを入力 | |
print("result") | |
x = Variable(np.atleast_2d(np.array([[3], [4], [5]], dtype=np.float32))) | |
y = model(x) | |
print(y.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment