首页 > 解决方案 > 尝试在 Tensorflow 中组合数字和文本特征:ValueError:层模型需要 2 个输入,但它接收到 1 个输入张量

问题描述

我正在尝试使用葡萄酒评论数据集做一个沙盒项目,并希望将文本数据和一些工程数字特征结合到神经网络中,但我收到了一个值错误。

我拥有的三组功能是描述(实际评论)、按比例缩放的价格和按比例缩放的字数(描述长度)。我将 y 目标变量转换为代表好评或差评的二分变量,将其转化为分类问题。

这些是否是最好的功能并不是重点,但我希望尝试将 NLP 与元数据或数字数据结合起来。当我仅使用描述运行代码时,它可以正常工作,但是添加其他变量会导致值错误。

y = df['y']
X = df.drop('y', axis=1)

# split up the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)

X_train.head();
description_train = X_train['description']
description_test = X_test['description']

#subsetting the numeric variables
numeric_train = X_train[['scaled_price','scaled_num_words']].to_numpy()
numeric_test = X_test[['scaled_price','scaled_num_words']].to_numpy()

MAX_VOCAB_SIZE = 60000
tokenizer = Tokenizer(num_words=MAX_VOCAB_SIZE)
tokenizer.fit_on_texts(description_train)
sequences_train = tokenizer.texts_to_sequences(description_train)
sequences_test = tokenizer.texts_to_sequences(description_test)

word2idx = tokenizer.word_index
V = len(word2idx)
print('Found %s unique tokens.' % V)
Found 31598 unique tokens.

nlp_train = pad_sequences(sequences_train)
print('Shape of data train tensor:', nlp_train.shape)
Shape of data train tensor: (91944, 136)

# get sequence length
T = nlp_train.shape[1]

nlp_test = pad_sequences(sequences_test, maxlen=T)
print('Shape of data test tensor:', nlp_test.shape)
Shape of data test tensor: (45286, 136)

data_train = np.concatenate((nlp_train,numeric_train), axis=1)
data_test = np.concatenate((nlp_test,numeric_test), axis=1)



# Choosing embedding dimensionality
D = 20

# Hidden state dimensionality
M = 40

nlp_input = Input(shape=(T,),name= 'nlp_input')
meta_input = Input(shape=(2,), name='meta_input')
emb = Embedding(V + 1, D)(nlp_input)
emb = Bidirectional(LSTM(64, return_sequences=True))(emb)
emb = Dropout(0.40)(emb)
emb = Bidirectional(LSTM(128))(emb)
nlp_out = Dropout(0.40)(emb)
x = tf.concat([nlp_out, meta_input], 1)
x = Dense(64, activation='swish')(x)
x = Dropout(0.40)(x)
x = Dense(1, activation='sigmoid')(x)

model = Model(inputs=[nlp_input, meta_input], outputs=[x])

#next, create a custom optimizer
optimizer1 = RMSprop(learning_rate=0.0001)

# Compile and fit
model.compile(
  loss='binary_crossentropy',
  optimizer='adam',
  metrics=['accuracy']
)


print('Training model...')
r = model.fit(
  data_train,
  y_train,
  epochs=5, 
  validation_data=(data_test, y_test))

如果这太过分了,我深表歉意,但我想确保我没有遗漏任何可能有用的相关线索或信息。我从运行代码中得到的错误是

ValueError: Layer model expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 138) dtype=float32>]

我该如何解决该错误?

标签: pythontensorflowkerasdeep-learningnlp

解决方案


感谢您发布所有代码。这两行是问题所在:

data_train = np.concatenate((nlp_train,numeric_train), axis=1)
data_test = np.concatenate((nlp_test,numeric_test), axis=1)

numpy 数组被解释为一个输入,无论其形状如何。使用tf.data.Dataset您的数据集并将其直接提供给您的模型:

train_dataset = tf.data.Dataset.from_tensor_slices((nlp_train, numeric_train))
labels = tf.data.Dataset.from_tensor_slices(y_train)
dataset = tf.data.Dataset.zip((train_dataset, train_dataset))
r = model.fit(dataset, epochs=5)

或者只是将您的数据直接model.fit()作为输入列表提供:

r = model.fit(
  [nlp_train, numeric_train],
  y_train,
  epochs=5, 
  validation_data=([nlp_test, numeric_test], y_test))

推荐阅读