Python 基于成人收入数据集的神经网络训练精度低

Python 基于成人收入数据集的神经网络训练精度低,python,machine-learning,tensorflow,neural-network,deep-learning,Python,Machine Learning,Tensorflow,Neural Network,Deep Learning,我用tensorflow建立了一个神经网络。它是一个简单的三层神经网络,最后一层是softmax 我在标准成人收入数据集(例如)上试用了它,因为它是公开的,有大量的数据(大约5万个例子),并且还提供了单独的测试数据 由于有一些分类属性,我将它们转换为一个热编码。对于神经网络,我使用Xavier初始化和Adam优化器。由于只有两个输出类(>50k和),我没有在这个数据集上进行实验,但在看了一些论文和做了一些研究之后,看起来您的网络运行正常 首先,你的准确度是从训练集还是测试集计算出来的?两者都有会

我用tensorflow建立了一个神经网络。它是一个简单的三层神经网络,最后一层是softmax

我在标准成人收入数据集(例如)上试用了它,因为它是公开的,有大量的数据(大约5万个例子),并且还提供了单独的测试数据


由于有一些分类属性,我将它们转换为一个热编码。对于神经网络,我使用Xavier初始化和Adam优化器。由于只有两个输出类(>50k和),我没有在这个数据集上进行实验,但在看了一些论文和做了一些研究之后,看起来您的网络运行正常

首先,你的准确度是从训练集还是测试集计算出来的?两者都有会给你一个很好的提示,说明你的网络是如何运行的

我对机器学习还是有点陌生,但我可以提供一些帮助:

通过查看此处的数据文档链接:

本文:

从这些链接来看,训练和测试集85%的准确率看起来是一个不错的分数,你还不算太远

您是否有某种交叉验证来寻找网络的过度拟合

我没有你的代码,所以如果这是一个bug或与编程相关的问题,我无法帮助你,也许共享你的代码可能是一个好主意

我认为您可以通过稍微预处理数据来获得更高的准确性: 数据中有很多未知因素,神经网络对错误标记和坏数据非常敏感

  • 你应该试着找到并替换或移除未知的东西

  • 您还可以尝试识别最有用的功能,并删除那些几乎无用的功能

  • 特征缩放/数据规范化对于神经网络也非常重要,我没有深入研究数据,但如果还没有完成,您可以尝试找出如何在[0,1]之间缩放数据

  • 我链接的文档显示,通过添加最多5层的层,您似乎看到了性能的提升,您是否尝试添加更多层

  • 如果你的网络过度拥挤,你也可以增加辍学率,如果你还没有这样做的话

  • 我可能会尝试其他通常对这些任务很好的网络,比如SVM(支持向量机)或逻辑回归,甚至是随机森林,但通过观察结果,我不确定这些网络的性能是否比人工神经网络更好

我还想看看这些链接:

在这个链接中,有一些人尝试算法并给出处理数据和解决这个问题的技巧

希望有帮助

祝你好运,
Marc.

我认为你过于关注你的网络结构,你忘记了你的结果在很大程度上也取决于数据质量。我尝试了一个快速的现成随机林,它给了我与你类似的结果(acc=0.8275238)

我建议你做一些特征工程(由@Marc提供的kaggle链接有一些很好的例子)。为你的NA(外观)决定一个策略,当你在分类变量中有许多因素水平时(例如,将国家分组为大陆)分组值,或者离散连续变量(年龄变量分为老年、中年、年轻的水平)

玩你的数据,研究你的数据集,并尝试应用专门知识来删除冗余或过窄的信息。一旦完成,然后开始调整你的模型。另外,你可以考虑我做的事情:使用集成模型(通常是快速的,非常精确的默认值)。如RF或XGB,检查所有模型之间的结果是否一致。一旦确定正确,就可以开始调整结构、图层等,看看是否可以进一步推动结果

希望这有帮助


祝你好运!

谢谢这些链接。我会浏览它们。这是训练精度,而不是训练数据。我没有计算测试精度,因为我认为训练精度本身很低。我将与大家分享我的代码,并尝试预处理。很高兴知道我没有走远:)否则,我期望至少95%以上的训练准确率…没问题,希望我的回答能帮助你!让我知道你的结果,我很感兴趣。
def create_placeholders(n_x, n_y):
    X = tf.placeholder(tf.float32, [n_x, None], name = "X")
    Y = tf.placeholder(tf.float32, [n_y, None], name = "Y")
    return X, Y

