CNN卷积网络

3 篇文章 0 订阅
1 篇文章 0 订阅

卷积网络包含卷积,池化,全连接。
卷积。是对图像进行卷积。
池化是对某片区域提取特征代表区域。防止拟合(个人理解是运算过大,导致超出计算结果)
全连接是对所有特征进行全局图片化。

import tensorflow as tf
import numpy as np
import matplotlib.pylab as plt
import os
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('MNIST_data',one_hot=True)
#卷积网络,图形数据处理
#函数为tf.nn.softmax 将一系列数据回归占比率,故而特征明显则明显辨别
width=64
high=64
paths=['0','1','2','3']
batch_size=40
class ml:
    
    def __init__(self):
        print("cnn test")
        self.sess=tf.Session()
        self.init=None
    #展示图片  
    def show_im(self,tmp_im):
        plt.imshow(tmp_im)
        plt.axis('off')
        plt.show()
        
    #读取文件 制作训练数据集
    def read_pic(self):
        #创建空的得数据集用于存储待训练图片
        #读取所有数据集
        imgs=[]
        labels=[]
        for path in paths:
            filenames=os.listdir(path)
            le=len(filenames)
            for item in filenames:
                pic=plt.imread(path+'/'+item)
                
                tmp_pic=pic[:high,:width,:]
                imgs.append(tmp_pic)
                value=np.zeros((10))
                value[int(item[0:1])]=item[0:1]
                labels.append(value)
            
        #训练批量制作完成
    #     imgs=np.array(pics,dtype="float32")
        imgs=np.reshape(imgs,(len(imgs),high,width,3))
        #即为所值,共计十个,真正得为数字,其他为0
        labels=np.reshape(labels,(len(labels),10))
        
        return imgs,labels
    
    #读取文件 制作训练数据集
    def read_pic_batch(self):
        
        imgs=[]
        labels=[]
        #创建空的得数据集用于存储待训练图片
        #读取所有数据集
        p1=1
        p2=10
        for i in range(p1):
            batch_xs,batch_ys=mnist.train.next_batch(p2)
            #转为图片组,-1代编不定值,任一个图片
            shape=(-1,28,28,1)
            shape_y=(-1,10)
            x=batch_xs.reshape(shape)
            y=batch_ys.reshape(shape_y)
            for i in range(p2):
                tmp_pic=np.zeros((28,28,3))
                for a in range(shape[1]):
                    for b in range(shape[2]):
                        tmp_pic[a,b,:]=x[i,a,b,:]*3
                imgs.append(tmp_pic)
                #真实值
                labels.append(y[i])
#                 plt.imshow(tmp_pic)
#                 #前面不能有show否则保存空白图片
#                 plt.savefig(str(i)+'.jpg')
#                 plt.show()
            
            
        #训练批量制作完成
    #     imgs=np.array(pics,dtype="float32")
        imgs=np.reshape(imgs,(len(imgs),28,28,3))
        #即为所值,共计十个,真正得为数字,其他为0
        labels=np.reshape(labels,(len(labels),10))
        
        return imgs,labels
    
    
    #卷积网络
    def cnn_network(self,inputdata,conv,strides=None,padding=None):
        return tf.nn.conv2d(inputdata,conv,strides,padding=padding)   
    
    #全连接
    def layer_connecter(self,datas):
        return tf.layers.dense(datas)
    
    #训练网络  
    def train(self):
        #读取训练数据
        imgs,labels=self.read_pic_batch()
        #初始化所有变量
        
        #定义x输入图片
        x=tf.placeholder(tf.float32,shape=[None,28,28,3])
        #定义y图片所属类型
        y=tf.placeholder(tf.float32,shape=[None,10])
        
        #第一次卷积
        w_conv1=tf.Variable(tf.truncated_normal([5,5,3,32], stddev=0.1))
        b_conv1=tf.Variable(tf.constant(0.1,shape=[32]))
        
        #卷积后
        L1_conv=self.cnn_network(x,w_conv1,strides=[1,1,1,1],padding='SAME')
        #池化操作,防止拟合
        L1_relu=tf.nn.relu(L1_conv+b_conv1)
        #每两个格缩小一次
        L1_pool=tf.nn.max_pool(L1_relu,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
        
        #第二层卷积
        w_conv2=tf.Variable(tf.truncated_normal([3,3,32,64], stddev=0.1))
        b_conv2=tf.Variable(tf.constant(0.1,shape=[64]))
        
        #卷积后
        L2_conv=self.cnn_network(L1_pool,w_conv2,strides=[1,1,1,1],padding='SAME')
        #池化操作,防止拟合
        L2_relu=tf.nn.relu(L2_conv+b_conv2)
        L2_pool=tf.nn.max_pool(L2_relu,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
        
        
        #全连接层
        #第一个为图片得值
        w_fc1=tf.Variable(tf.truncated_normal([7*7*64,1024],stddev=0.1))
        b_fc1=tf.Variable(tf.constant(0.1,shape=[1024]))
        
        #展平为正常维度,即为图片组,图片组放的的是图所有数据为一个数组
        h_pool2_flat=tf.reshape(L2_pool,[-1,7*7*64])
        h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,w_fc1)+b_fc1)
        
        #dropout
        keep_prob=tf.placeholder(tf.float32)
        h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
        
        #readout层
        w_fc2=tf.Variable(tf.truncated_normal([1024,10],stddev=0.1))
        b_fc2=tf.Variable(tf.constant(0.1,shape=[10]))
        
        y_conv=tf.matmul(h_fc1_drop,w_fc2)+b_fc2
        
        #定义优化器
        cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=y_conv))
        
        train_step=tf.train.AdamOptimizer(0.01).minimize(cross_entropy)
        #断定损失值
        correct_prediction=tf.equal(tf.argmax(y_conv,1),tf.argmax(y,1))
        
        accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
         
        self.sess.run(tf.global_variables_initializer())
        for _ in range(1000):
            
            self.sess.run(train_step,feed_dict={x:imgs,y:labels,keep_prob:0.5})
            if _%100==0:
                data=self.sess.run(accuracy,feed_dict={x:imgs,y:labels,keep_prob:0.5})
                print(data)
        
        
    def save_data(self):
        print(1)  
        
if __name__=='__main__':
    obj=ml()
    obj.train()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值