Tensorflow估计器ValueError:logits和标签必须具有相同的形状((?,1)vs(?,)) [英] Tensorflow estimator ValueError: logits and labels must have the same shape ((?, 1) vs (?,))

查看:1027
本文介绍了Tensorflow估计器ValueError:logits和标签必须具有相同的形状((?,1)vs(?,))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ML比较陌生,以为我将从keras开始.在这里,我使用二进制交叉熵将电影评论分为正面评论或负面评论.因此,当我尝试使用张量流估计器包装我的keras模型时,出现错误:

I'm relatively new to ML, thought I'll start with keras. Here I'm classifying movie reviews as positive or negative using binary crossentropy. So, when I'm trying to wrap my keras model with tensorflow estimator, I get the error:

Tensorflow估算器ValueError:登录件和标签的形状必须相同((?,1)vs(?,))

Tensorflow estimator ValueError: logits and labels must have the same shape ((?, 1) vs (?,))

我将S型激活用作最后一层,猜想我这里缺少一些琐碎的东西.有什么帮助吗?

I'm using sigmoid activation as my last layer, guess I'm missing something trivial here. Any help?

from tensorflow import keras
import tensorflow as tf
print("Tensorflow {} loaded".format(tf.__version__))
import numpy as np

keras.__version__
from keras.datasets import imdb

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
def vectorize_sequences(sequences, dimension=10000):
    # Create an all-zero matrix of shape (len(sequences), dimension)
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.  # set specific indices of results[i] to 1s
    return results.astype('float32')

# Our vectorized training data
x_train = vectorize_sequences(train_data)

# Our vectorized test data
x_test = vectorize_sequences(test_data)

# Our vectorized labels
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]

model = keras.models.Sequential()
model.add(keras.layers.Dense(16, activation='relu', input_shape=(10000,), name='reviews'))
model.add(keras.layers.Dense(16, activation='relu'))
model.add(keras.layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])
estimator_model = keras.estimator.model_to_estimator(keras_model=model)

def input_function(features,labels=None,shuffle=False,epochs=None,batch_size=None):
    input_fn = tf.estimator.inputs.numpy_input_fn(
        x={"reviews_input": features},
        y=labels,
        shuffle=shuffle,
        num_epochs=epochs,
        batch_size=batch_size
    )
    return input_fn

estimator_model.train(input_fn=input_function(partial_x_train, partial_y_train, True,20,512))
score = estimator_model.evaluate(input_function(x_val, labels=y_val))
print(score)

推荐答案

您应将标签重塑为2d张量(第一个尺寸为批处理尺寸,第二个为标量标签):

You should reshape your labels as 2d-tensor (the first dimension will be the batch dimension and the second the scalar label):

# Our vectorized labels
y_train = np.asarray(train_labels).astype('float32').reshape((-1,1))
y_test = np.asarray(test_labels).astype('float32').reshape((-1,1))

这篇关于Tensorflow估计器ValueError:logits和标签必须具有相同的形状((?,1)vs(?,))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