train.py
from skimage import io,transform
import glob
import os
import tensorflow as tf
import numpy as np
import time
import matplotlib.pyplot as plt
#資料集位址
path='D:\date_1\\flowers\\'
#模型儲存位址
model_path='D:\model_1\\model.ckpt\\'
#将所有的圖檔resize成100*100
w=100 #寬
h=100 #高
c=3 #通道數
#讀取圖檔
def read_img(path):
cate=[path+x for x in os.listdir(path) if os.path.isdir(path+x)]
imgs=[]
labels=[]
for idx,folder in enumerate(cate):
for im in glob.glob(folder+'/*.jpg'):
print('reading the images:%s'%(im))
img=io.imread(im)
img=transform.resize(img,(w,h),mode='constant')
imgs.append(img)
labels.append(idx)
return np.asarray(imgs,np.float32),np.asarray(labels,np.int32)
data,label=read_img(path)
#打亂順序
num_example=data.shape[0]
arr=np.arange(num_example)
np.random.shuffle(arr)
data=data[arr]
label=label[arr]
#将所有資料分為訓練集和驗證集 訓練集(train)優化、驗證集(validation)人工處理參數調整 和測試集(test)不經過處理
ratio=0.8
s=np.int(num_example*ratio)
x_train=data[:s] #訓練集%80 驗證集20%
y_train=label[:s]
x_val=data[s:]
y_val=label[s:]
#-----------------建構網絡----------------------
#占位符
tf.reset_default_graph()
#定義一個容器 存放圖像資料
x=tf.placeholder(tf.float32,shape=[None,w,h,c],name='x') #參數有 資料類型 資料形狀 名稱
y_=tf.placeholder(tf.int32,shape=[None,],name='y_')
#卷積層全都采用了補0,是以經過卷積層長和寬不變,隻有深度加深。池化層全都沒有補0,是以經過池化層長和寬均減小,深度不變。
#卷積層提取特征 池化層對輸入的特征圖進行壓縮,一方面使特征圖變小,簡化網絡計算複雜度;一方面進行特征壓縮,提取主要特征
#全連接配接層連接配接所有的特征,将輸出值送給分類器(如softmax分類器)
def inference(input_tensor, train, regularizer): # 張量 訓練 正則化
with tf.variable_scope('layer1-conv1'):
#卷積核5x5 輸入通道3個 輸出通道32個
conv1_weights = tf.get_variable("weight",[5,5,3,32],initializer=tf.truncated_normal_initializer(stddev=0.1))
conv1_biases = tf.get_variable("bias", [32], initializer=tf.constant_initializer(0.0))
conv1 = tf.nn.conv2d(input_tensor, conv1_weights, strides=[1, 1, 1, 1], padding='SAME')
#激活relu非線性處理
relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))
with tf.name_scope("layer2-pool1"):
pool1 = tf.nn.max_pool(relu1, ksize = [1,2,2,1],strides=[1,2,2,1],padding="VALID")
with tf.variable_scope("layer3-conv2"):
conv2_weights = tf.get_variable("weight",[5,5,32,64],initializer=tf.truncated_normal_initializer(stddev=0.1))
conv2_biases = tf.get_variable("bias", [64], initializer=tf.constant_initializer(0.0))
conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))
with tf.name_scope("layer4-pool2"):
pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
with tf.variable_scope("layer5-conv3"):
conv3_weights = tf.get_variable("weight",[3,3,64,128],initializer=tf.truncated_normal_initializer(stddev=0.1))
conv3_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0))
conv3 = tf.nn.conv2d(pool2, conv3_weights, strides=[1, 1, 1, 1], padding='SAME')
relu3 = tf.nn.relu(tf.nn.bias_add(conv3, conv3_biases))
with tf.name_scope("layer6-pool3"):
pool3 = tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
with tf.variable_scope("layer7-conv4"):
conv4_weights = tf.get_variable("weight",[3,3,128,128],initializer=tf.truncated_normal_initializer(stddev=0.1))
conv4_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0))
conv4 = tf.nn.conv2d(pool3, conv4_weights, strides=[1, 1, 1, 1], padding='SAME')
relu4 = tf.nn.relu(tf.nn.bias_add(conv4, conv4_biases))
with tf.name_scope("layer8-pool4"):
pool4 = tf.nn.max_pool(relu4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
nodes = 6*6*128
reshaped = tf.reshape(pool4,[-1,nodes])
with tf.variable_scope('layer9-fc1'):
fc1_weights = tf.get_variable("weight", [nodes, 1024],
initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None: tf.add_to_collection('losses', regularizer(fc1_weights))
fc1_biases = tf.get_variable("bias", [1024], initializer=tf.constant_initializer(0.1))
fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights) + fc1_biases)
if train: fc1 = tf.nn.dropout(fc1, 0.5)
with tf.variable_scope('layer10-fc2'):
fc2_weights = tf.get_variable("weight", [1024, 512],
initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None: tf.add_to_collection('losses', regularizer(fc2_weights))
fc2_biases = tf.get_variable("bias", [512], initializer=tf.constant_initializer(0.1))
fc2 = tf.nn.relu(tf.matmul(fc1, fc2_weights) + fc2_biases)
if train: fc2 = tf.nn.dropout(fc2, 0.5)
with tf.variable_scope('layer11-fc3'):
fc3_weights = tf.get_variable("weight", [512, 5],
initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None: tf.add_to_collection('losses', regularizer(fc3_weights))
fc3_biases = tf.get_variable("bias", [5], initializer=tf.constant_initializer(0.1))
logit = tf.matmul(fc2, fc3_weights) + fc3_biases
return logit
#---------------------------網絡結束---------------------------
regularizer = tf.contrib.layers.l2_regularizer(0.0001)
logits = inference(x,False,regularizer)
#(小處理)将logits乘以1指派給logits_eval,定義name,友善在後續調用模型時通過tensor名字調用輸出tensor
b = tf.constant(value=1,dtype=tf.float32)
logits_eval = tf.multiply(logits,b,name='logits_eval')
loss=tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y_)
train_op=tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
correct_prediction = tf.equal(tf.cast(tf.argmax(logits,1),tf.int32), y_)
acc= tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#定義一個函數,按批次取資料
def minibatches(inputs=None, targets=None, batch_size=None, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.arange(len(inputs))
np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):
if shuffle:
excerpt = indices[start_idx:start_idx + batch_size]
else:
excerpt = slice(start_idx, start_idx + batch_size)
yield inputs[excerpt], targets[excerpt]
#訓練和測試資料,可将n_epoch設定更大一些 交叉熵計算損失
n_epoch=5 #訓練次數
batch_size=64 #批處理參數 訓練集樣本總數
saver=tf.train.Saver() #定義模型儲存器/載入器
sess=tf.Session()
sess.run(tf.global_variables_initializer())
fig_loss = np.zeros([n_epoch])
fig_acc1 = np.zeros([n_epoch])
fig_acc2= np.zeros([n_epoch])
for epoch in range(n_epoch):
start_time = time.time()
#training
train_loss, train_acc, n_batch = 0, 0, 0
for x_train_a, y_train_a in minibatches(x_train, y_train, batch_size, shuffle=True):
_,err,ac=sess.run([train_op,loss,acc], feed_dict={x: x_train_a, y_: y_train_a})
train_loss += err; train_acc += ac; n_batch += 1
print(" train loss: %f" % (np.sum(train_loss)/ n_batch))
print(" train acc: %f" % (np.sum(train_acc)/ n_batch))
fig_loss[epoch] = np.sum(train_loss)/ n_batch
fig_acc1[epoch] = np.sum(train_acc) / n_batch
#validation
val_loss, val_acc, n_batch = 0, 0, 0
for x_val_a, y_val_a in minibatches(x_val, y_val, batch_size, shuffle=False):
err, ac = sess.run([loss,acc], feed_dict={x: x_val_a, y_: y_val_a})
val_loss += err; val_acc += ac; n_batch += 1
print(" validation loss: %f" % (np.sum(val_loss)/ n_batch))
print(" validation acc: %f" % (np.sum(val_acc)/ n_batch))
fig_acc2[epoch] = np.sum(val_acc) / n_batch
# 訓練loss圖
fig, ax1 = plt.subplots()
lns1 = ax1.plot(np.arange(n_epoch), fig_loss, label="Loss")
ax1.set_xlabel('iteration')
ax1.set_ylabel('training loss')
# 訓練和驗證兩種準确率曲線圖放在一張圖中
fig2, ax2 = plt.subplots()
ax3 = ax2.twinx()#由ax2圖生成ax3圖
lns2 = ax2.plot(np.arange(n_epoch), fig_acc1, label="Loss")
lns3 = ax3.plot(np.arange(n_epoch), fig_acc2, label="Loss")
ax2.set_xlabel('iteration')
ax2.set_ylabel('training acc')
ax3.set_ylabel('val acc')
# 合并圖例
lns = lns3 + lns2
labels = ["train acc", "val acc"]
plt.legend(lns, labels, loc=7)
plt.show()
saver.save(sess,model_path)
sess.close()
predict.py
from skimage import io,transform
import tensorflow as tf
import numpy as np
path1 = "D:\date_1\\flowers\\tulip\\8838983024_5c1a767878_n.jpg"
path2 = "D:\date_1\\flowers\\sunflower\\4895721242_89014e723c_n.jpg"
path3 = "D:\date_1\\flowers\\rose\\475947979_554062a608_m.jpg"
path4 = "D:\date_1\\flowers\\dandelion\\5749815755_12f9214649_n.jpg"
path5 = "D:\date_1\\flowers\\daisy\\286875003_f7c0e1882d.jpg"
path=[path1,path2,path3,path4,path5]
flower_dict = {0:'dasiy',1:'dandelion',2:'rose',3:'sunflower',4:'tulip'}
w=100
h=100
c=3
def read_one_image(path):
img = io.imread(path)
img = transform.resize(img,(w,h),mode='constant')
return np.asarray(img)
with tf.Session() as sess:
data = []
data1 = read_one_image(path1)
data2 = read_one_image(path2)
data3 = read_one_image(path3)
data4 = read_one_image(path4)
data5 = read_one_image(path5)
data.append(data1)
data.append(data2)
data.append(data3)
data.append(data4)
data.append(data5)
saver = tf.train.import_meta_graph('D:\model_1\\model.ckpt\\.meta')
saver.restore(sess,tf.train.latest_checkpoint('D:\model_1\\'))
graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
feed_dict = {x:data}
logits = graph.get_tensor_by_name("logits_eval:0")
classification_result = sess.run(logits,feed_dict)
#列印出預測矩陣
print(classification_result)
#列印出預測矩陣每一行最大值的索引
print(tf.argmax(classification_result,1).eval())
#根據索引通過字典對應花的分類
output = []
output = tf.argmax(classification_result,1).eval()
for i in range(len(output)):
print("第",i+1,"朵花預測:"+flower_dict[output[i]]+"-----"+"原圖像路徑:"+path[i])