TensorFlow linear regression model calculations

Beginner TensorFlow

Not much to say directly bonded to the code

Copy of the code, comments, their own understanding, welcomed the exchange

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

def normalize(X):
    """"Normalize the array"""
    mean = np.mean(X)
    std = np.std(X);
    X = (X-mean)/std
    return X

boston = tf.contrib.learn.datasets.load_dataset("boston")
#   http://c.biancheng.net/view/1906.html

boston = tf.contrib.learn.datasets.load_dataset('boston'Import data#)
X_train, Y_train boston.data = [:,. 5], boston.target # data samples assignment 
N_SAMPLES = len (X_train) # reads the number of the training set 
X-tf.placeholder = (tf.float32, name = ' X- ' ) # variable Definition model =====> model W * = X + Y B 
the Y = tf.placeholder (tf.float32, name = ' the Y ' ) 
B = tf.Variable (0.0 ) 
W = tf.Variable ( 0.0 )
 # define end 

Y_hat = * W + X- B 
loss = tf.square (the Y - Y_hat, name = ' loss ' ) # define loss function
= tf.train.GradientDescentOptimizer Optimizer (learning_rate = 0.01) .minimize (Loss) # optimal solution for the loss function, the present process is the key to solving the optimal operational function 
init_op tf.global_variables_initializer = () # initialize 
Total = [] 
tf.Session with () AS Sess: # use with the method calculates the tf.Session () returns the result is placed in Sess 
    sess.run (init_op)   # initialization run 
    Writer = tf.summary.FileWriter ( ' Graph ' , Sess .graph) # generates operation log file, the algorithm can be viewed constructed ===> to view: at the command line D: \ PythonProject \ TensorFlow> tensorboard --logdir = graph, graph Filewriter input parameters will return the URL of replication paste 
    for I in Range (100 ): 
        total_loss =0
         for X, Y in ZIP (X_train, Y_train): 
            _, L = sess.run ([Optimizer, Loss], = {X-feed_dict: X, the Y: Y}) # calculated error value 
            total_loss = L + # this is "L" return error accumulates 
        total.append (total_loss / N_SAMPLES) # not explained 
        Print ( ' Epoch {0}: Loss. 1 {} ' .format (I, total_loss / N_SAMPLES)) 
    writer.Close () 
    b_value, w_value = sess.run ([B, W]) 
y_pred = X_train w_value * + b_value
 Print ( ' the Done ' )
plt.plot(X_train, Y_train, 'bo',label='Real data')
plt.plot(X_train, Y_pred, 'r', label='Predicted Data')
plt.legend()
plt.show()
plt.plot(total)
plt.show()

 

Guess you like

Origin www.cnblogs.com/JasssonNill-CNSDJN2011-2018/p/11334984.html