Tensorflow估算器ValueError:logits和标签必须具有相同的形状((?,1)vs(?,))

时间:2018-02-18 12:15:43

标签: python tensorflow keras

我对ML相对较新,我想我会从keras开始。在这里,我使用二进制交叉熵将电影评论分类为正面或负面。所以,当我试图用tensorflow估算器包装我的keras模型时,我得到错误:

  

Tensorflow估算器ValueError:logits和标签必须具有相同的形状((?,1)vs(?,))

我正在使用sigmoid激活作为我的最后一层,猜测我在这里遗漏了一些微不足道的东西。有帮助吗?

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)

2 个答案:

答案 0 :(得分:4)

您应该将标签重塑为2d张量(第一个维度是批量维度,第二个维度是标量标签):

# 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))

答案 1 :(得分:0)

使用model.summary()检查网络

最终,您需要精简网络以使其具有与类相同的输出。 例如,对数字进行OCR运算并最终输出Dense(10)(对于数字0到9)。

例如表征狗与猫的关系。最后一层必须有两个输出(0-dog,1-cat)