Realize linear fitting with my algorithm -tensorflow.

TensorFlow™ It is an open source software library for high performance numerical computation. With its flexible architecture, users can easily deploy computing to multiple platforms (CPU, GPU, TPU) and devices (desktop devices, server clusters, mobile devices, edge devices, etc.). TensorFlOw @ was originally developed by researchers and engineers on the Google Brain team, which is part of Google’s AI division, to provide strong support for machine learning and in-depth learning, and its flexible numerical computing core is widely used in many other scientific disciplines.field

Next, we will illustrate by a simple example of linear fitting.

The first step is to create a batch of Gauss distribution data through np.random.normal.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf


num_points = 1000
vector_sector = []

# Create 1000 points
for num_point in range(num_points):
    x = np.random.normal(0.0, 0.55)
    y = x*0.1 + 0.3 + np.random.normal(0, 0.03)
    vector_sector.append([x, y])
#Add assignment operation
x_data = [v[0] for v in vector_sector]
y_data = [v[1] for v in vector_sector]

Second step: initialization parameter and mean square error of using estimated value and real value to represent loss.

W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
# A b value with an initial value of 0 is generated.
b = tf.Variable(tf.zeros([1]), name='b')
# Constructing linear functions
y = W * x_data + b
print(np.shape(y))
# The mean square error between the estimated y and the actual value y_data is used as a loss.
loss = tf.reduce_mean(tf.square(y-y_data), name='loss')

The third step is to initialize the model and iterate to reduce loss and optimize the model.

optimizer = tf.train.GradientDescentOptimizer(0.5)
# When training, this parameter is minimized.
train = optimizer.minimize(loss)

#Initialization
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
# Print current value
print('W', sess.run(W), 'b', sess.run(b), 'loss', sess.run(loss))

#Cycle 20 times, train train, reduce loss
for i in range(20):
    sess.run(train)
    print(print('W', sess.run(W), 'b', sess.run(b), 'loss', sess.run(loss)))

The fourth step: making the fitting curve.

# Fitting curves for scatter plots
plt.scatter(x_data, y_data, c='r')
plt.plot(x_data, x_data*sess.run(W)+ sess.run(b))
plt.show()

 

Leave a Reply

Your email address will not be published. Required fields are marked *