1. 程式人生 > >生成對抗網路DCGAN+Tensorflow程式碼學習筆記(二)----utils.py

生成對抗網路DCGAN+Tensorflow程式碼學習筆記(二)----utils.py

utils.py主要是定義了各種對影象處理的函式,主要負責影象的一些基本操作,獲取影象、儲存影象、影象翻轉,和利用moviepy模組視覺化訓練過程。相當於其他3個檔案的標頭檔案。

"""
Some codes from https://github.com/Newmu/dcgan_code
"""
from __future__ import division
import math
import json
import random
import pprint
import scipy.misc
import numpy as np
from time import gmtime, strftime
from six.moves import xrange

import tensorflow as tf
import tensorflow.contrib.slim as slim
#1.首先定義了一個pp = pprint.PrettyPrinter(),以方便列印資料結構資訊
pp = pprint.PrettyPrinter()
#2.定義了get_stddev函式,是三個引數乘積後開平方的倒數,應該是為了隨機化用
get_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.get_shape()[-1])

def show_all_variables():
  model_vars = tf.trainable_variables()
  slim.model_analyzer.analyze_vars(model_vars, print_info=True)

def get_image(image_path, input_height, input_width,
              resize_height=64, resize_width=64,
              crop=True, grayscale=False):
#根據影象路徑引數讀取路徑,根據灰度化引數選擇是否進行灰度化
  image = imread(image_path, grayscale)
#對影象參照輸入的引數進行裁剪
  return transform(image, input_height, input_width,
                   resize_height, resize_width, crop)
#儲存新影象
def save_images(images, size, image_path):
  return imsave(inverse_transform(images), size, image_path)
#判斷grayscale引數是否進行範圍灰度化,並進行型別轉換為np.float
def imread(path, grayscale = False):
  if (grayscale):
    return scipy.misc.imread(path, flatten = True).astype(np.float)
  else:
    return scipy.misc.imread(path).astype(np.float)
#返回新影象
def merge_images(images, size):
  return inverse_transform(images)
# 產生一個大畫布,用來儲存生成的 batch_size 個影象
def merge(images, size):
  #影象的高、寬
  h, w = images.shape[1], images.shape[2]
  if (images.shape[3] in (3,4)):
    #影象的通道數
    c = images.shape[3]
    # 迴圈使得畫布特定地方值為某一幅影象的值
    img = np.zeros((h * size[0], w * size[1], c))
    for idx, image in enumerate(images):
      i = idx % size[1]
      j = idx // size[1]
      img[j * h:j * h + h, i * w:i * w + w, :] = image
    return img
  elif images.shape[3]==1:
    img = np.zeros((h * size[0], w * size[1]))
    for idx, image in enumerate(images):
      i = idx % size[1]
      j = idx // size[1]
      img[j * h:j * h + h, i * w:i * w + w] = image[:,:,0]
    return img
  else:
    raise ValueError('in merge(images,size) images parameter '
                     'must have dimensions: HxW or HxWx3 or HxWx4')
#首先將merge()函式返回的影象,用 np.squeeze()函式移除長度為1的軸。
# 然後利用scipy.misc.imsave()函式將新影象儲存到指定路徑中。
def imsave(images, size, path):
  image = np.squeeze(merge(images, size))
  return scipy.misc.imsave(path, image)
#對影象的H和W與crop的H和W相減,得到取整的值,根據這個值作為下標依據來scipy.misc.resize影象。
def center_crop(x, crop_h, crop_w,
                resize_h=64, resize_w=64):
  if crop_w is None:
    crop_w = crop_h
  h, w = x.shape[:2]
  j = int(round((h - crop_h)/2.))
  i = int(round((w - crop_w)/2.))
  return scipy.misc.imresize(
      x[j:j+crop_h, i:i+crop_w], [resize_h, resize_w])
#對輸入的影象進行裁剪
def transform(image, input_height, input_width, 
              resize_height=64, resize_width=64, crop=True):
  if crop:
    cropped_image = center_crop(
      image, input_height, input_width, 
      resize_height, resize_width)
  else:
    cropped_image = scipy.misc.imresize(image, [resize_height, resize_width])
  return np.array(cropped_image)/127.5 - 1.
#對影象進行翻轉後返回新影象
def inverse_transform(images):
  return (images+1.)/2.
