search
HomeTechnology peripheralsAIPython Deep Learning 18-DeepDream of Generative Deep Learning

​DeepDream Introduction

DeepDream is an artistic image modification technology, which is mainly based on the trained convolutional neural network CNN to generate images.

When generating images, the neural network is frozen, that is, the weights of the network are no longer updated, only the input images need to be updated. Commonly used pre-trained convolutional networks include Google's Inception, VGG network and ResNet network, etc.

Basic steps of DeePDream:

  • Get the input image
  • Input the image into the network and get the output value of the neuron you want to visualize
  • Calculate the gradient of the neuron output value to each pixel of the picture
  • Use gradient descent to continuously update the picture

Repeat steps 2, 3, and 4 until the set conditions are met

The following is the general process of using Keras to implement DeepDream:

Using Keras to implement DeepDream

Get the test image

In [1]:

# ---------------
from tensorflow import keras
import matplotlib.pyplot as plt
%matplotlib inline

base_image_path = keras.utils.get_file(
"coast.jpg", 
origin="https://img-datasets.s3.amazonaws.com/coast.jpg")

plt.axis("off")
plt.imshow(keras.utils.load_img(base_image_path))
plt.show()

Python Deep Learning 18-DeepDream of Generative Deep Learning

The above is a picture of the coastline that comes with Keras. Here are the changes to this picture.

Prepare the pre-trained model InceptionV3

In [2]:

# 使用Inception V3实现
from keras.applications import inception_v3

# 使用预训练的ImageNet权重来加载模型
model = inception_v3.InceptionV3(weights="imagenet", # 构建不包含全连接层的Inceptino 
 include_top=False)
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5
87916544/87910968 [==============================] - 74s 1us/step
87924736/87910968 [==============================] - 74s 1us/step

In [3]:

model.summary()

Python Deep Learning 18-DeepDream of Generative Deep Learning

Set DeepDream configuration

In [4]:

# 层的名称 + 系数:该层对需要最大化的损失的贡献大小

layer_settings = {"mixed4":1.0, 
"mixed5":1.5,
"mixed6":2.0,
"mixed7":2.5}

outputs_dict = dict(
[
(layer.name, layer.output) # 层的名字 + 该层的输出
for layer in [model.get_layer(name) for name in layer_settings.keys()]
]
)

outputs_dict

Out[4]:

{'mixed4': <KerasTensor: shape=(None, None, None, 768) dtype=float32 (created by layer 'mixed4')>,
 'mixed5': <KerasTensor: shape=(None, None, None, 768) dtype=float32 (created by layer 'mixed5')>,
 'mixed6': <KerasTensor: shape=(None, None, None, 768) dtype=float32 (created by layer 'mixed6')>,
 'mixed7': <KerasTensor: shape=(None, None, None, 768) dtype=float32 (created by layer 'mixed7')>}

In [5]:

# 特征提取

feature_extractor = keras.Model(inputs=model.inputs, outputs=outputs_dict)
feature_extractor

Out[5]:

<keras.engine.functional.Functional at 0x15b5ff0d0>

Calculating loss

In [6]:

def compute_loss(image):
features = feature_extractor(image)# 特征提取
loss = tf.zeros(shape=())# 损失初始化

for name in features.keys():# 遍历层
coeff = layer_settings[name] # 某个层的系数
activation = features[name]# 某个层的激活函数
#为了避免出现边界伪影,损失中仅包含非边界的像素
loss += coeff * tf.reduce_mean(tf.square(activation[:, 2:-2, 2:-2, :])) # 将该层的L2范数添加到loss中;
return loss

Gradient ascent process

In [7]:

import tensorflow as tf

@tf.function
def gradient_ascent_step(image, lr): # lr--->learning_rate学习率
with tf.GradientTape() as tape:
tape.watch(image)
loss = compute_loss(image)# 调用计算损失方法
grads = tape.gradient(loss, image)# 梯度更新
grads = tf.math.l2_normalize(grads)
image += lr * grads
return loss, image

