王若葳 网盘,吃遍福州,沈阳一周天气
本文是python通过tensorflow卷积神经网络实现猫狗识别的姊妹篇,是加载上一篇训练好的模型,进行猫狗识别
本文逻辑:
代码如下:
#coding=utf-8 import tensorflow as tf from pil import image import matplotlib.pyplot as plt import input_data import numpy as np import model import os #从指定目录中选取一张图片 def get_one_image(train): files = os.listdir(train) n = len(files) ind = np.random.randint(0,n) img_dir = os.path.join(train,files[ind]) image = image.open(img_dir) plt.imshow(image) plt.show() image = image.resize([208, 208]) image = np.array(image) return image def evaluate_one_image(): #存放的是我从百度下载的猫狗图片路径 train = '/users/yangyibo/gitwork/pythonlean/ai/猫狗识别/testimg/' image_array = get_one_image(train) with tf.graph().as_default(): batch_size = 1 # 因为只读取一副图片 所以batch 设置为1 n_classes = 2 # 2个输出神经元,[1,0] 或者 [0,1]猫和狗的概率 # 转化图片格式 image = tf.cast(image_array, tf.float32) # 图片标准化 image = tf.image.per_image_standardization(image) # 图片原来是三维的 [208, 208, 3] 重新定义图片形状 改为一个4d 四维的 tensor image = tf.reshape(image, [1, 208, 208, 3]) logit = model.inference(image, batch_size, n_classes) # 因为 inference 的返回没有用激活函数,所以在这里对结果用softmax 激活 logit = tf.nn.softmax(logit) # 用最原始的输入数据的方式向模型输入数据 placeholder x = tf.placeholder(tf.float32, shape=[208, 208, 3]) # 我门存放模型的路径 logs_train_dir = '/users/yangyibo/gitwork/pythonlean/ai/猫狗识别/savenet/' # 定义saver saver = tf.train.saver() with tf.session() as sess: print("从指定的路径中加载模型。。。。") # 将模型加载到sess 中 ckpt = tf.train.get_checkpoint_state(logs_train_dir) if ckpt and ckpt.model_checkpoint_path: global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] saver.restore(sess, ckpt.model_checkpoint_path) print('模型加载成功, 训练的步数为 %s' % global_step) else: print('模型加载失败,,,文件没有找到') # 将图片输入到模型计算 prediction = sess.run(logit, feed_dict={x: image_array}) # 获取输出结果中最大概率的索引 max_index = np.argmax(prediction) if max_index==0: print('猫的概率 %.6f' %prediction[:, 0]) else: print('狗的概率 %.6f' %prediction[:, 1]) # 测试 evaluate_one_image()
/users/yangyibo/gitwork/pythonlean/ai/猫狗识别/testimg/ 存放的是我从百度下载的猫狗图片
执行结果:
因为从testimg 中选取图片是随机的,所以每次执行的结果不同
从指定的路径中加载模型。。。。
模型加载成功, 训练的步数为 11999
狗的概率 0.964047
[finished in 6.8s]
代码地址:https://github.com/527515025/my-tensorflow-tutorials/blob/master/猫狗识别/evaluatecatordog.py
欢迎star。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
新手学习Python2和Python3中print不同的用法
Python基于os.environ从windows获取环境变量
网友评论