【计算机视觉】DINOv2的四种模型代码示范,以 28 * 28 的图像示例(含源代码)

简介: DINOv2利用最大模型ViT-g的知识蒸馏,而不是从头开始训练,从而提高了性能。这个过程包括将知识从更大、更复杂的模型(教师)转移到更小的模型(学生)。学生模型被训练来模仿教师的输出,从而继承其优越的能力。这个过程提高了小型模型的性能,使它们更有效率。

一、ViT-S/14

import torch
import torchvision.transforms as T
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as mpimg 
from PIL import Image
from sklearn.decomposition import PCA
import matplotlib

patch_h = 28
patch_w = 28
feat_dim = 384 # vits14

transform = T.Compose([
    T.GaussianBlur(9, sigma=(0.1, 2.0)),
    T.Resize((patch_h * 14, patch_w * 14)),
    T.CenterCrop((patch_h * 14, patch_w * 14)),
    T.ToTensor(),
    T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
])

dinov2_vits14 = torch.hub.load('', 'dinov2_vits14',source='local').cuda()

features = torch.zeros(4, patch_h * patch_w, feat_dim)
imgs_tensor = torch.zeros(4, 3, patch_h * 14, patch_w * 14).cuda()

img_path = f'/kaggle/input/demo-image/1 (4).png'
img = Image.open(img_path).convert('RGB')
imgs_tensor[0] = transform(img)[:3]
with torch.no_grad():
    features_dict = dinov2_vits14.forward_features(imgs_tensor)
    features = features_dict['x_norm_patchtokens']

features = features.reshape(4 * patch_h * patch_w, feat_dim).cpu()
pca = PCA(n_components = 3)
pca.fit(features)
pca_features = pca.transform(features)
pca_features[:, 0] = (pca_features[:, 0] - pca_features[:, 0].min()) / (pca_features[:, 0].max() - pca_features[:, 0].min())

pca_features_fg = pca_features[:, 0] > 0.3
pca_features_bg = ~pca_features_fg

b = np.where(pca_features_bg)

## 前景
pca.fit(features[pca_features_fg])
pca_features_rem = pca.transform(features[pca_features_fg])
for i in range(3):
    pca_features_rem[:, i] = (pca_features_rem[:, i] - pca_features_rem[:, i].min()) / (pca_features_rem[:, i].max() - pca_features_rem[:, i].min())
    # 使用平均值和标准差进行变换,个人发现这种变换可以提供更好的可视化效果
    # pca_features_rem[:, i] = (pca_features_rem[:, i] - pca_features_rem[:, i].mean()) / (pca_features_rem[:, i].std() ** 2) + 0.5

pca_features_rgb = pca_features.copy()
pca_features_rgb[pca_features_fg] = pca_features_rem
pca_features_rgb[b] = 0
pca_features_rgb = pca_features_rgb.reshape(4, patch_h, patch_w, 3)
plt.imshow(pca_features_rgb[0][...,::-1])
plt.savefig('features_s14.png')
plt.show()
plt.close()

image.png

print('---s14---')
print(features)
print('---维度---')
print(features.shape)

image.png

print('---pca_features---')
print(pca_features)
print('---维度---')
print(pca_features.shape)

image.png

二、ViT-B/14

patch_h = 28
patch_w = 28
feat_dim = 768

transform = T.Compose([
    T.GaussianBlur(9, sigma=(0.1, 2.0)),
    T.Resize((patch_h * 14, patch_w * 14)),
    T.CenterCrop((patch_h * 14, patch_w * 14)),
    T.ToTensor(),
    T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
])

dinov2_vitb14 = torch.hub.load('', 'dinov2_vitb14',source='local').cuda()

features_b14 = torch.zeros(4, patch_h * patch_w, feat_dim)
imgs_tensor_b14 = torch.zeros(4, 3, patch_h * 14, patch_w * 14).cuda()

img_path = f'/kaggle/input/demo-image/1 (4).png'
img = Image.open(img_path).convert('RGB')
imgs_tensor_b14[0] = transform(img)[:3]
with torch.no_grad():
    features_dict_b14 = dinov2_vitb14.forward_features(imgs_tensor_b14)
    features_b14 = features_dict_b14['x_norm_patchtokens']

features_b14 = features_b14.reshape(4 * patch_h * patch_w, feat_dim).cpu()
pca = PCA(n_components = 3)
pca.fit(features_b14)
pca_features_b14 = pca.transform(features_b14)
pca_features_b14[:, 0] = (pca_features_b14[:, 0] - pca_features_b14[:, 0].min()) / (pca_features_b14[:, 0].max() - pca_features_b14[:, 0].min())

pca_features_fg_b14 = pca_features_b14[:, 0] > 0.3
pca_features_bg_b14 = ~pca_features_fg_b14