def gradient_ascent_loop(image, iterations, lr, max_loss=None):
for i in range(iterations):
loss, image = gradient_ascent_step(image, lr)
if max_loss is not None and loss > max_loss:
break
print(f"第{i}步的损失值是{loss:.2f}")

return image

Picture generation

np.expand_dims usage (personal addition)

In [8]:

import numpy as np

array = np.array([[1,2,3],
[4,5,6]]
)
array

Out[8]:

array([[1, 2, 3],
 [4, 5, 6]])

In [9]:

array.shape

Out[9]:

(2, 3)

In [10]:

array1 = np.expand_dims(array,axis=0)
array1

Out[10]:

array([[[1, 2, 3],
[4, 5, 6]]])

In [ 11]:

array1.shape

Out[11]:

(1, 2, 3)

In [12]:

array2 = np.expand_dims(array,axis=1)
array2

Out[12]:

array([[[1, 2, 3]],

 [[4, 5, 6]]])

In [13] :

array2.shape

Out[13]:

(2, 1, 3)

In [14]:

array3 = np.expand_dims(array,axis=-1)
array3

Out[14]:

array([[[1],
[2],
[3]],

 [[4],
[5],
[6]]])

In [15]:

array3.shape

Out[15]:

(2, 3, 1)

np.clip function (personally added)

np.clip(
array, 
min(array), 
max(array), 
out=None):

In [16]:

array = np.array([1,2,3,4,5,6])

np.clip(array, 2, 5)# 输出长度和原数组相同

Out[16]:

array([2, 2, 3, 4, 5, 5])

In [17]:

array = np.arange(18).reshape((6,3))
array

Out[17]:

array([[ 0,1,2],
 [ 3,4,5],
 [ 6,7,8],
 [ 9, 10, 11],
 [12, 13, 14],
 [15, 16, 17]])

In [18]:

np.clip(array, 5, 15)

Out[18]:

array([[ 5,5,5],
 [ 5,5,5],
 [ 6,7,8],
 [ 9, 10, 11],
 [12, 13, 14],
 [15, 15, 15]])

Parameter setting

In [19]:

step = 20.#梯度上升的步长
num_octave = 3# 运行梯度上升的尺度个数
octave_scale = 1.4# 两个尺度间的比例大小
iterations = 30# 在每个尺度上运行梯度上升的步数
max_loss = 15.# 损失值若大于15,则中断梯度上升过程

Picture preprocessing

In [20]:

import numpy as np

def preprocess_image(image_path):# 预处理
img = keras.utils.load_img(image_path)# 导入图片
img = keras.utils.img_to_array(img)# 转成数组
img = np.expand_dims(img, axis=0)# 增加数组维度;见上面解释(x,y) ---->(1,x,y)
img = keras.applications.inception_v3.preprocess_input(img) 
return img


def deprocess_image(img):# 图片压缩处理
img = img.reshape((img.shape[1], img.shape[2], 3))
img /= 2.0
img += 0.5
img *= 255.
# np.clip:截断功能,保证数组中的取值在0-255之间
img = np.clip(img, 0, 255).astype("uint8")
return img

Generate picture

In [21]:

# step = 20.#梯度上升的步长
# num_octave = 3# 运行梯度上升的尺度个数
# octave_scale = 1.4# 两个尺度间的比例大小
# iterations = 30# 在每个尺度上运行梯度上升的步数
# max_loss = 15.0# 损失值若大于15,则中断梯度上升过程

original_img = preprocess_image(base_image_path)# 预处理函数
original_shape = original_img.shape[1:3]

print(original_img.shape)# 四维图像
print(original_shape)# 第2和3维度的值
(1, 900, 1200, 3)
(900, 1200)

In [22]:

successive_shapes = [original_shape]

for i in range(1, num_octave):
shape = tuple([int(dim / (octave_scale ** i)) for dim in original_shape])
successive_shapes.append(shape)
successive_shapes = successive_shapes[::-1]# 翻转

