CLIP
類別keras_cv.models.CLIP(
embed_dim=512,
image_resolution=224,
vision_layers=12,
vision_width=768,
vision_patch_size=32,
context_length=77,
vocab_size=49408,
transformer_width=512,
transformer_heads=8,
transformer_layers=12,
**kwargs
)
CLIP 实现了对比语言-图像预训练 (CLIP) 架构,该架构支持联合学习视觉和文本表示,用于各种下游任务。默认的基本模型架构将设置为 clip-vit-base-patch32。
參數
範例
processor = CLIPProcessor(
input_resolution=224,
"path_to_vocab.json",
"path_to_merges.txt"
)
processed_image = processor.process_images(["cat.jpg"])
tokens = processor(
["mountains", "cat on tortoise", "two cats"]
)
model = CLIP.from_preset("clip-vit-base-patch16")
image_logits, text_logits = model(
{
"images": processed_image,
"token_ids": tokens["token_ids"],
"padding_mask": tokens["padding_mask"],
}
)
from_preset
方法CLIP.from_preset()
从预设配置和权重实例化 CLIP 模型。
參數
None
,这取决于预设是否有可用的预训练权重。None
。如果为 None
,则将使用预设值。範例
# Load architecture and weights from preset
model = keras_cv.models.CLIP.from_preset(
"clip-vit-base-patch16",
)
# Load randomly initialized model from preset architecture with weights
model = keras_cv.models.CLIP.from_preset(
"clip-vit-base-patch16",
load_weights=False,
预设名称 | 参数 | 说明 |
---|---|---|
clip-vit-base-patch16 | 149.62M | 此模型使用 ViT-B/16 Transformer 架構作為圖像編碼器,並使用遮罩自注意力 Transformer 作為文字編碼器。這些編碼器經過訓練,可透過對比損失最大化(圖像、文字)對的相似性。此模型使用 16 的區塊大小和大小為 (224, 224) 的輸入圖像 |
clip-vit-base-patch32 | 151.28M | 此模型使用 ViT-B/32 Transformer 架構作為圖像編碼器,並使用遮罩自注意力 Transformer 作為文字編碼器。這些編碼器經過訓練,可透過對比損失最大化(圖像、文字)對的相似性。此模型使用 32 的區塊大小和大小為 (224, 224) 的輸入圖像 |
clip-vit-large-patch14 | 427.62M | 此模型使用 ViT-L/14 Transformer 架構作為圖像編碼器,並使用遮罩自注意力 Transformer 作為文字編碼器。這些編碼器經過訓練,可透過對比損失最大化(圖像、文字)對的相似性。此模型使用 14 的區塊大小和大小為 (224, 224) 的輸入圖像 |
clip-vit-large-patch14-336 | 427.94M | 此模型使用 ViT-L/14 Transformer 架構作為圖像編碼器,並使用遮罩自注意力 Transformer 作為文字編碼器。這些編碼器經過訓練,可透過對比損失最大化(圖像、文字)對的相似性。此模型使用 14 的區塊大小和大小為 (336, 336) 的輸入圖像 |
CLIPAttention
類別keras_cv.models.feature_extractor.CLIPAttention(
proj_dim, num_heads, num_hidden_layers, dropout=0.0, **kwargs
)
改編自 https://github.com/huggingface/transformers/blob/main/src/transformers/models/clip/modeling_clip.py # noqa: E501
CLIPEncoder
類別keras_cv.models.feature_extractor.CLIPEncoder(width, num_layers, heads, **kwargs)
這是所有層級繼承的類別。
層級是一個可呼叫的物件,它將一個或多個張量作為輸入,並輸出一個或多個張量。它涉及在 call()
方法中定義的*計算*,以及*狀態*(權重變數)。狀態可以在
__init__()
中建立,例如透過 self.add_weight()
;build()
方法中建立,該方法由對層級的第一次 __call__()
呼叫,並提供輸入的形狀,這些形狀在初始化時可能未知。層級是遞迴可組合的:如果您將一個層級實例分配為另一個層級的屬性,則外部層級將開始追蹤內部層級建立的權重。應在 __init__()
方法或 build()
方法中實例化巢狀層級。
使用者只需實例化一個層級,然後將其視為可呼叫的物件。
參數
keras.DTypePolicy
,它允許計算和權重 dtype 不同。預設值為 None
。None
表示使用 keras.config.dtype_policy()
,這是一個 float32
策略,除非設定為不同的值(透過 keras.config.set_dtype_policy()
)。屬性
layer.variable_dtype
的別名。keras.DTypePolicy
一起使用時,這將與 variable_dtype
不同。layer.trainable_weights
的一部分返回。InputSpec
物件,用於指定此圖層可接受的輸入限制。我們建議 Layer
的子類別實作以下方法:
__init__()
:定義自訂圖層屬性,並使用 add_weight()
或其他狀態建立不依賴輸入形狀的圖層權重。build(self, input_shape)
:此方法可用於使用 add_weight()
或其他狀態建立依賴輸入形狀的權重。__call__()
會透過呼叫 build()
自動建構圖層(如果尚未建構)。call(self, *args, **kwargs)
:在確認已呼叫 build()
後於 __call__
中呼叫。call()
會執行將圖層套用到輸入引數的邏輯。您可以在 call()
中選擇性地使用兩個保留的關鍵字引數:1. training
(布林值,表示呼叫是在推論模式還是訓練模式)。2. mask
(布林張量,用於編碼輸入中被遮罩的時間步長,例如在 RNN 圖層中使用)。此方法的典型簽章是 call(self, inputs)
,如果圖層需要,使用者可以選擇性地新增 training
和 mask
。get_config(self)
:傳回包含用於初始化此圖層的配置的字典。如果金鑰與 __init__()
中的引數不同,則也需要覆寫 from_config(self)
。儲存圖層或包含此圖層的模型時會使用此方法。範例
以下是一個基本範例:具有兩個變數 w
和 b
的圖層,傳回 y = w . x + b
。它顯示如何實作 build()
和 call()
。設定為圖層屬性的變數會被追蹤為圖層的權重(位於 layer.weights
中)。
class SimpleDense(Layer):
def __init__(self, units=32):
super().__init__()
self.units = units
# Create the state of the layer (weights)
def build(self, input_shape):
self.kernel = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="glorot_uniform",
trainable=True,
name="kernel",
)
self.bias = self.add_weight(
shape=(self.units,),
initializer="zeros",
trainable=True,
name="bias",
)
# Defines the computation
def call(self, inputs):
return ops.matmul(inputs, self.kernel) + self.bias
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(ops.ones((2, 2)))
assert len(linear_layer.weights) == 2
# These weights are trainable, so they're listed in `trainable_weights`:
assert len(linear_layer.trainable_weights) == 2
除了透過訓練期間的反向傳播更新的可訓練權重外,圖層也可以具有不可訓練的權重。這些權重旨在於 call()
期間手動更新。以下是一個計算輸入值的累加總和的圖層範例:
class ComputeSum(Layer):
def __init__(self, input_dim):
super(ComputeSum, self).__init__()
# Create a non-trainable weight.
self.total = self.add_weight(
shape=(),
initializer="zeros",
trainable=False,
name="total",
)
def call(self, inputs):
self.total.assign(self.total + ops.sum(inputs))
return self.total
my_sum = ComputeSum(2)
x = ops.ones((2, 2))
y = my_sum(x)
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []
CLIPImageEncoder
類別keras_cv.models.feature_extractor.CLIPImageEncoder(
input_resolution, patch_size, width, num_layers, heads, output_dim, **kwargs
)
將圖層組合成具有訓練/推論功能的物件的模型。
有三種方法可以實例化 Model
:
您從 Input
開始,連結圖層呼叫以指定模型的前向傳遞,最後從輸入和輸出建立模型。
inputs = keras.Input(shape=(37,))
x = keras.layers.Dense(32, activation="relu")(inputs)
outputs = keras.layers.Dense(5, activation="softmax")(x)
model = keras.Model(inputs=inputs, outputs=outputs)
注意:僅支援輸入張量的字典、清單和元組。不支援巢狀輸入(例如清單的清單或字典的字典)。
也可以使用中間張量建立新的函數式 API 模型。這讓您可以快速提取模型的子元件。
範例
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=128, height=128)(inputs)
conv = keras.layers.Conv2D(filters=32, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
請注意,backbone
和 activations
模型不是使用 keras.Input
物件建立的,而是使用源自 keras.Input
物件的張量建立的。在底層,圖層和權重會在這些模型之間共用,以便使用者可以訓練 full_model
,並使用 backbone
或 activations
進行特徵提取。模型的輸入和輸出也可以是張量的巢狀結構,而建立的模型是支援所有現有 API 的標準函數式 API 模型。
Model
類別在這種情況下,您應該在 __init__()
中定義圖層,並在 call()
中實作模型的前向傳遞。
class MyModel(keras.Model):
def __init__(self):
super().__init__()
self.dense1 = keras.layers.Dense(32, activation="relu")
self.dense2 = keras.layers.Dense(5, activation="softmax")
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
如果您繼承 Model
,則可以在 call()
中選擇性地使用 training
引數(布林值),您可以使用它來指定訓練和推論中的不同行為。
class MyModel(keras.Model):
def __init__(self):
super().__init__()
self.dense1 = keras.layers.Dense(32, activation="relu")
self.dense2 = keras.layers.Dense(5, activation="softmax")
self.dropout = keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
建立模型後,您可以使用 model.compile()
設定模型的損失和指標,使用 model.fit()
訓練模型,或使用模型使用 model.predict()
進行預測。
Sequential
類別此外,keras.Sequential
是一種特殊類型的模型,其中模型純粹是由單輸入、單輸出層組成的堆疊。
model = keras.Sequential([
keras.Input(shape=(None, None, 3)),
keras.layers.Conv2D(filters=32, kernel_size=3),
])
CLIPProcessor
類別keras_cv.models.feature_extractor.CLIPProcessor(vocabulary, merges, **kwargs)
CLIPProcessor 是一個工具類別,提供在 CLIP(對比語言-圖像預訓練)模型的上下文中處理文字的功能。
參數
CLIPTextEncoder
類別keras_cv.models.feature_extractor.CLIPTextEncoder(
transformer_width,
transformer_layers,
transformer_heads,
vocab_size,
embed_dim,
context_length,
**kwargs
)
將圖層組合成具有訓練/推論功能的物件的模型。
有三種方法可以實例化 Model
:
您從 Input
開始,連結圖層呼叫以指定模型的前向傳遞,最後從輸入和輸出建立模型。
inputs = keras.Input(shape=(37,))
x = keras.layers.Dense(32, activation="relu")(inputs)
outputs = keras.layers.Dense(5, activation="softmax")(x)
model = keras.Model(inputs=inputs, outputs=outputs)
注意:僅支援輸入張量的字典、清單和元組。不支援巢狀輸入(例如清單的清單或字典的字典)。
也可以使用中間張量建立新的函數式 API 模型。這讓您可以快速提取模型的子元件。
範例
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=128, height=128)(inputs)
conv = keras.layers.Conv2D(filters=32, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
請注意,backbone
和 activations
模型不是使用 keras.Input
物件建立的,而是使用源自 keras.Input
物件的張量建立的。在底層,圖層和權重會在這些模型之間共用,以便使用者可以訓練 full_model
,並使用 backbone
或 activations
進行特徵提取。模型的輸入和輸出也可以是張量的巢狀結構,而建立的模型是支援所有現有 API 的標準函數式 API 模型。
Model
類別在這種情況下,您應該在 __init__()
中定義圖層,並在 call()
中實作模型的前向傳遞。
class MyModel(keras.Model):
def __init__(self):
super().__init__()
self.dense1 = keras.layers.Dense(32, activation="relu")
self.dense2 = keras.layers.Dense(5, activation="softmax")
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
如果您繼承 Model
,則可以在 call()
中選擇性地使用 training
引數(布林值),您可以使用它來指定訓練和推論中的不同行為。
class MyModel(keras.Model):
def __init__(self):
super().__init__()
self.dense1 = keras.layers.Dense(32, activation="relu")
self.dense2 = keras.layers.Dense(5, activation="softmax")
self.dropout = keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
建立模型後,您可以使用 model.compile()
設定模型的損失和指標,使用 model.fit()
訓練模型,或使用模型使用 model.predict()
進行預測。
Sequential
類別此外,keras.Sequential
是一種特殊類型的模型,其中模型純粹是由單輸入、單輸出層組成的堆疊。
model = keras.Sequential([
keras.Input(shape=(None, None, 3)),
keras.layers.Conv2D(filters=32, kernel_size=3),
])
QuickGELU
類別keras_cv.models.feature_extractor.QuickGELU(**kwargs)
這是所有層級繼承的類別。
層級是一個可呼叫的物件,它將一個或多個張量作為輸入,並輸出一個或多個張量。它涉及在 call()
方法中定義的*計算*,以及*狀態*(權重變數)。狀態可以在
__init__()
中建立,例如透過 self.add_weight()
;build()
方法中建立,該方法由對層級的第一次 __call__()
呼叫,並提供輸入的形狀,這些形狀在初始化時可能未知。層級是遞迴可組合的:如果您將一個層級實例分配為另一個層級的屬性,則外部層級將開始追蹤內部層級建立的權重。應在 __init__()
方法或 build()
方法中實例化巢狀層級。
使用者只需實例化一個層級,然後將其視為可呼叫的物件。
參數
keras.DTypePolicy
,它允許計算和權重 dtype 不同。預設值為 None
。None
表示使用 keras.config.dtype_policy()
,這是一個 float32
策略,除非設定為不同的值(透過 keras.config.set_dtype_policy()
)。屬性
layer.variable_dtype
的別名。keras.DTypePolicy
一起使用時,這將與 variable_dtype
不同。layer.trainable_weights
的一部分返回。InputSpec
物件,用於指定此圖層可接受的輸入限制。我們建議 Layer
的子類別實作以下方法:
__init__()
:定義自訂圖層屬性,並使用 add_weight()
或其他狀態建立不依賴輸入形狀的圖層權重。build(self, input_shape)
:此方法可用於使用 add_weight()
或其他狀態建立依賴輸入形狀的權重。__call__()
會透過呼叫 build()
自動建構圖層(如果尚未建構)。call(self, *args, **kwargs)
:在確認已呼叫 build()
後於 __call__
中呼叫。call()
會執行將圖層套用到輸入引數的邏輯。您可以在 call()
中選擇性地使用兩個保留的關鍵字引數:1. training
(布林值,表示呼叫是在推論模式還是訓練模式)。2. mask
(布林張量,用於編碼輸入中被遮罩的時間步長,例如在 RNN 圖層中使用)。此方法的典型簽章是 call(self, inputs)
,如果圖層需要,使用者可以選擇性地新增 training
和 mask
。get_config(self)
:傳回包含用於初始化此圖層的配置的字典。如果金鑰與 __init__()
中的引數不同,則也需要覆寫 from_config(self)
。儲存圖層或包含此圖層的模型時會使用此方法。範例
以下是一個基本範例:具有兩個變數 w
和 b
的圖層,傳回 y = w . x + b
。它顯示如何實作 build()
和 call()
。設定為圖層屬性的變數會被追蹤為圖層的權重(位於 layer.weights
中)。
class SimpleDense(Layer):
def __init__(self, units=32):
super().__init__()
self.units = units
# Create the state of the layer (weights)
def build(self, input_shape):
self.kernel = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="glorot_uniform",
trainable=True,
name="kernel",
)
self.bias = self.add_weight(
shape=(self.units,),
initializer="zeros",
trainable=True,
name="bias",
)
# Defines the computation
def call(self, inputs):
return ops.matmul(inputs, self.kernel) + self.bias
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(ops.ones((2, 2)))
assert len(linear_layer.weights) == 2
# These weights are trainable, so they're listed in `trainable_weights`:
assert len(linear_layer.trainable_weights) == 2
除了透過訓練期間的反向傳播更新的可訓練權重外,圖層也可以具有不可訓練的權重。這些權重旨在於 call()
期間手動更新。以下是一個計算輸入值的累加總和的圖層範例:
class ComputeSum(Layer):
def __init__(self, input_dim):
super(ComputeSum, self).__init__()
# Create a non-trainable weight.
self.total = self.add_weight(
shape=(),
initializer="zeros",
trainable=False,
name="total",
)
def call(self, inputs):
self.total.assign(self.total + ops.sum(inputs))
return self.total
my_sum = ComputeSum(2)
x = ops.ones((2, 2))
y = my_sum(x)
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []
ResidualAttention
類別keras_cv.models.feature_extractor.ResidualAttention(
proj_dim, num_heads, num_hidden_layers, **kwargs
)
這是所有層級繼承的類別。
層級是一個可呼叫的物件,它將一個或多個張量作為輸入,並輸出一個或多個張量。它涉及在 call()
方法中定義的*計算*,以及*狀態*(權重變數)。狀態可以在
__init__()
中建立,例如透過 self.add_weight()
;build()
方法中建立,該方法由對層級的第一次 __call__()
呼叫,並提供輸入的形狀,這些形狀在初始化時可能未知。層級是遞迴可組合的:如果您將一個層級實例分配為另一個層級的屬性,則外部層級將開始追蹤內部層級建立的權重。應在 __init__()
方法或 build()
方法中實例化巢狀層級。
使用者只需實例化一個層級,然後將其視為可呼叫的物件。
參數
keras.DTypePolicy
,它允許計算和權重 dtype 不同。預設值為 None
。None
表示使用 keras.config.dtype_policy()
,這是一個 float32
策略,除非設定為不同的值(透過 keras.config.set_dtype_policy()
)。屬性
layer.variable_dtype
的別名。keras.DTypePolicy
一起使用時,這將與 variable_dtype
不同。layer.trainable_weights
的一部分返回。InputSpec
物件,用於指定此圖層可接受的輸入限制。我們建議 Layer
的子類別實作以下方法:
__init__()
:定義自訂圖層屬性,並使用 add_weight()
或其他狀態建立不依賴輸入形狀的圖層權重。build(self, input_shape)
:此方法可用於使用 add_weight()
或其他狀態建立依賴輸入形狀的權重。__call__()
會透過呼叫 build()
自動建構圖層(如果尚未建構)。call(self, *args, **kwargs)
:在確認已呼叫 build()
後於 __call__
中呼叫。call()
會執行將圖層套用到輸入引數的邏輯。您可以在 call()
中選擇性地使用兩個保留的關鍵字引數:1. training
(布林值,表示呼叫是在推論模式還是訓練模式)。2. mask
(布林張量,用於編碼輸入中被遮罩的時間步長,例如在 RNN 圖層中使用)。此方法的典型簽章是 call(self, inputs)
,如果圖層需要,使用者可以選擇性地新增 training
和 mask
。get_config(self)
:傳回包含用於初始化此圖層的配置的字典。如果金鑰與 __init__()
中的引數不同,則也需要覆寫 from_config(self)
。儲存圖層或包含此圖層的模型時會使用此方法。範例
以下是一個基本範例:具有兩個變數 w
和 b
的圖層,傳回 y = w . x + b
。它顯示如何實作 build()
和 call()
。設定為圖層屬性的變數會被追蹤為圖層的權重(位於 layer.weights
中)。
class SimpleDense(Layer):
def __init__(self, units=32):
super().__init__()
self.units = units
# Create the state of the layer (weights)
def build(self, input_shape):
self.kernel = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="glorot_uniform",
trainable=True,
name="kernel",
)
self.bias = self.add_weight(
shape=(self.units,),
initializer="zeros",
trainable=True,
name="bias",
)
# Defines the computation
def call(self, inputs):
return ops.matmul(inputs, self.kernel) + self.bias
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(ops.ones((2, 2)))
assert len(linear_layer.weights) == 2
# These weights are trainable, so they're listed in `trainable_weights`:
assert len(linear_layer.trainable_weights) == 2
除了透過訓練期間的反向傳播更新的可訓練權重外,圖層也可以具有不可訓練的權重。這些權重旨在於 call()
期間手動更新。以下是一個計算輸入值的累加總和的圖層範例:
class ComputeSum(Layer):
def __init__(self, input_dim):
super(ComputeSum, self).__init__()
# Create a non-trainable weight.
self.total = self.add_weight(
shape=(),
initializer="zeros",
trainable=False,
name="total",
)
def call(self, inputs):
self.total.assign(self.total + ops.sum(inputs))
return self.total
my_sum = ComputeSum(2)
x = ops.ones((2, 2))
y = my_sum(x)
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []