美文网首页
无监督算法

无监督算法

作者: 求索_700e | 来源:发表于2020-02-21 19:03 被阅读0次

from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D

from keras.models import Model

from keras import optimizers

from keras import backend as K

import tensorflow

import cv2

import glob

mh=704

mw=160

num_epochs=1000

input_img = Input(shape=(mh, mw, 1))  # adapt this if using `channels_first` image data format

# Encode-----------------------------------------------------------

x = Conv2D(32, (4, 4), strides=2 , activation='relu', padding='same')(input_img)

x = Conv2D(32, (4, 4), strides=2, activation='relu', padding='same')(x)

x = Conv2D(32, (3, 3), strides=1, activation='relu', padding='same')(x)

x = Conv2D(64, (4, 4), strides=2, activation='relu', padding='same')(x)

x = Conv2D(64, (3, 3), strides=1, activation='relu', padding='same')(x)

x = Conv2D(128, (4, 4), strides=2, activation='relu', padding='same')(x)

x = Conv2D(64, (3, 3), strides=1, activation='relu', padding='same')(x)

x = Conv2D(32, (3, 3), strides=1, activation='relu', padding='same')(x)

encoded = Conv2D(1, (8, 8), strides=1, padding='same')(x)

# Decode---------------------------------------------------------------------

x = Conv2D(32, (3, 3), strides=1, activation='relu', padding='same')(encoded)

x = Conv2D(64, (3, 3), strides=1, activation='relu', padding='same')(x)

x = UpSampling2D((2, 2))(x)

x = Conv2D(128, (4, 4), strides=2, activation='relu', padding='same')(x)

x = UpSampling2D((2, 2))(x)

x = Conv2D(64, (3, 3), strides=1, activation='relu', padding='same')(x)

x = UpSampling2D((2, 2))(x)

x = Conv2D(64, (4, 4), strides=2, activation='relu', padding='same')(x)

x = UpSampling2D((2, 2))(x)

x = Conv2D(32, (3, 3), strides=1, activation='relu', padding='same')(x)

x = UpSampling2D((2, 2))(x)

x = Conv2D(32, (4, 4), strides=2, activation='relu', padding='same')(x)

x = UpSampling2D((4, 4))(x)

x = Conv2D(32, (4, 4), strides=2, activation='relu', padding='same')(x)

x = UpSampling2D((2, 2))(x)

decoded = Conv2D(1, (8, 8), activation='sigmoid', padding='same')(x)

# ---------------------------------------------------------------------

autoencoder = Model(input_img, decoded)

adam = optimizers.Adam(lr=0.0002, decay=0.00001)

autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

autoencoder.summary()

import os, glob

import numpy as np

from sklearn.model_selection import train_test_split

from PIL import Image

# Own Your Image Directory

img_dir = ("./Samples/")

img_files = glob.glob(img_dir + "*.png")

# Setting Image Propertie

width = mw

height = mh

pixels = width * height * 1 # gray scale

# Load Image

# AutoEncoder does not have to label data

x = []

for i, f in enumerate(img_files):

    img = Image.open(f)

#    img = img.convert("RGB")

    img = img.convert("L") # gray sclae

    img = img.resize((width,height), 1)

    data = np.asarray(img)

    x.append(data)

    if i % 10 == 0:

        print(i, "\n", data)

x = np.array(x)

(x_train, x_test) = train_test_split(x, shuffle=False, train_size=0.7, random_state=1)

img_list = (x_train, x_test)

np.save("./obj.npy", img_list)

print("OK", len(x))

# change to float32

x_train = x_train.astype('float32') / 255.

x_test = x_test.astype('float32') / 255.

x_train = np.reshape(x_train, (len(x_train), mh, mw, 1))  # adapt this if using `channels_first` image data format

x_test = np.reshape(x_test, (len(x_test), mh,  mw, 1))  # adapt this if using `channels_first` image data format

print (x_train.shape)

print (x_test.shape)

from keras.callbacks import TensorBoard

autoencoder.fit(x_train, x_train,

                epochs=num_epochs,

                batch_size=32,

                shuffle=True,

                validation_data=(x_test, x_test),

                callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])

####################################################

####################################################

####################################################

####################################################

####################################################

####################################################

####################################################

'''

import matplotlib.pyplot as plt

decoded_imgs = autoencoder.predict(x_train)

n = 8  # how many digits we will display

plt.figure(figsize=(20, 5), dpi=100)

for i in range(n):

    # display original

    ax = plt.subplot(2, n, i + 1)

    plt.imshow(x_train[i].reshape(mh, mw))

    plt.gray()

    ax.get_xaxis().set_visible(True)

    ax.get_yaxis().set_visible(False)

    # SSIM Encode

    ax.set_title("Encode_Image")

    npImg = x_train[i]

    npImg = npImg.reshape((mh, mw))

    formatted = (npImg * 255 / np.max(npImg)).astype('uint8')

    img = Image.fromarray(formatted)

    # display reconstruction

    ax = plt.subplot(2, n, i + 1 + n)

    plt.imshow(decoded_imgs[i].reshape(mh, mw))

    plt.gray()

    ax.get_xaxis().set_visible(True)

    ax.get_yaxis().set_visible(False)

    # SSIM Decoded   

    npDecoded = decoded_imgs[i]

    npDecoded = npDecoded.reshape((mh,mw))

    formatted2 = (npDecoded * 255 / np.max(npDecoded)).astype('uint8')

    decoded = Image.fromarray(formatted2)

    from SSIM_PIL import compare_ssim as ssim

    value = ssim(img, decoded)

    label = 'SSIM: {:.3f}'

    ax.set_title("Decoded_Image")

    ax.set_xlabel(label.format(value))

plt.show()

'''

