首先介绍一下自编码器,Hinton教授在Science发表了文章Reducing the dimensionality of data with neural networks,讲解使用自编码器进行降维的方法,自编码器就是可以使用自身的高阶特征编码自己。自编码器的输入节点和输出节点是一致的,但如果只是单纯的逐个复制输入节点则没有意义,所以我们可以加入几种限制:
(1)如果限制中间隐藏节点的数量,比如让中间隐含节点的数量小于输入/输出节点的数量,就相当于一个降维的过程。
(2)如果给数据加入噪声,那么就是Denoising AutoEncoder(去噪自编码器),我们将从噪声中学习到数据的特征。
下面就来实现去噪自编码器。
import numpy as np
import sklearn.preprocessing as prep
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#xavier初始化
def xavier_init(fan_in, fan_out, constant=1):
low = -constant * np.sqrt(6.0 / (fan_in + fan_out))
high = constant * np.sqrt(6.0 / (fan_in + fan_out))
return tf.random_uniform((fan_in, fan_out), minval = low,
maxval = high, dtype = tf.float32)
下面我们来定义一个去噪编码器的class,方便使用,这个类包含一个构建函数__init__(),还有一些常用的成员函数,因此会比较长,下面一步步来实现。
3. __init__函数包含这样几个输入:n_input(输入变量数),n_hidden(隐含层节点数),transfer_function(隐含激活函数,默认为softplus),optimizer(优化器,默认为Adam),scale(高斯噪声系数,默认为0.1)。其中,class类的scale参数做成了一个placeholder,参数初始化则使用了接下来定义的_initializer_weights函数。这里需要注意的是,我们只使用了一个隐藏层。
#定义自编码器类
class AdditiveGaussianNoiseAutoencoder(object):
#计算softplus:log(exp(features) + 1)
def __init__(self, n_input, n_hidden, transfer_function=tf.nn.softplus,
optimizer=tf.train.AdamOptimizer(), scale=0.1):
#定义输入信息
self.n_input = n_input
self.n_hidden = n_hidden
self.transfer = transfer_function
self.scale = tf.placeholder(tf.float32)
self.training_scale = scale
network_weights = self._initialize_weights()
self.weights = network_weights
#定义网络结构
self.x = tf.placeholder(tf.float32, [None, self.n_input])
self.hidden = self.transfer(tf.add(tf.matmul(self.x + scale*tf.random_normal((n_input,)),
self.weights['w1']), self.weights['b1']))
self.reconstruction = tf.add(tf.matmul(self.hidden, self.weights['w2']), self.weights['b2'])
#定义损失函数
self.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0))
self.optimizer = optimizer.minimize(self.cost)
#创建Session
init = tf.global_variables_initializer()
self.sess = tf.Session()
self.sess.run(init)
#参数初始化函数
def _initialize_weights(self):
all_weights = dict()
all_weights['w1'] = tf.Variable(xavier_init(self.n_input, self.n_hidden))
all_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden], dtype=tf.float32))
all_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden, self.n_input], dtype=tf.float32))
all_weights['b2'] = tf.Variable(tf.zeros([self.n_input]), dtype=tf.float32)
return all_weights
#使用一个batch数据进行训练并返回当前的损失cost
def partial_fit(self, X):
cost, opt = self.sess.run((self.cost, self.optimizer),
feed_dict={self.x: X, self.scale: self.training_scale})
#只求损失cost的函数,在测试阶段用
def cal_total_cost(self, X):
return self.sess.run(self.cost, feed_dict={self.x:X, self.scale:self.training_scale})
#返回自编码器隐藏层的输出结果,学习出数据中的高阶特征
def transform(self, X):
return self.sess.run(self.hidden, feed_dict={self.x: X, self.scale: self.training_scale})
定义generate函数,将隐层的输出结果作为输入,重建复原数据
def generate(self, hidden = None):
if hidden is None:
hidden = np.random.normal(size=self.weights["b1"])
return self.sess.run(self.reconstruction, feed_dict={self.hidden: hidden})
#定义reconstruct函数
def reconstruct(self, X):
return self.sess.run(self.reconstruction, feed_dict={self.x: X, self.scale: self.training_scale})
#getWeights获取隐藏层的权重W1
def getWeights(self):
return self.sess.run(self.weights['w1'])
#getBias获取隐藏层的偏置b1
def getBiases(self):
return self.sess.run(self.weights['b1'])
#在Mnist数据集上测试去噪自编码器
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
#定义一个对训练和测试数据进行标准化处理的函数
def standard_scale(X_train, X_test):
preprocessor = prep.StandardScaler().fit(X_train)
X_train = preprocessor.transform(X_train)
X_test = preprocessor.transform(X_test)
return X_train, X_test
#定义一个获取随机block数据的函数,不放回抽样
def get_random_block_from_data(data, batch_size):
start_index = np.random.randint(0, len(data)-batch_size)
return data[start_index:(start_index+batch_size)]
#对训练数据和测试数据标准化
X_train, X_test = standard_scale(mnist.train.images, mnist.test.images)
#定义一些参数
n_samples = int(mnist.train.num_examples)
training_epochs = 20
batch_size = 128
display_step = 1
#创建一个AGN自编码器的实例
autoencoder = AdditiveGaussianNoiseAutoencoder(n_input=784, n_hidden=200, transfer_function=tf.nn.softplus,
optimizer=tf.train.AdamOptimizer(learning_rate=0.001), scale=0.01)
#训练
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(n_samples / batch_size)
for i in range(total_batch):
batch_xs = get_random_block_from_data(X_train, batch_size)
cost = autoencoder.partial_fit(batch_xs)
avg_cost += cost / n_samples * batch_size
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
#测试
print("Total cost: " + str(autoencoder.cal_total_cost(X_test)))
#coding=utf-8
#自编码器
import numpy as np
import sklearn.preprocessing as prep
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#xavier初始化
def xavier_init(fan_in, fan_out, constant=1):
low = -constant * np.sqrt(6.0 / (fan_in + fan_out))
high = constant * np.sqrt(6.0 / (fan_in + fan_out))
return tf.random_uniform((fan_in, fan_out), minval = low,
maxval = high, dtype = tf.float32)
#定义自编码器类
class AdditiveGaussianNoiseAutoencoder(object):
#计算softplus:log(exp(features) + 1)
def __init__(self, n_input, n_hidden, transfer_function=tf.nn.softplus,
optimizer=tf.train.AdamOptimizer(), scale=0.1):
#定义输入信息
self.n_input = n_input
self.n_hidden = n_hidden
self.transfer = transfer_function
self.scale = tf.placeholder(tf.float32)
self.training_scale = scale
network_weights = self._initialize_weights()
self.weights = network_weights
#定义网络结构
self.x = tf.placeholder(tf.float32, [None, self.n_input])
self.hidden = self.transfer(tf.add(tf.matmul(self.x + scale*tf.random_normal((n_input,)),
self.weights['w1']), self.weights['b1']))
self.reconstruction = tf.add(tf.matmul(self.hidden, self.weights['w2']), self.weights['b2'])
#定义损失函数
self.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0))
self.optimizer = optimizer.minimize(self.cost)
#创建Session
init = tf.global_variables_initializer()
self.sess = tf.Session()
self.sess.run(init)
#参数初始化函数
def _initialize_weights(self):
all_weights = dict()
all_weights['w1'] = tf.Variable(xavier_init(self.n_input, self.n_hidden))
all_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden], dtype=tf.float32))
all_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden, self.n_input], dtype=tf.float32))
all_weights['b2'] = tf.Variable(tf.zeros([self.n_input]), dtype=tf.float32)
return all_weights
#使用一个batch数据进行训练并返回当前的损失cost
def partial_fit(self, X):
cost, opt = self.sess.run((self.cost, self.optimizer),
feed_dict={self.x: X, self.scale: self.training_scale})
return cost
#只求损失cost的函数,在测试阶段用
def cal_total_cost(self, X):
return self.sess.run(self.cost, feed_dict={self.x:X, self.scale:self.training_scale})
#返回自编码器隐藏层的输出结果,学习出数据中的高阶特征
def transform(self, X):
return self.sess.run(self.hidden, feed_dict={self.x: X, self.scale: self.training_scale})
#定义generate函数,将隐层的输出结果作为输入,重建复原数据
def generate(self, hidden = None):
if hidden is None:
hidden = np.random.normal(size=self.weights["b1"])
return self.sess.run(self.reconstruction, feed_dict={self.hidden: hidden})
#定义reconstruct函数
def reconstruct(self, X):
return self.sess.run(self.reconstruction, feed_dict={self.x: X, self.scale: self.training_scale})
#getWeights获取隐藏层的权重W1
def getWeights(self):
return self.sess.run(self.weights['w1'])
#getBias获取隐藏层的偏置b1
def getBiases(self):
return self.sess.run(self.weights['b1'])
#在Mnist数据集上测试去噪自编码器
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
#定义一个对训练和测试数据进行标准化处理的函数
def standard_scale(X_train, X_test):
preprocessor = prep.StandardScaler().fit(X_train)
X_train = preprocessor.transform(X_train)
X_test = preprocessor.transform(X_test)
return X_train, X_test
#定义一个获取随机block数据的函数,不放回抽样
def get_random_block_from_data(data, batch_size):
start_index = np.random.randint(0, len(data)-batch_size)
return data[start_index:(start_index+batch_size)]
#对训练数据和测试数据标准化
X_train, X_test = standard_scale(mnist.train.images, mnist.test.images)
#定义一些参数
n_samples = int(mnist.train.num_examples)
training_epochs = 20
batch_size = 128
display_step = 1
#创建一个AGN自编码器的实例
autoencoder = AdditiveGaussianNoiseAutoencoder(n_input=784, n_hidden=200, transfer_function=tf.nn.softplus,
optimizer=tf.train.AdamOptimizer(learning_rate=0.001), scale=0.01)
#训练
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(n_samples / batch_size)
for i in range(total_batch):
batch_xs = get_random_block_from_data(X_train, batch_size)
cost = autoencoder.partial_fit(batch_xs)
avg_cost += cost / n_samples * batch_size
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
#测试
print("Total cost: " + str(autoencoder.cal_total_cost(X_test)))