Tensorflow the trained model predictions

This section covers the point:

  1. From the command line parameter read demand prediction data
  2. Reading data from a file prediction
  3. Reading data from an arbitrary string prediction

First, data is read from the command line parameter prediction is required

 Is to train the neural network neural network with availability, the real neural network, you need to predict the new input data,

 These training data as input data is not a target value (standard answer), but need to get the results predicted by the neural network computing.

 

Input data from the command line parameters:

 

Import numpy AS NP
 Import SYS 

predictData = None 
argt = the sys.argv [. 1 :] 

# Get command cycle parameter is determined for each line parameters, and to find out whether there is "-predict =" as the start character string 
# member function startswith determining whether to begin another specified string 
# if removed "-predict =" prefix, just take back the remaining string 
#   tmpStr = V [len ( "- = Predict")] function is equal to the command so tmpStr remove the line head character parameter v "-predict =" after the 
# action len () is to obtain the length of any string 
# use numpy package fromstring function to convert the string to an array tmpStr   
for v in argt:
     IF v.startswith ( " -predict = " ): 
        tmpStr = V [len (" -Predict = " ) : ] Note the use of the slice #
         Print ( " tmpStr:% S " % tmpStr) 
        predictData = np.fromstring (tmpStr, DTYPE = np.float32, On Sep = " , " ) 

Print ( " predictData: S% " % predictData)

Results are as follows:

 

 Use Anaconda to perform this procedure:

 

# Numpy string into an array function np.fromstring (tmpStr, dtype = np.float32,    sep = ",")

TmpStr refers to a string, the character "" as a separator, into a data array within the data item type is an array float32

 

Call the trained neural network to predict:

import tensorflow as tf
import numpy as np
import random
import os
import sys

ifRestartT = False

predictData = None

argt = sys.argv[1:]

for v in argt:
    if v == "-restart":
        ifRestartT = True
    if v.startswith("-predict="):
        tmpStr = v[len("-predict="):]
        predictData = np.fromstring(tmpStr, dtype=np.float32, sep=",")

print("predictData: %s""=
TranrisultfthPredictdt)
%./save/idcard2"

random.seed()

x = tf.placeholder(tf.float32)
yTrain = tf.placeholder(tf.float32)

w1 = tf.Variable(tf.random_normal([4, 8], mean=0.5, stddev=0.1), dtype=tf.float32)
b1 = tf.Variable(0, dtype=tf.float32)

xr = tf.reshape(x, [1, 4])

n1 = tf.nn.tanh(tf.matmul(xr, w1) + b1)

w2 = tf.Variable(tf.random_normal([8, 2], mean=0.5, stddev=0.1), dtype=tf.float32)
b2 = tf.Variable(0, dtype=tf.float32)

n2 = tf.matmul(n1, w2) + b2

y = tf.nn.softmax(tf.reshape(n2, [2]))

loss = tf.reduce_mean(tf.square(y - yTrain))

optimizer = tf.train.RMSPropOptimizer(0.01)

train = optimizer.minimize(loss)

sess = tf.Session()

if ifRestartT:
    print("force restart...")
    sess.run(tf.global_variables_initializer())
elif os.path.exists(trainResultPath + ".index"):
    print("loading: %s" % trainResultPath)
    tf.train.Saver () Restore (Sess, the save_path. = trainResultPath)
 the else :
     Print ( " Train Result Not EXISTS path:% S " % trainResultPath) 
    sess.run (tf.global_variables_initializer ()) 

IF predictData None Not IS: 
    Result sess.run = ([X, Y], feed_dict = {X: predictData}) 
    Print (Result [. 1]) 
    Print (y.eval (= Sess the session, feed_dict = {X: predictData})) # the second output neural network computing results, explain below
     sys.exit (0) # terminate the program

# If predictData data is "None", then continue training
# else illustrate the need to read the data from the command line parameters have been predicted, then it is called the neural network to predict the output end of the program
lossSum
= 0.0 for i in Range (. 5 ): xDataRandom= [int(random.random() * 10), int(random.random() * 10), int(random.random() * 10), int(random.random() * 10)] if xDataRandom[2] % 2 == 0: yTrainDataRandom = [0, 1] else: yTrainDataRandom = [1, 0] result = sess.run([train, x, yTrain, y, loss], feed_dict={x: xDataRandom, yTrain: yTrainDataRandom}) lossSum = lossSum + float(result[len(result) - 1]) print("i: %d, loss: %10.10f, avgLoss: %10.10f" % (i, float(result[len(result) - 1]), lossSum / (i + 1))) if os.path.exists("save.txt"): os.remove("save.txt") print("saving...") tf.train.Saver().save(sess, save_path=trainResultPath) resultT = input('Would you like to save? (y/n)') if resultT == "y": print("saving...") tf.train.Saver().save(sess, save_path=trainResultPath)

