日本語

This is program made in Python (basic 014) article in Japanese.
This is a sample of tensorflow ver1.15 (not tensorflow ver2).
- Data of csv file is loaded (1st row is x-axis, 2nd row is y-axis).
- Regression line (y = a * x + b) is obtained through machine learning.
- The original data is plotted and the line from machine learning is displayed.

■ Example
■ Code
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as mp

DATA_SIZE=30
MAX_DATA=120
MIN_DATA=1
FILENAME="sampleCode002_tensorflow_leastsquare_ANSI.csv"

learning_rate = 0.00001
training_epochs = 100000
batch_size = 1
display_step = 100

##############################################################################################################
# csvファイルの入力、データ変換
##############################################################################################################
data = np.loadtxt(FILENAME, delimiter=",")

x_axis_data = [[0] for i in range(DATA_SIZE)]
y_axis_data = [[0] for i in range(DATA_SIZE)]

for index in range(len(data)):
      x_axis_data[index][0] = data[index][0]

for index in range(len(data)):
      y_axis_data[index][0] = data[index][1]

x_axis_tf = []
y_axis_tf = []

##############################################################################################################
# tensorflowの部分
###############################################################################################################
def inference(input_data):
    init = tf.constant_initializer(value=0)
    W = tf.get_variable("W", [1, 1], initializer=init)
    b = tf.get_variable("b", [1, 1], initializer=init)
    output = tf.matmul(input_data, W) + b
    return output

def loss(output, actual_data):
    loss = 1 / 2 * tf.reduce_sum(tf.math.square(actual_data - output))
    return loss

def training(cost, global_step):
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    train_op = optimizer.minimize(cost, global_step=global_step)
    return train_op

with tf.Graph().as_default():
    input_data = tf.placeholder("float", [None, 1])
    actual_data = tf.placeholder("float", [None, 1])
    output = inference(input_data)
    cost = loss(output, actual_data)
    global_step = tf.Variable(0, name="global_step", trainable=False)
    train_op = training(cost, global_step)
    init_op = tf.global_variables_initializer()
    sess = tf.Session()
    sess.run(init_op)

    for epoch in range(training_epochs):
        avg_cost = 0
        total_batch = int(len(x_axis_data) / batch_size)
        for i in range(0, total_batch, batch_size):
            minibatch_xy = np.array(x_axis_data[i:i + batch_size])
            minibatch_z = np.array(y_axis_data[i:i + batch_size])
            sess.run(train_op, feed_dict={input_data: minibatch_xy, actual_data: minibatch_z})
            avg_cost += sess.run(
                cost, feed_dict={input_data: minibatch_xy, actual_data: minibatch_z}
            )

        if epoch % display_step == 0:
            print("Epoch: {:04d} cost: {:.9f}".format(epoch + 1, avg_cost))
            print("Optimization Finished!")

##############################################################################################################
# x軸に対してtensorflowからyの値を得る。
#############################################################################################################

    for var in range(MIN_DATA, MAX_DATA, 1):
        result = sess.run(output, feed_dict={input_data: [[var]]})
        y_axis_tf.append(result[0])
        x_axis_tf.append(var)

##############################################################################################################
# グラフ表示
##############################################################################################################
    mp.plot(x_axis_tf, y_axis_tf, color="orange")
    mp.scatter(x_axis_data, y_axis_data, marker='.')
    mp.grid()
    mp.show()