卷积神经网络代码详解_fpga卷积神经网络

(29) 2024-08-31 18:01:03

卷积神经网络自编码器实现与结果分析

(1)实现框架:Keras
(2)数据集:Mnist 手写数字识别
(3)关键代码:

环境配置

使用conda,新建一个keras 和tensorflow的环境

在win cmd 终端中建立一个新的环境
新建用pip安装三个包

C:\Users\TJ619\Downloads\autoencoder-master>conda create -n keras_only python=3.9 (base) C:\Users\TJ619\Downloads\autoencoder-master>conda activate keras_only (keras_only) C:\Users\TJ619\Downloads\autoencoder-master> conda install pip (keras_only) C:\Users\TJ619\Downloads\autoencoder-master>pip install keras tensorflow matplotlib (keras_only) C:\Users\TJ619\Downloads\autoencoder-master>conda list # packages in environment at C:\Users\TJ619\AppData\Local\Continuum\anaconda3\envs\keras_only:  # # Name Version Build Channel absl-py 1.0.0 pypi_0 pypi astunparse 1.6.3 pypi_0 pypi ca-certificates 2021.10.26 haa95532_2 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main cachetools 4.2.4 pypi_0 pypi certifi 2021.10.8 py39haa95532_0 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main charset-normalizer 2.0.9 pypi_0 pypi cycler 0.11.0 pypi_0 pypi flatbuffers 2.0 pypi_0 pypi fonttools 4.28.3 pypi_0 pypi gast 0.4.0 pypi_0 pypi google-auth 2.3.3 pypi_0 pypi google-auth-oauthlib 0.4.6 pypi_0 pypi google-pasta 0.2.0 pypi_0 pypi grpcio 1.42.0 pypi_0 pypi h5py 3.6.0 pypi_0 pypi idna 3.3 pypi_0 pypi importlib-metadata 4.8.2 pypi_0 pypi keras 2.7.0 pypi_0 pypi keras-preprocessing 1.1.2 pypi_0 pypi kiwisolver 1.3.2 pypi_0 pypi libclang 12.0.0 pypi_0 pypi markdown 3.3.6 pypi_0 pypi matplotlib 3.5.0 pypi_0 pypi numpy 1.21.4 pypi_0 pypi oauthlib 3.1.1 pypi_0 pypi openssl 1.1.1l h2bbff1b_0 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main opt-einsum 3.3.0 pypi_0 pypi packaging 21.3 pypi_0 pypi pillow 8.4.0 pypi_0 pypi pip 21.2.4 py39haa95532_0 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main protobuf 3.19.1 pypi_0 pypi pyasn1 0.4.8 pypi_0 pypi pyasn1-modules 0.2.8 pypi_0 pypi pyparsing 3.0.6 pypi_0 pypi python 3.9.7 h_1 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main python-dateutil 2.8.2 pypi_0 pypi requests 2.26.0 pypi_0 pypi requests-oauthlib 1.3.0 pypi_0 pypi rsa 4.8 pypi_0 pypi setuptools 58.0.4 py39haa95532_0 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main setuptools-scm 6.3.2 pypi_0 pypi six 1.16.0 pypi_0 pypi sqlite 3.36.0 h2bbff1b_0 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main tensorboard 2.7.0 pypi_0 pypi tensorboard-data-server 0.6.1 pypi_0 pypi tensorboard-plugin-wit 1.8.0 pypi_0 pypi tensorflow 2.7.0 pypi_0 pypi tensorflow-estimator 2.7.0 pypi_0 pypi tensorflow-io-gcs-filesystem 0.22.0 pypi_0 pypi termcolor 1.1.0 pypi_0 pypi tomli 1.2.2 pypi_0 pypi typing-extensions 4.0.1 pypi_0 pypi tzdata 2021e hda174b7_0 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main urllib3 1.26.7 pypi_0 pypi vc 14.2 h21ff451_1 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main vs2015_runtime 14.27.29016 h5e58377_2 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main werkzeug 2.0.2 pypi_0 pypi wheel 0.37.0 pyhd3eb1b0_1 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main wincertstore 0.2 py39haa95532_2 http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main wrapt 1.13.3 pypi_0 pypi zipp 3.6.0 pypi_0 pypi 

