深度学习:猫狗数据集搭建网络训练集

1.读取图片,使用cv2转成功统一大小,分割训练集和测试
2.搭建网络并训练模型
3.输出测试集准确率

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import cv2
import glob
from sklearn.model_selection import train_test_split

image_size = 60
X = []
y = []

# 导入数据
files = glob.glob("MAO/*g")
for file in files:
    try:
        image = cv2.imread(file)  # 读取图片数据
        image = cv2.resize(image, (image_size, image_size),interpolation=cv2.INTER_CUBIC)  # 压缩图片,一定要等比例缩放
        X.append(image)
        y.append([0, 1])
    except Exception as e:
        print(file,e)

files = glob.glob("GOU/*g")
for file in files:
    try:
        image = cv2.imread(file)  # 读取图片数据
        image = cv2.resize(image, (image_size, image_size),interpolation=cv2.INTER_CUBIC)  # 压缩图片
        X.append(image)
        y.append([1, 0])
    except Exception as e:
        print(file,e)

X = np.array(X).reshape((len(X),-1))
y = np.array(y)

X_train,X_test,y_train,y_test = train_test_split(X,y)


#定义网络结构
#l0层 input
input = tf.placeholder(dtype=tf.float32,shape=(None,image_size * image_size * 3),name="input")
#l1层
l1 = tf.layers.dense(input,20,tf.nn.relu)
#l2层
l2 = tf.layers.dense(l1,10,tf.nn.relu)
#output
output = tf.layers.dense(l2,2)

y_true = tf.placeholder(dtype=tf.int32,shape=(None,2),name="y_true")
#损失函数
loss = tf.losses.softmax_cross_entropy(onehot_labels=y_true,logits=output)
# y_true -> (0,1) or (1,0)
#优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0001)
#目标:最小化loss
train = optimizer.minimize(loss)

batch_size = 30
with tf.Session() as sess:
    #初始化全局变量
    init = tf.global_variables_initializer()
    sess.run(init)
    #训练网络
    for i in range(100000):
        start = np.random.randint(0, len(X_train) - batch_size)
        end = start + batch_size
        x_train_batchsize = X_train[start:end, :]
        y_train_batchsize = y_train[start:end, :]
        result = sess.run([train, loss], feed_dict={input: x_train_batchsize, y_true: y_train_batchsize})  # run 目标
        if i % 500 == 0:
            print(result)

    #算出准确率
    y_predict = sess.run(output, feed_dict={input: X_test, y_true: y_test})
    y_test = np.array([np.argmax(i) for i in y_test])
    y_predict = np.array([np.argmax(i) for i in y_predict])
    count = np.sum(y_test == y_predict)
    acc = count / len(y_test)
    print(acc)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值