print(y.eval(session=sess, feed_dict={x: predictData}))

 Eval function is called directly tensor of y, and the session parameters named objects Sess incoming sessions, need to predict the incoming feed_dict named parameter input data, calculation results can be obtained in y

 

Note: calculated using neural networks, do not need to pass the target yTrain, you do not need to specify the variables in the results of the training function of the array trian sess.run

 

 

 

Second, data is read from a file prediction

Suppose this file in the directory of program execution:

 

 

 

Import tensorflow TF AS
 Import numpy AS NP
 Import Random
 Import OS
 Import SYS 

ifRestartT = False 

predictData = None 

argt = the sys.argv [. 1 :]
 # Similarly, to obtain the command line parameters, traversal from front forget, if "-file =" , reads from the parameter specifies the data file 
# after reading the data into predictData but this time, predictData will be a two-dimensional array, where each row represents a row of data file 
# for consistency, we have command line parameters "-predict =" predicted input data specified also put into a two-dimensional array of square brackets [] Although only one row 
# use predictData.shape [0] number of rows acquired two-dimensional array 
# because the array form, that is an array, where the subscript represents the number of its rows is the number 0 
for V in argt:
     IF v == "-restart":
        ifRestartT = True
    if v.startswith("-file="):
        tmpStr = v[len("-file="):]
        print(tmpStr)
        predictData = np.loadtxt(tmpStr, dtype=np.float32, delimiter=",")
        predictRowCount = predictData.shape[0]
        print("predictRowCount: %s" % predictRowCount)
    if v.startswith("-predict="):
        tmpStr = v[len("-predict="):]
        predictData = [np.fromstring(tmpStr, dtype=np.float32, sep=",")]

print("predictData: %s" % predictData)

trainResultPath = "./save/idcard2"

random.seed()

x = tf.placeholder(tf.float32)
yTrain = tf.placeholder(tf.float32)

w1 = tf.Variable(tf.random_normal([4, 8], mean=0.5, stddev=0.1), dtype=tf.float32)
b1 = tf.Variable(0, dtype=tf.float32)

xr = tf.reshape(x, [1, 4])

n1 = tf.nn.tanh(tf.matmul(xr, w1) + b1)

w2 = tf.Variable(tf.random_normal([8, 2], mean=0.5, stddev=0.1), dtype=tf.float32)
b2 = tf.Variable(0, dtype=tf.float32)

n2 = tf.matmul(n1, w2) + b2

y = tf.nn.softmax(tf.reshape(n2, [2]))

loss = tf.reduce_mean(tf.square(y - yTrain))

optimizer = tf.train.RMSPropOptimizer(0.01)

train = optimizer.minimize(loss)

sess = tf.Session()

if ifRestartT:
    print("force restart...")
    sess.run(tf.global_variables_initializer())
elif os.path.exists(trainResultPath + ".index"):
    print("loading: %s" % trainResultPath)
    tf.train.Saver().restore(sess, save_path=trainResultPath)
else:
    print("train result path not exists: %s" % trainResultPath)
    sess.run(tf.global_variables_initializer())

if predictData is not None:
    I in Range for (predictRowCount): 
        Print (y.eval (= Sess the session, feed_dict = {X: predictData [I]})) the sys.exit (0)


    # with a cycle, the data in all rows are predictData the input side of the neural network is calculated, the final output 