def initialize_parameters(num_features):
    tf.set_random_seed(1)                   # so that your "random" numbers match ours
    layer_one_neurons = 5
    layer_two_neurons = 5
    layer_three_neurons = 2
    W1 = tf.get_variable("W1", [layer_one_neurons,num_features], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
    b1 = tf.get_variable("b1", [layer_one_neurons,1], initializer = tf.zeros_initializer())
    W2 = tf.get_variable("W2", [layer_two_neurons,layer_one_neurons], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
    b2 = tf.get_variable("b2", [layer_two_neurons,1], initializer = tf.zeros_initializer())
    W3 = tf.get_variable("W3", [layer_three_neurons,layer_two_neurons], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
    b3 = tf.get_variable("b3", [layer_three_neurons,1], initializer = tf.zeros_initializer())
    parameters = {"W1": W1,
                      "b1": b1,
                      "W2": W2,
                      "b2": b2,
                      "W3": W3,
                      "b3": b3}

    return parameters

def forward_propagation(X, parameters):
    """
    Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX

    Arguments:
    X -- input dataset placeholder, of shape (input size, number of examples)
    parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"
                  the shapes are given in initialize_parameters

    Returns:
    Z3 -- the output of the last LINEAR unit
    """

    # Retrieve the parameters from the dictionary "parameters" 
    W1 = parameters['W1']
    b1 = parameters['b1']
    W2 = parameters['W2']
    b2 = parameters['b2']
    W3 = parameters['W3']
    b3 = parameters['b3']

    Z1 = tf.add(tf.matmul(W1, X), b1)                                           
    A1 = tf.nn.relu(Z1)                                             
    Z2 = tf.add(tf.matmul(W2, A1), b2)                                  
    A2 = tf.nn.relu(Z2)                                         
    Z3 = tf.add(tf.matmul(W3, A2), b3)

    return Z3

def compute_cost(Z3, Y):
    """
    Computes the cost

    Arguments:
    Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
    Y -- "true" labels vector placeholder, same shape as Z3

    Returns:
    cost - Tensor of the cost function
    """

    # to fit the tensorflow requirement for tf.nn.softmax_cross_entropy_with_logits(...,...)
    logits = tf.transpose(Z3)
    labels = tf.transpose(Y)

    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))

    return cost

def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1000, print_cost = True):
    """
    Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.

    Arguments:
    X_train -- training set, of shape (input size = 12288, number of training examples = 1080)
    Y_train -- test set, of shape (output size = 6, number of training examples = 1080)
    X_test -- training set, of shape (input size = 12288, number of training examples = 120)
    Y_test -- test set, of shape (output size = 6, number of test examples = 120)
    learning_rate -- learning rate of the optimization
    num_epochs -- number of epochs of the optimization loop
    print_cost -- True to print the cost every 100 epochs

    Returns:
    parameters -- parameters learnt by the model. They can then be used to predict.
    """

    ops.reset_default_graph()                         # to be able to rerun the model without overwriting tf variables
    tf.set_random_seed(1)                             # to keep consistent results
    seed = 3                                          # to keep consistent results
    (n_x, m) = X_train.shape                          # (n_x: input size, m : number of examples in the train set)
    n_y = Y_train.shape[0]                            # n_y : output size
    costs = []                                        # To keep track of the cost

    # Create Placeholders of shape (n_x, n_y)
    X, Y = create_placeholders(n_x, n_y)

    # Initialize parameters
    parameters = initialize_parameters(X_train.shape[0])

    # Forward propagation: Build the forward propagation in the tensorflow graph
    Z3 = forward_propagation(X, parameters)

    # Cost function: Add cost function to tensorflow graph
    cost = compute_cost(Z3, Y)

    # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer.
    optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)

    # Initialize all the variables
    init = tf.global_variables_initializer()

    # Start the session to compute the tensorflow graph
    with tf.Session() as sess:

        # Run the initialization
        sess.run(init)

        # Do the training loop
        for epoch in range(num_epochs):
            _ , epoch_cost = sess.run([optimizer, cost], feed_dict={X: X_train, Y: Y_train})

            # Print the cost every epoch
            if print_cost == True and epoch % 100 == 0:
                print ("Cost after epoch %i: %f" % (epoch, epoch_cost))
            if print_cost == True and epoch % 5 == 0:
                costs.append(epoch_cost)

        # plot the cost
        plt.plot(np.squeeze(costs))
        plt.ylabel('cost')
        plt.xlabel('iterations (per tens)')
        plt.title("Learning rate =" + str(learning_rate))
        plt.show()

        # lets save the parameters in a variable
        parameters = sess.run(parameters)
        print ("Parameters have been trained!")

        # Calculate the correct predictions
        correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))

        # Calculate accuracy on the test set
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

        print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train}))
        #print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test}))

        return parameters

import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
import pandas as pd
%matplotlib inline
np.random.seed(1)

df = pd.read_csv('adult.data', header = None)
X_train_orig = df.drop(df.columns[[14]], axis=1, inplace=False)
Y_train_orig = df[[14]]
X_train = pd.get_dummies(X_train_orig) # get one hot encoding
Y_train = pd.get_dummies(Y_train_orig) # get one hot encoding
parameters = model(X_train.T, Y_train.T, None, None, num_epochs = 10000)
Random Forest:    86
SVM:              96
kNN:              83
MLP:              79