东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 14152|回复: 23
打印 上一主题 下一主题

[课堂笔记] 预训练好的卷积神经网络CNN模型:vgg16.npy vgg19.npy 下载

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14432
QQ
跳转到指定楼层
楼主
发表于 2019-2-3 22:43:15 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式


预训练好的卷积神经网络CNN模型:vgg16.npy vgg19.npy 下载


文件比较大 保存到了百度网盘 方便大家转存  16层与19层的VGG网络


下载地址【回复本帖可见】:
游客,如果您要查看本帖隐藏内容请回复


  1. # _*_ coding: utf-8  _*_

  2. import numpy as np

  3. vgg16_data = np.load('vgg16.npy', encoding='bytes')

  4. print(type(vgg16_data))
  5. # print(vgg16_data)

  6. data_dict = vgg16_data.item()

  7. print(type(data_dict))

  8. print(data_dict.keys())

  9. print(len(data_dict))

  10. conv1_1 = data_dict[b'conv1_1']

  11. print(len(conv1_1))

  12. w, b = conv1_1

  13. print(w.shape)
  14. print(b.shape)

  15. fc6 = data_dict[b'fc6']
  16. print(len(fc6))

  17. w, b = fc6
  18. print(w.shape)
  19. print(b.shape)

复制代码

  1. # _*_ coding: utf-8  _*_
  2. import os
  3. import math
  4. import numpy as np
  5. import tensorflow as tf
  6. import time
  7. from PIL import Image

  8. VGG_MEAN = [103.939, 116.779, 123.68]


  9. class VGGNet:
  10.     """
  11.     构建VGG16的网络结构 并从预处理模型中加载训练好的参数
  12.     """
  13.     def __init__(self, data_dict):
  14.         self.data_dict = data_dict

  15.     def get_conv_kernel(self, name):
  16.         # 卷积核的参数 w:0 bias:1
  17.         return tf.constant(self.data_dict[name][0], name='conv')

  18.     def get_fc_weight(self, name):
  19.         return tf.constant(self.data_dict[name][0], name='fc')

  20.     def get_bias(self, name):
  21.         return tf.constant(self.data_dict[name][1], name='bias')

  22.     def conv_layer(self, inputs, name):
  23.         """构建一个卷积计算层"""
  24.         # 多使用name_scope的好处:1、防止参数命名冲突 2、可视化的显示规整
  25.         with tf.name_scope(name):
  26.             conv_w = self.get_conv_kernel(name)
  27.             conv_b = self.get_bias(name)
  28.             # tf.layers.conv2d() 里面没有参数的 不能用了
  29.             result = tf.nn.conv2d(inputs, conv_w, [1, 1, 1, 1], padding='SAME')
  30.             result = tf.nn.bias_add(result, conv_b)
  31.             result = tf.nn.relu(result)
  32.             return result

  33.     def pooling_layer(self, inputs, name):
  34.         """构建一个池化层 tf.layers.max_pooling2d()"""
  35.         result = tf.nn.max_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name=name)
  36.         return result

  37.     def fc_layer(self, inputs, name, activation=tf.nn.relu):
  38.         """构建全连接层的计算"""
  39.         with tf.name_scope(name):
  40.             fc_w = self.get_fc_weight(name)
  41.             fc_b = self.get_bias(name)
  42.             result = tf.nn.bias_add(tf.matmul(inputs, fc_w), fc_b)
  43.             if activation is None:
  44.                 return result
  45.             else:
  46.                 return activation(result)

  47.     def flatten_op(self, inputs, name):
  48.         """展平操作 tf.layers.flatten()"""
  49.         with tf.name_scope(name):
  50.             # [N H W C]---> [N H*W*C]
  51.             x_shape = inputs.get_shape().as_list()
  52.             dim = 1
  53.             for d in x_shape[1:]:
  54.                 dim *= d
  55.             inputs = tf.reshape(inputs, shape=[-1, dim])
  56.             return inputs

  57.     def build(self, input_rgb):
  58.         """构建vgg16网络 提取特征 FP过程
  59.            参数:
  60.            --input_rgb: [1, 224, 224, 3]
  61.         """
  62.         start_time = time.time()
  63.         print('building start...')

  64.         # r, g, b = tf.split(value=input_rgb, num_or_size_splits=[1, 1, 1], axis=3)
  65.         r, g, b = tf.split(value=input_rgb, num_or_size_splits=3, axis=3)
  66.         # 输入vgg的图像是bgr的顺序(跟opencv一样 倒序的)而不是rgb
  67.         x_bgr = tf.concat(values=[
  68.             b - VGG_MEAN[0],
  69.             g - VGG_MEAN[1],
  70.             r - VGG_MEAN[2]
  71.         ], axis=3)

  72.         assert x_bgr.get_shape().as_list()[1:] == [224, 224, 3]
  73.         # stage 1
  74.         self.conv1_1 = self.conv_layer(x_bgr, 'conv1_1')
  75.         self.conv1_2 = self.conv_layer(self.conv1_1, 'conv1_2')
  76.         self.pool1 = self.pooling_layer(self.conv1_2, 'pool1')
  77.         # stage 2
  78.         self.conv2_1 = self.conv_layer(self.pool1, 'conv2_1')
  79.         self.conv2_2 = self.conv_layer(self.conv2_1, 'conv2_2')
  80.         self.pool2 = self.pooling_layer(self.conv2_2, 'pool2')

  81.         # stage 3
  82.         self.conv3_1 = self.conv_layer(self.pool2, 'conv3_1')
  83.         self.conv3_2 = self.conv_layer(self.conv3_1, 'conv3_2')
  84.         self.conv3_3 = self.conv_layer(self.conv3_2, 'conv3_3')
  85.         self.pool3 = self.pooling_layer(self.conv3_3, 'pool3')
  86.         # stage 4
  87.         self.conv4_1 = self.conv_layer(self.pool3, 'conv4_1')
  88.         self.conv4_2 = self.conv_layer(self.conv4_1, 'conv4_2')
  89.         self.conv4_3 = self.conv_layer(self.conv4_2, 'conv4_3')
  90.         self.pool4 = self.pooling_layer(self.conv4_3, 'pool4')
  91.         # stage 5
  92.         self.conv5_1 = self.conv_layer(self.pool4, 'conv5_1')
  93.         self.conv5_2 = self.conv_layer(self.conv5_1, 'conv5_2')
  94.         self.conv5_3 = self.conv_layer(self.conv5_2, 'conv5_3')
  95.         self.pool5 = self.pooling_layer(self.conv5_3, 'pool5')
  96.         # stage 6
  97.         self.flatten5 = self.flatten_op(self.pool5, 'flatten5')
  98.         self.fc6 = self.fc_layer(self.flatten5, 'fc6')
  99.         self.fc7 = self.fc_layer(self.fc6, 'fc7')
  100.         self.fc8 = self.fc_layer(self.fc7, 'fc8', activation=None)
  101.         self.prob = tf.nn.softmax(self.fc8, name='prob')

  102.         print(self.prob.shape)

  103.         print('buliding finished 耗时:%4ds' % (time.time() - start_time))
  104.         pass

  105. vgg16_npy_path = './vgg16.npy'
  106. vgg16_data = np.load(vgg16_npy_path, encoding='latin1')
  107. data_dict = vgg16_data.item()

  108. print(data_dict.keys())

  109. vgg16_for_result = VGGNet(data_dict)

  110. image_rgb = tf.placeholder(dtype=tf.float32, shape=[1, 224, 224, 3], name='image_rgb')

  111. vgg16_for_result.build(image_rgb)

