python - TensorFlow 二元分类器输出 3 个类而不是 2 个类的预测?

标签 python machine-learning tensorflow neural-network classification

当我打印出预测时,输出包括 3 个单独的类 0、1 和 2,但我只在训练集中给它 2 个单独的类 0 和 1 >。我不知道为什么会发生这种情况。我正在尝试详细说明 TensorFlow Machine Learning Cookbook 的教程。这是基于第 2 章的最后一个示例(如果有人可以访问的话)。请注意,存在一些错误,但这可能是文本中旧版本之间的不兼容。

无论如何,我在构建模型时试图开发一个非常刚性的结构,这样我就可以让它根深蒂固地融入肌肉内存中。我预先为一组计算的每个 tf.Session 实例化 tf.Graph 并设置要使用的线程数。请注意,我将 TensorFlow 1.0.1Python 3.6.1 结合使用,因此如果您使用 f"formatstring{var}" 将无法工作有旧版本的 Python。

让我感到困惑的是# Accuracy Predictions部分下预测的最后一步。 为什么我的分类得到了 3 个类别,为什么对于如此简单的分类,我的准确性如此之差? 我对这种基于模型的机器学习相当陌生,所以我确信这是某种语法我所做的错误或假设。 我的代码有错误吗?

import numpy as np
import tensorflow as tf 
import matplotlib.pyplot as plt
import multiprocessing

# Set number of CPU to use
tf_max_threads = tf.ConfigProto(intra_op_parallelism_threads=multiprocessing.cpu_count())

# Data
seed= 0
size = 50
x = np.concatenate((np.random.RandomState(seed).normal(-1,1,size),
                    np.random.RandomState(seed).normal(2,1,size)
                   )
                  )
y = np.concatenate((np.repeat(0, size), 
                    np.repeat(1, size)
                   )
                  )

# Containers
loss_data = list()
A_data = list()

# Graph
G_6 = tf.Graph()
n = 25

# Containers
loss_data = list()
A_data = list()

# Iterations
n_iter = 5000

# Train / Test Set
tr_ratio = 0.8
tr_idx = np.random.RandomState(seed).choice(x.size, round(tr_ratio*x.size), replace=False)
te_idx = np.array(list(set(range(x.size)) - set(tr_idx)))


# Build Graph
with G_6.as_default():
    # Placeholders
    pH_x = tf.placeholder(tf.float32, shape=[None,1], name="pH_x")
    pH_y_hat = tf.placeholder(tf.float32, shape=[None,1], name="pH_y_hat")

    # Train Set
    x_train = x[tr_idx].reshape(-1,1)
    y_train = y[tr_idx].reshape(-1,1)
    # Test Set
    x_test= x[te_idx].reshape(-1,1)
    y_test = y[te_idx].reshape(-1,1)

    # Model
    A = tf.Variable(tf.random_normal(mean=10, stddev=1, shape=[1], seed=seed), name="A")
    model = tf.multiply(pH_x, A)

    # Loss
    loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=model, labels=pH_y_hat))
    with tf.Session(graph=G_6, config=tf_max_threads) as sess:
        sess.run(tf.global_variables_initializer())
        # Optimizer
        op = tf.train.GradientDescentOptimizer(0.03)
        train_step = op.minimize(loss)
        # Train linear model 
        for i in range(n_iter):
            idx_random = np.random.RandomState(i).choice(x_train.size, size=n)
            x_tr = x[idx_random].reshape(-1,1)
            y_tr = y[idx_random].reshape(-1,1)

            sess.run(train_step, feed_dict={pH_x:x_tr, pH_y_hat:y_tr})

            # Iterations
            A_iter = sess.run(A)[0]
            loss_iter = sess.run(loss, feed_dict={pH_x:x_tr, pH_y_hat:y_tr}).mean()
            # Append
            loss_data.append(loss_iter)
            A_data.append(A_iter)

