使用神经网络进行多类分类

时间:2017-09-01 09:45:00

标签: tensorflow neural-network statistics multiclass-classification

我有大约200个面部3D网格的东西,我想基于两个参数 - 高斯曲率和平均曲率对其顶点进行分类。我决定使用TensorFlow神经网络来实现这一目的。

我在所有脸上标记了18个突出的顶点 - 即鼻尖,下巴,眼角等。通过查看高斯和平均曲率的热图,可以很容易地识别所有这些点。所以我决定在这些点上制作这些参数的直方图(不同尺度 - 6 mm,4 mm,2 mm),并将其用作神经网络的输入。输入是608个特征的向量(对于6个直方图中的每一个有101个整数,对于点的平均和高斯曲率有2个浮点数)。输出应该是描述顶点所在类的向量。

以下是10个面的标尺6 mm的可视化直方图(每列描述一个突出点;每行一个面;有18列但只有11个类,因为例如内眼角 - 第5和第6列 - 是对称的,因此两列都属于同一类)enter image description here

我修改了this example。首先,我尝试制作二元分类器。由此产生的netowrk可以很好地识别鼻尖与剩余点或下巴与剩余点的关系,准确率约为98%。我让神经网络对网格的所有顶点进行分类。令我惊讶的是,输出向量总是[1.0,0.0]或[0.0,1.0] - 我猜它有时候不应该确定,所以它应该返回例如[0.5,0.5]。的 1。问题 - 为什么?

现在我想创建一个单一的神经网络告诉我:"这一点是0.2概率鼻尖和0.7下巴,0.05内眼角,..."。但是通过向输出层添加更多类来提高准确性。所以11个班级的准确率只有30%左右。的 2。问题 - 为什么以及如何解决它?并且具有概率的输出向量仍然只有一个1和十个0。

我将不胜感激。

以下是traintest数据。 这是我的代码:

import numpy as np
import tensorflow as tf

# Parameters
learning_rate = 0.001
training_epochs = 100
batch_size = 100

# Network Parameters
n_hidden_1 = 100 # 1st layer number of features
n_hidden_2 = 100 # 2nd layer number of features
n_input = 608   # input number of features
n_classes = 11  # output number of labels

# Input files
train_data_filename = "data/train.csv"
test_data_filename = "data/test.csv"
model_name = "model"

# Extract numpy representations of the labels and features given rows consisting of:
#   label, feat_0, feat_1, ..., feat_n
def extract_data(filename):
    labels = []
    fvecs = []

    # Iterate over the rows, splitting the label from the features. Convert labels
    # to integers and features to floats.
    with open(filename) as file:
        for line in file:
            row = list(filter(None, line.strip().split(";")))

            labels.append([int(x) for x in row[:n_classes]])
            fvecs.append([float(x) for x in row[n_classes:]])

    fvecs_np = np.matrix(fvecs).astype(np.float32)
    labels_np = np.matrix(labels).astype(np.uint8)

    return fvecs_np, labels_np

# Create model
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output layer with linear activation
    out_layer = tf.add(tf.matmul(layer_2, weights['out']), biases['out'])
    return out_layer

def main(argv=None):

    train_data, train_labels = extract_data(train_data_filename)
    test_data, test_labels = extract_data(test_data_filename)

    train_size, num_features = train_data.shape
    test_size, _ = test_data.shape

    x = tf.placeholder("float", [None, n_input], name="input_node")
    y = tf.placeholder("float", [None, n_classes])

    weights = {
        'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
        'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
        'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
    }
    biases = {
        'b1': tf.Variable(tf.random_normal([n_hidden_1])),
        'b2': tf.Variable(tf.random_normal([n_hidden_2])),
        'out': tf.Variable(tf.random_normal([n_classes]))
    }

    prediction = multilayer_perceptron(x, weights, biases)
    probabilities = tf.nn.softmax(prediction, name="output_node")

    # Define probabilities, loss and optimizer
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

    # Evaluation.
    correct_prediction = tf.equal(tf.argmax(probabilities, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

    # Create a local session to run this computation.
    with tf.Session() as s:

        tf.global_variables_initializer().run()

        print('Initialized!')
        print('Training.')

        for step in range(training_epochs * train_size // batch_size):

            offset = (step * batch_size) % train_size
            batch_data = train_data[offset:(offset + batch_size), :]
            batch_labels = train_labels[offset:(offset + batch_size)]

            _, c = s.run([optimizer, cost], feed_dict={x: batch_data, y: batch_labels})

            if step % 100 == 0:
                print('Training Step:' + str(step) + '  Accuracy =  ' + str(
                        s.run(accuracy, feed_dict={x: test_data, y: test_labels})) + '  Loss = ' + str(
                        s.run(cost, {x: train_data, y: train_labels})))

        print("Optimization Finished!")
        print("Accuracy - test:", accuracy.eval({x: test_data, y: test_labels}))
        print("Accuracy - train:", accuracy.eval({x: train_data, y: train_labels}))

if __name__ == '__main__':
    tf.app.run()

0 个答案:

没有答案