'''

import matplotlib.pyplot as plt

decoded_imgs = autoencoder.predict(x_test)

n = 3 # how many digits we will display

for i in range(n):

    # display original

    ax = plt.subplot(2, n, i + 1)

    plt.imshow(x_test[i].reshape(mh, mw))

    plt.gray()

    ax.get_xaxis().set_visible(True)

    ax.get_yaxis().set_visible(False)

    # SSIM Encode

    ax.set_title("Encode_Image")

    npImg = x_test[i]

    npImg = npImg.reshape((mh, mw))

    formatted = (npImg * 255 / np.max(npImg)).astype('uint8')

    img = Image.fromarray(formatted)

    # display reconstruction

    ax = plt.subplot(2, n, i + 1 + n)

    plt.imshow(decoded_imgs[i].reshape(mh, mw))

    plt.gray()

    ax.get_xaxis().set_visible(True)

    ax.get_yaxis().set_visible(False)

    # SSIM Decoded   

    npDecoded = decoded_imgs[i]

    npDecoded = npDecoded.reshape((mh,mw))

    formatted2 = (npDecoded * 255 / np.max(npDecoded)).astype('uint8')

    decoded = Image.fromarray(formatted2)

    from SSIM_PIL import compare_ssim as ssim

    value = ssim(img, decoded)

    label = 'SSIM: {:.3f}'

    ax.set_title("Decoded_Image")

    ax.set_xlabel(label.format(value))

plt.show()

'''

def  search_imgs():

      path = "./test/*.png"

      path_lists = glob.glob(path)

      imgs=[]

      for p in path_lists:

                img=cv2.imread(p,0)

                img=cv2.resize(img,(mw,mh))

                img=np.expand_dims(img,3)

                imgs.append(img.astype('float32') / 255.)

      imgs=np.array(imgs)

      print("------------------------------------------=",imgs.shape)

      #x_test = x_test.astype('float32') / 255.

      #x_test = np.reshape(imgs, (len(imgs), mh,  mw, 1))  # adapt this if using `channels_first` image data format

      return imgs

import matplotlib.pyplot as plt

x_test=search_imgs()

decoded_imgs = autoencoder.predict(x_test)

for i in range(len(x_test)):

    # display original

    ori_img = x_test[i].reshape(mh, mw)

    cv2.imwrite("./xxx/"+str(i)+"_ori_.jpg", (ori_img*255).astype(np.uint8))

    # Decoded   

    npDecoded = decoded_imgs[i]

    npDecoded = npDecoded.reshape((mh,mw))

    cv2.imwrite("./xxx/"+str(i)+"_npDecoded _.jpg", (npDecoded*255).astype(np.uint8) )

plt.show()

相关文章

  • 机器学习算法

    机器学习的算法分监督算法和无监督 算法。监督算法包括回归算法,神经网络,SVM;无监督算法包括聚类算法,降维算法。...

  • 机器学习算法分类大全

    机器学习算法可以分为监督学习算法、无监督学习算法和半监督学习算法,下面以思维导图的形式总结了一下常见的监督学习和无...

  • 聚类算法k-means

    聚类算法 聚类算法 是 无监督学习 聚类算法有特征,无标签,是无监督分类。 sklearn 聚类模块 cluste...

  • 机器学习算法之聚类(Clustering)

    1.无监督学习:简介 聚类算法:第一个无监督学习算法(无标签的数据) 什么是无监督学习呢?对比:监督学习问题指的是...

  • 聚类(Clustering)

    1.无监督学习:简介 聚类算法:第一个无监督学习算法(无标签的数据) 什么是无监督学习呢?对比:监督学习问题指的是...

  • 无监督算法

    from keras.layers import Input, Dense, Conv2D, MaxPooling...

  • 吴恩达机器学习(七)

    第一百零八课:无监督学习 聚类算法:第一个无监督学习算法(无标签的数据)什么是无监督学习呢?对比:监督学习问题指的...

  • 机器学习算法

    算法常见分类 有监督算法 KNN ID3 无监督算法 Apriori Kmens 其他算法 算法:计算机解决特定问...

  • 吴恩达机器学习-Chapter 14 无监督学习

    目的:无监督学习 聚类算法 1. Lesson 108 无监督学习     1. 目的:介绍无监督学习,无标签...

  • 机器学习(7)——聚类算法

    聚类算法 前面介绍的集中算法都是属于有监督机器学习方法,这章和前面不同,介绍无监督学习算法,也就是聚类算法。在无监...

网友评论

      本文标题:无监督算法

      本文链接:https://www.haomeiwen.com/subject/xxrhqhtx.html