#             Log
            if (i + 1) % 1000 == 0:
                print(f"Step #{i + 1}:\tA = {A_iter}", f"Loss = {to_precision(loss_iter)}", sep="\t")
                print()   

        # Accuracy Predictions
        A_result = sess.run(A)
        y_ = tf.squeeze(tf.round(tf.nn.sigmoid_cross_entropy_with_logits(logits=model, labels=pH_y_hat)))

        correct_predictions = tf.equal(y_, pH_y_hat)
        accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
        print(sess.run(y_, feed_dict={pH_x:x_train, pH_y_hat:y_train}))
        print("Training:",
              f"Accuracy = {sess.run(accuracy, feed_dict={pH_x:x_train, pH_y_hat:y_train})}", 
              f"Shape = {x_train.shape}", sep="\t")

        print("Testing:",
              f"Accuracy = {sess.run(accuracy, feed_dict={pH_x:x_test, pH_y_hat:y_test})}", 
              f"Shape = {x_test.shape}", sep="\t")

# Plot path
with plt.style.context("seaborn-whitegrid"):
    fig, ax = plt.subplots(nrows=3, figsize=(6,6))
    pd.Series(loss_data,).plot(ax=ax[0], label="loss", legend=True)
    pd.Series(A_data,).plot(ax=ax[1], color="red", label="A", legend=True)
    ax[2].hist(x[:size], np.linspace(-5,5), label="class_0", color="red")
    ax[2].hist(x[size:], np.linspace(-5,5), label="class_1", color="blue")

    alphas = np.linspace(0,0.5, len(A_data))
    for i in range(0, len(A_data), 100):
        alpha = alphas[i]
        a = A_data[i]
        ax[2].axvline(a, alpha=alpha, linestyle="--", color="black")
    ax[2].legend(loc="upper right")
    fig.suptitle("training-process", fontsize=15, y=0.95)

输出结果:

Step #1000: A = 6.72    Loss = 1.13

Step #2000: A = 3.93    Loss = 0.58

Step #3000: A = 2.12    Loss = 0.319

Step #4000: A = 1.63    Loss = 0.331

Step #5000: A = 1.58    Loss = 0.222

[ 0.  0.  1.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  2.
  0.  0.  2.  0.  2.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.  0.  0.  0.  0.  0.  0.  1.  0.
  1.  0.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.
  0.  0.  0.  0.  0.  0.  0.  0.]
Training:   Accuracy = 0.475    Shape = (80, 1)
Testing:    Accuracy = 0.5  Shape = (20, 1)

enter image description here

最佳答案

您的模型不进行分类

您有一个线性回归模型,即您的输出变量 (model = tf.multiply(pH_x, A)) 为每个输入输出一个具有任意范围的单个标量值。这通常是一个预测模型,需要预测一些数值,而不是分类器。

之后,您将其视为包含典型的 n 元分类器输出(例如,通过传递它 sigmoid_cross_entropy_with_logits),但它与该函数的期望不匹配 - 在这种情况下,模型变量的“形状”应该每个输入数据点有多个值(例如,在您的情况下为2个),每个值对应于与每个类别的概率相对应的某个指标;然后通常传递给 softmax 函数来标准化它们。

或者,您可能需要一个二元分类器模型,根据类别输出单个值 0 或 1 - 但是,在这种情况下,您需要类似于矩阵乘法后的逻辑函数;这需要一个不同的损失函数,比如简单的均方差,而不是 sigmoid_cross_entropy_with_logits。

目前编写的模型似乎是两个不同的、不兼容的教程的混搭。

关于python - TensorFlow 二元分类器输出 3 个类而不是 2 个类的预测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43793801/

相关文章:

python - 使用重新编码自动连接 FFMPEG

python - 针对其他指标优化 RandomForestRegressor

python - 安装OpenCV以与PyPy一起使用

r - 如何从R社区的角度打造最好的交互式R语言在线学习平台?

python - 是否可以将多个 TensorFlow 图合并为一个?

tensorflow - 使用 TensorFlow 模型进行预测

python - 根据现有列中的值计算新列

python-3.x - 梯度下降的线性回归没有给出正确的结果

python - Python 中使用随机梯度下降的岭回归

gpu - 为 Tensorflow 推荐的 GPU