Attempting to Combine Numeric and Text Features in Tensorflow: ValueError: Layer model expects 2 input(s), but it received 1 input tensors

Attempting to Combine Numeric and Text Features in Tensorflow: ValueError: Layer model expects 2 input(s), but it received 1 input tensors

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

我拥有的三组特征是描述(实际评论)、比例价格和比例字数(描述的长度)。 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>]

如何解决该错误?

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

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