b = np.where(pca_features_bg_b14)
pca.fit(features_b14[pca_features_fg_b14])
pca_features_rem_b14 = pca.transform(features_b14[pca_features_fg_b14])
for i in range(3):
    pca_features_rem_b14[:, i] = (pca_features_rem_b14[:, i] - pca_features_rem_b14[:, i].min()) \
    / (pca_features_rem_b14[:, i].max() - pca_features_rem_b14[:, i].min())

pca_features_rgb_b14 = pca_features_b14.copy()
pca_features_rgb_b14[pca_features_fg_b14] = pca_features_rem_b14
pca_features_rgb_b14[b] = 0
pca_features_rgb_b14 = pca_features_rgb_b14.reshape(4, patch_h, patch_w, 3)
plt.imshow(pca_features_rgb_b14[0][...,::-1])
plt.savefig('features_b14.png')
plt.show()
plt.close()

image.png

print('---b14---')
print(features_b14)
print('---维度---')
print(features_b14.shape)

image.png

print('---pca_features_b14---')
print(pca_features_b14)
print('---维度---')
print(pca_features_b14.shape)

image.png

三、ViT-L/14

patch_h = 28
patch_w = 28
feat_dim = 1024

transform = T.Compose([
    T.GaussianBlur(9, sigma=(0.1, 2.0)),
    T.Resize((patch_h * 14, patch_w * 14)),
    T.CenterCrop((patch_h * 14, patch_w * 14)),
    T.ToTensor(),
    T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
])

dinov2_vitl14 = torch.hub.load('', 'dinov2_vitl14',source='local').cuda()

features_l14 = torch.zeros(4, patch_h * patch_w, feat_dim)
imgs_tensor_l14 = torch.zeros(4, 3, patch_h * 14, patch_w * 14).cuda()

img_path = f'/kaggle/input/demo-image/1 (4).png'
img = Image.open(img_path).convert('RGB')
imgs_tensor_l14[0] = transform(img)[:3]
with torch.no_grad():
    features_dict_l14 = dinov2_vitl14.forward_features(imgs_tensor_l14)
    features_l14 = features_dict_l14['x_norm_patchtokens']

features_l14 = features_l14.reshape(4 * patch_h * patch_w, feat_dim).cpu()
pca = PCA(n_components = 3)
pca.fit(features_l14)
pca_features_l14 = pca.transform(features_l14)
pca_features_l14[:, 0] = (pca_features_l14[:, 0] - pca_features_l14[:, 0].min()) \
/ (pca_features_l14[:, 0].max() - pca_features_l14[:, 0].min())

pca_features_fg_l14 = pca_features_l14[:, 0] > 0.3
pca_features_bg_l14 = ~pca_features_fg_l14

b = np.where(pca_features_bg_l14)
pca.fit(features_l14[pca_features_fg_l14])
pca_features_rem_l14 = pca.transform(features_l14[pca_features_fg_l14])
for i in range(3):
    pca_features_rem_l14[:, i] = (pca_features_rem_l14[:, i] - pca_features_rem_l14[:, i].min()) \
    / (pca_features_rem_l14[:, i].max() - pca_features_rem_l14[:, i].min())

pca_features_rgb_l14 = pca_features_l14.copy()
pca_features_rgb_l14[pca_features_fg_l14] = pca_features_rem_l14
pca_features_rgb_l14[b] = 0
pca_features_rgb_l14 = pca_features_rgb_l14.reshape(4, patch_h, patch_w, 3)
plt.imshow(pca_features_rgb_l14[0][...,::-1])
plt.savefig('features_l14.png')
plt.show()
plt.close()

image.png

print('---l14---')
print(features_l14)
print('---维度---')
print(features_l14.shape)

image.png

print('---pca_features_l14---')
print(pca_features_l14)
print('---维度---')
print(pca_features_l14.shape)

image.png

四、ViT-g/14

patch_h = 28
patch_w = 28
feat_dim = 1536

transform = T.Compose([
    T.GaussianBlur(9, sigma=(0.1, 2.0)),
    T.Resize((patch_h * 14, patch_w * 14)),
    T.CenterCrop((patch_h * 14, patch_w * 14)),
    T.ToTensor(),
    T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
])

dinov2_vitg14 = torch.hub.load('', 'dinov2_vitg14',source='local').cuda()

features_g14 = torch.zeros(4, patch_h * patch_w, feat_dim)
imgs_tensor_g14 = torch.zeros(4, 3, patch_h * 14, patch_w * 14).cuda()

img_path = f'/kaggle/input/demo-image/1 (4).png'
img = Image.open(img_path).convert('RGB')
imgs_tensor_g14[0] = transform(img)[:3]
with torch.no_grad():
    features_dict_g14 = dinov2_vitg14.forward_features(imgs_tensor_g14)
    features_g14 = features_dict_g14['x_norm_patchtokens']

