TensorFlow实战(二)Tensorflow实现自编码器及多层感知机

tensorflow实现自编码器

# -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 20:01:39 2018

@author:huizhang
"""
import numpy as np
import sklearn.preprocessing as prep
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#xaviver 让权重瞒住0均值,同时方差为2/(nin+nout),分布可以用均匀分布或高斯分布
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 AdditionGaussianNoiseAutoencoder(object):
    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])
        #x加上噪声
#       tf.matmul( self.x+scale*tf.random_normal((n_input,)),self.weighs['w1'])
        self.hidden=self.transfer(tf.add(   tf.matmul( self.x+scale*tf.random_normal((n_input,)),self.weighs['w1']),self.weights['b1']))
        self.reconstruction=tf.add(tf.matmul(self.hidden,self.weights['w2']),self.weights['b2'])
        


TensorFlow实现多层感知机

# -*- coding: utf-8 -*-



import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#第一步定义算法公式
mnist=input_data.read_data_sets("D:/ProgramData/Anaconda3/envs/MNIST_data/",one_hot=True)
in_units = 784 #输入节点数
h1_units = 300 #隐含层节点数
W1 = tf.Variable(tf.truncated_normal([in_units, h1_units], stddev=0.1)) #初始化隐含层权重W1,服从默认均值为0,标准差为0.1的截断正态分布
b1 = tf.Variable(tf.zeros([h1_units])) #隐含层偏置b1全部初始化为0
W2 = tf.Variable(tf.zeros([h1_units, 10])) 
b2 = tf.Variable(tf.zeros([10]))
x = tf.placeholder(tf.float32, [None, in_units])
keep_prob = tf.placeholder(tf.float32) #Dropout失活率


#模型结构
hidden1 = tf.nn.relu(tf.matmul(x, W1) + b1)
hidden1_drop = tf.nn.dropout(hidden1, keep_prob)
y = tf.nn.softmax(tf.matmul(hidden1_drop, W2) + b2)


#第二步定义损失函数和选择优化器训练部分
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.AdagradOptimizer(0.3).minimize(cross_entropy)


#第三步:训练步骤,定义一个InteractiveSession会话并初始化全部变量
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
第四步对模型的评测
for i in range(3001):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    train_step.run({x: batch_xs, y_: batch_ys, keep_prob: 0.75})
    if i % 200 ==0:
		#训练过程每200步在测试集上验证一下准确率,动态显示训练过程
        print(i, 'training_arruracy:', accuracy.eval({x: mnist.test.images, y_: mnist.test.labels, 
                             keep_prob: 1.0}))
print('final_accuracy:', accuracy.eval({x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))


实验结果:

Extracting D:/ProgramData/Anaconda3/envs/MNIST_data/train-images-idx3-ubyte.gz
Extracting D:/ProgramData/Anaconda3/envs/MNIST_data/train-labels-idx1-ubyte.gz
Extracting D:/ProgramData/Anaconda3/envs/MNIST_data/t10k-images-idx3-ubyte.gz
Extracting D:/ProgramData/Anaconda3/envs/MNIST_data/t10k-labels-idx1-ubyte.gz
WARNING:tensorflow:From E:/Python文件/tessorflow_Dropout.py:68: arg_max (from tensorflow.python.ops.gen_math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `argmax` instead
0 training_arruracy: 0.1032
200 training_arruracy: 0.9286
400 training_arruracy: 0.9539
600 training_arruracy: 0.9624
800 training_arruracy: 0.9687
1000 training_arruracy: 0.9706
1200 training_arruracy: 0.9735
1400 training_arruracy: 0.9749
1600 training_arruracy: 0.978
1800 training_arruracy: 0.9775
2000 training_arruracy: 0.9778
2200 training_arruracy: 0.9773
2400 training_arruracy: 0.9754
2600 training_arruracy: 0.9795
2800 training_arruracy: 0.9779
3000 training_arruracy: 0.9769
final_accuracy: 0.9769

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值