shrunk_original_img = tf.image.resize(original_img, successive_shapes[0])

img = tf.identity(original_img)
for i, shape in enumerate(successive_shapes):
print(f"Processing octave {i} with shape {shape}")
# resize
img = tf.image.resize(img, shape)
img = gradient_ascent_loop(# 梯度上升函数调用
img, 
iteratinotallow=iterations, 
lr=step, 
max_loss=max_loss
)
# resize
upscaled_shrunk_original_img = tf.image.resize(shrunk_original_img, shape)
same_size_original = tf.image.resize(original_img, shape)

lost_detail = same_size_original - upscaled_shrunk_original_img
img += lost_detail
shrunk_original_img = tf.image.resize(original_img, shape)

keras.utils.save_img("dream.png", deprocess_image(img.numpy()))

The result is:

Processing octave 0 with shape (459, 612)
第0步的损失值是0.80
第1步的损失值是1.07
第2步的损失值是1.44
第3步的损失值是1.82
......
第26步的损失值是11.44
第27步的损失值是11.72
第28步的损失值是12.03
第29步的损失值是12.49

At the same time, a new picture is generated locally. Take a look at the effect:

Python Deep Learning 18-DeepDream of Generative Deep Learning

Take another look at the original picture: In comparison, the new picture is a bit dreamy!

Python Deep Learning 18-DeepDream of Generative Deep Learning


The above is the detailed content of Python Deep Learning 18-DeepDream of Generative Deep Learning. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
人工智能(AI)、机器学习(ML)和深度学习(DL):有什么区别?人工智能(AI)、机器学习(ML)和深度学习(DL):有什么区别?Apr 12, 2023 pm 01:25 PM

人工智能Artificial Intelligence(AI)、机器学习Machine Learning(ML)和深度学习Deep Learning(DL)通常可以互换使用。但是,它们并不完全相同。人工智能是最广泛的概念,它赋予机器模仿人类行为的能力。机器学习是将人工智能应用到系统或机器中,帮助其自我学习和不断改进。最后,深度学习使用复杂的算法和深度神经网络来重复训练特定的模型或模式。让我们看看每个术语的演变和历程,以更好地理解人工智能、机器学习和深度学习实际指的是什么。人工智能自过去 70 多

深度学习GPU选购指南:哪款显卡配得上我的炼丹炉?深度学习GPU选购指南:哪款显卡配得上我的炼丹炉?Apr 12, 2023 pm 04:31 PM

众所周知,在处理深度学习和神经网络任务时,最好使用GPU而不是CPU来处理,因为在神经网络方面,即使是一个比较低端的GPU,性能也会胜过CPU。深度学习是一个对计算有着大量需求的领域,从一定程度上来说,GPU的选择将从根本上决定深度学习的体验。但问题来了,如何选购合适的GPU也是件头疼烧脑的事。怎么避免踩雷,如何做出性价比高的选择?曾经拿到过斯坦福、UCL、CMU、NYU、UW 博士 offer、目前在华盛顿大学读博的知名评测博主Tim Dettmers就针对深度学习领域需要怎样的GPU,结合自

字节跳动模型大规模部署实战字节跳动模型大规模部署实战Apr 12, 2023 pm 08:31 PM

一. 背景介绍在字节跳动,基于深度学习的应用遍地开花,工程师关注模型效果的同时也需要关注线上服务一致性和性能,早期这通常需要算法专家和工程专家分工合作并紧密配合来完成,这种模式存在比较高的 diff 排查验证等成本。随着 PyTorch/TensorFlow 框架的流行,深度学习模型训练和在线推理完成了统一,开发者仅需要关注具体算法逻辑,调用框架的 Python API 完成训练验证过程即可,之后模型可以很方便的序列化导出,并由统一的高性能 C++ 引擎完成推理工作。提升了开发者训练到部署的体验