复制代码


  1. # -*- coding: utf-8 -*-
  2. __author__ = 'dongfangyao'
  3. __date__ = '2019/2/4 下午3:33'
  4. __product__ = 'PyCharm'
  5. __filename__ = '10_image_style_conversion'
  6. """
  7.    TensorFlow实现图像风格转换 V1算法
  8. """
  9. import os
  10. import numpy as np
  11. import tensorflow as tf
  12. import time
  13. from PIL import Image
  14. import matplotlib.pyplot as plt

  15. VGG_MEAN = [103.939, 116.779, 123.68]


  16. class VGGNet:
  17.     """
  18.     构建VGG16的网络结构 并从预处理模型中加载训练好的参数
  19.     """
  20.     def __init__(self, data_dict):
  21.         self.data_dict = data_dict

  22.     def get_conv_kernel(self, name):
  23.         # 卷积核的参数 w:0 bias:1
  24.         return tf.constant(self.data_dict[name][0], name='conv')

  25.     def get_fc_weight(self, name):
  26.         return tf.constant(self.data_dict[name][0], name='fc')

  27.     def get_bias(self, name):
  28.         return tf.constant(self.data_dict[name][1], name='bias')

  29.     def conv_layer(self, inputs, name):
  30.         """构建一个卷积计算层"""
  31.         # 多使用name_scope的好处:1、防止参数命名冲突 2、可视化的显示规整
  32.         with tf.name_scope(name):
  33.             conv_w = self.get_conv_kernel(name)
  34.             conv_b = self.get_bias(name)
  35.             # tf.layers.conv2d() 里面没有参数的 不能用了
  36.             result = tf.nn.conv2d(inputs, conv_w, [1, 1, 1, 1], padding='SAME')
  37.             result = tf.nn.bias_add(result, conv_b)
  38.             result = tf.nn.relu(result)
  39.             return result

  40.     def pooling_layer(self, inputs, name):
  41.         """构建一个池化层 tf.layers.max_pooling2d()"""
  42.         result = tf.nn.max_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name=name)
  43.         return result

  44.     def fc_layer(self, inputs, name, activation=tf.nn.relu):
  45.         """构建全连接层的计算"""
  46.         with tf.name_scope(name):
  47.             fc_w = self.get_fc_weight(name)
  48.             fc_b = self.get_bias(name)
  49.             result = tf.nn.bias_add(tf.matmul(inputs, fc_w), fc_b)
  50.             if activation is None:
  51.                 return result
  52.             else:
  53.                 return activation(result)

  54.     def flatten_op(self, inputs, name):
  55.         """展平操作 tf.layers.flatten()"""
  56.         with tf.name_scope(name):
  57.             # [N H W C]---> [N H*W*C]
  58.             x_shape = inputs.get_shape().as_list()
  59.             dim = 1
  60.             for d in x_shape[1:]:
  61.                 dim *= d
  62.             inputs = tf.reshape(inputs, shape=[-1, dim])
  63.             return inputs

  64.     def build(self, input_rgb):
  65.         """构建vgg16网络 提取特征 FP过程
  66.            参数:
  67.            --input_rgb: [1, 224, 224, 3]
  68.         """
  69.         start_time = time.time()
  70.         print('building start...')

  71.         # r, g, b = tf.split(value=input_rgb, num_or_size_splits=[1, 1, 1], axis=3)
  72.         r, g, b = tf.split(value=input_rgb, num_or_size_splits=3, axis=3)
  73.         # 输入vgg的图像是bgr的顺序(跟opencv一样 倒序的)而不是rgb
  74.         x_bgr = tf.concat(values=[
  75.             b - VGG_MEAN[0],
  76.             g - VGG_MEAN[1],
  77.             r - VGG_MEAN[2]
  78.         ], axis=3)

  79.         assert x_bgr.get_shape().as_list()[1:] == [224, 224, 3]
  80.         # stage 1
  81.         self.conv1_1 = self.conv_layer(x_bgr, 'conv1_1')
  82.         self.conv1_2 = self.conv_layer(self.conv1_1, 'conv1_2')
  83.         self.pool1 = self.pooling_layer(self.conv1_2, 'pool1')
  84.         # stage 2
  85.         self.conv2_1 = self.conv_layer(self.pool1, 'conv2_1')
  86.         self.conv2_2 = self.conv_layer(self.conv2_1, 'conv2_2')
  87.         self.pool2 = self.pooling_layer(self.conv2_2, 'pool2')

  88.         # stage 3
  89.         self.conv3_1 = self.conv_layer(self.pool2, 'conv3_1')
  90.         self.conv3_2 = self.conv_layer(self.conv3_1, 'conv3_2')
  91.         self.conv3_3 = self.conv_layer(self.conv3_2, 'conv3_3')
  92.         self.pool3 = self.pooling_layer(self.conv3_3, 'pool3')
  93.         # stage 4
  94.         self.conv4_1 = self.conv_layer(self.pool3, 'conv4_1')
  95.         self.conv4_2 = self.conv_layer(self.conv4_1, 'conv4_2')
  96.         self.conv4_3 = self.conv_layer(self.conv4_2, 'conv4_3')
  97.         self.pool4 = self.pooling_layer(self.conv4_3, 'pool4')
  98.         # stage 5
  99.         self.conv5_1 = self.conv_layer(self.pool4, 'conv5_1')
  100.         self.conv5_2 = self.conv_layer(self.conv5_1, 'conv5_2')
  101.         self.conv5_3 = self.conv_layer(self.conv5_2, 'conv5_3')
  102.         self.pool5 = self.pooling_layer(self.conv5_3, 'pool5')
  103.         # stage 6
  104.         # self.flatten5 = self.flatten_op(self.pool5, 'flatten5')
  105.         # self.fc6 = self.fc_layer(self.flatten5, 'fc6')
  106.         # self.fc7 = self.fc_layer(self.fc6, 'fc7')
  107.         # self.fc8 = self.fc_layer(self.fc7, 'fc8', activation=None)
  108.         # self.prob = tf.nn.softmax(self.fc8, name='prob')

  109.         # print(self.prob.shape)

  110.         print('buliding finished 耗时:%4ds' % (time.time() - start_time))
  111.         pass

  112. vgg16_npy_path = './vgg16.npy'
  113. # vgg16_data = np.load(vgg16_npy_path, encoding='latin1')
  114. # data_dict = vgg16_data.item()
  115. #
  116. # print(data_dict.keys())
  117. #
  118. # vgg16_for_result = VGGNet(data_dict)
  119. #
  120. # image_rgb = tf.placeholder(dtype=tf.float32, shape=[1, 224, 224, 3], name='image_rgb')
  121. #
  122. # vgg16_for_result.build(image_rgb)

  123. # 224 * 224
  124. content_img_path = './img/content.jpeg'
  125. style_img_path = './img/style.jpeg'

  126. num_steps = 100
  127. learning_rate = 10

  128. lambda_c = 0.1
  129. lambda_s = 500

  130. output_dir = './img/output_img'

  131. if not os.path.exists(output_dir):
  132.     os.mkdir(output_dir)


  133. def initial_image(shape, mean, stddev):
  134.     initial_image = tf.truncated_normal(shape=shape, mean=mean, stddev=stddev, dtype=tf.float32)
  135.     return tf.Variable(initial_image)


  136. initial_image_result = initial_image([1, 224, 224, 3], mean=127.5, stddev=20)


  137. def read_img(image_name):
  138.     img = Image.open(image_name)
  139.     # [224 224 3]
  140.     np_img = np.array(img)
  141.     # np_img = tf.reshape(np_img, shape=[1, 224, 224, 3])
  142.     # [1 224 224 3]
  143.     # np_img = np.reshape(np_img, newshape=[1, 224, 224, 3])
  144.     np_img = np.asarray([np_img], dtype=np.float32)
  145.     print(np_img.shape)
  146.     return np_img

  147. # plt.imshow(read_img(style_img_path)[0])
  148. # plt.show()


  149. content_img_arr_val = read_img(content_img_path)
  150. style_img_arr_val = read_img(style_img_path)

  151. content_img = tf.placeholder(dtype=tf.float32, shape=[1, 224, 224, 3], name='content_img')
  152. style_img = tf.placeholder(dtype=tf.float32, shape=[1, 224, 224, 3], name='style_img')

  153. # initial_image_result content_img style_img 三张图片进入vgg网络 提取特征
  154. vgg16_data = np.load(vgg16_npy_path, encoding='latin1')
  155. data_dict = vgg16_data.item()

  156. print(data_dict.keys())

  157. vgg16_for_initial_result = VGGNet(data_dict)
  158. vgg16_for_content_img = VGGNet(data_dict)
  159. vgg16_for_style_img = VGGNet(data_dict)

  160. vgg16_for_content_img.build(content_img)
  161. vgg16_for_style_img.build(style_img)
  162. vgg16_for_initial_result.build(initial_image_result)

  163. # 定义提取哪些层的特征 cnn的

  164. # 内容特征 越低层越精细
  165. content_features = [
  166.     vgg16_for_content_img.conv1_2,
  167.     vgg16_for_content_img.conv2_2,
  168.     # vgg16_for_content_img.conv3_3,
  169.     # vgg16_for_content_img.conv4_3,
  170.     # vgg16_for_content_img.conv5_3
  171. ]

  172. # 结果的内容特征必须与内容特征一致
  173. result_content_features = [
  174.     vgg16_for_initial_result.conv1_2,
  175.     vgg16_for_initial_result.conv2_2,
  176.     # vgg16_for_initial_result.conv3_3,
  177.     # vgg16_for_initial_result.conv4_3,
  178.     # vgg16_for_initial_result.conv5_3
  179. ]

  180. # 风格特征 越高层越抽象
  181. style_features = [
  182.     # vgg16_for_style_img.conv1_2,
  183.     # vgg16_for_style_img.conv2_2,
  184.     # vgg16_for_style_img.conv3_3,
  185.     vgg16_for_style_img.conv4_3,
  186.     vgg16_for_style_img.conv5_3
  187. ]

  188. # 结果的风格特征必须与风格特征一致
  189. result_style_features = [
  190.     # vgg16_for_initial_result.conv1_2,
  191.     # vgg16_for_initial_result.conv2_2,
  192.     # vgg16_for_initial_result.conv3_3,
  193.     vgg16_for_initial_result.conv4_3,
  194.     vgg16_for_initial_result.conv5_3
  195. ]

  196. # 开始计算损失
  197. content_loss = tf.zeros(shape=1, dtype=tf.float32)
  198. # zip([1, 2], [3, 4]) ---> [(1, 3), (2, 4)] 两个数组变成 一个数组
  199. # c与c_的shape(卷积激励之后):[1 height width channel] 在通道axis=[1, 2, 3]求平均
  200. # loss = mse 平方差损失函数
  201. for c, c_ in zip(content_features, result_content_features):
  202.     content_loss += tf.reduce_mean(tf.square(c - c_), axis=[1, 2, 3])
  203.     pass

  204. # 计算Gram矩阵
  205. def gram_matrix(x):
  206.     """Gram矩阵计算 k个feature_map 两两之间的关联性 相似度 k*k的矩阵
  207.     Args:
  208.     ---x feature_map from Conv层 shape:[1 height width channels]    """
  209.     b, h ,w, ch = x.get_shape().as_list()
  210.     features = tf.reshape(x, shape=[b, h*w, ch])
  211.     # [ch ch] = [ch h*w] 矩阵相乘 [h*w ch]
  212.     # 除以维度相乘是为了防止 值过大 除以统一的数
  213.     # features是三维的 导致gram矩阵也是三维的
  214.     gram = tf.matmul(features, features, adjoint_a=True) / tf.constant(h*w*ch, tf.float32)
  215.     # features是2维的 导致gram矩阵也是2维的
  216.     # gram = tf.matmul(tf.matrix_transpose(features[0]), features[0]) / tf.constant(h*w*ch, tf.float32)
  217.     return gram
  218.     pass


  219. style_gram_matrix = [gram_matrix(feature) for feature in style_features]
  220. result_style_gram_matrix = [gram_matrix(feature) for feature in result_style_features]

  221. style_loss = tf.zeros(shape=1, dtype=tf.float32)
  222. for s, s_ in zip(style_gram_matrix, result_style_gram_matrix):
  223.     # loss = mse 平方差损失函数
  224.     # axis=[0, 1, 2, 3] 这里会报错  gram矩阵输出是三维的
  225.     style_loss += tf.reduce_mean(tf.square(s - s_), axis=[1, 2])
  226.     # gram矩阵输出是二维的
  227.     # style_loss += tf.reduce_mean(tf.square(s - s_), axis=[0, 1])
  228.     pass

  229. loss = content_loss * lambda_c + style_loss * lambda_s

  230. with tf.name_scope('train'):
  231.     train_op = tf.train.AdamOptimizer(learning_rate).minimize(loss)


  232. init_op = tf.global_variables_initializer()

  233. with tf.Session() as sess:
  234.     sess.run(init_op)
  235.     for step in range(num_steps):
  236.         loss_value, content_loss_value, style_loss_value, _ = \
  237.         sess.run(fetches=[loss, content_loss, style_loss, train_op], feed_dict={
  238.             content_img: content_img_arr_val,
  239.             style_img: style_img_arr_val
  240.         })
  241.         print('step:%d loss_value:%8.4f content_loss_value:%8.4f style_loss_value:%8.4f'
  242.               % (step+1, loss_value[0], content_loss_value[0], style_loss_value[0]))
  243.         # result_image:shape [224, 224, 3]
  244.         result_image = initial_image_result.eval(sess)[0]
  245.         # np.clip值裁剪 小于0的变为0 大于255的变为255
  246.         result_image = np.clip(result_image, 0, 255)
  247.         result_image = np.asarray(result_image, dtype=np.uint8)
  248.         # np_img = np.asarray([np_img], dtype=np.float32)
  249.         img = Image.fromarray(result_image)
  250.         result_image_path = os.path.join(output_dir, 'result-%05d.jpg' % (step + 1))
  251.         img.save(result_image_path)

  252.     pass



