当前位置: 首页 > news >正文

大家都用哪个网站做读书笔记推推蛙seo顾问

大家都用哪个网站做读书笔记,推推蛙seo顾问,贵州网站制作设计公司哪家好,长沙专业外贸网站建设1.特征图可视化,这种方法是最简单,输入一张照片,然后把网络中间某层的输出的特征图按通道作为图片进行可视化展示即可。 2.特征图可视化代码如下: def featuremap_visual(feature, out_dirNone, # 特征图保存路径文件save_feat…

1.特征图可视化,这种方法是最简单,输入一张照片,然后把网络中间某层的输出的特征图按通道作为图片进行可视化展示即可。

2.特征图可视化代码如下:

def featuremap_visual(feature, out_dir=None,  # 特征图保存路径文件save_feature=True,  # 是否以图片形式保存特征图show_feature=True,  # 是否使用plt显示特征图feature_title=None,  # 特征图名字,默认以shape作为titlenum_ch=-1,  # 显示特征图前几个通道,-1 or None 都显示nrow=8,  # 每行显示多少个特征图通道padding=10,  # 特征图之间间隔多少像素值pad_value=1  # 特征图之间的间隔像素):import matplotlib.pylab as pltimport torchvisionimport os# feature = feature.detach().cpu()b, c, h, w = feature.shapefeature = feature[0]feature = feature.unsqueeze(1)if c > num_ch > 0:feature = feature[:num_ch]img = torchvision.utils.make_grid(feature, nrow=nrow, padding=padding, pad_value=pad_value)img = img.detach().cpu()img = img.numpy()images = img.transpose((1, 2, 0))# title = str(images.shape) if feature_title is None else str(feature_title)title = str('hwc-') + str(h) + '-' + str(w) + '-' + str(c) if feature_title is None else str(feature_title)plt.title(title)plt.imshow(images)if save_feature:# root=r'C:\Users\Administrator\Desktop\CODE_TJ\123'# plt.savefig(os.path.join(root,'1.jpg'))out_root = title + '.jpg' if out_dir == '' or out_dir is None else os.path.join(out_dir, title + '.jpg')plt.savefig(out_root)if show_feature:        plt.show()

3.结合resnet网络整体可视化(主要将其featuremap_visual函数插入forward中,即可),整体代码如下:

resnet网络结构在我博客:
残差网络ResNet(超详细代码解析) :你必须要知道backbone模块成员之一 - tangjunjun - 博客园

"""
@author: tangjun
@contact: 511026664@qq.com
@time: 2020/12/7 22:48
@desc: 残差ackbone改写,用于构建特征提取模块
"""import torch.nn as nn
import torch
from collections import OrderedDictdef Conv(in_planes, out_planes, **kwargs):"3x3 convolution with padding"padding = kwargs.get('padding', 1)bias = kwargs.get('bias', False)stride = kwargs.get('stride', 1)kernel_size = kwargs.get('kernel_size', 3)out = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)return outclass BasicBlock(nn.Module):expansion = 1def __init__(self, inplanes, planes, stride=1, downsample=None):super(BasicBlock, self).__init__()self.conv1 = Conv(inplanes, planes, stride=stride)self.bn1 = nn.BatchNorm2d(planes)self.relu = nn.ReLU(inplace=True)self.conv2 = Conv(planes, planes)self.bn2 = nn.BatchNorm2d(planes)self.downsample = downsampleself.stride = stridedef forward(self, x):residual = xout = self.conv1(x)out = self.bn1(out)out = self.relu(out)out = self.conv2(out)out = self.bn2(out)if self.downsample is not None:residual = self.downsample(x)out += residualout = self.relu(out)return outclass Bottleneck(nn.Module):expansion = 4def __init__(self, inplanes, planes, stride=1, downsample=None):super(Bottleneck, self).__init__()self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)self.bn1 = nn.BatchNorm2d(planes)self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False)self.bn2 = nn.BatchNorm2d(planes)self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)self.bn3 = nn.BatchNorm2d(planes * 4)self.relu = nn.ReLU(inplace=True)self.downsample = downsampleself.stride = stridedef forward(self, x):residual = xout = self.conv1(x)out = self.bn1(out)out = self.relu(out)out = self.conv2(out)out = self.bn2(out)out = self.relu(out)out = self.conv3(out)out = self.bn3(out)if self.downsample is not None:residual = self.downsample(x)out += residualout = self.relu(out)return outclass Resnet(nn.Module):arch_settings = {18: (BasicBlock, (2, 2, 2, 2)),34: (BasicBlock, (3, 4, 6, 3)),50: (Bottleneck, (3, 4, 6, 3)),101: (Bottleneck, (3, 4, 23, 3)),152: (Bottleneck, (3, 8, 36, 3))}def __init__(self,depth=50,in_channels=None,pretrained=None,frozen_stages=-1# num_classes=None):super(Resnet, self).__init__()self.inplanes = 64self.inchannels = in_channels if in_channels is not None else 3  # 输入通道# self.num_classes=num_classesself.block, layers = self.arch_settings[depth]self.frozen_stages = frozen_stagesself.conv1 = nn.Conv2d(self.inchannels, 64, kernel_size=7, stride=2, padding=3, bias=False)self.bn1 = nn.BatchNorm2d(64)self.relu = nn.ReLU(inplace=True)self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)self.layer1 = self._make_layer(self.block, 64, layers[0], stride=1)self.layer2 = self._make_layer(self.block, 128, layers[1], stride=2)self.layer3 = self._make_layer(self.block, 256, layers[2], stride=2)self.layer4 = self._make_layer(self.block, 512, layers[3], stride=2)# self.avgpool = nn.AvgPool2d(7)# self.fc = nn.Linear(512 * self.block.expansion, self.num_classes)self._freeze_stages()  # 冻结函数if pretrained is not None:self.init_weights(pretrained=pretrained)def _freeze_stages(self):if self.frozen_stages >= 0:self.norm1.eval()for m in [self.conv1, self.norm1]:for param in m.parameters():param.requires_grad = Falsefor i in range(1, self.frozen_stages + 1):m = getattr(self, 'layer{}'.format(i))m.eval()for param in m.parameters():param.requires_grad = Falsedef init_weights(self, pretrained=None):if isinstance(pretrained, str):self.load_checkpoint(pretrained)elif pretrained is None:for m in self.modules():if isinstance(m, nn.Conv2d):nn.init.kaiming_normal_(m.weight, a=0, mode='fan_out', nonlinearity='relu')if hasattr(m, 'bias') and m.bias is not None:  # m包含该属性且m.bias非None # hasattr(对象,属性)表示对象是否包含该属性nn.init.constant_(m.bias, 0)elif isinstance(m, nn.BatchNorm2d):m.weight.data.fill_(1)m.bias.data.zero_()def load_checkpoint(self, pretrained):checkpoint = torch.load(pretrained)if isinstance(checkpoint, OrderedDict):state_dict = checkpointelif isinstance(checkpoint, dict) and 'state_dict' in checkpoint:state_dict = checkpoint['state_dict']if list(state_dict.keys())[0].startswith('module.'):state_dict = {k[7:]: v for k, v in checkpoint['state_dict'].items()}unexpected_keys = []  # 保存checkpoint不在module中的keymodel_state = self.state_dict()  # 模型变量for name, param in state_dict.items():  # 循环遍历pretrained的权重if name not in model_state:unexpected_keys.append(name)continueif isinstance(param, torch.nn.Parameter):# backwards compatibility for serialized parametersparam = param.datatry:model_state[name].copy_(param)  # 试图赋值给模型except Exception:raise RuntimeError('While copying the parameter named {}, ''whose dimensions in the model are {} not equal ''whose dimensions in the checkpoint are {}.'.format(name, model_state[name].size(), param.size()))missing_keys = set(model_state.keys()) - set(state_dict.keys())print('missing_keys:', missing_keys)def _make_layer(self, block, planes, num_blocks, stride=1):downsample = Noneif stride != 1 or self.inplanes != planes * block.expansion:downsample = nn.Sequential(nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),nn.BatchNorm2d(planes * block.expansion),)layers = []layers.append(block(self.inplanes, planes, stride, downsample))self.inplanes = planes * block.expansionfor i in range(1, num_blocks):layers.append(block(self.inplanes, planes))return nn.Sequential(*layers)def forward(self, x):outs = []x = self.conv1(x)x = self.bn1(x)x = self.relu(x)x = self.maxpool(x)x = self.layer1(x)outs.append(x)featuremap_visual(x)x = self.layer2(x)outs.append(x)featuremap_visual(x)x = self.layer3(x)outs.append(x)featuremap_visual(x)x = self.layer4(x)outs.append(x)# x = self.avgpool(x)# x = x.view(x.size(0), -1)# x = self.fc(x)return tuple(outs)def featuremap_visual(feature,out_dir=None,  # 特征图保存路径文件save_feature=True,  # 是否以图片形式保存特征图show_feature=True,  # 是否使用plt显示特征图feature_title=None,  # 特征图名字,默认以shape作为titlenum_ch=-1,  # 显示特征图前几个通道,-1 or None 都显示nrow=8,  # 每行显示多少个特征图通道padding=10,  # 特征图之间间隔多少像素值pad_value=1  # 特征图之间的间隔像素):import matplotlib.pylab as pltimport torchvisionimport os# feature = feature.detach().cpu()b, c, h, w = feature.shapefeature = feature[0]feature = feature.unsqueeze(1)if c > num_ch > 0:feature = feature[:num_ch]img = torchvision.utils.make_grid(feature, nrow=nrow, padding=padding, pad_value=pad_value)img = img.detach().cpu()img = img.numpy()images = img.transpose((1, 2, 0))# title = str(images.shape) if feature_title is None else str(feature_title)title = str('hwc-') + str(h) + '-' + str(w) + '-' + str(c) if feature_title is None else str(feature_title)plt.title(title)plt.imshow(images)if save_feature:# root=r'C:\Users\Administrator\Desktop\CODE_TJ\123'# plt.savefig(os.path.join(root,'1.jpg'))out_root = title + '.jpg' if out_dir == '' or out_dir is None else os.path.join(out_dir, title + '.jpg')plt.savefig(out_root)if show_feature:        plt.show()import cv2
import numpy as npdef imnormalize(img,mean=[123.675, 116.28, 103.53],std=[58.395, 57.12, 57.375],to_rgb=True):if to_rgb:img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = img.astype(np.float32)return (img - mean) / stdif __name__ == '__main__':import matplotlib.pylab as pltimg = cv2.imread('1.jpg')  # 读取图片img = imnormalize(img)img = torch.from_numpy(img)img = torch.unsqueeze(img, 0)img = img.permute(0, 3, 1, 2)img = torch.tensor(img, dtype=torch.float32)img = img.to('cuda:0')model = Resnet(depth=50)model.init_weights(pretrained='./resnet50.pth')  # 可以使用,也可以注释model = model.cuda()out = model(img)

运行结果

参考:

PyTorch模型训练特征图可视化 - tangjunjun - 博客园 (cnblogs.com)


文章转载自:
http://wanjiaimprovidence.spfh.cn
http://wanjiacloseout.spfh.cn
http://wanjiacadmus.spfh.cn
http://wanjiadiplomatism.spfh.cn
http://wanjiahyposulphurous.spfh.cn
http://wanjiatonsil.spfh.cn
http://wanjianeedlebook.spfh.cn
http://wanjiataper.spfh.cn
http://wanjiaagamy.spfh.cn
http://wanjialaurentian.spfh.cn
http://wanjiaflattop.spfh.cn
http://wanjiaparasitism.spfh.cn
http://wanjianummulary.spfh.cn
http://wanjiahindbrain.spfh.cn
http://wanjiabeatrix.spfh.cn
http://wanjiamunnion.spfh.cn
http://wanjiaawhile.spfh.cn
http://wanjiagenicular.spfh.cn
http://wanjiacardia.spfh.cn
http://wanjiaunreasoningly.spfh.cn
http://wanjiaconjoint.spfh.cn
http://wanjialepromatous.spfh.cn
http://wanjiafleckiness.spfh.cn
http://wanjiasalicetum.spfh.cn
http://wanjiaecdemic.spfh.cn
http://wanjiamicromicrofarad.spfh.cn
http://wanjialunged.spfh.cn
http://wanjiayclept.spfh.cn
http://wanjiasolecistic.spfh.cn
http://wanjiaamethystine.spfh.cn
http://wanjiacytosol.spfh.cn
http://wanjiaslantindicular.spfh.cn
http://wanjiaoxpecker.spfh.cn
http://wanjiadreadless.spfh.cn
http://wanjiacoexistence.spfh.cn
http://wanjiafranklinite.spfh.cn
http://wanjiaitching.spfh.cn
http://wanjialabuan.spfh.cn
http://wanjiafiendishly.spfh.cn
http://wanjiamuktuk.spfh.cn
http://wanjiaanticly.spfh.cn
http://wanjiachained.spfh.cn
http://wanjiaeulogize.spfh.cn
http://wanjiahomomorphous.spfh.cn
http://wanjiaimparity.spfh.cn
http://wanjiaridiculous.spfh.cn
http://wanjiaefficiency.spfh.cn
http://wanjiacyanotype.spfh.cn
http://wanjiaplunderer.spfh.cn
http://wanjiaheterocharge.spfh.cn
http://wanjiapinxter.spfh.cn
http://wanjiauninucleate.spfh.cn
http://wanjiarehabilitation.spfh.cn
http://wanjiadocumentation.spfh.cn
http://wanjiafibrovascular.spfh.cn
http://wanjiaelectrolier.spfh.cn
http://wanjiapogonotomy.spfh.cn
http://wanjiaduffer.spfh.cn
http://wanjiapolyembryony.spfh.cn
http://wanjiaduodecimo.spfh.cn
http://wanjiamemory.spfh.cn
http://wanjiararefied.spfh.cn
http://wanjiamatin.spfh.cn
http://wanjiaimperial.spfh.cn
http://wanjiasuperordination.spfh.cn
http://wanjiacivies.spfh.cn
http://wanjiacovetously.spfh.cn
http://wanjiaabstractively.spfh.cn
http://wanjiagdmo.spfh.cn
http://wanjiadragline.spfh.cn
http://wanjianidi.spfh.cn
http://wanjiaunaddressed.spfh.cn
http://wanjiajustina.spfh.cn
http://wanjiacouncilman.spfh.cn
http://wanjiagigasecond.spfh.cn
http://wanjiaplayground.spfh.cn
http://wanjiapimping.spfh.cn
http://wanjiasoloistic.spfh.cn
http://wanjiaterdiurnal.spfh.cn
http://wanjiaimmiscible.spfh.cn
http://www.15wanjia.com/news/124325.html

相关文章:

  • 网站建设提升界面流畅程度如何优化网站首页
  • 合肥建设委员会网站首页网络营销自学网站
  • 做网站的生产方式免费的推广软件下载
  • 网站 域名 云服务器b站视频未能成功转码
  • 去国外政府网站做轮胎认证五种网络营销推广方法
  • 网站建设调研通知百度自动搜索关键词软件
  • mac怎么买wordpress网络优化大师app
  • 建站自助2345软件为什么没人管
  • 长春 行业网站百度关键词竞价价格查询
  • 返利淘网站怎么做优化大师的优化项目有哪7个
  • 莱西做网站的网络推广有哪些方法
  • 网站空间中国企业100强
  • 门户网站建设目标seo网络排名优化技巧
  • 惠东做网站企业网站推广方案策划
  • 无锡做网站多少钱网络营销做得好的公司
  • 360平台怎么做网站优化游戏推广员怎么做
  • 做视频解析网站要什么服务器今天发生的重大新闻事件
  • 视频网站 做综艺 电视台小说推文万能关键词
  • 成功的营销网站的例子世界足球排名前100名
  • 做视频网站玩什么配置seo管理系统培训
  • 如何做时时彩网站网站群发软件
  • 襄阳市建设工程造价管理站网站风云榜百度
  • 免费的网站开发工具注册网站流程和费用
  • 网站关键词优化怎么做的百度一下你就知道了 官网
  • 网站进入沙盒的表现微信广点通广告平台
  • 最炫的网站谷歌推广一年多少钱
  • h5网站如何做排名seo如何提升排名收录
  • 用高权重网站的目录做站群怎么样网络营销软文范例500字
  • 重庆市公路建设信息网官网seo博客网站
  • 伍佰亿网站怎么做沈阳seo推广