TensorFlow-cifar训练与测试(可对自己数据进行分类和测试)

第一部分:测试软硬件

硬件:NVIDIA-GTX1080

软件:Windows7、python3.6.5、tensorflow-gpu-1.4.0

第二部分:数据下载

数据集下载链接

第三部分:代码分步展示

第一步:导入tensorflow

import os
from PIL import Image
import numpy as np
import tensorflow as tf

第二步:定义模型函数

def model_load(x_, y_, keep_prob):
    conv1 = tf.layers.conv2d(x_, 20, 5, activation=tf.nn.relu)
    pool1 = tf.layers.max_pooling2d(conv1, [2, 2], [2, 2])
    conv2 = tf.layers.conv2d(pool1, 40, 4, activation=tf.nn.relu)
    pool2 = tf.layers.max_pooling2d(conv2, [2, 2], [2, 2])
    pool2_reshape = tf.layers.flatten(pool2)
    fc = tf.layers.dense(pool2_reshape, 400, activation=tf.nn.relu)
    fc_dropout = tf.layers.dropout(fc, keep_prob)
    y_out = tf.layers.dense(fc_dropout, 3)
    return y_out

第三步:定义数据读取函数

def read_data(data_dir):
    datas = []
    labels = []
    fpaths = []
    for fname in os.listdir(data_dir):
        fpath = os.path.join(data_dir, fname)
        fpaths.append(fpath)
        image = Image.open(fpath)
        data = np.array(image) / 255.0
        label = int(fname.split("_")[0])
        datas.append(data)
        labels.append(label)

    datas = np.array(datas)
    labels = np.array(labels)
    return fpaths, datas, labels

第四步:定义网络输入输出

#define x y size
x_ = tf.placeholder(tf.float32, [None, 32, 32, 3])
y_ = tf.placeholder(tf.int32, [None])
keep_prob = tf.placeholder(tf.float32)

#load model
y_out = model_load(x_, y_, keep_prob)

#define loss
losses = tf.nn.softmax_cross_entropy_with_logits(labels = tf.one_hot(y_, 3), logits = y_out)
mean_loss = tf.reduce_mean(losses)
optimizer = tf.train.AdamOptimizer(learning_rate=1e-2).minimize(mean_loss)

#define predict top1
predicted_labels = tf.argmax(y_out, 1)

第五步:读取cifar数据集

#read data
data_dir = "data"
model_path = "model/cifar_model"
fpaths, datas, labels = read_data(data_dir)

第六步:训练和测试(100%准确率

#define saver and sess
saver = tf.train.Saver()
sess = tf.Session()

#train or test
train = True
if train:
    sess.run(tf.global_variables_initializer())
    for step in range(150):
        _, mean_loss_val = sess.run([optimizer, mean_loss], feed_dict={x_:datas, y_:labels, keep_prob:0.25})
        if step % 10 == 0:
            print("step = {}\tmean loss = {}".format(step, mean_loss_val))
    saver.save(sess, model_path + str(150))
else:
    labels_name = ["plane", "car", "bird"]
    saver.restore(sess, model_path)
    predicted_labels_val = sess.run(predicted_labels, feed_dict={x_:datas, y_:labels, keep_prob:0})
    img_count = 0
    for fpath in fpaths:
        print("{}\t{} =? {}".format(fpath, labels_name[labels[img_count]], labels_name[predicted_labels_val[img_count]]))
        img_count += 1

第七步:备注

若发现loss不下降,说明训练过拟合了,原因是参数初始化问题。这个没关系,删除model,重新训练一遍即可。

 

任何问题请加唯一QQ2258205918(名称samylee)!

唯一VX:samylee_csdn

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值