10 훈련된 모델로 예측

10518 단어 심도 있는 학습
명령행 매개 변수에서 예측할 데이터 읽기
10.1 predict1 프로그램:
import numpy as np
import sys

predictData = None

argt = sys.argv[1:]

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

print("predictData: %s" % predictData)

결과:predictData:None
10.2 predict2 프로그램:
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" % 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:
    result = sess.run([x, y], feed_dict={x: predictData})
    print(result[1])
    print(y.eval(session=sess, feed_dict={x: predictData}))
    sys.exit(0)

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)


결과:
predictData: None
loading: ./save/idcard2
i: 0, loss: 0.0000723387, avgLoss: 0.0000723387
i: 1, loss: 0.1840327382, avgLoss: 0.0920525385
i: 2, loss: 0.1533217579, avgLoss: 0.1124756116
i: 3, loss: 0.0000722930, avgLoss: 0.0843747820
i: 4, loss: 0.3304394484, avgLoss: 0.1335877152
Would you like to save? (y/n)y
saving...

10.3 predict3
코드 동급 디렉터리 아래 데이터 2.txt 파일:
1,2,3,4
2,4,6,8
5,6,1,2
7,9,0,3

test0712.py 프로그램:
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("-file="):#          ,predictData        
        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:
    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)

명령줄 입력:
e:

cd E:\PycharmProjects\test20190712

python test0712.py -file=data2.txt

결과:
data2.txt
predictRowCount: 4
predictData: [[1. 2. 3. 4.]
 [2. 4. 6. 8.]
 [5. 6. 1. 2.]
 [7. 9. 0. 3.]]
 
loading: ./save/idcard2

[0.4777626 0.5222374]
[0.46356556 0.5364345 ]
[0.99819934 0.0018006 ]
[0.00806343 0.99193656]

임의의 문자열에서 데이터를 읽어서 예측합니다
10.4 predict4
코드 동급 디렉터리 아래 데이터 3.txt 파일:
[[1,2,3,4], [2,4,6,8], [5,6,1,2], [7,9,0,3]]

test0712.py 프로그램:
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("-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="):#               ,           filStr  
        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" % 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:
    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)

명령줄 입력:
e:

cd E:\PycharmProjects\test20190712

python test0712.py -dataFile=data3.txt

결과:
predictRowCount: 4
predictData: [[1 2 3 4]
 [2 4 6 8]
 [5 6 1 2]
 [7 9 0 3]]
loading: ./save/idcard2
[0.4777626 0.5222374]
[0.46356556 0.5364345 ]
[0.99819934 0.0018006 ]
[0.00806343 0.99193656]

좋은 웹페이지 즐겨찾기