MNIST手写数字分类:像素归一化后准确率低_问题出在哪儿?
TensorFlow MNIST分类:像素归一化后准确率低的原因及解决方案
在使用TensorFlow进行MNIST手写数字分类时,许多开发者可能会遇到一个难题:对数据集进行像素归一化处理后,模型训练准确率却异常低。本文将结合代码示例,深入分析此问题并提供解决方案。
问题根源在于对tf.nn.softmax_cross_entropy_with_logits函数的误用。原始代码中,预测值y_pred使用了tf.nn.softmax函数进行softmax概率计算:
y_pred = tf.nn.softmax(tf.matmul(x, w) + b)
然而,tf.nn.softmax_cross_entropy_with_logits函数期望输入的是线性输出(logits),而不是softmax概率。 将已进行softmax转换的y_pred传入该函数计算损失,导致了损失函数计算错误,进而影响模型训练效果。
解决方案:
关键在于修改y_pred的计算方式,移除tf.nn.softmax函数:
y_pred = tf.matmul(x, w) + b
同时,在计算准确率时,需要对y_pred应用tf.nn.softmax函数以获得概率分布,以便与真实标签进行比较:
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(tf.nn.softmax(y_pred), 1))
修改后的代码片段如下(假设部分代码已存在):
# … (导入包和设置超参数的代码部分保持不变)# 下载数据集mnist = input_data.read_data_sets(‘original_data/’, one_hot=True)train_img = mnist.train.imagestrain_label = mnist.train.labelstest_img = mnist.test.imagestest_label = mnist.test.labelstrain_img /= 255.0test_img /= 255.0X = tf.pat.v1.placeholder(tf.float32, shape=[None, inputSize])y = tf.pat.v1.placeholder(tf.float32, shape=[None, numClasses])W = tf.Variable(tf.random_normal([inputSize, numClasses], stddev=0.1))B = tf.Variable(tf.constant(0.1), [numClasses])y_pred = tf.matmul(X, W) + B # 修改:移除softmaxloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_pred)) + 0.01 * tf.nn.l2_loss(W)opt = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(tf.nn.softmax(y_pred), 1)) # 修改:在计算准确率时应用softmaxaccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))saver = tf.train.Saver()multiclass_parameters = {}# … (运行代码部分保持不变)
通过以上调整,tf.nn.softmax_cross_entropy_with_logits函数将接收正确的线性输出,计算出正确的损失值,从而使模型有效训练并获得更高的准确率。 这再次强调了正确理解和使用TensorFlow函数对于构建高效深度学习模型的重要性。
以上就是MNIST手写数字分类:像素归一化后准确率低,问题出在哪儿?的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » MNIST手写数字分类:像素归一化后准确率低_问题出在哪儿?