features_g14 = features_g14.reshape(4 * patch_h * patch_w, feat_dim).cpu()
pca = PCA(n_components = 3)
pca.fit(features_g14)
pca_features_g14 = pca.transform(features_g14)
pca_features_g14[:, 0] = (pca_features_g14[:, 0] - pca_features_g14[:, 0].min()) \
/ (pca_features_g14[:, 0].max() - pca_features_g14[:, 0].min())

pca_features_fg_g14 = pca_features_g14[:, 0] > 0.3
pca_features_bg_g14 = ~pca_features_fg_g14

b = np.where(pca_features_bg_g14)

pca.fit(features_g14[pca_features_fg_g14])
pca_features_rem_g14 = pca.transform(features_g14[pca_features_fg_g14])
for i in range(3):
    pca_features_rem_g14[:, i] = (pca_features_rem_g14[:, i] - pca_features_rem_g14[:, i].min()) \
    / (pca_features_rem_g14[:, i].max() - pca_features_rem_g14[:, i].min())

pca_features_rgb_g14 = pca_features_g14.copy()
pca_features_rgb_g14[pca_features_fg_g14] = pca_features_rem_g14
pca_features_rgb_g14[b] = 0
pca_features_rgb_g14 = pca_features_rgb_g14.reshape(4, patch_h, patch_w, 3)
plt.imshow(pca_features_rgb_g14[0][...,::-1])
plt.savefig('features_g14.png')
plt.show()
plt.close()

image.png

print('---g14---')
print(features_g14)
print('---维度---')
print(features_g14.shape)

image.png

print('---pca_features_g14---')
print(pca_features_g14)
print('---维度---')
print(pca_features_g14.shape)

image.png

相关文章
|
2天前
|
机器学习/深度学习 计算机视觉
AIGC核心技术——计算机视觉(CV)预训练大模型
【1月更文挑战第13天】AIGC核心技术——计算机视觉(CV)预训练大模型
401 3
AIGC核心技术——计算机视觉(CV)预训练大模型
|
5月前
|
机器学习/深度学习 PyTorch 算法框架/工具
Azure 机器学习 - 使用 ONNX 对来自 AutoML 的计算机视觉模型进行预测
Azure 机器学习 - 使用 ONNX 对来自 AutoML 的计算机视觉模型进行预测
69 0
|
2天前
|
机器学习/深度学习 算法 数据可视化
计算机视觉+深度学习+机器学习+opencv+目标检测跟踪+一站式学习(代码+视频+PPT)-2
计算机视觉+深度学习+机器学习+opencv+目标检测跟踪+一站式学习(代码+视频+PPT)
104 0
|
2天前
|
机器学习/深度学习 Ubuntu Linux
计算机视觉+深度学习+机器学习+opencv+目标检测跟踪+一站式学习(代码+视频+PPT)-1
计算机视觉+深度学习+机器学习+opencv+目标检测跟踪+一站式学习(代码+视频+PPT)
59 1
|
2天前
|
机器学习/深度学习 编解码 人工智能
Vision Mamba:将Mamba应用于计算机视觉任务的新模型
Mamba是LLM的一种新架构,与Transformers等传统模型相比,它能够更有效地处理长序列。就像VIT一样现在已经有人将他应用到了计算机视觉领域,让我们来看看最近的这篇论文“Vision Mamba: Efficient Visual Representation Learning with Bidirectional State Space Models,”
283 7
|
2天前
|
机器学习/深度学习 人工智能 计算机视觉
生成式计算机视觉(CV)模型的发展历程及最新进展
在计算机视觉(CV)领域,生成式AI技术的发展经历了多个阶段。在深度学习革命之前,传统的图像生成技术主要依赖于手工制作的特征,如纹理合成和纹理映射等方法。然而,这些方法在生成复杂和生动的图像方面的能力是有限的。
157 2
|
2天前
|
机器学习/深度学习 算法 数据可视化
基于计算机视觉手势识别控制系统YoloGesture (利用YOLO实现) 有详细代码+部署+在线服务器尝试+开源可复现
基于计算机视觉手势识别控制系统YoloGesture (利用YOLO实现) 有详细代码+部署+在线服务器尝试+开源可复现
|
2天前
|
机器学习/深度学习 自动驾驶 算法
【计算机视觉+自动驾驶】二、多任务深度学习网络并联式、级联式构建详细讲解(图像解释 超详细必看)
【计算机视觉+自动驾驶】二、多任务深度学习网络并联式、级联式构建详细讲解(图像解释 超详细必看)
89 1
|
2天前
|
算法 数据库 计算机视觉
【计算机视觉】FCN、Seg-Net、U-Net模型进行图像分割实战(附源码和数据集 超详细必看)
【计算机视觉】FCN、Seg-Net、U-Net模型进行图像分割实战(附源码和数据集 超详细必看)
89 2
|
5月前
|
机器学习/深度学习 存储 JSON
Azure - 机器学习:使用自动化机器学习训练计算机视觉模型的数据架构
Azure - 机器学习:使用自动化机器学习训练计算机视觉模型的数据架构
35 0

热门文章

最新文章