【Pytorch】Visualization of Feature Maps(5)——Deep Dream

在这里插入图片描述

学习参考来自:

  • PyTorch实现Deep Dream
  • https://github.com/duc0/deep-dream-in-pytorch

文章目录

  • 1 原理
  • 2 VGG 模型结构
  • 3 完整代码
  • 4 输出结果
  • 5 消融实验
  • 6 torch.norm()


1 原理

其实 Deep Dream大致的原理和【Pytorch】Visualization of Feature Maps(1)—— Maximize Filter 是有些相似的,前者希望整个 layer 的激活值都很大,而后者是希望某个 layer 中的某个 filter 的激活值最大。

在这里插入图片描述

这个图画的很好,递归只画了一层,下面来个三层的例子

在这里插入图片描述
CNN 处(def deepDream),指定网络的某一层,固定网络权重,开启输入图片的梯度,迭代指定层输出的负l2范数(相当于最大化该层激活),以改变输入图片。

loss = -out.norm() # 让负的变小, 正的变大

核心代码,loss 为指定特征图输出的二范数的负值,相当于放大了响应,负数负的更多,正数正的更多,二范数才越大,损失才越小

2 VGG 模型结构

VGG((features): Sequential((0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(1): ReLU(inplace=True)(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(3): ReLU(inplace=True)(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(6): ReLU(inplace=True)(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(8): ReLU(inplace=True)(9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(11): ReLU(inplace=True)(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(13): ReLU(inplace=True)(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(15): ReLU(inplace=True)(16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(18): ReLU(inplace=True)(19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(20): ReLU(inplace=True)(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(22): ReLU(inplace=True)(23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(25): ReLU(inplace=True)(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(27): ReLU(inplace=True)  # LAYER_ID 28(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(29): ReLU(inplace=True)  # LAYER_ID 30(30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False))(avgpool): AdaptiveAvgPool2d(output_size=(7, 7))(classifier): Sequential((0): Linear(in_features=25088, out_features=4096, bias=True)(1): ReLU(inplace=True)(2): Dropout(p=0.5, inplace=False)(3): Linear(in_features=4096, out_features=4096, bias=True)(4): ReLU(inplace=True)(5): Dropout(p=0.5, inplace=False)(6): Linear(in_features=4096, out_features=1000, bias=True))
)

(27): ReLU(inplace=True) # LAYER_ID 28
(29): ReLU(inplace=True) # LAYER_ID 30

3 完整代码

完整代码如下

# 导入使用的库
import torch
from torchvision import models, transforms
import torch.optim as optim
import numpy as np
from matplotlib import pyplot
from PIL import Image, ImageFilter, ImageChops# 定义超参数
CUDA_ENABLED = True
LAYER_ID = 28  # the layer to maximize the activations through
NUM_ITERATIONS = 5  # number of iterations to update the input image with the layer's gradient
LR = 0.2"we downscale the image recursively, apply the deep dream computation, scale up, and then" \
"blend with the original image"NUM_DOWNSCALES = 20
BLEND_ALPHA = 0.5# 定义好一些变量和图像的转换
class DeepDream:def __init__(self, image):self.image = imageself.model = models.vgg16(pretrained=True)# print(self.model)if CUDA_ENABLED:self.model = self.model.cuda()self.modules = list(self.model.features.modules())# vgg16 use 224x224 imagesimgsize = 224self.mean = [0.485, 0.456, 0.406]self.std = [0.229, 0.224, 0.225]self.normalise = transforms.Normalize(mean=self.mean,std=self.std)self.transformPreprocess = transforms.Compose([transforms.Resize((imgsize, imgsize)),transforms.ToTensor(),self.normalise])self.tensorMean = torch.Tensor(self.mean)if CUDA_ENABLED:self.tensorMean = self.tensorMean.cuda()self.tensorStd = torch.Tensor(self.std)if CUDA_ENABLED:self.tensorStd = self.tensorStd.cuda()def toimage(self, img):return img * self.tensorStd + self.tensorMeandef deepDream(self, image, layer, iterations, lr):"""核心代码:param image::param layer::param iterations::param lr::return:"""transformed = self.transformPreprocess(image).unsqueeze(0)  # 前处理输入都会 resize 至 224x224if CUDA_ENABLED:transformed = transformed.cuda()input_img = torch.autograd.Variable(transformed, requires_grad=True)self.model.zero_grad()optimizer = optim.Adam([input_img.requires_grad_()], lr=lr)for _ in range(iterations):optimizer.zero_grad()out = input_imgfor layerid in range(layer):  # 28out = self.modules[layerid+1](out)  # self.modules[28] ReLU(inplace=True)# out, torch.Size([1, 512, 14, 14])loss = -out.norm()  # 负的变小,正的变大 -l2loss.backward()optimizer.step()# input_img.data = input_img.data + lr*input_img.grad.data# remove batchsize, torch.Size([1, 3, 224, 224]) ->torch.Size([3, 224, 224])input_img = input_img.data.squeeze()# c,h,w 转为 h,w,c 以便于可视化input_img.transpose_(0, 1)  # torch.Size([224, 3, 224])input_img.transpose_(1, 2)  # torch.Size([224, 224, 3])input_img = self.toimage(input_img)  # torch.Size([224, 224, 3])if CUDA_ENABLED:input_img = input_img.cpu()input_img = np.clip(input_img, 0, 1)return Image.fromarray(np.uint8(input_img*255))# 可视化中间迭代的过程def deepDreamRecursive(self, image, layer, iterations, lr, num_downscales):""":param image::param layer::param iterations::param lr::param num_downscales::return:"""if num_downscales > 0:# scale down the imageimage_gauss = image.filter(ImageFilter.GaussianBlur(2))  # 高斯模糊half_size = (int(image.size[0]/2), int(image.size[1]/2))  # 长宽缩放 1/2if (half_size[0]==0 or half_size[1]==0):half_size = image.sizeimage_half = image_gauss.resize(half_size, Image.ANTIALIAS)# return deepDreamRecursive on the scaled down imageimage_half = self.deepDreamRecursive(image_half, layer, iterations, lr, num_downscales-1)print("Num Downscales: {}".format(num_downscales))print("====Half Image====", np.shape(image_half))# pyplot.imshow(image_half)# pyplot.show()# scale up the result image to the original sizeimage_large = image_half.resize(image.size, Image.ANTIALIAS)print("====Large Image====", np.shape(image_large))# pyplot.imshow(image_large)# pyplot.show()# Blend the two imageimage = ImageChops.blend(image, image_large, BLEND_ALPHA)print("====Blend Image====", np.shape(image))# pyplot.imshow(image)# pyplot.show()img_result = self.deepDream(image, layer, iterations, lr)  # 迭代改变输入图片,max activationprint(np.shape(img_result))img_result = img_result.resize(image.size)print(np.shape(img_result))# pyplot.imshow(img_result)# pyplot.show()return img_resultdef deepDreamProcess(self):return self.deepDreamRecursive(self.image, LAYER_ID, NUM_ITERATIONS, LR, NUM_DOWNSCALES)if __name__ == "__main__":img = Image.open("cat.png").convert('RGB')# 生成img_deep_dream = DeepDream(img).deepDreamProcess()pyplot.title("Deep dream images")pyplot.imshow(img_deep_dream)pyplot.show()

4 输出结果

output

    """(224, 224, 3)(1, 1, 3)Num Downscales: 1====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 2====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 3====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 4====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 5====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 6====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 7====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 8====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 9====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 10====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 11====half Image==== (1, 1, 3)====Large Image==== (1, 1, 3)====Blend Image==== (1, 1, 3)(224, 224, 3)(1, 1, 3)Num Downscales: 12====half Image==== (1, 1, 3)====Large Image==== (2, 2, 3)====Blend Image==== (2, 2, 3)(224, 224, 3)(2, 2, 3)Num Downscales: 13====half Image==== (2, 2, 3)====Large Image==== (5, 5, 3)====Blend Image==== (5, 5, 3)(224, 224, 3)(5, 5, 3)Num Downscales: 14====half Image==== (5, 5, 3)====Large Image==== (11, 11, 3)====Blend Image==== (11, 11, 3)(224, 224, 3)(11, 11, 3)Num Downscales: 15====half Image==== (11, 11, 3)====Large Image==== (23, 23, 3)====Blend Image==== (23, 23, 3)(224, 224, 3)(23, 23, 3)Num Downscales: 16====half Image==== (23, 23, 3)====Large Image==== (47, 47, 3)====Blend Image==== (47, 47, 3)(224, 224, 3)(47, 47, 3)Num Downscales: 17====half Image==== (47, 47, 3)====Large Image==== (94, 94, 3)====Blend Image==== (94, 94, 3)(224, 224, 3)(94, 94, 3)Num Downscales: 18====half Image==== (94, 94, 3)====Large Image==== (188, 188, 3)====Blend Image==== (188, 188, 3)(224, 224, 3)(188, 188, 3)Num Downscales: 19====half Image==== (188, 188, 3)====Large Image==== (376, 376, 3)====Blend Image==== (376, 376, 3)(224, 224, 3)(376, 376, 3)Num Downscales: 20====half Image==== (376, 376, 3)====Large Image==== (753, 753, 3)====Blend Image==== (753, 753, 3)(224, 224, 3)(753, 753, 3)"""

在这里插入图片描述


部分结果展示

Num Downscales: 15
在这里插入图片描述
Num Downscales: 16
在这里插入图片描述
Num Downscales: 17
在这里插入图片描述
Num Downscales: 18
在这里插入图片描述
Num Downscales: 19
在这里插入图片描述
Num Downscales: 20
在这里插入图片描述

5 消融实验

NUM_DOWNSCALES = 50

在这里插入图片描述

NUM_ITERATIONS = 10

在这里插入图片描述

LAYER_ID = 23

在这里插入图片描述
LAYER_ID = 30

在这里插入图片描述

6 torch.norm()

torch.norm() 是 PyTorch 中的一个函数,用于计算输入张量沿指定维度的范数。具体而言,当给定一个输入张量 x 和一个整数 p 时,torch.norm(x, p) 将返回输入张量 x 沿着最后一个维度(默认为所有维度)上所有元素的 p 范数,p 默认为 2。

除了使用标量 p 之外,torch.norm() 还接受以下参数:

  • dim:指定沿哪个轴计算范数,默认对所有维度计算。
  • keepdim:如果设置为 True,则输出张量维度与输入张量相同,其中指定轴尺寸为 1;否则,将从输出张量中删除指定轴。
  • out:可选输出张量结果。

PyTorch中torch.norm函数详解

import torchx = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32)
print(x.norm())
print(x.norm(1))
print(x.norm(2))

output

tensor(25.4951)
tensor(78.)
tensor(25.4951)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/182963.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一次Apollo Client升级导致的生产404 Not Found问题排查记录

概述 本文记录一次升级Apollo Client组件到1.7.0后遇到的重大生产事故。只想看结论的,可直接快进到文末。实际上,第一句话就是一个结论。 另,本文行文思路事后看起来可行略显思路清晰,实际上排查生产问题时如无头苍蝇&#xff0…

45、Flink 的指标体系介绍及验证(3)- 完整版

Flink 系列文章 1、Flink 部署、概念介绍、source、transformation、sink使用示例、四大基石介绍和示例等系列综合文章链接 13、Flink 的table api与sql的基本概念、通用api介绍及入门示例 14、Flink 的table api与sql之数据类型: 内置数据类型以及它们的属性 15、Flink 的ta…

从源代码出发,Jenkins 任务排队时间过长问题的解决过程

最近开发了一个部署相关的工具,使用 Jenkins 来构建应用。Jenkins 的任务从模板中创建而来。每次部署时,通过 Jenkins API 来触发构建任务。在线上运行时发现,通过 API 触发的 Jenkins 任务总是会时不时在队列中等待较长的时间。某些情况下的…

Node.js案例 - 记账本

目录 项目效果 项目的搭建 ​编辑 响应静态网页 ​编辑 ​编辑 结合MongoDB数据库 结合API接口 进行会话控制 项目效果 该案例实现账单的添加删除查看,用户的登录注册。功能比较简单,但是案例主要是使用前段时间学习的知识进行实现的&#xff0c…

C++ AVL 树

AVL树的概念 当数据有序或接近有序二叉搜索树将退化为单支树,此时二叉搜索树的搜索效率低下 解决方法:AVL树(降低树的高度,从而减少平均搜索长度) 一棵AVL树或者是空树,或者是具有以下性质的二叉搜索树&#xff1…

JavaScript基础—函数、参数、返回值、作用域、变量、匿名函数、综合案例—转换时间,逻辑中断,转换为Boolean型

版本说明 当前版本号[20231129]。 版本修改说明20231126初版20231129完善部分内容 目录 文章目录 版本说明目录JavaScript 基础 - 第4天笔记函数声明和调用声明(定义)调用细节补充 参数形参和实参函数默认值 返回值作用域全局作用域局部作用域 变量全…

laraval6.0 GatewayWorker 交互通信

laravel 6.0 GatewayWorker 通讯 开发前准备下载 GatewayWorker 及操作方式前端demo测试效果项目中安装GatewayClient 开发前准备 GatewayClient 官网:https://www.workerman.net/ 当前使用的是宝塔操作 下载 GatewayWorker 及操作方式 前端demo 测试效果 项目中安…

纹理烘焙:原理及实现

纹理烘焙是计算机图形学中常见的技术,用于将着色器的细节传输到纹理中。 如果你的着色器计算量很大,但会产生静态结果,例如,这非常有用。 复杂的噪音。 NSDT在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器…

Ajax的使用方法

1,什么是Ajax? Ajax(异步Javascript和XML),是指一种创建交互式网页应用的网页开发技术。 2,Ajax的作用 Ajax可以使网页实现异步更新----即在不更新整个页面的情况下实现对某一部分进行更新。 简单来说Ajax就是用于连接…

【Python】yaml.safe_load()函数详解和示例

在Python中,PyYAML库提供了对YAML(YAML Ain’t Markup Language)文件的强大支持。YAML是一种直观的数据序列化标准,可以方便地存储和加载配置文件、数据日志等。 yaml.safe_load和yaml.load是Python的PyYAML库提供的两个函数&…

从零搭建AlibabaCloud微服务项目

1&#xff0c;创建maven项目工程如下 equipment-admin 后台equipment-applet 前台或小程序端或app、h5equipment-common 公共模块equipment-gateway 网关equipment-mapper mapper层操作数据库equipment-model 实体类对应数据库表 2&#xff0c;在父pom文件引入依赖 <proper…

基于Java SSM框架实现美食推荐管理系统项目【项目源码+论文说明】计算机毕业设计

基于java的SSM框架实现美食推荐管理系统演示 摘要 21世纪的今天&#xff0c;随着社会的不断发展与进步&#xff0c;人们对于信息科学化的认识&#xff0c;已由低层次向高层次发展&#xff0c;由原来的感性认识向理性认识提高&#xff0c;管理工作的重要性已逐渐被人们所认识&a…

国内首个农业开源鸿蒙操作系统联合华为正式发布

2023年11月29日&#xff0c;在中国国际供应链促进博览会上&#xff0c;中信农业科技股份有限公司&#xff08;简称“中信农业”&#xff09;与深圳开鸿数字产业发展有限公司&#xff08;简称“深开鸿”&#xff09;以及华为技术有限公司&#xff08;简称“华为”&#xff09;联…

UniWebView 版本3 版本4 版本5介绍

一、介绍 UniWebView是iOS/Android上的web视图组件的包装器&#xff0c;所以运行时拥有与原生web相似性能。是针对Unity所写的插件&#xff0c;节省了项目的开发时间。 官网地址&#xff1a;UniWebView 二、下载&使用 1、下载 &#xff08;1&#xff09;、Unity Asset …

GAN:PacGAN-生成对抗网络中两个样本的威力

论文&#xff1a;https://arxiv.org/pdf/1712.04086.pdf 代码&#xff1a;GitHub - fjxmlzn/PacGAN: [NeurIPS 2018] [JSAIT] PacGAN: The power of two samples in generative adversarial networks 发表&#xff1a;2016 一、摘要 1&#xff1a;GAN最重大的缺陷是&#xf…

自己动手写 chatgpt: Attention 机制的原理与实现

chatgpt等大模型之所以成功都有赖于一种算法突破&#xff0c;那就是 attention 机制。这种机制能让神经网络更有效的从语言中抽取识别其内含的规律&#xff0c;同时它支持多路并行运算&#xff0c;因此相比于原来的自然语言处理算法&#xff0c;它能够通过并发的方式将训练的速…

leetcode 11. 盛最多水的容器(优质解法)

代码&#xff1a; class Solution {public int maxArea(int[] height) {int nheight.length;int left0;int rightn-1;int max0;while (left<right){//计算当前 left 和 right 所在位置的面积int areaMath.min(height[left],height[right])*(right-left);//重置最大值if(are…

进程间通信基础知识【Linux】——上篇

目录 一&#xff0c;理解进程之间的通信 1. 进程间通信目的 2. 进程间通信的技术背景 3&#xff0c;常见的进程间通信 二&#xff0c;管道 1. 尝试建立一个管道 管道的特点&#xff1a; 管道提供的访问控制&#xff1a; 2. 扩展&#xff1a;进程池 阶段一&#xff1a…

sqli-labs靶场详解(less32-less37)

宽字节注入 原理在下方 目录 less-32 less-33 less-34 less-35 less-36 less-37 less-32 正常页面 ?id1 下面有提示 获取到了Hint: The Query String you input is escaped as : 1\ ?id1 看来是把参数中的非法字符就加上了转义 从而在数据库中只能把单引号当成普通的字…

asla四大开源组件应用示例(alsa-lib、alsa-utils、alsa-tools、alsa-plugins)

文章目录 alsa设备文件/dev/snd//sys/class/sound/proc/asoundalsa-lib示例1alsa-utilsalsa-toolsalsa-plugins参考alsa设备文件 /dev/snd/ alsa设备文件目录位于,/dev/snd,如下所示 root@xboard:~#ls /dev/snd -l total 0 drwxr-xr-x 2 root root 60 Nov 6 2023 …