ToB企服应用市场:ToB评测及商务社交产业平台

标题: 【机器学习】机器学习的基天职类-自监督学习-对比学习(Contrastive Learni [打印本页]

作者: 慢吞云雾缓吐愁    时间: 2025-1-1 18:04
标题: 【机器学习】机器学习的基天职类-自监督学习-对比学习(Contrastive Learni
对比学习是一种自监督学习方法,其目的是学习数据的表征(representation),使得在表征空间中,相似的样本距离更近,不相似的样本距离更远。通过设计对比损失函数(Contrastive Loss),模型能够有效捕捉数据的语义结构。

焦颔首脑

对比学习的关键在于:
通过对比正负样本对,模型能够学习区分差别数据点的特征。

方法流程


对比学习的损失函数

1. 对比损失(Contrastive Loss)

对比损失鼓励正样本对的距离更小,负样本对的距离更大。


2. InfoNCE 损失

用于最大化正样本对的相似性,同时将负样本对的相似性最小化。



典范方法

1. SimCLR

SimCLR 是对比学习的经典方法之一:

2. MoCo(Momentum Contrast)

通过维护一个动态更新的“字典”,办理负样本数目不敷的问题。

3. BYOL(Bootstrap Your Own Latent)

无需显式的负样本,通过自回归(self-prediction)学习特征表征。

4. SWAV(Swapping Assignments Between Views)

联合聚类和对比学习,使用图像的多视图表征。


示例代码:SimCLR

以下是一个实现 SimCLR 的示例代码:
  1. import tensorflow as tf
  2. from tensorflow.keras import layers, models
  3. # 图像增强函数
  4. def augment_image(image):
  5.     image = tf.image.random_flip_left_right(image)
  6.     image = tf.image.random_crop(image, size=(32, 32, 3))
  7.     image = tf.image.random_brightness(image, max_delta=0.5)
  8.     return image
  9. # 定义编码器
  10. def create_encoder():
  11.     base_model = tf.keras.applications.ResNet50(include_top=False, pooling='avg', input_shape=(32, 32, 3))
  12.     return models.Model(inputs=base_model.input, outputs=base_model.output)
  13. # SimCLR 模型
  14. class SimCLRModel(tf.keras.Model):
  15.     def __init__(self, encoder, projection_dim):
  16.         super(SimCLRModel, self).__init__()
  17.         self.encoder = encoder
  18.         self.projection_head = tf.keras.Sequential([
  19.             layers.Dense(256, activation='relu'),
  20.             layers.Dense(projection_dim)
  21.         ])
  22.     def call(self, x):
  23.         features = self.encoder(x)
  24.         projections = self.projection_head(features)
  25.         return tf.math.l2_normalize(projections, axis=1)
  26. # 构建模型
  27. encoder = create_encoder()
  28. simclr_model = SimCLRModel(encoder, projection_dim=128)
  29. # InfoNCE 损失
  30. def info_nce_loss(features, temperature=0.5):
  31.     batch_size = tf.shape(features)[0]
  32.     labels = tf.range(batch_size)
  33.     similarity_matrix = tf.matmul(features, features, transpose_b=True)
  34.     logits = similarity_matrix / temperature
  35.     return tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True))
  36. # 训练
  37. (X_train, _), _ = tf.keras.datasets.cifar10.load_data()
  38. X_train = tf.image.resize(X_train, (32, 32)) / 255.0
  39. def preprocess_data(image):
  40.     return augment_image(image), augment_image(image)
  41. train_data = tf.data.Dataset.from_tensor_slices(X_train)
  42. train_data = train_data.map(preprocess_data).batch(32)
  43. optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3)
  44. for epoch in range(10):
  45.     for x1, x2 in train_data:
  46.         with tf.GradientTape() as tape:
  47.             z1 = simclr_model(x1)
  48.             z2 = simclr_model(x2)
  49.             loss = info_nce_loss(tf.concat([z1, z2], axis=0))
  50.         gradients = tape.gradient(loss, simclr_model.trainable_variables)
  51.         optimizer.apply_gradients(zip(gradients, simclr_model.trainable_variables))
  52.     print(f"Epoch {epoch + 1}, Loss: {loss.numpy()}")
复制代码
输出结果
  1. Epoch 1, Loss: 3.465735912322998
  2. Epoch 2, Loss: 3.465735912322998
  3. Epoch 3, Loss: 3.465735912322998
  4. Epoch 4, Loss: 3.465735912322998
  5. Epoch 5, Loss: 3.465735912322998
复制代码

对比学习的上风与寻衅

上风

寻衅


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4