本节涉及点:
从命令行参数读取需要预测的数据
从文件中读取数据进行预测
从任意字符串中读取数据进行预测
一、从命令行参数读取需要预测的数据
训练神经网络是让神经网络具备可用性,真正使用神经网络时,需要对新的输入数据进行预测,
这些输入数据 不像训练数据那样是有目标值(标准答案),而是需要通过神经网络计算来获得预测的结果。
通过命令行参数输入数据:
importnumpy as npimportsys
predictData=None
argt= sys.argv[1:]#获取命令行参数后循环判断每一个参数,并寻找是否有以“-predict=” 为开始的字符串#使用成员函数 startswith 判断是否以另一个指定的字符串开头#如果有,去掉 "-predict=" 这个前缀,只取后面剩余的字符串#tmpStr = v[len("-predict=")] 作用是让 tmpStr 等于命令行参数v 去掉开头 "-predict=" 后的字符#len() 的作用是 获得任意字符串的长度#使用 numpy包中的 fromstring 函数,把 tmpStr 中字符串转换为一个数组
for v inargt:if v.startswith("-predict="):
tmpStr= v[len("-predict="):] #注意这里使用了切片print("tmpStr: %s" %tmpStr)
predictData= np.fromstring(tmpStr, dtype=np.float32, sep=",")print("predictData: %s" % predictData)
运行结果如下:
使用 Anaconda 执行该程序:
# numpy 字符串转变为数组函数 np.fromstring(tmpStr,dtype=np.float32,sep=",")
是指将字符串 tmpStr,以字符 "," 为分隔符,转换为数组内数据项的数据类型是 float32 的数组
调用训练好的神经网络进行预测:
importtensorflow as tfimportnumpy as npimportrandomimportosimportsys
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]))