首页 > 解决方案 > ValueError: 维度必须相等,但对于 'softmax_cross_entropy_with_logits_sg 是 2 和 3799

问题描述

我正在开发一个用于分类良性和恶意软件 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)

pred和的形状y必须相同,但是通过运行我具有不同形状的代码predis(3799,2)而形状yis (1,3799)

标签: pythontensorflowmachine-learning

解决方案


我的评论:

  • 如果您的标签不是 one-hot 编码的,则tf.nn.sparse_softmax_cross_entropy_with_logits()无需将其转换为 one-hot 编码表示即可使用。否则,tf.nn.softmax_cross_entropy_with_logits()仅接受 one-hot 编码标签。
  • 如果您在图形模式下编写代码,则不能将numpy值作为输入传递给损失函数(或作为输入传递给除feed_dictin之外的任何内容)。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

推荐阅读