2019-08-14

2019-08-14  本文已影响0人  芜青子

Classification分类学习

把给定数据确定分成哪一类

import tensorflow as tf
import tensorflow.example.tutorials.mnist import input_data#输入数据的下载
#number 1 to 10 data
mnist=input_data.read_data_sets('MNIDT_data',one_hot=TTure) #如果电脑上没有这个数据包,会自动去网上下载,运行以后,就会存在于电脑中。
def add_layer(inputs,in_size,out_size,activation=None) #我们要添加一个层,需要一个输入。看我们是否需要激励函数,默认的话,我们可以暂时默认为没有就是一个线性函数。
     Weights=tf.Variable(tf.random_normal([in_size,out_size]))  #定义一个权重,大写开头因为它是矩阵。我们定义了一个权重,行有in_size个,列有out_size个,其中输出为随机变量值,这样要比全是0的话好很多,每一步都会有变化
      biases=tf.Variable(tf.zeros([1,out_size])+0.1)  #因为biases相当于一个列表类的,所以非矩阵因此首字母无需大写。由于全是0的话不太好,所以我们让其全是0.1
      Wx_plus_b=tf.matmul(inouts,Weights)+biases  #前面那个式子相当于一个矩阵的乘法,还未被激活,就先存放在这里,是一个线性方程
      if activation_function is None:  
          outputs=Wx_plus_b   #如果没有激活函数,就让输出继续保持线性关系输出就好。不用激活函数的非线性关系
      else:
           outputs=activation_functon(Wx_plus_b)
      return outputs
#####define placeholder for inputs to network
xs=tf.placeholder(tf,float32,[None,784]) #不规定有几个simple(None所定义的便是如此),784指的是一个simple的像素点
ys=tf.placeholder(tf,float32,[None,10]) #后面的10指10个输出
#####add output layer
prediction=add_layer(xs,785,10,activation_function=tf.nn.softmax)  #add_layer指的是前面所定义的一个层,xs指的是输入,其中784指的是输入的像素点,10指的是输出的特征
#####the error between prediction and real data
###详见8-11中所提到的
#用dropout 解决 overfitting 的问题
#load data
X=digits.data #表示从0~9的数字图形
y=LabelBinarizer().fit_transform(y) #表示
#卷积神经网络CNN
 不断增加厚度,减少长和宽,最后实现一个分类器的功能。
patch从图片中抽离的那一小部分,或叫channel.对应一种不同的长宽,厚度。
padding 分为抽离出来长和宽一样/长和宽不一样
convulution+padding可以更好的保存图片的性质。
full connection 全连接层相当于前面所提到的隐藏层
###CNN代码实现

import tensorflow as tf
import tensorflow.example.tutorials.mnist import input_data#输入数据的下载

number 1 to 10 data

mnist=input_data.read_data_sets('MNIDT_data',one_hot=TTure) #如果电脑上没有这个数据包,会自动去网上下载,运行以后,就会存在于电脑中。

def compute_accuracy(v_xs,v_ys):
global prediction
y_pre=sess.run(prediction,feed_dict={xs:v_xs,keep_prob:1})
correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
result=sess.run(accuracy,feed_diact={xs:v_xs,ys:v_ys,keep_prob:1})
return result #此处主要是建立输出准确度的

#####参数变量的形状

def weight_variable(shape)
inital=tf.truncated_normal(shape,stddev=0.1) #shape定义形状
return tf.Variable(initial)

def bias_variable(initial)
initial=tf.constant(0.1,shape=shape) #一开始bias是0.1,之后会变成其他值,为正值比较好
return tf.Variable(initial)

传入shape会返回出weight &bias的变量

#####定义卷积网络两大层的各个功能

