[Pytorch]可視化特徴マップ
コンピュータビジョンプロジェクト、特にオブジェクト分類、キーポイントの検出実験では、私たちはしばしば我々のモデルが助け私たちに、私たちが望む特徴を抽出できるかどうかを判断するために特徴マップの真ん中を視覚化する必要がありますまたはモデルのパラメータを調整します。
可視化コード:
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
def visualize_feature(x, model, layers=[0,1]):
net = nn.Sequential(*list(model.children())[:layers[0]])
img = net(x)
transform1 = transforms.ToPILImage(mode='L')
#img = torch.cpu().clone()
for i in range(img.size(0)):
image = img[i]
#print(image.size())
image = transform1(np.uint8(image.numpy().transpose(1,2,0)))
image.show()
変換関数を:
テンソルnumpyの又はndarray [データ型のPILImage型、両方の特定の要件]に変換
- ndarrayデータ型要件DTYPE = UINT8、範囲[0、 255]及び形状高さ×幅×C
- テンソルC X H X W FloadTensor要件の形状、又は他のタイプが許可DoubleTensor
PILにnumpyの:
#初始化随机数种子
np.random.seed(0)
data = np.random.randint(0, 255, 300)
print(data.dtype)
n_out = data.reshape(10,10,3)
#强制类型转换
n_out = n_out.astype(np.uint8)
print(n_out.dtype)
img2 = transforms.ToPILImage()(n_out)
img2.show()
PILにテンソル:
t_out = torch.randn(3,10,10)
img1 = transforms.ToPILImage()(t_out)
img1.show()
トレーニングプロセスの可視化関数の呼び出し
def train(epoch):
cnn.train()
for data in tqdm(train_loader, desc='Train: epoch {}'.format(epoch), leave=False, total=len(train_loader)): # 对于训练集的每一个batch
img, label = data
if cuda_available:
img = img.cuda()
label = label.cuda()
#visualize_feature(img, cnn)
out = cnn( img ) # 送进网络进行输出
#out = torch.nn.functional.softmax(out, dim=1)
#print(out.size())
#print(label.size())
loss = loss_function( out, label ) # 获得损失
optimizer.zero_grad() # 梯度归零
loss.backward() # 反向传播获得梯度,但是参数还没有更新
optimizer.step() # 更新梯度
プリロードダイレクトトレーニングモデルと良好な出力機能マップ
model = Residual_Model()
model.load_state_dict(torch.load('./model.pkl'))
output = get_features(model,x)## model是训练好的model,前面已经import 进来了Residual model
print('output.shape:',output.shape)