我有一個 TensorFlow 資料集,其中包含以下格式的專案
(
<tf.Tensor: shape=(14,), dtype=int64, numpy=array([ 1, 2, 3, 4, 5, 4, 6, 7, 8, 9, 10, 11, 9, 12])>,
<tf.Tensor: shape=(12,), dtype=int64, numpy=array([ 1, 2, 3, 4, 5, 4, 6, 7, 8, 9, 10, 11])>,
<tf.Tensor: shape=(), dtype=int64, numpy=0>
)
由此代碼創建
encoder = tfds.deprecated.text.TokenTextEncoder(token_counts)
def encode(text0, text1, label):
return encoder.encode(text0.numpy()), encoder.encode(text1.numpy()), label
def encode_map_fn(text, text2, label):
return tf.py_function(encode,
inp=[text, text2, label],
Tout=[tf.int64, tf.int64, tf.int64])
ds_train = ds_raw_train.map(encode_map_fn)
ds_train_valid = ds_raw_train_valid.map(encode_map_fn)
它使用以下代碼進行批處理,但這對問題沒有任何影響
train_data_batch = ds_train.padded_batch( 32, padded_shapes=([-1],[-1],[]))
valid_data_batch = ds_train_valid.padded_batch( 32, padded_shapes=([-1],[-1],[]))
它產生以下輸出
(
<tf.Tensor: shape=(32, 29), dtype=int64, numpy=array([[ 1, 2, 3, 4, 5, 4, 6, 7, 8, 9, 10, 11, 9, 12],...])>,
<tf.Tensor: shape=(32, 29), dtype=int64, numpy=array([[ 1, 2, 3, 4, 5, 4, 6, 7, 8, 9, 10, 11],...])>,
<tf.Tensor: shape=(32,), dtype=int64, numpy=array([0,...]>
)
創建模型后
lstm_layer = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = False))
size_dic = len(token_counts) 2
emb = Embedding(size_dic, 100, input_length=300)
input1 = tf.keras.Input(shape=(300,))
input2 = tf.keras.Input(shape=(300,))
e1 = emb(input1)
e2 = emb(input2)
x1 = lstm_layer(e1)
x2 = lstm_layer(e2)
mhd = lambda x: tf.keras.backend.abs(x[0] - x[1])
merged = tf.keras.layers.Lambda(function=mhd, output_shape= lambda x: x[0])([x1, x2])
preds = tf.keras.layers.Dense(1)(merged)
model = tf.keras.Model(inputs=(input1, input2), outputs=preds)
model.compile(optimizer=tf.keras.optimizers.Adam(1e-3),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=False),
metrics=['accuracy'])
我嘗試將模型與
history = model.fit(train_data_batch, validation_data=valid_data_batch, epochs=5)
這會導致以下錯誤
ValueError: Layer "model_1" expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None) dtype=int64>]
我認為資料集的專案應該是 format ([tf.int64, tf.int64], tf.int64),但是嘗試設定它Tout會導致錯誤。
有沒有辦法將資料集更改為所需的格式,更改模型以按原樣接受資料集,或者為資料集中每個專案的第一個、第二個和第三個屬性獲取單獨的迭代器?
uj5u.com熱心網友回復:
嘗試:
train_data_batch = train_data_batch.map(lambda x1, x2, y: ((x1, x2), y))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434163.html
上一篇:如何用資料集擬合keras模型?
