美文网首页程序员
TensorFlow 实现自编码器

TensorFlow 实现自编码器

作者: 羽恒 | 来源:发表于2017-07-15 18:33 被阅读107次

自编码器简介


深度学习在早期一度被认为是一种无监督的特征学(Unsupervised Feature Learning),模仿人脑对特征逐层抽象提取的过程
1.无监督学习:不需要对标注数据就可以对数据进行一定程度的学习,这种学习是对数据内容的组织形式的学习,提取的是频繁出现的特征
2.逐层抽象:特征是需要不断抽象的,就像人总是从简单基础概念开始学习,再到复杂的概念。深度学习也是一样,他从最简单的微观特征开始,不断抽象特征的层级,逐渐往复杂的宏观特征转变。

  • 自编码器(AUtoEncoder),顾名思义,既可以使用自身的高阶特征编码自己。
  • 自编码器其实也是一种神经网络,它的输入和输出是一致的,它借助稀疏编码的思想,目标是使用稀疏的一些高阶特征重新组合来重构自己。特点如下:

1.期望输入和输出一致
2.希望使用高阶特征来重构自己,而不只是复制像素点


TensorFlow 实现自编码器

  • 实现标准的均匀分布的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
class AddAutoencoder(object):
    # - n_input:输入变量数
    #  - n_hidden:隐含层节点数
    # - transfer_function:隐含层激活函数,默认为softplus
    # - optimizer:优化器,默认为Adam
    # - scale:高斯噪声系数,默认为0.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)

        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
    
    
    # 计算损失cost及进一步训练的函数
    # return:当前损失 
    
    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 calc_total_cost(self,X):
        return self.sess.run(self.cost,feed_dict={self.x:X,
                                                  self.scale:self.training_scale})

    
    # 获取抽象后的特征
    # return:自编码器隐含层的输出结果
    
    def transform(self,X):
        return self.sess.run(self.hidden,feed_dict = {self.x:X,self.scale:self.training_scale})
    
    # 隐含层的输出作为输入,将高阶特征复原为原始数据
    
    def generate(self,hidden = None):
        if hidden is None:
            hidden = np.random.normal(size = self.weights['w1'])

        return self.sess.run(self.reconstruction,feed_dict = {self.hidden:hidden})

    # 重构层,输入为原始数据,输出为复原后的数据

    def reconstruct(self,X):
        return self.sess.run(self.reconstruction,feed_dict = {self.x:X,self.scale:self.training_scale})
    
    # 获取隐含层的权重w1
    
    def generatetWeights(self):
        return self.sess.run(self.weights['w1'])

    # 获取隐含层的偏置系数b1

    def getBiases(self):
        return self.sess.run(self.weights['b1'])
  • 载入数据集(使用TensorFlow提供的示例数据)

mnist = input_data.read_data_sets('MNIST_data',one_hot = True

  • 载入数据集(使用TensorFlow提供的示例数据)
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_form_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)

  • 设置常用参数:总训练样本数、最大训练轮数、batch_size数、显示损失间隔
n_samples = int(mnist.train.num_examples)
training_epochs = 20
batch_size = 128
display_step = 1
  • 创建AGN编码器实例
autocode = AddAutoencoder(n_input = 784,
                         n_hidden = 200,
                         transfer_function = tf.nn.softplus,
                         optimizer = tf.train.AdamOptimizer(learning_rate = 0.001),
                         scale = 0.01)

  • 开始训练,并输出每次的损失cost、平均损失avg_cost
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_form_data(X_train,batch_size)

        cost = autocode.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(autocode.calc_total_cost(X_test)))

相关文章

网友评论

    本文标题:TensorFlow 实现自编码器

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