def conv2d(x,W): #x是输入值/图片的值,W是weight这个变量
#stide[1,x_movement,y_movement,1] #stides[1]&stides[3]都要为1,中间两个是x,y方向移动的距离
return tf.nn.con2d(x,W,strides=[1,1,1,1],padding='SAME') #图片所有信息就是x;在tensorflow中定义卷积层很简单,就是调用一个东西就好啦
```

def max_pool_2x2(x):  #有了pooling可以相比没有保留更多的信息
      return tf.nn.max.pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')  #ksize
将传入的图片信息换成另一种形式
#define placeholder for inputs to network
xs=tf.placeholder(tf.float32,[None,784])#28*28
ys=tf.placeholder(tf.float32,[None,10])
keep_prob=tf.placeholder(tf.float32)
x_image=tf.reshape(xs,[-1,28,28,1])  #[-1,28,28,1]中-1指的是输入的xs中的信息先不变,不管它;28,28指的是像素点784;1指的是只有1个channle,也就是说是黑白的
#print(x_image.shape)#[n_samples,28,28,1]
怎样添加各个层
##conv1 layer##co7yh  nvalution 1
W_conv1=weight_variable([5,5,1,32])  #中括号里面的信息指的是shape;patch5*5 像素指的是长和宽;in size 1 图片厚度;out size 32 输出图片的厚度
b_conv1=bias_variable([32]) #bias只有32个长度
h_conv1=tf.nn.relu(conc2d(x_image,W_conv1)+b_conv1) #括号里面两个相乘;进行非线性的处理使其非线性化 
#output size 28x28x32  卷积层1
#output size 14x14x32   池化层1
h_pool1=max_pool_2x2(h_conv1)

##conv2 layer ##
W_conv2=weight_variable([5,5,32,64])  #中括号里面的信息指的是shape;patch5*5 像素指的是长和宽;in size 32图片厚度;out size64 输出图片的厚度
b_conv2=bias_variable([64]) #bias只有32个长度
h_conv2=tf.nn.relu(conc2d(h_pool1,W_conv2)+b_conv2) #括号里面两个相乘;进行非线性的处理使其非线性化 
#output size14x14x64  卷积层1
#output size 7x7x64   池化层1
h_pool2=max_pool_2x2(h_conv1)
##func1 layer##
W_fc1=weight_variable([7*7*64,1024]) #让它厚度更大,1024
b_fc1=bias_variable([]1024)
#[n_samples,7,7,64]->>[n_sample,7*7*64]
h_plli2_falt=tf.reshape(h_pool2,[-1,7*7*64]) #让其展平
h_fac1=tf.nn.relu(tf.matmul(h_pool2_falt,W_fc1)+b_fc1)  
h_fac1_drop=tf.nn.fropout(h_fc1,keep_prob) #减少过拟合
##func2 layer##
W_fc2=weight_variable([1024,10]) #让它厚度更大,1024
b_fc2=bias_variable([10])
prediction=tf.nn.softmax(tf.matmul(h_fc2_drop,W_fc2)+b_fc2)  #括号里面是上一层的输出值。

the error between prediction and real data

cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1])) #loss
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #此处选用这个训练函数的原因是太庞大,所以使用这个来训练更好;定义训练效率为0.001

sess=tf.Session()

important step

sess.run(tf.initialize_all_variables())

for i in range(1000):
batch_xs,batch_ys=mnist.train.next_batch(100)
sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
if i%50==0:
print(compute_accuracy(
mnist.test.images,mnist.test.labels))

save保存

import tensorflow as tf
import numpy as np
##save to file
#remember to define the same dtype and shape when restore
W=yf.Variable([1,2,3],[3,4,5],dtype=tf.float32,name='weights')
b=tf.Variable([1,2,3],dtype=tf.float32,name='biases')

init=tf.ininalize_all_variables()

saver=tf.train.Saver()

with tf.Session() as sess:
      sess.run(init)
       save_path=saver.save(sess,"mu_net/save_net.ckpt")#官方网站的ckpt
print("Save to path:",save_path)
restore varibles,神经网络框架需要重新定义
#restore varibles
#redefine the same shape and same type for your variables
W=tf.Variable(np.arrange(6).reshape((2,3)),dtype=tf.float32,name="weights")
b=tf.Variable(np.arrange(3).reshape((1,3)),dtype=tf.float32,name="biases") #将变量存放到里面去

#not need init step
saver=tf.train.Saver()
with tf.Session() as saee:
   saver.restore(sess,"my_net/save_net.ckpt")
    print("weights:",sess.run(W))
    print("biases:",sess.run(b))   #这种定义以后,会进已保存到的那个文件中,去找已经定义好的这两种变量。
#迁移学习
用已训练出来的模型进行更改,只需要根据自己需要的功能将网络框架进行更改。
因为系统参数太多,要训练这些参数就需要迁移学习。解决资源,将以这个网络为基础,可以拆掉后面的部分拆掉换新的,然后只训练后面那个就可以了。
斯坦福——transfer learning

上一篇下一篇

猜你喜欢

热点阅读