我正在嘗試使用 Tensorflow 2.7.0 及其新TextVectorization層。然而,在這個簡單的例子中,有些事情并不完全正確:
import tensorflow as tf
import numpy as np
X = np.array(['this is a test', 'a nice test', 'best test this is'])
vectorize_layer = tf.keras.layers.TextVectorization()
vectorize_layer.adapt(X)
emb_layer = tf.keras.layers.Embedding(input_dim=vectorize_layer.vocabulary_size() 1, output_dim=2, input_length=4)
flatten_layer = tf.keras.layers.Flatten()
dense_layer = tf.keras.layers.Dense(1)
model = tf.keras.models.Sequential()
model.add(vectorize_layer)
model.add(emb_layer)
model.add(flatten_layer)
#model.add(dense_layer)
model(X)
到目前為止,這有效。我用單詞制作整數,嵌入它們,將它們壓平。但是如果我想Dense在展平后添加一個圖層(即取消注釋一行),事情就會中斷,我會從問題標題中收到錯誤訊息。我什至使用了層的input_length引數,Embedding因為檔案說我應該在使用 embedding->flatten->dense 時指定它。但它不起作用。
你知道我怎樣才能讓它作業,Flatten而不是像這樣GlobalAveragePooling1D嗎?
非常感謝!
uj5u.com熱心網友回復:
您需要定義序列的最大長度。
vectorize_layer = tf.keras.layers.TextVectorization(output_mode = 'int',
output_sequence_length=10)
如果您選中model.summary(),則輸出形狀TextVectorization將為(None, None).
第一個None表示模型可以接受任何批量大小,第二個表示傳遞給的任何句子TextVectorization都不會被截斷或填充。所以輸出的句子可以有可變的長度。
例子:
import tensorflow as tf
import numpy as np
X = np.array(['this is a test', 'a nice test', 'best test this is'])
vectorize_layer = tf.keras.layers.TextVectorization(output_mode = 'int')
vectorize_layer.adapt(X)
model = tf.keras.models.Sequential()
model.add(vectorize_layer)
model(np.array(['this is a test']))
>> <tf.Tensor: shape=(1, 4), dtype=int64, numpy=array([[3, 4, 5, 2]])>
model(np.array(['this is a longer test sentence']))
>> <tf.Tensor: shape=(1, 6), dtype=int64, numpy=array([[3, 4, 5, 1, 2, 1]])>
重新定義:
vectorize_layer = tf.keras.layers.TextVectorization(output_mode = 'int',
output_sequence_length = 5)
model(np.array(['this is a longer test sentence']))
>> <tf.Tensor: shape=(1, 5), dtype=int64, numpy=array([[3, 4, 5, 1, 2]])>
model(np.array(['this is']))
>> <tf.Tensor: shape=(1, 5), dtype=int64, numpy=array([[3, 4, 0, 0, 0]])>
定義output_sequence_length一個數字將確保輸出的長度是一個固定的數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400232.html
上一篇:在Tkinter中使用輸入時的網格方法不起作用。為什么?
下一篇:從檔案中拆分符號
