python - 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
必须相同,但是通过运行我具有不同形状的代码pred
is(3799,2)
而形状y
is (1,3799)
。
解决方案
我的评论:
- 如果您的标签不是 one-hot 编码的,则
tf.nn.sparse_softmax_cross_entropy_with_logits()
无需将其转换为 one-hot 编码表示即可使用。否则,tf.nn.softmax_cross_entropy_with_logits()
仅接受 one-hot 编码标签。 - 如果您在图形模式下编写代码,则不能将
numpy
值作为输入传递给损失函数(或作为输入传递给除feed_dict
in之外的任何内容)。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
推荐阅读
- vb.net - Visual basic .NET - 显示所选月份的天数
- go - 在银杏测试中检查非空值的正确方法
- java - 从 Firefox 74 / 75 发布 multipart/form-data 并在服务器端使用 Apache AJP 连接器时出现 java.io.IOException
- asp.net - 是否可以在 asp.net 上添加指向另一个页面的特定部分的链接?
- powershell - 批处理中的 Powershell:字符串到二进制并返回
- angular - 在动态创建的组件内动态创建组件
- android - 如何在我的 Android 清单文件中组织我的布局
- javascript - 发布时 Chrome 扩展后台脚本未运行
- microsoft-graph-api - 编辑实例时为系列主服务器发送图表日历更改通知
- rust - 在 rust 中使用 prost 和 tonic 时如何导入 .proto?