卷积神经网络代码详解_fpga卷积神经网络 (https://mushiming.com/)  第1张

I)在 Keras 编码中,反卷积的实现代码便是卷积操作,具体解释详见上述博
客。https://blog.csdn.net/quiet_girl/article/details/ 。
ii)UpSampling2D()实现的是反平均卷积的操作。
iii) autoencoder.summary()如下:

o enable them in other operations, rebuild TensorFlow with the appropriate compiler fl Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 28, 28, 1)] 0 conv2d (Conv2D) (None, 28, 28, 16) 160 max_pooling2d (MaxPooling2D (None, 14, 14, 16) 0 ) conv2d_1 (Conv2D) (None, 14, 14, 8) 1160 max_pooling2d_1 (MaxPooling (None, 7, 7, 8) 0 2D) conv2d_2 (Conv2D) (None, 7, 7, 8) 584 up_sampling2d (UpSampling2D (None, 14, 14, 8) 0 ) conv2d_3 (Conv2D) (None, 14, 14, 16) 1168 up_sampling2d_1 (UpSampling (None, 28, 28, 16) 0 2D) conv2d_4 (Conv2D) (None, 28, 28, 1) 145 ================================================================= Total params: 3,217 Trainable params: 3,217 Non-trainable params: 0 Non-trainable params: 0 _________________________________________________________________ Epoch 1/20 