lossSum = 0.0 for I in Range (500000 ): 
    xDataRandom = [int (random.random () * 10), int (random.random () * 10), int (Random. Random () * 10), int (random.random () * 10 )]
     IF xDataRandom [2]% 2 == 0: 
        yTrainDataRandom = [0,. 1 ]
     the else : 
        yTrainDataRandom = [. 1 , 0] 
    Result = sess.run ([train, x, yTrain,



 {X: xDataRandom, yTrain: yTrainDataRandom})

    lossSum = lossSum + float(result[len(result) - 1])

    print("i: %d, loss: %10.10f, avgLoss: %10.10f" % (i, float(result[len(result) - 1]), lossSum / (i + 1)))

    if os.path.exists("save.txt"):
        os.remove("save.txt")
        print("saving...")
        tf.train.Saver().save(sess, save_path=trainResultPath)

resultT = input('Would you like to save? (y/n)')

if resultT == "y":
    print("saving...")
    tf.train.Saver().save(sess, save_path=trainResultPath)

 

 

 

 Program can be obtained from data2.txt the data and convert it into a two-dimensional array, after training the neural network load process data in accordance with prevailing variable parameter values ​​for each row of data to predict

 

Third, the data is read from an arbitrary string prediction

 

[[1,2,3,4],[2,4,6,8],[5,6,1,2],[7,9,0,3]]

Defined above is written in python array, you can use the eval function python mentioned in this string converted into an array type you want.

Suppose there is a text file, data3.txt and there is only the character string as a file content, programming, reading data from a file prediction:

Import tensorflow AS TF
 Import numpy AS NP
 Import Random
 Import os
 Import SYS 

ifRestartT = False 

predictData = None 

argt = sys.argv [1 :]
 # If you develop a command line parameter "-datafile =", the program read from the specified file take the entire contents of the file 
# that is, the contents of the document as a whole read into a large string variables fileStr in 
# open function is used to open the python function to specify the location of the file, returns a file object 
# call the file object read function, it is possible to read the contents of a text file of all incoming 
# and then call the eval function to convert the string data object python 
# here, python will convert it to a list object directly with the array of function can put numpy convert it to an array 
 
for v in argt:
    if v == "-restart":
        ifRestartT = True
    if v.startswith("-file="):
        tmpStr = v[len("-file="):]
        predictData = np.loadtxt(tmpStr, dtype=np.float32, delimiter=",")
        predictRowCount = predictData.shape[0]
        print("predictRowCount: %s" % predictRowCount)
    if v.startswith("-dataFile="):
        tmpStr = v[len("-dataFile="):]
        fileStr = open(tmpStr).read()
        predictData = np.array(eval(fileStr))
        predictRowCount = predictData.shape[0]
        print("predictRowCount: %s" % predictRowCount)
    if v.startswith("-predict="):
        tmpStr = v[len("-predict="):]
        predictData = [np.fromstring(tmpStr, dtype=np.float32, sep=",")]

print("predictData: %s""=
TranrisultfthPredictdt)
%./save/idcard2"

random.seed()

x = tf.placeholder(tf.float32)
yTrain = tf.placeholder(tf.float32)

w1 = tf.Variable(tf.random_normal([4, 8], mean=0.5, stddev=0.1), dtype=tf.float32)
b1 = tf.Variable(0, dtype=tf.float32)

xr = tf.reshape(x, [1, 4])

n1 = tf.nn.tanh(tf.matmul(xr, w1) + b1)

w2 = tf.Variable(tf.random_normal([8, 2], mean=0.5, stddev=0.1), dtype=tf.float32)
b2 = tf.Variable(0, dtype=tf.float32)

n2 = tf.matmul(n1, w2) + b2

y = tf.nn.softmax(tf.reshape(n2, [2]))

loss = tf.reduce_mean(tf.square(y - yTrain))

optimizer = tf.train.RMSPropOptimizer(0.01)

train = optimizer.minimize(loss)

sess = tf.Session()

if ifRestartT:
    print("force restart...")
    sess.run(tf.global_variables_initializer())
elif os.path.exists(trainResultPath + ".index"):
    print("loading: %s" % trainResultPath)
    tf.train.Saver().restore(sess, save_path=trainResultPath)
else:
    print("train result path not exists: %s" % trainResultPath)
    sess.run(tf.global_variables_initializer())

if predictData is not None:
    for i in range(predictRowCount):
        print(y.eval(session=sess, feed_dict={x: predictData[i]}))

    sys.exit(0)

lossSum = 0.0

for i in range(500000):

    xDataRandom = [int(random.random() * 10), int(random.random() * 10), int(random.random() * 10), int(random.random() * 10)]
    if xDataRandom[2] % 2 == 0:
        yTrainDataRandom = [0, 1]
    else:
        yTrainDataRandom = [1, 0]

    result = sess.run([train, x, yTrain, y, loss], feed_dict={x: xDataRandom, yTrain: yTrainDataRandom})

    lossSum = lossSum + float(result[len(result) - 1])

    print("i: %d, loss: %10.10f, avgLoss: %10.10f" % (i, float(result[len(result) - 1]), lossSum / (i + 1)))

    if os.path.exists("save.txt"):
        os.remove("save.txt")
        print("saving...")
        tf.train.Saver().save(sess, save_path=trainResultPath)

resultT = input('Would you like to save? (y/n)')

if resultT == "y":
    print("saving...")
    tf.train.Saver().save(sess, save_path=trainResultPath)

 

 execute program:

 

 

 

 

Of course, the format here is also in line with one of the most popular formats to transfer data between the network: JSON

Guess you like

Origin www.cnblogs.com/expedition/p/11650613.html