我正在尝试使用 Cifar10 数据集为图像分类实现简单的逻辑回归。我只被允许使用 TensorFlow 1.x 进行训练。(我被允许使用 Keras 和其他库来操作数据)
我的问题是我建立的模型没有学习......所有时期的测试和训练的准确性都给出了 0.1 的值。
我认为在发送到模型之前操纵数据本身存在一些问题,我很乐意帮助理解为什么模型没有学习。
代码:
%tensorflow_version 1.x
import tensorflow as tf
import numpy as np
import keras
import cv2 as cv2
import matplotlib.pyplot as plt
from keras.utils import to_categorical
from keras.datasets import mnist, cifar10
def get_cifar10():
"""Retrieve the CIFAR dataset and process the data."""
# Set defaults.
nb_classes = 10
batch_size = 64
input_shape = (3072,)
# Get the data.
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.reshape(50000, 3072)
x_test = x_test.reshape(10000, 3072)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# x_train /= 255
# x_test /= 255
# convert class vectors to binary class matrices
y_train = to_categorical(y_train, nb_classes)
y_test = to_categorical(y_test, nb_classes)
return (nb_classes, batch_size, input_shape, x_train, x_test, y_train, y_test)
nb_classes, batch_size, input_shape, x_train, x_test, y_train, y_test = get_cifar10()
features = 3072
categories = nb_classes
x = tf.placeholder(tf.float32, [None, features])
y_ = tf.placeholder(tf.float32, [None, categories])
W = tf.Variable(tf.zeros([features,categories]))
b = tf.Variable(tf.zeros([categories]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
loss = -tf.reduce_mean(y_*tf.log(y))
update = tf.train.GradientDescentOptimizer(0.0001).minimize(loss)
correct_prediction = tf.equal(tf.argmax(y, 1),tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for epoch in range(0,1000):
sess.run(update, feed_dict = {x:x_train, y_:y_train}) #BGD
train_acc = sess.run(accuracy, feed_dict={x:x_train, y_:y_train})
test_acc = sess.run(accuracy, feed_dict={x:x_test, y_:y_test})
if(epoch % 10 == 0):
print ("epoch: %3d train_acc: %f test_acc: %f" % (epoch,train_acc, test_acc))
运行模型给出以下结果:
epoch: 0 train_acc: 0.099880 test_acc: 0.099900
epoch: 10 train_acc: 0.100000 test_acc: 0.100000
epoch: 20 train_acc: 0.100000 test_acc: 0.100000
epoch: 30 train_acc: 0.100000 test_acc: 0.100000
epoch: 40 train_acc: 0.100000 test_acc: 0.100000
epoch: 50 train_acc: 0.100000 test_acc: 0.100000
epoch: 60 train_acc: 0.100000 test_acc: 0.100000
epoch: 70 train_acc: 0.100000 test_acc: 0.100000
epoch: 80 train_acc: 0.100000 test_acc: 0.100000
epoch: 90 train_acc: 0.100000 test_acc: 0.100000
epoch: 100 train_acc: 0.100000 test_acc: 0.100000
epoch: 110 train_acc: 0.100000 test_acc: 0.100000
epoch: 120 train_acc: 0.100000 test_acc: 0.100000
epoch: 130 train_acc: 0.100000 test_acc: 0.100000
提前致谢!