0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

kerasでbackend その8

Posted at

概要

kerasのbackendで、sin問題やってみた。

実行結果

sin0.png

サンプルコード

from tensorflow.contrib.keras.python.keras import backend as K
from tensorflow.contrib.keras.python.keras.optimizers import SGD
import numpy as np
import matplotlib.pyplot as plt

dx = np.arange(-3, 3, 0.1)
dy = np.sin(dx)
input_dim = 1
output_dim = 1
hidden_dim = 8
x = K.placeholder(shape = (None, input_dim), name = "x")
ytrue = K.placeholder(shape = (None, output_dim), name = "y")
W1 = K.random_uniform_variable((input_dim, hidden_dim), 0, 1, name = "W1")
W2 = K.random_uniform_variable((hidden_dim, output_dim), 0, 1, name = "W2")
b1 = K.random_uniform_variable((hidden_dim, ), 0, 1, name = "b1")
b2 = K.random_uniform_variable((output_dim, ), 0, 1, name = "b2")
params = [W1, b1, W2, b2]
hidden = K.tanh(K.dot(x, W1) + b1)
ypred = K.tanh(K.dot(hidden, W2) + b2)
loss = K.mean(K.square(ypred - ytrue), axis = -1)
opt = SGD()
updates = opt.get_updates(params, [], loss)
train = K.function(inputs = [x, ytrue], outputs = [W1, b2, loss], updates = updates)
for ep in range(2000):
	for i in range(60):
		c1, c2, c3 = train([[[dx[i]]], [[dy[i]]]])
	if ep % 100 == 0:
		print (ep, c3[0])
test = K.function(inputs = [x], outputs = [ypred])
p = []
for i in range(60):
	preds = test([[[dx[i]]]])
	p.append(preds[0][0])
plt.plot(dx, dy, 'b', dx, p, 'r--')
plt.savefig("./sin0.png")
plt.show()



以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?