无监督学习 python AE tensorflow opencv搭建3层编码解码AutoEncoder神经网络

默认 已安装好 python、tensorflow、opencv等环境

一、主程序 AutoEncoder.py

# -*- coding: utf-8 -*-
"""
# _*_ coding:utf-8 _*_

#进行Autoencoder网络测试(3层半网络)

#3层编码 3层解码  
#开始日期:    20200909
#开发及测试人:shany 商
"""

from __future__ import  division, print_function, absolute_import
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import input_AEdata
import os
import cv2
from PIL import Image
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#加载AEtest数据集
#with tf.device('/gpu:0'):
# 得到数据集合MNIST
#from tensorflow.examples.tutorials.mnist import input_data

AEdata = input_AEdata.read_data_sets("F:/00AutoencoderTest/tmp/AEtest7", one_hot=True)

inputs_ = tf.placeholder(tf.float32, (None, 800, 800, 1), name='inputs')
targets_ = tf.placeholder(tf.float32, (None, 800, 800, 1), name='targets')
### Encoder
conv1 = tf.layers.conv2d(inputs_, 8, (3,3), padding='same', activation=tf.nn.relu) # 800x800x128
maxpool1 = tf.layers.max_pooling2d(conv1, (2,2), (2,2), padding='same') # 400x400x128
conv2 = tf.layers.conv2d(maxpool1, 4, (3,3), padding='same', activation=tf.nn.relu) # 400x400x64
maxpool2 = tf.layers.max_pooling2d(conv2, (2,2), (2,2), padding='same') # 200x200x64
conv3 = tf.layers.conv2d(maxpool2, 4, (3,3), padding='same', activation=tf.nn.relu) # 200x200x32
#maxpool3 = tf.layers.max_pooling2d(conv3, (2,2), (2,2), padding='same') # 100x100x32
#conv4 = tf.layers.conv2d(maxpool3, 4, (3,3), padding='same', activation=tf.nn.relu) # 100x100x16
encoded = tf.layers.max_pooling2d(conv3, (2,2), (2,2), padding='same') # 50x50x16
### Decoder
upsample1 = tf.image.resize_nearest_neighbor(encoded, (200,200)) # 100x100x16
conv5 = tf.layers.conv2d(upsample1, 4, (3,3), padding='same', activation=tf.nn.relu) # 100x100x16
upsample2 = tf.image.resize_nearest_neighbor(conv5, (400,400)) # 200x200x32
conv6 = tf.layers.conv2d(upsample2, 4, (3,3), padding='same', activation=tf.nn.relu) # 200x200x32
upsample3 = tf.image.resize_nearest_neighbor(conv6, (800,800)) # 400x400x64
conv7 = tf.layers.conv2d(upsample3, 8, (3,3), padding='same', activation=tf.nn.relu) # 400x400x64
#upsample4 = tf.image.resize_nearest_neighbor(conv7, (800,800)) # 800x800x128
#conv8 = tf.layers.conv2d(upsample4, 16, (3,3), padding='same', activation=tf.nn.relu) # 800x800x128
logits = tf.layers.conv2d(conv7, 1, (3,3), padding='same', activation=None) # 800x800x1
decoded = tf.nn.sigmoid(logits, name='decoded') # 800x800x1
### Loss and Optimization:
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=targets_, logits=logits)
cost = tf.reduce_mean(loss)
opt = tf.train.AdamOptimizer(0.01).minimize(cost)
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,log_device_placement=True))

