ValueError:尺寸必须相等,但对于'softmax_cross_entropy_with_logits_sg,尺寸应为2和3799

时间:2019-04-28 15:37:55

标签: python tensorflow machine-learning

我正在开发用于对良性和恶意软件apk进行分类的神经网络模型。

我尝试使用tf.squeeze()函数,但是使用它后我无法使用优化器

def neural_network_model(data):
    l1 = tf.add(tf.matmul(data,hidden_1_layer['weight']), hidden_1_layer['bias'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1,hidden_2_layer['weight']), hidden_2_layer['bias'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2,hidden_3_layer['weight']), hidden_3_layer['bias'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3,output_layer['weight']) + output_layer['bias']

    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels= y) )

    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

predy的形状必须相同,但是通过运行代码,我将pred的形状更改为(3799,2),而{{1}的形状}是y

1 个答案:

答案 0 :(得分:0)

我的评论:

  • 如果标签不是一键编码的,则可以使用tf.nn.sparse_softmax_cross_entropy_with_logits()而不将其转换为一键编码的表示形式。否则,tf.nn.softmax_cross_entropy_with_logits()仅接受一键编码的标签。
  • 如果您以图形方式编写代码,则不能将numpy的值作为损失函数的输入(或作为feed_dict中除session.run()以外的其他任何东西的输入)的传递。请改用占位符。

以下是说明如何使用占位符和馈送numpy数据数组的示例。

import numpy as np
import tensorflow as tf

# Dummy data with 3 classes for illustration
n_classes =3
x_train = np.random.normal(size=(3799, 2)) # 3799 samples of size (2, ) each
y_train = np.random.randint(low=0, high=n_classes, size=(1, 3799))

# Define placeholders here
x = tf.placeholder(tf.float32, shape=(None, 2))
y = tf.placeholder(tf.int32, shape=(1, None))

# Define your network here
w = tf.Variable(tf.random_normal(shape=[2, n_classes]), dtype=tf.float32)
b = tf.Variable(tf.zeros([n_classes, ]), dtype=tf.float32)
logits = tf.matmul(x, w) + b

labels = tf.squeeze(y)
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
                                                          labels=labels)
cost = tf.reduce_mean(xentropy)
train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

# Training
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    cost_val = sess.run(cost, feed_dict={x:x_train, y:y_train})
    print(cost_val) # 1.8630761
    sess.run(train_op, feed_dict={x:x_train, y:y_train}) # optimizer step
    cost_val = sess.run(cost, feed_dict={x:x_train, y:y_train})
    print(cost_val) # 1.8619089