2 回答

TA貢獻2021條經驗 獲得超8個贊
錯誤只是tokenizer.tokenize需要一個字符串,而你給它一個列表。這個簡單的編輯將會起作用。我只是做了一個循環,將所有字符串提供給分詞器,而不是給它一個字符串列表。
dataset = tf.data.experimental.make_csv_dataset(
'test.csv',
batch_size=2,
label_name='target',
num_epochs=1)
tokenizer = tfds.features.text.Tokenizer()
lowercase = True
vocabulary = Counter()
for features, _ in dataset:
text = features['text']
if lowercase:
text = tf.strings.lower(text)
for t in text:
tokens = tokenizer.tokenize(t.numpy())
vocabulary.update(tokens)

TA貢獻1799條經驗 獲得超6個贊
創建的數據集的每個元素make_csv_dataset
都是CVS 文件的一批行,而不是單個行;這就是為什么它需要batch_size
作為輸入參數。另一方面,for
用于處理和標記文本特征的當前循環期望一次單個輸入樣本(即行)。因此,tokenizer.tokenize
給定一批字符串會失敗并引發TypeError: Expected binary or unicode string, got array(...)
.
以最小的更改解決此問題的一種方法是首先以某種方式取消批處理數據集,對數據集執行所有預處理,然后再次對數據集進行批處理。unbatch
幸運的是,我們可以在這里使用一個內置方法:
dataset = tf.data.experimental.make_csv_dataset(
? ? ...,
? ? # This change is **IMPORTANT**, otherwise the `for` loop would continue forever!
? ? num_epochs=1
)
# Unbatch the dataset; this is required even if you have used `batch_size=1` above.
dataset = dataset.unbatch()
#############################################
#
# Do all the preprocessings on the dataset here...
#
##############################################
# When preprocessings are finished and you are ready to use your dataset:
#### 1. Batch the dataset (only if needed for or applicable to your specific workflow)
#### 2. Repeat the dataset (only if needed for or applicable to specific your workflow)
dataset = dataset.batch(BATCH_SIZE).repeat(NUM_EPOCHS or -1)
@NicolasGervais 的答案中建議的另一種解決方案是調整和修改所有預處理代碼,以處理一批樣本,而不是一次處理單個樣本。
添加回答
舉報