sess = tf.Session()
epochs = 100
batch_size = 10
sess.run(tf.global_variables_initializer())
for e in range(epochs):
    for ii in range(AEdata.train.num_examples//batch_size):
        batch = AEdata.train.next_batch(batch_size)
        imgs = batch[0].reshape((-1, 800, 800, 1))
        batch_cost, _ = sess.run([cost, opt], feed_dict={inputs_: imgs, targets_: imgs})
        print("Epoch: {}/{}...".format(e+1, epochs), "Training loss: {:.4f}".format(batch_cost))
#fig, axes = plt.subplots(nrows=2, ncols=6, sharex=True, sharey=True, figsize=(10,10))
#, figsize=(20,10)


#
saver = tf.train.Saver(max_to_keep=1)
#模型保存:
saver.save(sess, 'F:/00AutoencoderTest/tmp/AEtest7/AEtest7100.ckpt')
##模型导入:
saver.restore(sess,'F:/00AutoencoderTest/tmp/AEtest7/AEtest7100.ckpt')
# 数据路径也必须指定到具体某个模型的数据,但创建这个路径的方法很多,比如调用最后一个保存的模型tf.train.latest_checkpoint('./checkpoint_dir'),也可以是xx.ckpt-500.data,并且这两个是等效的,如果是xx.ckpt-0.data,就是第一个模型的数据

in_imgs = AEdata.test.images[:10]

reconstructed, compressed = sess.run([decoded,encoded], feed_dict={inputs_: in_imgs.reshape((10, 800, 800, 1))})
# plot
count_row=0
#for images, row in zip([in_imgs, reconstructed], axes):
row=0
#in_imgs.reshape((6,800, 800))
#reconstructed.reshape((6,800, 800))
for images,row in zip([in_imgs, reconstructed],[1,2]):
    count_row+=1
#    images.reshape((800, 800))
#    for img, ax in zip(images, row):
    count_col=0
    for img,col in zip(images,[1,2,3,4,5,6,7,8,9,10]):
        count_col+=1
#        plt.imshow(img.reshape((800, 800)), cmap='Greys_r')
#        plt.axis('off')
        img1=img.reshape((800, 800))
        CVimg=np.array(img1)
        plt.imshow(CVimg, cmap='Greys_r')
#        img.flags.writeable = True   # 将数组改为读写模式
#        CVimg=Image.fromarray(CVimg0)
#        plt.imshow(outimg, cmap='Greys_r')
#        cv2.cvtColor(img, outimage, CV_BGR2GRAY);
#        plt.savefig('F:/00AutoencoderTest/tmp/AEtest6/out101/'+str(count_row)+'_'+str(count_col)+'.jpg')
        cv2.imwrite('F:/00AutoencoderTest/tmp/AEtest7/out100/'+str(count_row)+'_'+str(count_col)+'.jpg',CVimg*255)
#        cv2.imwrite('F:/00AutoencoderTest/tmp/AEtest5/out/2.jpg',img)
#        ax.get_xaxis().set_visible(False)
#        ax.get_yaxis().set_visible(False)
        dir(cv2)
#fig.tight_layout(pad=0.1)
count_row=0
for imagesin,inx in zip(in_imgs, [1,2,3,4,5,6,7,8,9,10]):
    count_row+=1
    count_col=0
    for imagesout,outx in zip(reconstructed, [1,2,3,4,5,6,7,8,9,10]):
        count_col+=1
        if count_col == count_row:
            CVimgIn1=imagesin.reshape((800, 800))
            CVimgOut1=imagesout.reshape((800, 800))
            CVimgIn=np.array(CVimgIn1)
            CVimgOut=np.array(CVimgOut1)
            CVSubImg=CVimgIn-CVimgOut
            plt.imshow(CVSubImg, cmap='Greys_r')
#        img.flags.writeable = True   # 将数组改为读写模式
#        CVimg=Image.fromarray(CVimg0)
#        plt.imshow(outimg, cmap='Greys_r')
#        cv2.cvtColor(img, outimage, CV_BGR2GRAY);
#        plt.savefig('F:/00AutoencoderTest/tmp/AEtest6/out101/'+str(count_row)+'_'+str(count_col)+'.jpg')
            cv2.imwrite('F:/00AutoencoderTest/tmp/AEtest7/out100/sub/'+str(count_row)+'.jpg',CVSubImg*255)

sess.close()

二、input_AEdata.py

"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=unused-import
import gzip
import os
import tempfile

import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
from AEdata import read_data_sets
#from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
# pylint: enable=unused-import

三、AEdata.py


# ==============================================================================
"""Functions for downloading and reading AE data (deprecated).


"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gzip

import numpy
from six.moves import xrange  # pylint: disable=redefined-builtin

from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
from tensorflow.python.platform import gfile
from tensorflow.python.util.deprecation import deprecated

# CVDF mirror of http://yann.lecun.com/exdb/mnist/
DEFAULT_SOURCE_URL = 'https://storage.googleapis.com/cvdf-datasets/mnist/'


def _read32(bytestream):
  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]


@deprecated(None, 'Please use tf.data to implement this functionality.')
def extract_images(f):
  """Extract the images into a 4D uint8 numpy array [index, y, x, depth].

  Args:
    f: A file object that can be passed into a gzip reader.

  Returns:
    data: A 4D uint8 numpy array [index, y, x, depth].

  Raises:
    ValueError: If the bytestream does not start with 2051.

  """
  print('Extracting', f.name)
  with gzip.GzipFile(fileobj=f) as bytestream:
    magic = _read32(bytestream)
    if magic != 2051:
      raise ValueError('Invalid magic number %d in MNIST image file: %s' %
                       (magic, f.name))
    num_images = _read32(bytestream)
    rows = _read32(bytestream)
    cols = _read32(bytestream)
    buf = bytestream.read(rows * cols * num_images)
    data = numpy.frombuffer(buf, dtype=numpy.uint8)
    data = data.reshape(num_images, rows, cols, 1)
    return data


@deprecated(None, 'Please use tf.one_hot on tensors.')
def dense_to_one_hot(labels_dense, num_classes):
  """Convert class labels from scalars to one-hot vectors."""
  num_labels = labels_dense.shape[0]
  index_offset = numpy.arange(num_labels) * num_classes
  labels_one_hot = numpy.zeros((num_labels, num_classes))
  labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  return labels_one_hot


@deprecated(None, 'Please use tf.data to implement this functionality.')
def extract_labels(f, one_hot=False, num_classes=10):
  """Extract the labels into a 1D uint8 numpy array [index].

  Args:
    f: A file object that can be passed into a gzip reader.
    one_hot: Does one hot encoding for the result.
    num_classes: Number of classes for the one hot encoding.

  Returns:
    labels: a 1D uint8 numpy array.

  Raises:
    ValueError: If the bystream doesn't start with 2049.
  """
  print('Extracting', f.name)
  with gzip.GzipFile(fileobj=f) as bytestream:
    magic = _read32(bytestream)
    if magic != 2049:
      raise ValueError('Invalid magic number %d in MNIST label file: %s' %
                       (magic, f.name))
    num_items = _read32(bytestream)
    buf = bytestream.read(num_items)
    labels = numpy.frombuffer(buf, dtype=numpy.uint8)
    if one_hot:
      return dense_to_one_hot(labels, num_classes)
    return labels


class DataSet(object):
  """Container class for a dataset (deprecated).

  THIS CLASS IS DEPRECATED. See
  [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
  for general migration instructions.
  """

  @deprecated(None, 'Please use alternatives such as official/mnist/dataset.py'
              ' from tensorflow/models.')
  def __init__(self,
               images,
               labels,
               fake_data=False,
               one_hot=False,
               dtype=dtypes.float32,
               reshape=True,
               seed=None):
    """Construct a DataSet.
    one_hot arg is used only if fake_data is true.  `dtype` can be either
    `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
    `[0, 1]`.  Seed arg provides for convenient deterministic testing.
    """
    seed1, seed2 = random_seed.get_seed(seed)
    # If op level seed is not set, use whatever graph level seed is returned
    numpy.random.seed(seed1 if seed is None else seed2)
    dtype = dtypes.as_dtype(dtype).base_dtype
    if dtype not in (dtypes.uint8, dtypes.float32):
      raise TypeError(
          'Invalid image dtype %r, expected uint8 or float32' % dtype)
    if fake_data:
      self._num_examples = 10000
      self.one_hot = one_hot
    else:
      assert images.shape[0] == labels.shape[0], (
          'images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
      self._num_examples = images.shape[0]

      # Convert shape from [num examples, rows, columns, depth]
      # to [num examples, rows*columns] (assuming depth == 1)
      if reshape:
        assert images.shape[3] == 1
        images = images.reshape(images.shape[0],
                                images.shape[1] * images.shape[2])
      if dtype == dtypes.float32:
        # Convert from [0, 255] -> [0.0, 1.0].
        images = images.astype(numpy.float32)
        images = numpy.multiply(images, 1.0 / 255.0)
    self._images = images
    self._labels = labels
    self._epochs_completed = 0
    self._index_in_epoch = 0

  @property
  def images(self):
    return self._images

  @property
  def labels(self):
    return self._labels

  @property
  def num_examples(self):
    return self._num_examples

  @property
  def epochs_completed(self):
    return self._epochs_completed

  def next_batch(self, batch_size, fake_data=False, shuffle=True):
    """Return the next `batch_size` examples from this data set."""
    if fake_data:
      fake_image = [1] * 640000
      if self.one_hot:
        fake_label = [1] + [0] * 9
      else:
        fake_label = 0
      return [fake_image for _ in xrange(batch_size)], [
          fake_label for _ in xrange(batch_size)
      ]
    start = self._index_in_epoch
    # Shuffle for the first epoch
    if self._epochs_completed == 0 and start == 0 and shuffle:
      perm0 = numpy.arange(self._num_examples)
      numpy.random.shuffle(perm0)
      self._images = self.images[perm0]
      self._labels = self.labels[perm0]
    # Go to the next epoch
    if start + batch_size > self._num_examples:
      # Finished epoch
      self._epochs_completed += 1
      # Get the rest examples in this epoch
      rest_num_examples = self._num_examples - start
      images_rest_part = self._images[start:self._num_examples]
      labels_rest_part = self._labels[start:self._num_examples]
      # Shuffle the data
      if shuffle:
        perm = numpy.arange(self._num_examples)
        numpy.random.shuffle(perm)
        self._images = self.images[perm]
        self._labels = self.labels[perm]
      # Start next epoch
      start = 0
      self._index_in_epoch = batch_size - rest_num_examples
      end = self._index_in_epoch
      images_new_part = self._images[start:end]
      labels_new_part = self._labels[start:end]
      return numpy.concatenate(
          (images_rest_part, images_new_part), axis=0), numpy.concatenate(
              (labels_rest_part, labels_new_part), axis=0)
    else:
      self._index_in_epoch += batch_size
      end = self._index_in_epoch
      return self._images[start:end], self._labels[start:end]


@deprecated(None, 'Please use alternatives such as official/mnist/dataset.py'
            ' from tensorflow/models.')
def read_data_sets(train_dir,
                   fake_data=False,
                   one_hot=False,
                   dtype=dtypes.float32,
                   reshape=True,
                   validation_size=50,
                   seed=None,
                   source_url=DEFAULT_SOURCE_URL):
  if fake_data:

    def fake():
      return DataSet(
          [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed)

    train = fake()
    validation = fake()
    test = fake()
    return base.Datasets(train=train, validation=validation, test=test)

  if not source_url:  # empty string check
     source_url = DEFAULT_SOURCE_URL
#  source_url = True

  TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
  TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
  TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
  TEST_LABELS = 't10k-labels-idx1-ubyte.gz'

  local_file = base.maybe_download(TRAIN_IMAGES, train_dir,
                                   source_url + TRAIN_IMAGES)
  with gfile.Open(local_file, 'rb') as f:
    train_images = extract_images(f)

  local_file = base.maybe_download(TRAIN_LABELS, train_dir,
                                   source_url + TRAIN_LABELS)
  with gfile.Open(local_file, 'rb') as f:
    train_labels = extract_labels(f, one_hot=one_hot)

  local_file = base.maybe_download(TEST_IMAGES, train_dir,
                                   source_url + TEST_IMAGES)
  with gfile.Open(local_file, 'rb') as f:
    test_images = extract_images(f)

  local_file = base.maybe_download(TEST_LABELS, train_dir,
                                   source_url + TEST_LABELS)
  with gfile.Open(local_file, 'rb') as f:
    test_labels = extract_labels(f, one_hot=one_hot)

  if not 0 <= validation_size <= len(train_images):
    raise ValueError('Validation size should be between 0 and {}. Received: {}.'
                     .format(len(train_images), validation_size))

  validation_images = train_images[:validation_size]
  validation_labels = train_labels[:validation_size]
  train_images = train_images[validation_size:]
  train_labels = train_labels[validation_size:]

  options = dict(dtype=dtype, reshape=reshape, seed=seed)

  train = DataSet(train_images, train_labels, **options)
  validation = DataSet(validation_images, validation_labels, **options)
  test = DataSet(test_images, test_labels, **options)

  return base.Datasets(train=train, validation=validation, test=test)


@deprecated(None, 'Please use alternatives such as official/mnist/dataset.py'
            ' from tensorflow/models.')
def load_mnist(train_dir='MNIST-data'):
  return read_data_sets(train_dir)


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值