Tensorflow入门二 mnist识别(一)

时间:2021-10-18 20:00:23

话不多说,直接上代码

看注释就 OK 啦

import numpy as np
import sklearn.preprocessing as prep
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#fan_in是输入节点的数量
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)
#n_input为输入变量 transfer_function隐含层激活函数,默认为softplus optimizer优化器
class AdditivieGaussianNoiseAutoencoder(object):
#只有一个隐含层
def __init__(self,n_input,n_hidden,transfer_function=tf.nn.relu,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 reconstruct(self,X):
return self.sess.run(self.reconstruction,feed_dict={self.x:X,self.scale:self.training_scale})

#获取隐含层权重w1
def getWeights(self):
return self.sess.run(self.weight['w1'])

#获取隐含层偏执系数
def getBiases(self):
return self.sess.run(self.weights['b1'])

# 返回自编码器隐含层的输出结果
def transform(self, X):
return self.sess.run(self.hidden, feed_dict={self.x: X, self.scale: self.training_scale})

# 只求cost的函数,在训练完之后调用用于测试
def calc_total_cost(self, X):
return self.sess.run(self.cost, feed_dict={self.x: X, self.scale: self.training_scale})

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以及进一步训练计算
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

# 将隐含层的输出结果作为输入,再通过重建层将提取到的高阶特征复原
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})
#导入数据
mnist=input_data.read_data_sets('MNIST_data',one_hot=True)

#对数据进行测试与标准化,让数据变成0均值,标准差为1
#使用StandardScaler().fit可以完成
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数据,0到len(data)-batch size之间的随机整数,以此为起始位置顺序取batch size数据
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#每隔一轮显示一次损失cost

#创建一个AGN自编码实例,定义模型输入节点数n_input为784
#隐含层节点数n_hidden为200,隐含层激活函数transfer_function为softplus
#优化器optimizer为Adam,学习速率为0.001,噪声系数为0.01
autoencoder=AdditivieGaussianNoiseAutoencoder(n_input=784,n_hidden=200,transfer_function=tf.nn.relu,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.calc_total_cost(X_test)))