我正在开发一个神经网络模型,用于对良性和恶意软件 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
的形状必须相同,但是通过运行代码,我得到不同形状的 pred
为 ( 3799,2)
而 y
的形状为 (1,3799)
。
最佳答案
我的评论:
- 如果您的标签不是 one-hot 编码的,您可以使用
tf.nn.sparse_softmax_cross_entropy_with_logits()
,而无需将其转换为 one-hot 编码表示形式。否则,tf.nn.softmax_cross_entropy_with_logits()
仅接受单热编码标签。 - 您无法将
numpy
值作为损失函数的输入传递(或作为session.run() 中除
) 如果您正在以图形模式编写代码。请改用占位符。feed_dict
之外的任何内容的输入)
以下示例说明如何使用占位符并提供 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
关于python - ValueError : Dimensions must be equal,,但“softmax_cross_entropy_with_logits_sg”的值为 2 和 3799,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55891843/