簡體   English   中英

Keras / Tensorflow:使用tf.data.Dataset API預測

[英]Keras / Tensorflow: Predict Using tf.data.Dataset API

我正在使用帶有Tensorflow后端的Keras來構建這個問題的模型: https ://www.kaggle.com/cfpb/us-consumer-finance-complaints(只是練習)。

我使用tf.data.Dataset API訓練我的tf.data.Dataset模型。 現在,我有一個Pandas DataFrame, df_testing ,其列是complaint (字符串)和label (也是字符串)。 我想預測這些新樣本。 我創建了一個tf.data.Dataset對象,執行預處理,創建一個Iterator,並在我的模型上調用predict:

data = df_testing["complaint"].values
labels = df_testing["label"].values

dataset = tf.data.Dataset.from_tensor_slices((data))
dataset = dataset.map(lambda x: ({'reviews': x}))
dataset = dataset.batch(self.batch_size).repeat()
dataset = dataset.map(lambda x: self.preprocess_text(x, self.data_table))
dataset = dataset.map(lambda x: x['reviews'])
dataset = dataset.make_initializable_iterator()

我的訓練使用了tf.data.Dataset ,其中每個元素的形式({'reviews': "movie was great"}, "positive")所以我在這里模仿預測。 此外,我的預處理只是將我的字符串轉換為整數Tensor

我打電話的時候:

preds = model.predict(dataset)

但我告訴我的predict呼叫失敗:

ValueError: When using iterators as input to a model, you should specify the `steps` argument.

所以我將此調用修改為:

preds = model.predict(dataset, steps=3)

但現在我回來了:

ValueError: Please provide data as a list or tuple of 2 elements  - input and target pair. Received Tensor("IteratorGetNext_2:0", shape=(?, 100), dtype=int32)

我在這里做錯了什么? 在預測時我不應該提供2個元素的元組(我不需要標簽)。

謝謝你的盡心幫助!

你在哪個版本的Keras? 我在代碼庫中找不到特定的錯誤消息,但我想我找到了以前的位置。

這是我認為接近您正在運行的版本的代碼版本中的錯誤: commit

這是該錯誤的更新版本: https//github.com/tensorflow/tensorflow/blob/master/tensorflow/python/keras/engine/training_eager.py#L464

輸入驗證的條件已經改變(在最新版本中您的輸入將被接受),但相關的是錯誤消息更加清晰:

raise ValueError(
    'Please provide data as a list or tuple of 1, 2, or 3 elements '
    ' - `(input)`, or `(input, target)`, or `(input, target,'
    'sample_weights)`. Received %s. We do not use the `target` or'
    '`sample_weights` value here.' % inputs.output_shapes)

目標值從未在預測函數中使用,因此可以是任何東西。 查看函數的其余部分next_element[1]從未使用過。

[ TLDR ]使用當前版本,為數據添加虛擬目標值,或更新Keras。

以下代碼適用於我(在tensorflow 1.10.0上測試):

[TLDR]僅插入空字典作為虛擬輸入並指定步數:

model.predict(x={},steps=4)

完整代碼:

import numpy as np
import tensorflow as tf
from tensorflow.data import Dataset
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model


# dummy data:
x = np.arange(4).reshape(-1, 1).astype('float32')
y = np.arange(5, 9).reshape(-1, 1).astype('float32')

# build the Datasets
ds_x = Dataset.from_tensor_slices(x).repeat().batch(4)
it_x = ds_x.make_one_shot_iterator()

ds_y = Dataset.from_tensor_slices(y).repeat().batch(4)
it_y = ds_y.make_one_shot_iterator()


# build compile and train the model
input_vals = Input(tensor=it_x.get_next())
output = Dense(1, activation='relu')(input_vals)
model = Model(inputs=input_vals, outputs=output)
model.compile('rmsprop', 'mse', target_tensors=[it_y.get_next()])
model.fit(steps_per_epoch=1, epochs=5, verbose=2)

# infer using the dataset
model.predict(x={},steps=4)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM