0

More than 5 years have passed since last update.

Posted at

# 概要

raspberry pi 1でtensorflow liteやってみた。
tfliteファイルを作ってみた。
sessionから作ってみた。
データセットは、xor.

tensorflow 1.12

# モデルを学習してsessionをtfliteファイルに変換する。

``````import tensorflow as tf
import tensorflow.contrib.lite as lite
import numpy as np

X = [[0, 0], [0, 1], [1, 0], [1, 1]]
Y = [[1, 0], [0, 1], [0, 1], [1, 0]]
x = tf.placeholder(tf.float32, shape = [None, 2], name = "input")
y = tf.placeholder(tf.float32, shape = [None, 2], name = "output")
w1 = tf.Variable(tf.random_uniform([2, 2], -1, 1, seed = 0))
w2 = tf.Variable(tf.random_uniform([2, 2], -1, 1, seed = 0))
b1 = tf.Variable(tf.zeros([2]))
b2 = tf.Variable(tf.zeros([2]))
h1 = tf.sigmoid(tf.matmul(x, w1) + b1)
h2 = tf.nn.softmax(tf.matmul(h1, w2) + b2)
cost = -tf.reduce_sum(y * tf.log(h2))
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(10000):
sess.run(opti, feed_dict = {
x: X,
y: Y
})
for i in [[1, 1], [1, 0], [0, 1], [0, 0]]:
print (i, sess.run(h2, feed_dict = {
x: [i],
}))
converter = lite.TFLiteConverter.from_session(sess, [x], [h2])
tflite_model = converter.convert()
open("xor1_model.tflite", "wb").write(tflite_model)
``````

# tfliteファイルを用いて、検証する。

``````import numpy as np
import tensorflow as tf
import tensorflow.contrib.lite as lite

interpreter = lite.Interpreter(model_path = "xor1_model.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print (input_details)
print (output_details)
input_shape = input_details[0]['shape']
input_data = np.array([[0.0, 0.0]], dtype = np.float32)
print(input_data)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print (output_data)
input_data = np.array([[1.0, 0.0]], dtype = np.float32)
print(input_data)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print (output_data)
input_data = np.array([[0.0, 1.0]], dtype = np.float32)
print(input_data)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print (output_data)
input_data = np.array([[1.0, 1.0]], dtype = np.float32)
print(input_data)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print (output_data)
``````

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