简介
我有一个基于tensorflow的普通CNN网络,我的目标是训练它,然后使用它将图像分为2类。在
关于列车数据集
X:图像(健康,不健康),128*128
标签:[1,0](不正常)或[0,1](健康)
我使用TFrecords生成数据集。在
关于CNN模式def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev = 0.1, dtype = tf.float32)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape = shape, dtype = tf.float32)
return tf.Variable(initial)
def conv2d(x, W):
#(input, filter, strides, padding)
#[batch, height, width, in_channels]
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
#(value, ksize, strides, padding)
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
def cnn_model():
epochs = 1
batch_size = 200
learning_rate = 0.001
hidden = 1024
cap_c = 498
cap_h = 478
num = cap_c + cap_h # the sum number of the training x
image_size = 128
label_size = 2
ex = 2
#train_loss = np.empty((num//(batch_size * ex)) * epochs)
#train_acc = np.empty((num//(batch_size * ex)) * epochs)
x = tf.placeholder(tf.float32, shape = [None, image_size * image_size])
y = tf.placeholder(tf.float32, shape = [None, label_size])
X_train_ = tf.reshape(x, [-1, image_size, image_size, 1])
#First layer
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(X_train_, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#Second layer
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#Third layer
#W_conv3 = weight_variable([5, 5, 64, 128])
#b_conv3 = bias_variable([128])
#h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)
#h_pool3 = max_pool_2x2(h_conv3)
#Full connect layer
W_fc1 = weight_variable([64 * 64 * 32, hidden])
b_fc1 = bias_variable([hidden])
h_pool2_flat = tf.reshape(h_pool2, [-1, 64 * 64 * 32])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
#Output_Softmax
W_fc2 = weight_variable([hidden, label_size])
b_fc2 = bias_variable([label_size])
y_conv = tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y, logits = y_conv))
optimize = tf.train.AdamOptimizer(learning_rate).minimize(loss)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
然后是数据读取或sess部分。在
关于形状
作为占位符的形状,如果批量大小为200
X形:[200128*128]
标签形状:[200,2]
输出形状:[200,2]
关于输出结果
我觉得预测值应该训练成[1,0]或者[0,1],但是大约5步之后,预测值都是[1,0]或者[0,1]。例如,如果批大小为5,则结果为
^{pr2}$
或者完全相反。
然而,有时结果会不一样,就像这样[[1, 0],
[0, 1],
[1, 0],
[0, 1],
[1, 0]]
但这只持续大约5个步骤,那个么结果将是一样的。在
关于损失和准确性
由于预测结果不正确,损失不收敛。换句话说,损失和准确度完全取决于训练数据集的X,这是毫无意义的。在
我的想法
我认为数据集TFrecords没有问题,因为我已经打印了图像矩阵和标签,它们都是正确的。所以我认为问题出在模型上。在
我没有得到答案,可以解决我的问题和问题,从谷歌搜索和其他问题,所以,真的谢谢你,如果你能帮助我这一点。请让我知道,如果你需要更多的结果或代码的参考。在