#獲取每一層的權值、偏置值
def to_json(output_path, *layers):
  with open(output_path, "w") as layer_f:
    lines = ""
    for w, b, bn in layers:
      layer_idx = w.name.split('/')[0].split('h')[1]

      B = b.eval()

      if "lin/" in w.name:
        W = w.eval()
        depth = W.shape[1]
      else:
        W = np.rollaxis(w.eval(), 2, 0)
        depth = W.shape[0]

      biases = {"sy": 1, "sx": 1, "depth": depth, "w": ['%.2f' % elem for elem in list(B)]}
      if bn != None:
        gamma = bn.gamma.eval()
        beta = bn.beta.eval()

        gamma = {"sy": 1, "sx": 1, "depth": depth, "w": ['%.2f' % elem for elem in list(gamma)]}
        beta = {"sy": 1, "sx": 1, "depth": depth, "w": ['%.2f' % elem for elem in list(beta)]}
      else:
        gamma = {"sy": 1, "sx": 1, "depth": 0, "w": []}
        beta = {"sy": 1, "sx": 1, "depth": 0, "w": []}

      if "lin/" in w.name:
        fs = []
        for w in W.T:
          fs.append({"sy": 1, "sx": 1, "depth": W.shape[0], "w": ['%.2f' % elem for elem in list(w)]})

        lines += """
          var layer_%s = {
            "layer_type": "fc", 
            "sy": 1, "sx": 1, 
            "out_sx": 1, "out_sy": 1,
            "stride": 1, "pad": 0,
            "out_depth": %s, "in_depth": %s,
            "biases": %s,
            "gamma": %s,
            "beta": %s,
            "filters": %s
          };""" % (layer_idx.split('_')[0], W.shape[1], W.shape[0], biases, gamma, beta, fs)
      else:
        fs = []
        for w_ in W:
          fs.append({"sy": 5, "sx": 5, "depth": W.shape[3], "w": ['%.2f' % elem for elem in list(w_.flatten())]})

        lines += """
          var layer_%s = {
            "layer_type": "deconv", 
            "sy": 5, "sx": 5,
            "out_sx": %s, "out_sy": %s,
            "stride": 2, "pad": 1,
            "out_depth": %s, "in_depth": %s,
            "biases": %s,
            "gamma": %s,
            "beta": %s,
            "filters": %s
          };""" % (layer_idx, 2**(int(layer_idx)+2), 2**(int(layer_idx)+2),
               W.shape[0], W.shape[3], biases, gamma, beta, fs)
    layer_f.write(" ".join(lines.replace("'","").split()))
#根據影象集的長度和持續的時間做一個除法,然後返回每幀影象。最後視訊修剪並製作成GIF動畫。
def make_gif(images, fname, duration=2, true_image=False):
  import moviepy.editor as mpy

  def make_frame(t):
    try:
      x = images[int(len(images)/duration*t)]
    except:
      x = images[-1]

    if true_image:
      return x.astype(np.uint8)
    else:
      return ((x+1)/2*255).astype(np.uint8)

  clip = mpy.VideoClip(make_frame, duration=duration)
  clip.write_gif(fname, fps = len(images) / duration)
#儲存影象視覺化
def visualize(sess, dcgan, config, option):
  image_frame_dim = int(math.ceil(config.batch_size**.5))
  if option == 0:
    z_sample = np.random.uniform(-0.5, 0.5, size=(config.batch_size, dcgan.z_dim))
    samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})
    save_images(samples, [image_frame_dim, image_frame_dim], './samples/test_%s.png' % strftime("%Y-%m-%d-%H-%M-%S", gmtime()))
  elif option == 1:
    values = np.arange(0, 1, 1./config.batch_size)
    for idx in xrange(dcgan.z_dim):
      print(" [*] %d" % idx)
      z_sample = np.random.uniform(-1, 1, size=(config.batch_size , dcgan.z_dim))
      for kdx, z in enumerate(z_sample):
        z[idx] = values[kdx]

      if config.dataset == "mnist":
        y = np.random.choice(10, config.batch_size)
        y_one_hot = np.zeros((config.batch_size, 10))
        y_one_hot[np.arange(config.batch_size), y] = 1

        samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample, dcgan.y: y_one_hot})
      else:
        samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})

      save_images(samples, [image_frame_dim, image_frame_dim], './samples/test_arange_%s.png' % (idx))
  elif option == 2:
    values = np.arange(0, 1, 1./config.batch_size)
    for idx in [random.randint(0, dcgan.z_dim - 1) for _ in xrange(dcgan.z_dim)]:
      print(" [*] %d" % idx)
      z = np.random.uniform(-0.2, 0.2, size=(dcgan.z_dim))
      z_sample = np.tile(z, (config.batch_size, 1))
      #z_sample = np.zeros([config.batch_size, dcgan.z_dim])
      for kdx, z in enumerate(z_sample):
        z[idx] = values[kdx]

      if config.dataset == "mnist":
        y = np.random.choice(10, config.batch_size)
        y_one_hot = np.zeros((config.batch_size, 10))
        y_one_hot[np.arange(config.batch_size), y] = 1

        samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample, dcgan.y: y_one_hot})
      else:
        samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})

      try:
        make_gif(samples, './samples/test_gif_%s.gif' % (idx))
      except:
        save_images(samples, [image_frame_dim, image_frame_dim], './samples/test_%s.png' % strftime("%Y-%m-%d-%H-%M-%S", gmtime()))
  elif option == 3:
    values = np.arange(0, 1, 1./config.batch_size)
    for idx in xrange(dcgan.z_dim):
      print(" [*] %d" % idx)
      z_sample = np.zeros([config.batch_size, dcgan.z_dim])
      for kdx, z in enumerate(z_sample):
        z[idx] = values[kdx]

      samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})
      make_gif(samples, './samples/test_gif_%s.gif' % (idx))
  elif option == 4:
    image_set = []
    values = np.arange(0, 1, 1./config.batch_size)

    for idx in xrange(dcgan.z_dim):
      print(" [*] %d" % idx)
      z_sample = np.zeros([config.batch_size, dcgan.z_dim])
      for kdx, z in enumerate(z_sample): z[idx] = values[kdx]

      image_set.append(sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}))
      make_gif(image_set[-1], './samples/test_gif_%s.gif' % (idx))

    new_image_set = [merge(np.array([images[idx] for images in image_set]), [10, 10]) \
        for idx in range(64) + range(63, -1, -1)]
    make_gif(new_image_set, './samples/test_gif_merged.gif', duration=8)


