SimCLR/utils.py

43 lines
1.2 KiB
Python
Raw Normal View History

2020-02-18 03:05:44 +08:00
import cv2
import numpy as np
2020-02-25 05:23:44 +08:00
import torch
2020-02-18 03:05:44 +08:00
np.random.seed(0)
2020-02-18 03:05:44 +08:00
2020-02-25 05:23:44 +08:00
def get_negative_mask(batch_size):
negative_mask = torch.ones((batch_size, 2 * batch_size), dtype=bool)
for i in range(batch_size):
negative_mask[i, i] = 0
negative_mask[i, i + batch_size] = 0
return negative_mask
2020-02-18 03:05:44 +08:00
class GaussianBlur(object):
def __init__(self, min=0.1, max=2.0, kernel_size=9):
self.min = min
self.max = max
self.kernel_size = kernel_size
def __call__(self, sample):
sample = np.array(sample)
2020-02-19 04:21:50 +08:00
# blur the image with a 50% chance
2020-02-19 02:06:14 +08:00
prob = np.random.random_sample()
if prob < 0.5:
sigma = (self.max - self.min) * np.random.random_sample() + self.min
sample = cv2.GaussianBlur(sample, (self.kernel_size, self.kernel_size), sigma)
return sample
# if use_cosine_similarity:
# cos1d = torch.nn.CosineSimilarity(dim=1)
# cos2d = torch.nn.CosineSimilarity(dim=2)
# similarity_dim1 = lambda x, y: cos1d(x, y.unsqueeze(0))
# similarity_dim2 = lambda x, y: cos2d(x, y.unsqueeze(0))
# else:
# similarity_dim1 = lambda x, y: torch.bmm(x.unsqueeze(1), y.unsqueeze(2))
# similarity_dim2 = lambda x, y: torch.tensordot(x, y.T.unsqueeze(0), dims=2)