【发布时间】:2018-05-04 00:07:49
【问题描述】:
我正在学习 tensorflow,作为练习,我正在尝试为 iris 数据集训练分类器。我试探性地从the official tensorflow's iris example 中获取了网络架构,并尝试使用层 API 重新创建它:它应该是一个具有三个隐藏层的神经网络,大小分别为 10、20 和 10;之后,由于 iris 是一个 3 路分类问题,我放置了一个具有 softmax 激活的最终大小为 3 的密集层。这是代码:
def parse_csv(line):
data = tf.decode_csv(line, record_defaults=[[]] * 5)
return tf.stack(data[:4]), data[4]
trn_data, trn_targ = tf.data.TextLineDataset("../data/train.csv").map(parse_csv).shuffle(200).repeat().batch(32).make_one_shot_iterator().get_next()
evl_data, evl_targ = tf.data.TextLineDataset("../data/test.csv").map(parse_csv).shuffle(200).repeat().batch(32).make_one_shot_iterator().get_next()
x = tf.placeholder(tf.float32, [None, 4], name="input")
y_ = tf.placeholder(tf.int64, [None, ], name="target")
# definition of the neural network
a1 = tf.layers.dense(x, 10, activation=tf.nn.relu)
a2 = tf.layers.dense(a1, 20, activation=tf.nn.relu)
a3 = tf.layers.dense(a2, 10, activation=tf.nn.relu)
y = tf.layers.dense(a3, 3, activation=tf.nn.softmax)
# training step
loss = tf.losses.softmax_cross_entropy(tf.one_hot(y_, 3), y)
train_op = tf.train.AdamOptimizer(0.001).minimize(loss, global_step=tf.train.get_or_create_global_step())
# evaluation of the results
predictions = tf.argmax(y, 1, name="predictions")
correct_prediction = tf.equal(y_, predictions) # boolean tensor that says if we did good
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
cm = tf.confusion_matrix(y_, predictions)
with tf.Session() as sess:
tf.global_variables_initializer().run()
for n in range(401):
if n % 50 == 0: # see what's going on every 50 steps
feed_train = {x: sess.run(evl_data), y_: sess.run(evl_targ)}
acc, c = sess.run([accuracy, cm], feed_dict=feed_train)
print(c, acc)
else: # train
feed_eval = {x: sess.run(trn_data), y_: sess.run(trn_targ)}
_ = sess.run(train_op, feed_dict=feed_eval)
但是,准确度确实很差,并且与网络没有学习任何东西的假设大致兼容(它徘徊在 0.33 左右)。为了更好地理解,我在不同的步骤和不同的运行中打印了混淆矩阵:它们通常表明网络预测所有输入的相同结果,而不管它们的特征或标签如何。使用张量板对网络参数进行可视化显示,偏差会随着时间而变化,但权重(或内核,因为它们在文档中定义)不会。
我传递数据或进行训练或其他任何事情的方式一定有错误,但我找不到。你能帮忙吗?
【问题讨论】:
标签: python tensorflow