在人工智能的开展越来越炽热的今天,此中智能应用也在陪伴着我们的生活,此中更具有代表性的即是图像识别,而且此中的应用触目皆是,如车站的人脸识别系统,交通的智能监控车商标系统等等。而卷积神经收集做为图像识此外首选算法,关于图像的特征提取具有很好的效果,而TensorFlow做为Google的开源框架具有很好的构造化特征,而本篇文章将操纵卷积神经收集算法对图像识别停止应用,开发出颜值评分器的功用。
做者 | 苏溪镇的水
出品 | AI科技大本营(ID:rgznai100)在人工智能的开展越来越炽热的今天,此中智能应用也在陪伴着我们的生活,此中更具有代表性的即是图像识别,而且此中的应用触目皆是,如车站的人脸识别系统,交通的智能监控车商标系统等等。而卷积神经收集做为图像识此外首选算法,关于图像的特征提取具有很好的效果,而TensorFlow做为Google的开源框架具有很好的构造化特征,而本篇文章将操纵卷积神经收集算法对图像识别停止应用,开发出颜值评分器的功用。
起首我们筹办训练的数据集文件保留在images文件夹下,此中的数据集如下:
此中需要训练的数据集的标签保留在Excel中,为All_Ratings.xlsx,即标签就为图像的颜值评分,此中的数据如下:
接着我们新建一个python文件为_input_data.py,即用来读取数据集以到达训练的目标。那里和卷积神经收集无关,故我仅仅大要申明一下并加以附上代码,此中要导入的模块代码:
import numpy as np import tensorflow as tf import os import cv2 import matplotlib.pyplot as plt import os from PIL import Image import pandas as pd然后定义一个函数用来获取文件夹下的图片,并定义四个数组别离为meis,chous,chous_label,meis_label那几个数组别离保留着美人的图片名及途径,丑人的图片名及途径,丑人的标签设为0保留到chous_label那个数组中,美人的标签设为1保留在meis_label。代码如下:
def get_files(file_dir): chous = [] meis = [] chous_label = [] meis_label = [] img_dirs = os.listdir(file_dir)#读取文件名下所有!目次名(列表形式) labpath = "F:/python操练/test1/All_Ratings.xlsx" date = pd.read_excel(labpath) filenames = date[Filename] label = date[Rating] for i in range(filenames.shape[0]): if int(label[i])>3: meis_label.append(1) meis.append(file_dir + filenames[i]) else: chous_label.append(0) chous.append(file_dir + filenames[i]) img_list = np.hstack((chous, meis))#列表(字符串形式) label_list = np.hstack((chous_label, meis_label))#列表(整数形式) return img_list, label_list接着再定义一个函数用来获取图片的长和宽,一次训练的个数等等。详细代码如下:
def get_batch(image, label, image_w, image_h, batch_size, capacity):#capacity: 队列中 最多包容图片的个数 input_queue = tf.train.slice_input_producer([image, label])#tf.train.slice_input_producer是一个tensor生成器,感化是 # 根据设定,每次从一个tensor列表中按挨次或者随机抽取出一个tensor放入文件名队列。 label = input_queue[1] img_contents = tf.read_file(input_queue[0])#一维 image = tf.image.decode_jpeg(img_contents, channels=3)#解码成三维矩阵 image = tf.image.resize_image_with_crop_or_pad(image, image_w, image_h) image = tf.cast(image, tf.float32) image = tf.image.per_image_standardization(image) # 生成批次 num_threads 有几个线程按照电脑设置装备摆设设置 image_batch, label_batch = tf.train.batch([image, label], batch_size=batch_size, num_threads=64, capacity=capacity) return image_batch, label_batch接着下面是卷积神经收集的算法部门,我们需要成立一个文件名为model.py的文件,用来保留算法构造参数,起首导入TensorFlow框架,代码为:
import tensorflow as tf起首简单申明下那篇文章所用的卷积神经收集的原理和构造:此中第一层为输入层,即能够读取图像的各点像素值保留在矩阵中,接着为卷积一层我把它定名为“conv1”,即为第一个卷积层,即操纵我定义的卷积核来乘上本来输入层的矩阵,而所谓的卷积核也就是一个矩阵,而此中相乘包罗步长等等那里不详细申明。
接着接上一个池化层定名为“pooling1_lrn”,其次要目标是降采样,即将此中图像的像素矩阵变小。接着再接上卷积二层,定名为“conv2”,每一层的输入层为上一层的输出值,再接上池化二层“pooling2_lrn”,同样目标降采样,接着接上全毗连层中的两个隐藏层名为“local3”,和“local4”,最初输出层接的是softmax激活函数,为二分类的激活函数,次要原因是我需要的成果是美和丑两种成果,详细代码见下:
import tensorflow as tf #卷积神经收集提取特征 def inference(image, batch_size, n_classes): #第一个卷积层 with tf.variable_scope("conv1") as scope:#课本108,variable_scope控造get_variable是获取(reuse=True)仍是创建变量 weights = tf.get_variable("weights", shape=[3,3,3,16], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32)) biases = tf.get_variable("biases", shape=[16], dtype=tf.float32, initializer=tf.constant_initializer(0.1)) conv = tf.nn.conv2d(image, weights, strides=[1,1,1,1], padding="SAME") pre_activation = tf.nn.bias_add(conv, biases) conv1 = tf.nn.relu(pre_activation, name=scope.name) #池化层,降采样 with tf.variable_scope("pooling1_lrn") as scope: pool1 = tf.nn.max_pool(conv1, ksize=[1,3,3,1], strides=[1,2,2,1], padding="SAME", name="pooling1") norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001/9.0,beta=0.75, name="norm1")#部分响应归一化?????? with tf.variable_scope("conv2") as scope: weights = tf.get_variable("weights", shape=[3,3,16,16], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32)) biases = tf.get_variable("biases", shape=[16], dtype=tf.float32, initializer=tf.constant_initializer(0.1)) conv = tf.nn.conv2d(norm1, weights, strides=[1,1,1,1], padding="SAME") pre_activation = tf.nn.bias_add(conv, biases) conv2 = tf.nn.relu(pre_activation, name=scope.name) with tf.variable_scope("pooling2_lrn") as scope: norm2 = tf.nn.lrn(conv2, depth_radius=4, bias=1.0, alpha=0.001/9.0,beta=0.75, name="norm2") pool2 = tf.nn.max_pool(norm2, ksize=[1,3,3,1], strides=[1,2,2,1], padding="SAME", name="pooling2") #全毗连层 with tf.variable_scope("local3") as scope: reshape = tf.reshape(pool2, shape=[batch_size, -1]) dim = reshape.get_shape()[1].value weights = tf.get_variable("weights", shape=[dim, 128], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32)) biases = tf.get_variable("biases", shape=[128], dtype=tf.float32, initializer=tf.constant_initializer(0.1)) local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name) with tf.variable_scope("local4") as scope: weights = tf.get_variable("weights", shape=[128, 128], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32)) biases = tf.get_variable("biases", shape=[128], dtype=tf.float32, initializer=tf.constant_initializer(0.1)) local4 = tf.nn.relu(tf.matmul(local3, weights) + biases,name="local4") #softmax二分类 with tf.variable_scope("softmax_linear") as scope: weights = tf.get_variable("weights", shape=[128, n_classes], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32)) biases = tf.get_variable("biases", shape=[n_classes], dtype=tf.float32, initializer=tf.constant_initializer(0.1)) softmax_linear = tf.nn.relu(tf.matmul(local4, weights) + biases,name="softmax_linear") return softmax_linear def loss(logits, labels):#输出成果和尺度谜底 with tf.variable_scope("loss") as scope: cross_entropy= tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels, name="entropy_per_example") loss = tf.reduce_mean(cross_entropy) tf.summary.scalar(scope.name +"/loss",loss)#对标量数据汇总和记录利用tf.summary.scalar return loss def training(loss, learning_rate): with tf.name_scope("optimizer"): global_step = tf.Variable(0, name="global_step", trainable=False)#定义训练的轮数,为不成训练的参数 optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op= optimizer.minimize(loss, global_step=global_step) #上两行等价于train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss,global_step=global_step) return train_op def evalution(logits, labels): with tf.variable_scope("accuracy") as scope: correct = tf.nn.in_top_k(logits, labels, 1)#下面 correct = tf.cast(correct, tf.float16) accuracy = tf.reduce_mean(correct) tf.summary.scalar(scope.name+"/accuracy", accuracy)#用来显示标量信息 return accuracy"""
top_1_op取样本的更大预测概率的索引与现实标签比照,top_2_op取样本的更大和仅次更大的两个预测概率与现实标签比照,
若是现实标签在此中则为True,不然为False。
"""
此中定义的几个函数是为了训练利用而定义的,loss函数计算每次训练的丧失值,training函数用来加载训练,包罗丧失值和进修率,evalution用来评估每次训练的精准度。
接着起头模子的训练,新建一个python文件名为“training.py”,此中设定常量:
N_CLASSES = 2 IMG_W = 350 IMG_H = 350 BATCH_SIZE = 32 CAPACITY = 256 STEP =500 #训练步数应当大于10000 LEARNING_RATE = 0.0001别离暗示成果输出为二分类(美和丑),图片的长和宽,每次训练的图片数目,训练容量,训练次数,进修率;接着将前面成立的python文件中的函数间接拿来利用,起首照旧是导入库以及前面成立的两个python文件:
import tensorflow as tf import numpy as np import os import _input_data import model接着定义训练数据所保留的途径,模子保留的途径,此中应留意模子保留的途径中不克不及呈现中文,不然报错;接着利用函数训练。详细代码如下:
x = tf.placeholder(tf.float32, shape=[None,129792]) y_ = tf.placeholder(tf.float32, shape=[None, 5]) def run_training(): train_dir = "F:/python操练/test1/Images/" log_train_dir = "F:/train_savenet/" train,train_labels = _input_data.get_files(train_dir) train_batch, train_label_batch = _input_data.get_batch(train, train_labels, IMG_W,IMG_H,BATCH_SIZE,CAPACITY) train_logits= model.inference(train_batch, BATCH_SIZE, N_CLASSES) train_loss= model.loss(train_logits, train_label_batch) train_op = model.training(train_loss, LEARNING_RATE) train_acc = model.evalution(train_logits, train_label_batch) summary_op = tf.summary.merge_all()#merge_all 能够将所有summary全数保留到磁盘,以便tensorboard显示。 # 一般那一句就可显示训练时的各类信息。 sess = tf.Session() train_writer =tf.summary.FileWriter(log_train_dir, sess.graph)#指定一个文件用来保留图 saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # Coordinator 和 start_queue_runners 监控 queue 的形态,不断的入队出队 coord = tf.train.Coordinator()#https://blog.csdn.net/weixin_42052460/article/details/80714539 threads = tf.train.start_queue_runners(sess=sess, coord=coord) try: for step in np.arange(STEP): if coord.should_stop(): break _, tra_loss, tra_acc = sess.run([train_op, train_loss, train_acc]) if step % 4 == 0 or (step + 1) == STEP: # 每隔2步保留一下模子,模子保留在 checkpoint_path 中 checkpoint_path = os.path.join(log_train_dir, "model.ckpt") saver.save(sess, checkpoint_path, global_step=step) except tf.errors.OutOfRangeError: print(Done training -- epoch limit reached) finally: coord.request_stop() coord.join(threads) sess.close() run_training()训练过程如图:
训练完毕后,会构成一些训练出来模子文件,能够间接拿来利用,那时候成立一个python文件名为“predict.py”用来利用模子,那部门不是重点,给出代码和成果即可:
# -*- coding: utf-8 -*- import tensorflow as tf from PIL import Image import numpy as np import os import model import matplotlib.pyplot as plt import _input_data from matplotlib import pyplot from matplotlib.font_manager import FontProperties def get_one_img(test):#从指定目次中拔取一张图片 file = os.listdir(test)#os.listdir()返回指定目次下的所有文件和目次名。 n = len(file) ind = np.random.randint(0, n) img_dir = os.path.join(test, file[ind])#判断能否存在文件或目次name global image1 image1= Image.open(img_dir) #plt.imshow(image) #plt.show() image = image1.resize([350, 350]) image = np.array(image) return image def evaluate_one_img(): test = "F:/python操练/test1/Images/" test_array = get_one_img(test) with tf.Graph().as_default():#https://www.cnblogs.com/studylyn/p/9105818.html BATCH_SIZE = 1 N_CLASSES = 2 image = tf.cast(test_array, tf.float32) image = tf.image.per_image_standardization(image) image = tf.reshape(image,[1,350,350,3]) logit = model.inference(image, BATCH_SIZE, N_CLASSES) logit = tf.nn.softmax(logit) x =tf.placeholder(tf.float32, shape =[350,350,3]) log_test_dir = F:/train_savenet/ saver = tf.train.Saver() global title with tf.Session() as sess: print("从指定途径中加载模子。。。") #将模子加载到sess中 ckpt = tf.train.get_checkpoint_state(log_test_dir) if ckpt and ckpt.model_checkpoint_path:#https://blog.csdn.net/u011500062/article/details/51728830/ global_step = ckpt.model_checkpoint_path.split("/")[-1].split("-")[-1] saver.restore(sess, ckpt.model_checkpoint_path) print("模子加载胜利,训练的步数为 "+global_step) else: print("模子加载失败,文件没有找到。") #将图片输入到模子计算 prediction = sess.run(logit, feed_dict={x: test_array}) max_index = tf.argmax(prediction) # 将图片输入到模子计算 if float(prediction[:, 0])>0.5: print(丑的概率 %.6f %prediction[:, 0]) print("丑") title=u丑+str(prediction[:, 0]*100) else: print(美的概率 %.6f %prediction[:, 1]) print("美") title=u美+str(prediction[:, 1]*100) # 测试 evaluate_one_img() imgplot = plt.imshow(image1) myfont = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15) plt.title(title,fontproperties=myfont) plt.show()最末拿一个图片来尝试的成果如下:
由此可见模子根本准确,也能够晓得卷积神经收集关于图像特征提取比力擅长。
(*本文为AI科技大本营投稿文章,转载请微信联络 1092722531)
出色保举
2019 中国大数据手艺大会(BDTC)再度来袭!奢华主席阵容及百位手艺专家齐聚,15 场精选专题手艺和行业论坛,超强干货+手艺分析+行业理论立体解读,深切解析热门手艺在行业中的理论落地。6.6 折票限时特惠(立减1400元),学生票仅 599 元!