def image_manifold_size(num_images):
  manifold_h = int(np.floor(np.sqrt(num_images)))
  manifold_w = int(np.ceil(np.sqrt(num_images)))
  assert manifold_h * manifold_w == num_images
  return manifold_h, manifold_w


相關推薦

生成對抗網路DCGAN+Tensorflow程式碼學習筆記----utils.py

utils.py主要是定義了各種對影象處理的函式,主要負責影象的一些基本操作,獲取影象、儲存影象、影象翻轉,和利用moviepy模組視覺化訓練過程。相當於其他3個檔案的標頭檔案。 """ Some codes from https://github.com/Newmu/d

GitHub超過4700星的TensorFlowAmirsina Torfi博士程式碼學習筆記

上次的比較基礎,本章節(第二個檔案)主要是基礎機器學習模型學習。和筆記(一)相比較複雜,並且很多模型我都沒有引用成功。避免文章太長 ,所以本文只學習gradient_boosted_decision_tree.py,kmeans.py和linear_regression.py 完整程式碼連結

Tensorflow深度學習筆記--BPNN手寫數字識別視覺化

資料集:MNIST 啟用函式:Relu 損失函式:交叉熵 Optimizer:AdamOptimizer 視覺化工具:tensorboad 迭代21epoch,accuracy結果如下: Iter 16,Testing Accuracy:

GitHub超過4700星的TensorFlowAmirsina Torfi博士程式碼學習筆記

用TensorFlow的應該都知道,git上的一個大神弗吉尼亞理工博士Amirsina Torfi在GitHub上貢獻了一個新的教程,星星數當天就破千,現在已經4721了,估計這個文章寫完又得漲點。 完整程式碼連結(1積分):https://download.csdn.net/downloa

Tensorflow 學習筆記: 深層神經網路

Tensorflow 學習筆記(二): 深層神經網路 前言 本文是閱讀《TensorFlow:實戰Google深度學習框架》第四章提煉出來的筆記。 同時我在github找到這本書作者提供的配套原始碼,發現和書相比多了一些例子(code),推薦結合書一起使用! 深度學習與深層神

tensorflow學習筆記

example initial turn rate mnist pac rac test mode import tensorflow as tfimport numpy as npimport mathimport tensorflow.examples.tutorial

Effective_STL 學習筆記小心對 “容器無關程式碼” 的幻想

    STL 是建立在泛化上的,陣列泛化為容器,引數化了所包含的物件的型別。函式泛化為演算法,引數化了所用的迭代器型別。指標泛化為迭代器,引數化了所指向物件的型別。   泛化繼續,獨立的容器型別泛化為序列或關聯容器。標準的記憶體相鄰的容器都提供隨機訪問迭代器,標準的基於節點的容器都提供雙向迭代

【Python】搭建你的第一個簡單的神經網路_準備篇_NN&DL學習筆記

前言 本文為《Neural Network and Deep Learning》學習筆記(二),可以轉載但請標明原文地址。 本人剛剛入門、筆記簡陋不足、多有謬誤,而原書精妙易懂、不長篇幅常有柳暗花明之處,故推薦閱讀原書。 《Neural Network and Deep Learning

【複雜網路】複雜網路分析庫NetworkX學習筆記4:統計指標計算

無論是實際網路還是對模型網路進行分析,都離不開對網路拓撲統計指標的計算。反映網路結構與動力學特性的統計指標有很多,Costa等的Characterization of Complex Networks: A Survey of measurements一文對此有全面的綜述,本文僅介紹一些常用的統計指

java學習筆記static方法以及static程式碼

一:static方法 1.靜態方法中可以直接呼叫同類中的靜態成員, 但不能直接呼叫非靜態成員。 如果希望在靜態方法中呼叫非靜態變數,可以通過建立類的物件, 然後通過物件來訪問非靜態變數 2.在普通成員方法中,則可以直接訪問同類的非靜態變數和靜態變數, 3.靜態方法中不能直接呼叫非靜態方法, 需要

tensorflow學習筆記實現MNIST

import tensorflow as tf from tensorflow.contrib import rnn import numpy as np import input_data input_vec_size = lstm_size = 28 time_st

cs231n斯坦福基於卷積神經網路的CV學習筆記神經網路訓練細節

五,神經網路 注意點part1 例項:邏輯迴歸二層神經網路訓練函式 使用權重w和偏差值biase計算出第一個隱含層h,然後計算損失,評分,進行反向傳播回去 多種常用啟用函式(一般預設max(0,x)),如sigmoid函式具有飽和區梯度0,非零點中心,計算x複

Tensorflow學習筆記8——input_data.py解析

這裡學習一下前面用到的讀取mnist資料庫檔案的程式碼。其實並沒有用到Tensorlfow的東西,但是讀取資料庫檔案是使用Tensorflow程式設計實現功能的基礎,因此歸到Tensorflow的學習筆記中。 這裡需要注意的主要有以下幾點: 1.dense_

《白話深度學習Tensorflow學習筆記2梯度下降、梯度消失、引數、歸一化

1、CUDA(compute unified device architecture)可用於平行計算: GTX1060 CUDA核心數:1280 視訊記憶體大小:6G 2、隨機梯度下降:計算偏導數需要的計算量很大,而採用隨機梯度下降(即採用取樣的概念)從中提取一部分樣

TensorFlow學習筆記之視覺化(Tensorboard

一、Tensorboard簡介 Tensorboard是TensorFlow自帶的一個強大的視覺化工具,也是一個web應用程式套件。通過將tensorflow程式輸出的日誌檔案的資訊視覺化使得tensorflow程式的理解、除錯和優化更加簡單高效。支援其七種視

google機器學習框架tensorflow學習筆記

線性迴歸 人們早就知曉 ,相比涼爽的天氣,蟋蟀在較為炎熱的天氣裡鳴叫更為頻繁。數十年來,專業和業餘昆蟲學者已將每分鐘的鳴叫聲和溫度方面的資料編入目錄。Ruth 阿姨將她喜愛的蟋蟀資料庫作為生日禮物送給您,並邀請您自己利用該資料庫訓練一個模型,從而預測鳴叫聲與溫度的關係。如果把資料

機器學習pytorch平臺程式碼學習筆記8——優化器 Optimizer

用Spyder中如果有列舉enumerate都要在程式碼開始的地方加if __name__ == '__main__':  原因參考連結最後:https://blog.csdn.net/u010327061/article/details/80218836以下包括以下幾種模式

《白話深度學習Tensorflow學習筆記4Deep Residual Networks

深度殘差網路:主要應用於計算機視覺——影象分類、語義分割(semantic segmentation)、目標檢測(object detection),其主要是使用CNN進行改造。何愷明老師有一篇文獻《Deep Residual Networks——Deep learnin

計算機網路-網路學習筆記

地址解析協議ARP 主要作用:已知IP的情況下,找到硬體地址。 RARP:知道硬體地址找IP。現已包含在DHCP中。 IP地址32位;硬體地址48位。 地址解析協議ARP在ARP快取記憶體中存放一個從IP地址到硬體地址的對映表。並時常動態更新。以銜接IP地址與硬體地址。 每個主機都有

《白話深度學習Tensorflow學習筆記7RBM限制玻爾茲曼機

不受限的:在實際工程中用處不大,所以目前只需要研究受限玻爾茲曼機。 一層是視覺化層,一般來說是輸入層,另一層是隱含層,也就是我們一般指的特徵提取層。 RBM是可以多層疊加在一起的。 上面的h1到hn是n個實數,下面的v1到vm是m個實數,都是0到1