Hope is a Dream. Dream is a Hope.

非公開ブログは再開しました。

Vagrant+UbuntuでTensorFlow1.x 環境構築 (その2)

Vagrant+UbuntuでTensorFlow1.x 環境構築 (その2)

前回はVagrantで構築したUbuntu環境にPython3+TensorFlow環境を自分で入れました. しかし,今後は同じ環境をAWS上の複数のインスタンスに作ることを考えると手間がかかってしかたありません. そこで,Vagrantを使って仮想マシンの構築と,Python環境構築を自動で実施したいと思います.

ファイル構成はこち

/--MyVagrant 
  -- Vagrantfile
  -- data/
      -- tf_mnist_test.py

Vagrantfileには,python3をインストールする項目を追加しておきます. これで,Vagrant仮想マシンが作られる工程でPython3環境も作られます.

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
   config.vm.provision "shell", inline: <<-SHELL
     sudo apt-get update
     sudo apt-get install -y python3-pip python3-dev python-virtualenv
     sudo pip3 install --upgrade pip
     sudo pip3 install --upgrade tensorflow
     # sudo pip install keras
     cd /vagrant/data
     sudo python3 /vagrant/data/tf_mnist_test.py > /vagrant/data/log.txt 2>&1
   SHELL
end

tf_mnist_test.py

"""
USAGE
python3 /vagrant/data/tf_mnist_test.py > /vagrant/data/log.txt 2>&1
"""

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)

y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

上を準備した上で,

$ vagrant up

でセットアップされます. セットアップが終わったらSSHで入って,MNISTの解析が無事に終わっているか確認しましょう

$ vagrant statsu

$ vagrant ssh

$ cat /vagrant/data/log.txt

エラーが起きてなければ成功! 以上.

次回は,AWSインスタンスを動かします.