我用tensorflow编写了cnn程序,但它学得不好。 数据集是cifar-10,并且将彩色图像分类为10个类。 这是代码。
from __future__ import print_function
import tensorflow as tf
import os
import numpy as np
import cv2
import random
NUM_CLASSES = 10
IMG_SIZE = 32
STEPS = 5000
BATCH_SIZE=20
train_img_dirs = ["airplane","automobile","bird","cat","deer","dog","frog","horse","ship","truck"]
train_image = []
train_label = []
config = tf.ConfigProto(
gpu_options=tf.GPUOptions(
per_process_gpu_memory_fraction=0.1
)
)
for i, d in enumerate(train_img_dirs):
files = os.listdir('./' + d)
for f in files:
img = cv2.imread('./' + d + '/' + f)
img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
img = img.flatten().astype(np.float32)/255.0
train_image.append(img)
tmp = np.zeros(NUM_CLASSES)
tmp[i] = 1
train_label.append(tmp)
train_image = np.asarray(train_image)
train_label = np.asarray(train_label)
def weight_variable(shape,name):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial,name=name)
def bias_variable(shape,name):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial,name=name)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
# Input layer
x = tf.placeholder(tf.float32, [None, 32*32*3], name='x')
y_ = tf.placeholder(tf.float32, [None, 10], name='y_')
x_image = tf.reshape(x, [-1, 32, 32, 3])
# Convolutional layer 1
W_conv1 = weight_variable([5, 5, 3, 32],"W_conv1")
b_conv1 = bias_variable([32],"b_conv1")
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# Convolutional layer 2
W_conv2 = weight_variable([5, 5, 32, 64],"W_conv2")
b_conv2 = bias_variable([64],"b_conv2")
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# Convolutional layer 3
W_conv3 = weight_variable([5, 5, 64, 128],"W_conv3")
b_conv3 = bias_variable([128],"b_conv3")
h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)
h_pool3 = max_pool_2x2(h_conv3)
# Fully connected layer 1
h_pool3_flat = tf.reshape(h_pool3, [-1, 4*4*128])
W_fc1 = weight_variable([4 * 4 * 128, 1024],"W_fc1")
b_fc1 = bias_variable([1024],"b_fc1")
h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1)
# Dropout
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# Fully connected layer 2 (Output layer)
W_fc2 = weight_variable([1024, 10],"W_fc2")
b_fc2 = bias_variable([10],"b_fc2")
y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name='y')
# Evaluation functions
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
# Training algorithm
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Training steps
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver({'W_conv1': W_conv1, 'b_conv1': b_conv1, 'W_conv2': W_conv2, 'b_conv2': b_conv2 ,'W_conv3': W_conv3, 'b_conv3': b_conv3})
max_steps = 1000
for i in range(STEPS):
random_seq = list(range(len(train_image)))
random.shuffle(random_seq)
for j in range(len(train_image)//BATCH_SIZE):
batch = BATCH_SIZE * j
train_image_batch = []
train_label_batch = []
for k in range(BATCH_SIZE):
train_image_batch.append(train_image[random_seq[batch + k]])
train_label_batch.append(train_label[random_seq[batch + k]])
train_step.run(feed_dict={x: train_image_batch, y_: train_label_batch, keep_prob: 0.5})
train_accuracy = accuracy.eval(feed_dict={
x:train_image_batch, y_: train_label_batch, keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
saver.save(sess, "model.ckpt")
在学习结束之前,训练准确度一直保持在0.1左右。 这是一个错误吗?或者CNN的结构不好? python版本是2.7,tensorflow版本是1.4.0。