卷积神经网络代码详解_fpga卷积神经网络 (https://mushiming.com/)  第2张

整体程序如下

# python3 # -*- coding: utf-8 -*- # @Author : ziyue # @Time : 2021 12 10 """ Convolutional Autoencoder. """ import numpy as np from keras.datasets import mnist from keras.models import Model from keras.layers import Conv2D, MaxPool2D,Input, UpSampling2D import matplotlib.pyplot as plt np.random.seed(33) # random seed,to reproduce results. def train(x_train): """ build autoencoder. :param x_train: the train data :return: encoder and decoder """ # input placeholder input_image = Input(shape=(28, 28, 1)) # encoding layer x = Conv2D(CHANNEL_1, (3, 3), activation='relu', padding="same")(input_image) x = MaxPool2D((2, 2), padding='same')(x) x = Conv2D(CHANNEL_2, (3, 3), activation='relu', padding='same')(x) encoded = MaxPool2D((2, 2), padding='same')(x) # decoding layer x = Conv2D(CHANNEL_2, (3, 3), activation='relu', padding='same')(encoded) x = UpSampling2D((2, 2))(x) x = Conv2D(CHANNEL_1, (3, 3),activation='relu', padding='same')(x) x = UpSampling2D((2, 2))(x) decoded = Conv2D(CHANNEL_OUTPUT, (3, 3), activation='sigmoid', padding='same')(x) # build autoencoder, encoder, decoder autoencoder = Model(inputs=input_image, outputs=decoded) encoder = Model(inputs=input_image, outputs=encoded) # compile autoencoder autoencoder.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) autoencoder.summary() # training # need return history, otherwise can not use history["acc"] history_record = autoencoder.fit(x_train, x_train, epochs=EPOCHS, batch_size=BATCH_SIZE, shuffle=True, ) return encoder, autoencoder, history_record def plot_accuray(history_record): """ plot the accuracy and loss line. :param history_record: :return: """ accuracy = history_record.history["accuracy"] loss = history_record.history["loss"] epochs = range(len(accuracy)) plt.plot(epochs, accuracy, 'bo', label='Training accuracy') plt.title('Training accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.title('Training loss') plt.legend() plt.show() def show_images(decode_images, x_test): """ plot the images. :param decode_images: the images after decoding :param x_test: testing data :return: """ n = 10 plt.figure(figsize=(20, 4)) for i in range(n): ax = plt.subplot(2, n, i+1) ax.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax = plt.subplot(2, n, i + 1 + n) ax.imshow(decode_images[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() if __name__ == '__main__': CHANNEL_1 = 16 CHANNEL_2 = 8 CHANNEL_OUTPUT = 1 EPOCHS = 1 BATCH_SIZE = 64 # Step1: load data x_train: (60000, 28, 28), y_train: (60000,) x_test: (10000, 28, 28), y_test: (10000,) (x_train, y_train), (x_test, y_test) = mnist.load_data() # Step2: normalize x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. # Step3: reshape data, x_train: (60000, 28, 28, 1), x_test: (10000, 28, 28, 1), one row denotes one sample. x_train = x_train.reshape((x_train.shape[0], 28, 28, 1)) x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)) # Step4: train encoder, autoencoder, history_record = train(x_train=x_train) # show images decode_images = autoencoder.predict(x_test) show_images(decode_images, x_test) plot_accuray(history_record) 

论文名称:Stacked Convolutional Auto-Encoders for
Hierarchical Feature Extraction

论文地址:https://people.idsia.ch//~ciresan/data/icann2011.pdf
摘要:

我们提出了一种新颖的卷积自动编码器(CAE),用于 无监督特征学习。一堆 CAE 形成一个卷积 神经网络(CNN)。每个 CAE 都使用传统的在线训练 没有额外的正则化项的梯度下降。最大池化 层对于学习生物学上合理的特征是必不可少的 以前的方法发现的那些。用 a 的过滤器初始化 CNN 训练有素的 CAE 堆栈在数字 (MNIST) 和 对象识别 (CIFAR10) 基准。

介绍:

无监督学习方法的主要目的是从未标记的数据中提取普遍有用的特征,检测和去除输入冗余,以及
仅保留数据的基本方面以稳健和有区别的表示。无监督方法已在许多科学中常规使用和工业应用。在神经网络架构的背景下,无监督层可以相互堆叠以构建深层层次结构[7]。输入层激活被馈送到第一层,它馈送下一层,并且
依此类推,对于层次结构中的所有层。可以训练深度架构无监督的逐层时尚,然后通过反向传播进行微调以成为分类器 [9]。无监督初始化倾向于避免局部最小值和提高网络的性能稳定性[6]。

3 卷积自编码器 (CAE) 全连接 AE 和 DAE 都忽略了 2D 图像结构。这不是 只是在处理实际大小的输入时出现问题,而且还引入了 参数中的冗余,迫使每个特征都是全局的(即跨越 整个视野)。然而,视觉和物体识别的趋势采用 最成功的模型 [17,25] 是发现在整个输入中重复的局部特征。 CAE 与传统 AE 的不同之处在于它们的 权重在输入中的所有位置之间共享,从而保持空间局部性。 因此重建是由于基本图像块的线性组合 基于潜在代码。

卷积神经网络代码详解_fpga卷积神经网络 (https://mushiming.com/)  第3张

卷积神经网络代码详解_fpga卷积神经网络 (https://mushiming.com/)  第4张
卷积神经网络代码详解_fpga卷积神经网络 (https://mushiming.com/)  第5张

结论
我们介绍了卷积自动编码器,这是一种用于分层特征提取的无监督方法。它学习生物学上合理的过滤器。一个CNN可以由 CAE 堆栈初始化。虽然 CAE 的过完备隐藏表示使学习比标准自动编码器更难,但好的过滤器
如果我们使用最大池化层,就会出现,这是一种强制执行稀疏代码的优雅方式无需通过反复试验设置任何正则化参数。预训练CNN 的性能往往略胜于随机初始化的网络,但始终如一。我们的 CIFAR10 结果是任何在原始数据上训练的无监督方法的最佳结果数据,并接近该基准测试的最佳发布结果.

THE END

发表回复