基于深度学习的Deepfake检测综述基于深度学习的Deepfake检测综述Apr 12, 2023 pm 06:04 PM

深度学习 (DL) 已成为计算机科学中最具影响力的领域之一,直接影响着当今人类生活和社会。与历史上所有其他技术创新一样,深度学习也被用于一些违法的行为。Deepfakes 就是这样一种深度学习应用,在过去的几年里已经进行了数百项研究,发明和优化各种使用 AI 的 Deepfake 检测,本文主要就是讨论如何对 Deepfake 进行检测。为了应对Deepfake,已经开发出了深度学习方法以及机器学习(非深度学习)方法来检测 。深度学习模型需要考虑大量参数,因此需要大量数据来训练此类模型。这正是

聊聊实时通信中的AI降噪技术聊聊实时通信中的AI降噪技术Apr 12, 2023 pm 01:07 PM

Part 01 概述 在实时音视频通信场景,麦克风采集用户语音的同时会采集大量环境噪声,传统降噪算法仅对平稳噪声(如电扇风声、白噪声、电路底噪等)有一定效果,对非平稳的瞬态噪声(如餐厅嘈杂噪声、地铁环境噪声、家庭厨房噪声等)降噪效果较差,严重影响用户的通话体验。针对泛家庭、办公等复杂场景中的上百种非平稳噪声问题,融合通信系统部生态赋能团队自主研发基于GRU模型的AI音频降噪技术,并通过算法和工程优化,将降噪模型尺寸从2.4MB压缩至82KB,运行内存降低约65%;计算复杂度从约186Mflop

地址标准化服务AI深度学习模型推理优化实践地址标准化服务AI深度学习模型推理优化实践Apr 11, 2023 pm 07:28 PM

导读深度学习已在面向自然语言处理等领域的实际业务场景中广泛落地,对它的推理性能优化成为了部署环节中重要的一环。推理性能的提升:一方面,可以充分发挥部署硬件的能力,降低用户响应时间,同时节省成本;另一方面,可以在保持响应时间不变的前提下,使用结构更为复杂的深度学习模型,进而提升业务精度指标。本文针对地址标准化服务中的深度学习模型开展了推理性能优化工作。通过高性能算子、量化、编译优化等优化手段,在精度指标不降低的前提下,AI模型的模型端到端推理速度最高可获得了4.11倍的提升。1. 模型推理性能优化

深度学习撞墙?LeCun与Marcus到底谁捅了马蜂窝深度学习撞墙?LeCun与Marcus到底谁捅了马蜂窝Apr 09, 2023 am 09:41 AM

今天的主角,是一对AI界相爱相杀的老冤家:Yann LeCun和Gary Marcus在正式讲述这一次的「新仇」之前,我们先来回顾一下,两位大神的「旧恨」。LeCun与Marcus之争Facebook首席人工智能科学家和纽约大学教授,2018年图灵奖(Turing Award)得主杨立昆(Yann LeCun)在NOEMA杂志发表文章,回应此前Gary Marcus对AI与深度学习的评论。此前,Marcus在杂志Nautilus中发文,称深度学习已经「无法前进」Marcus此人,属于是看热闹的不

英伟达首席科学家:深度学习硬件的过去、现在和未来英伟达首席科学家:深度学习硬件的过去、现在和未来Apr 12, 2023 pm 03:07 PM

过去十年是深度学习的“黄金十年”,它彻底改变了人类的工作和娱乐方式,并且广泛应用到医疗、教育、产品设计等各行各业,而这一切离不开计算硬件的进步,特别是GPU的革新。 深度学习技术的成功实现取决于三大要素:第一是算法。20世纪80年代甚至更早就提出了大多数深度学习算法如深度神经网络、卷积神经网络、反向传播算法和随机梯度下降等。 第二是数据集。训练神经网络的数据集必须足够大,才能使神经网络的性能优于其他技术。直至21世纪初,诸如Pascal和ImageNet等大数据集才得以现世。 第三是硬件。只有

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version