LoginSignup
0
0

More than 5 years have passed since last update.

convnetjsとtensorflow その4

Last updated at Posted at 2017-04-26

概要

MNIST問題をconvnetjsとtensorflowでやってみた。

学習データの用意

データ

MNSIT

ラベル

MNIST

モデルの作成

分類 classification です。

入力、出力

convnetjsの場合

{
    type: 'input',
    out_sx: 24,
    out_sy: 24,
    out_depth: 1
}
{
    type: 'softmax',
    num_classes: 10
}

tensorflowの場合

n_input = 784
n_classes = 10
x = tf.placeholder("float", [None, n_input], name = 'x')
y = tf.placeholder("float", [None, n_classes], name = 'y')

重みとバイアス

convnetjsの場合

{
    type: 'conv',
    sx: 5,
    filters: 8,
    stride: 1,
    pad: 2,
    activation: 'relu'
}
{
    type: 'pool',
    sx: 2,
    stride: 2
}
{
    type: 'conv',
    sx: 5,
    filters: 16,
    stride: 1,
    pad: 2,
    activation: 'relu'
}
{
    type: 'pool',
    sx: 3,
    stride: 3
}

tensorflowの場合

def multilayer_perceptron(x, weights, biases):
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}
pred = multilayer_perceptron(x, weights, biases)

活性化関数を使う

convnetjsの場合

activation: 'relu'

tensorflowの場合

layer_1 = tf.nn.relu(layer_1)

ロス値を定義

convnetjsの場合

stats.loss;

tensorflowの場合

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = pred, labels = y))

最適化の方法定義

convnetjsの場合

var trainer = new convnetjs.Trainer(net);

tensorflowの場合

optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)

セッションを定義して学習する。
convnetjsの場合

var x = sample.x;
var y = sample.label;
var stats = trainer.train(x, y);

tensorflowの場合

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(training_epochs):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict = {
                x: batch_x,
                y: batch_y
            })

グラフとデータのセーブ

convnetjsの場合

JSON.stringify(net.toJSON());

tensorflowの場合

minimal_graph = convert_variables_to_constants(sess, sess.graph_def, ['accuracy'])
tf.train.write_graph(minimal_graph, './', 'trained_graph.pb', as_text = False)

グラフとデータの復帰

convnetjsの場合

var json = JSON.parse(jsonString);
net = new convnetjs.Net();
net.fromJSON(json);

tensorflowの場合

with graph.as_default():
    with open('trained_graph.pb', 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name = '')

テストデータで取り出す。

convnetjsの場合

var aavg = new convnetjs.Vol(1, 1, num_classes, 0.0);
var xs = [].concat(sample.x);
var n = xs.length;
for (var i = 0; i < n; i++) 
{
      var a = net.forward(xs[i]);
      aavg.addFrom(a);
}

tensorflowの場合

print("ans:", sess.run([correct_prediction], feed_dict = {
    x: mnist.test.images
}))

サンプルコード

convnetjsの場合の学習
http://jsdo.it/ohisama1/20xy
convnetjsの場合の分類
http://jsdo.it/ohisama1/UALE
tensorflowの場合
https://github.com/ohisama/tensorflow-tegaki

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