复制代码




让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

0

主题

1

帖子

4

积分

新手上路

Rank: 1

积分
4
沙发
发表于 2019-9-14 18:41:38 | 只看该作者
多谢提供
回复

使用道具 举报

0

主题

1

帖子

4

积分

新手上路

Rank: 1

积分
4
板凳
发表于 2019-11-5 11:35:03 | 只看该作者
nice多谢
回复

使用道具 举报

0

主题

5

帖子

12

积分

新手上路

Rank: 1

积分
12
地板
发表于 2019-11-16 18:54:48 | 只看该作者
非常好的资料,谢谢
回复

使用道具 举报

0

主题

1

帖子

4

积分

新手上路

Rank: 1

积分
4
5#
发表于 2020-3-6 19:47:25 | 只看该作者
haodongxi xiexie
回复

使用道具 举报

0

主题

1

帖子

4

积分

新手上路

Rank: 1

积分
4
6#
发表于 2020-3-7 12:47:43 | 只看该作者
回复

使用道具 举报

0

主题

1

帖子

4

积分

新手上路

Rank: 1

积分
4
7#
发表于 2020-4-9 15:34:23 | 只看该作者
想要下载资源~
回复

使用道具 举报

0

主题

3

帖子

10

积分

新手上路

Rank: 1

积分
10
8#
发表于 2020-4-21 19:17:13 | 只看该作者
好的好好看看
回复

使用道具 举报

0

主题

2

帖子

6

积分

新手上路

Rank: 1

积分
6
9#
发表于 2020-6-23 19:22:48 | 只看该作者
谢谢大佬新手求教
回复

使用道具 举报

0

主题

2

帖子

6

积分

新手上路

Rank: 1

积分
6
10#
发表于 2020-8-24 15:56:50 | 只看该作者
aggjlkj;klgyjudytuytui
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-4-26 12:36 , Processed in 0.185672 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表