python - logits 和标签必须是可广播的

标签 python tensorflow neural-network deep-learning

我已经启动了tensorflow,并尝试实现简单的神经网络,并识别来自analyticsvidhya.com的数字练习问题,并遵循以下帖子: https://www.analyticsvidhya.com/blog/2016/10/an-introduction-to-implementing-neural-networks-using-tensorflow/

这是我的完整代码: https://github.com/NilSagor/AV_ml_practice/blob/master/digit_reco/digit_practise_01.ipynb

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(
    logits =output_layer, labels =y))

错误:日志和标签必须可广播

图像 reshape

temp = []
for img_name in train.filename:
    image_path = os.path.join(data_dir, 'train', 'Images', 'train', img_name)
    img = Image.open(filepath)
    img= np.array(img).astype('float32')
    temp.append(img)

train_x = np.stack(temp)

temp = []
for img_name in test.filename:
    image_path = os.path.join(data_dir, 'train', 'Images', 'test', img_name)   
    img = Image.open(filepath)    
    img= np.array(img).astype('float32')
    temp.append(img)

test_x = np.stack(temp)


with tf.Session() as sess:
    sess.run(init)

    for epoch in range(epochs):
        avg_cost = 0
        total_batch = int(train_data.shape[0]//batch_size)
        for i in range(total_batch):
            batch_x, batch_y = batch_creator(batch_size, train_x.shape[0], 'train')

            _,c = sess.run([optimizer, cost], feed_dict = {x: batch_x, y: batch_y})
            avg_cost += c/total_batch
        print("Epoch: ", (epoch+1), "cost: ", "{:.5f}".format(avg_cost))
    print("Training complete")

和batch_creator函数

def batch_creator(batch_size, dataset_length, dataset_name):
    """ Create batch with random samples and return appropiate format"""
    batch_mask = rng.choice(dataset_length, batch_size)
    batch_x = eval(dataset_name + "_x")[[batch_mask]].reshape(-1, input_num_units)
    batch_x = preproc(batch_x)
    if dataset_name == "train":
        batch_y = eval(dataset_name).ix[batch_mask, 'label'].values
        batch_y = dense_to_one_hot(batch_y)

    return batch_x, batch_y

weights = {
    'hidden': tf.Variable(tf.random_normal([input_num_units, hidden_num_units], seed = seed)),
    'output': tf.Variable(tf.random_normal([hidden_num_units, output_num_units], seed = seed))
}

biases = {
    'hidden': tf.Variable(tf.random_normal([hidden_num_units], seed = seed)),
    'output': tf.Variable(tf.random_normal([output_num_units], seed = seed))

}

hidden_layer = tf.add(tf.matmul(x, weights['hidden']), biases['hidden'])
hidden_layer = tf.nn.relu(hidden_layer)
output_layer = tf.matmul(hidden_layer, weights['output']) + biases['output']



cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits =output_layer, labels =y))
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)

如何消除错误以及如何高效地创建批处理?

提前致谢

最佳答案

替换

    from matplotlib.pyplot import imread
    img = imread(image_path)

    from scipy.misc import imread
    img = imread(image_path, flatten=True)

这就是上面帖子中所做的事情,它很重要,因为在读取图像的同时,它还将颜色层展平为单个灰度层。在您的情况下,(28, 28, 4)(28, 28)

关于python - logits 和标签必须是可广播的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57355681/

相关文章:

python - 如何从非 ascii "bytes"生成 Python 字符串

tensorflow - 当数据集不平衡时多类分类的最佳损失函数?

python - keras如何使用ReduceLROnPlateau

neural-network - 使用卷积神经网络检测四边形/矩形的想法

python - 导入错误 : No module named can but it's there according to pip list

python - FastAPI:如何从请求中获取原始 URL 路径?

python - 如果我安装了两个不同的版本,如何指定要导入的 pytorch?

python - GPU 安装 Tensorflow 错误

python - Tensorflow:是否可以修改检查点中的全局步骤

python - 在 matplotlib 中绘制 2D 函数