Tensorflow Iris 数据集无法收敛

我正在尝试在 Iris 数据集上运行一个标准的神经网络。标签是一个单列,可以根据物种类型取值0、1、2。我将特征转置到 x 轴上,将样本转置到 y 轴上。

需要关注的领域:成本函数 – 大家似乎都在使用预构建的成本函数,但由于我的数据不是独热编码的,我使用的是标准损失函数。优化器 – 我把它当成一个黑盒子使用,不确定是否能正确更新成本函数。

提前感谢您的帮助。

import tensorflow as tfimport numpy as npimport pandas as pdimport tensorflow as tfdef create_layer(previous_layer, weight, bias, activation_function=None):    z = tf.add(tf.matmul(weight, previous_layer), bias)    if activation_function is None:        return z    a = activation_function(z)    return adef cost_compute(prediction, correct_values):    return tf.nn.softmax_cross_entropy_with_logits(logits = prediction, labels = correct_values)input_features = 4n_hidden_units1 = 10n_hidden_units2 = 14n_hidden_units3 = 12n_hidden_units4 = 1rate = .000001weights = dict(            w1=tf.Variable(tf.random_normal([n_hidden_units1, input_features])),            w2=tf.Variable(tf.random_normal([n_hidden_units2, n_hidden_units1])),            w3=tf.Variable(tf.random_normal([n_hidden_units3, n_hidden_units2])),            w4=tf.Variable(tf.random_normal([n_hidden_units4, n_hidden_units3]))            )biases = dict(            b1=tf.Variable(tf.zeros([n_hidden_units1, 1])),            b2=tf.Variable(tf.zeros([n_hidden_units2, 1])),            b3=tf.Variable(tf.zeros([n_hidden_units3, 1])),            b4=tf.Variable(tf.zeros([n_hidden_units4, 1]))            )train = pd.read_csv("/Users/yazen/Desktop/datasets/iris_training.csv")test = pd.read_csv("/Users/yazen/Desktop/datasets/iris_test.csv")train.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'species']test.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'species']train_labels = np.expand_dims(train['species'].as_matrix(), 1)test_labels = np.expand_dims(test['species'].as_matrix(), 1)train_features = train.drop('species', axis=1)test_features = test.drop('species', axis=1)test_labels = test_labels.transpose()train_labels = train_labels.transpose()test_features = test_features.transpose()train_features = train_features.transpose()x = tf.placeholder("float32", [4, None], name="asdfadsf")y = tf.placeholder("float32", [1, None], name="asdfasdf2")layer = create_layer(x, weights['w1'], biases['b1'], tf.nn.relu)layer = create_layer(layer, weights['w2'], biases['b2'], tf.nn.relu)layer = create_layer(layer, weights['w3'], biases['b3'], tf.nn.relu)Z4 = create_layer(layer, weights['w4'], biases['b4'])cost = cost_compute(Z4, y)with tf.Session() as sess:    sess.run(tf.global_variables_initializer())    for iteration in range(1,50):        optimizer = tf.train.GradientDescentOptimizer(learning_rate=rate).minimize(cost)        _, c = sess.run([optimizer, cost], feed_dict={x: train_features, y: train_labels})        print("Iteration " + str(iteration) + " cost: " + str(c))    prediction = tf.equal(Z4, y)    accuracy = tf.reduce_mean(tf.cast(prediction, "float"))    print(sess.run(Z4, feed_dict={x: train_features, y: train_labels}))    print(accuracy.eval({x: train_features, y: train_labels}))

回答:

由于您面对的是一个分类问题,您需要将标签转换为独热编码形式。您可以使用 tf.one_hot 来实现这一点。此外,您还可以在成本函数上应用 tf.reduce_mean,如下面的示例所示(示例来自 这里)。此外,您的学习率对我来说似乎太小了。

  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)  x = tf.placeholder(tf.float32, [None, 784])  W = tf.Variable(tf.zeros([784, 10]))  b = tf.Variable(tf.zeros([10]))  y = tf.matmul(x, W) + b  # Define loss and optimizer  y_ = tf.placeholder(tf.float32, [None, 10])  cross_entropy = tf.reduce_mean(      tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))  train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)  sess = tf.InteractiveSession()  tf.global_variables_initializer().run()  # Train  for _ in range(1000):    batch_xs, batch_ys = mnist.train.next_batch(100)    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})  # Test trained model  correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  print(sess.run(accuracy, feed_dict={x: mnist.test.images,                                      y_: mnist.test.labels}))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注