基于tensorflow搭建一个简单的CNN模型(code),下载函

确保目录结构存在。每次创建文件,确保父目录已经存在。确保指定路径全部或部分目录已经存在。创建沿指定路径上不存在目录。

今天开始进行第一次MNIST的入门调试。 教程是按照Tensorflow中文社区的MNIST入门教程来进行的。 


  • 服务器端:server_server.py

    1 #!usr/bin/env python 2 # -- coding:utf-8 -- 3 # auther:Mr.chen 4 # 描述: 5 6 import socket 7 import os 8 import threading 9 import time 10 import json 11 from user_users import PersonInfo 12 13 DIR = os.path.dirname(os.path.abspath(file)) 14 DIR = DIR+'/Folder/' 15 16 TAG = True 17 18 19 20 def tcplink(conn,addr): 21 """ 22 tcp请求分析函数 23 :param conn: tcp连接对象 24 :param addr: 连接地址 25 :return: 26 """ 27 print ("收到来自{0}的连接请求".format(addr)) 28 conn.send('与主机通信中...') 29 while TAG: 30 try: 31 data = conn.recv(4096) 32 time.sleep(1) 33 if not data: 34 break 35 else: 36 print (data) 37 if data == 'ls': 38 P.view_file(conn) 39 continue 40 action,filename = data.strip().split() 41 action = action.lower() 42 if action == 'put': 43 re = P.Recvfile(conn,filename) 44 if re == True: 45 print ("文件接收成功!") 46 else: 47 print ("文件接收失败!") 48 elif action == 'get': 49 50 P.Sendfile(conn,filename) 51 elif action == 'login': 52 name, password = filename.split(',') 53 P = PersonInfo(name, password) 54 re = P.login() 55 if re == True: 56 conn.send('Ready!') 57 else: 58 conn.send('False!') 59 elif action == 'register': 60 name,password = filename.split(',') 61 P = PersonInfo(name, password) 62 re = P.register() 63 if re == True: 64 conn.send('Ready!') 65 else: 66 conn.send('False!') 67 else: 68 print ("请求方的输入有错!") 69 continue 70 except Exception,e: 71 print "tcplink处理出现问题",e 72 break 73 74 75 76 77 if name == 'main': 78 host = 'localhost' 79 port = 8888 80 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 81 s.bind((host,port)) 82 s.listen(5) 83 print ("服务运行中:正在监听{0}地址的{1}端口:".format(host,port)) 84 while TAG: 85 # 接受一个新连接 86 conn,addr = s.accept() 87 # 创建一个新线程处理TCP连接 88 t = threading.Thread(target=tcplink,args=(conn,addr)) 89 t.start()

下载函数,如果文件名未指定,从URL解析。下载文件,返回本地文件系统文件名。如果文件存在,不下载。如果文件未指定,从URL解析,返回filepath 。实际下载前,检查下载位置是否有目标名称文件。是,跳过下载。下载文件,返回路径。重复下载,把文件从文件系统删除。

本文包含两点:MNIST数据集的下载与导入;MNIST手写数字的识别测试

上一篇搭建了一个简单的cnn网络用来识别手写数字。

 

import os
import shutil
import errno
from lxml import etree
from urllib.request import urlopen

1. MNIST数据集的下载与导入

由于某些不可名说的原因,教程中的MNIST数据集无法下载打开导致一直出错,现在百度网盘放出下载资源:

百度网盘:链接: 密码: 58kw

有需要的同学可以下载使用。

提取和导入MNIST的代码如下:

# Copyright 2015 Google Inc. All Rights Reserved.

#

# Licensed under the Apache License, Version 2.0 (the "License");

# you may not use this file except in compliance with the License.

# You may obtain a copy of the License at

#

#   

#

# Unless required by applicable law or agreed to in writing, software

# distributed under the License is distributed on an "AS IS" BASIS,

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

# See the License for the specific language governing permissions and

# limitations under the License.

#

"""Functions for downloading and reading MNIST data."""

from __future__ import absolute_import

from __future__ import division

from __future__ import print_function

import gzip

import os

import tensorflow.python.platform

import numpy

from six.moves import urllib

from six.moves import xrange  # pylint: disable=redefined-builtin

import tensorflow as tf

SOURCE_URL = ''

def maybe_download(filename, work_directory):

  """Download the data from Yann's website, unless it's already here."""

  if not os.path.exists(work_directory):

    os.mkdir(work_directory)

  filepath = os.path.join(work_directory, filename)

  if not os.path.exists(filepath):

    filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)

    statinfo = os.stat(filepath)

    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')

  return filepath

def _read32(bytestream):

  dt = numpy.dtype(numpy.uint32).newbyteorder('>')

  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]

def extract_images(filename):

  """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""

  print('Extracting', filename)

  with gzip.open(filename) as bytestream:

    magic = _read32(bytestream)

    if magic != 2051:

      raise ValueError(

          'Invalid magic number %d in MNIST image file: %s' %

          (magic, filename))

    num_images = _read32(bytestream)

    rows = _read32(bytestream)

    cols = _read32(bytestream)

    buf = bytestream.read(rows * cols * num_images)

    data = numpy.frombuffer(buf, dtype=numpy.uint8)

    data = data.reshape(num_images, rows, cols, 1)

    return data

def dense_to_one_hot(labels_dense, num_classes=10):

  """Convert class labels from scalars to one-hot vectors."""

  num_labels = labels_dense.shape[0]

  index_offset = numpy.arange(num_labels) * num_classes

  labels_one_hot = numpy.zeros((num_labels, num_classes))

  labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1

  return labels_one_hot

def extract_labels(filename, one_hot=False):

  """Extract the labels into a 1D uint8 numpy array [index]."""

  print('Extracting', filename)

  with gzip.open(filename) as bytestream:

    magic = _read32(bytestream)

    if magic != 2049:

      raise ValueError(

          'Invalid magic number %d in MNIST label file: %s' %

          (magic, filename))

    num_items = _read32(bytestream)

    buf = bytestream.read(num_items)

    labels = numpy.frombuffer(buf, dtype=numpy.uint8)

    if one_hot:

      return dense_to_one_hot(labels)

    return labels

class DataSet(object):

  def __init__(self, images, labels, fake_data=False, one_hot=False,

              dtype=tf.float32):

    """Construct a DataSet.

    one_hot arg is used only if fake_data is true.  `dtype` can be either

    `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into

    `[0, 1]`.

    """

    dtype = tf.as_dtype(dtype).base_dtype

    if dtype not in (tf.uint8, tf.float32):

      raise TypeError('Invalid image dtype %r, expected uint8 or float32' %

                      dtype)

    if fake_data:

      self._num_examples = 10000

      self.one_hot = one_hot

    else:

      assert images.shape[0] == labels.shape[0], (

          'images.shape: %s labels.shape: %s' % (images.shape,

                                                labels.shape))

      self._num_examples = images.shape[0]

      # Convert shape from [num examples, rows, columns, depth]

      # to [num examples, rows*columns] (assuming depth == 1)

      assert images.shape[3] == 1

      images = images.reshape(images.shape[0],

                              images.shape[1] * images.shape[2])

      if dtype == tf.float32:

        # Convert from [0, 255] -> [0.0, 1.0].

        images = images.astype(numpy.float32)

        images = numpy.multiply(images, 1.0 / 255.0)

    self._images = images

    self._labels = labels

    self._epochs_completed = 0

    self._index_in_epoch = 0

  @property

  def images(self):

    return self._images

  @property

  def labels(self):

    return self._labels

  @property

  def num_examples(self):

    return self._num_examples

  @property

  def epochs_completed(self):

    return self._epochs_completed

  def next_batch(self, batch_size, fake_data=False):

    """Return the next `batch_size` examples from this data set."""

    if fake_data:

      fake_image = [1] * 784

      if self.one_hot:

        fake_label = [1] + [0] * 9

      else:

        fake_label = 0

      return [fake_image for _ in xrange(batch_size)], [

          fake_label for _ in xrange(batch_size)]

    start = self._index_in_epoch

    self._index_in_epoch += batch_size

    if self._index_in_epoch > self._num_examples:

      # Finished epoch

      self._epochs_completed += 1

      # Shuffle the data

      perm = numpy.arange(self._num_examples)

      numpy.random.shuffle(perm)

      self._images = self._images[perm]

      self._labels = self._labels[perm]

      # Start next epoch

      start = 0

      self._index_in_epoch = batch_size

      assert batch_size <= self._num_examples

    end = self._index_in_epoch

    return self._images[start:end], self._labels[start:end]

def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=tf.float32):

  class DataSets(object):

    pass

  data_sets = DataSets()

  if fake_data:

    def fake():

      return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)

    data_sets.train = fake()

    data_sets.validation = fake()

    data_sets.test = fake()

    return data_sets

  TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'

  TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'

  TEST_IMAGES = 't10k-images-idx3-ubyte.gz'

  TEST_LABELS = 't10k-labels-idx1-ubyte.gz'

  VALIDATION_SIZE = 5000

  local_file = maybe_download(TRAIN_IMAGES, train_dir)

  train_images = extract_images(local_file)

  local_file = maybe_download(TRAIN_LABELS, train_dir)

  train_labels = extract_labels(local_file, one_hot=one_hot)

  local_file = maybe_download(TEST_IMAGES, train_dir)

  test_images = extract_images(local_file)

  local_file = maybe_download(TEST_LABELS, train_dir)

  test_labels = extract_labels(local_file, one_hot=one_hot)

  validation_images = train_images[:VALIDATION_SIZE]

  validation_labels = train_labels[:VALIDATION_SIZE]

  train_images = train_images[VALIDATION_SIZE:]

  train_labels = train_labels[VALIDATION_SIZE:]

  data_sets.train = DataSet(train_images, train_labels, dtype=dtype)

  data_sets.validation = DataSet(validation_images, validation_labels,

                                dtype=dtype)

  data_sets.test = DataSet(test_images, test_labels, dtype=dtype)

  return data_sets

存为“input_data.py”文件即可。至此,MNIST文件的获取和导入即已完成。

基于tensorflow搭建一个简单的CNN模型(code)

  • 服务器端:user_users.py

    1 #!usr/bin/env python 2 # -- coding:utf-8 -- 3 # auther:Mr.chen 4 # 描述: 5 6 import time 7 import os 8 import pickle 9 10 11 class PersonInfo: 12 """ 13 用户模型类 14 """ 15 DIR = os.path.dirname(os.path.abspath(file)) 16 DIR = DIR + '/Folder/' 17 ConfigDir = DIR.replace('Folder','db') 18 19 def init(self,name,password): 20 self.Name = name #用户名 21 self.Password = password #密码 22 self.DIR = PersonInfo.DIR + self.Name +'/' #用户家目录 23 24 25 def login(self): 26 """ 27 用户登陆 28 :return: 29 """ 30 dict = PersonInfo.config_read() 31 if dict == None: 32 return False 33 if self.Name in dict: 34 if dict[self.Name] == self.Password: 35 return True 36 return False 37 38 39 40 def register(self): 41 """ 42 用户注册 43 :return: 44 """ 45 if os.path.exists(self.DIR) != True: 46 os.system('mkdir'+' '+ self.DIR) 47 try: 48 dict = PersonInfo.config_read() 49 if dict == None: 50 dict = {} 51 if self.Name not in dict: 52 dict[self.Name] = self.Password 53 else: 54 print ("姓名重复") 55 return False 56 re = PersonInfo.config_write(dict) 57 if re == True: 58 return True 59 except Exception,e: 60 print "注册出现异常!",e 61 return False 62 63 64 65 def view_file(self,conn): 66 """ 67 查看用户家目录 68 :param conn: 69 :return: 70 """ 71 data = os.popen('ls'+' '+ self.DIR).read() 72 conn.sendall(data) 73 74 def Recvfile(self,conn,filename): 75 """ 76 接收文件方法 77 :param conn:tcp连接对象 78 :param filename:目标文件名 79 :return: 80 """ 81 print ("开始接收文件...") 82 conn.send('Ready!') 83 buffer = [] 84 while True: 85 d = conn.recv(4096) 86 if d == 'exit': 87 break 88 else: 89 buffer.append(d) 90 data = ''.join(buffer) 91 if data == '': 92 return False 93 print (data) 94 print (filename) 95 print (self.DIR) 96 with open(self.DIR + filename, 'w') as f: 97 f.write(data) 98 return True 99 100 101 def Sendfile(self,conn,filename): 102 """ 103 放送文件方法 104 :param conn: tcp连接对象 105 :param filename: 目标文件名 106 :return: 107 """ 108 109 if os.path.exists(self.DIR + filename): 110 print ("开始放送文件...") 111 conn.send('Ready!') 112 time.sleep(1) 113 with open(self.DIR + filename, 'r') as f: 114 while True: 115 data = f.read(4096) 116 print (data) 117 if not data: 118 break 119 conn.sendall(data) 120 time.sleep(1) 121 conn.send('exit') 122 print ("文件放送成功!") 123 else: 124 conn.send('False!') 125 126 127 @staticmethod 128 def config_read(): 129 """ 130 配置文件全部读取 131 :return: 132 """ 133 if os.path.exists(PersonInfo.ConfigDir+'user_config'): 134 with open(PersonInfo.ConfigDir+'user_config','r') as f: 135 dict = pickle.load(f) 136 return dict 137 138 139 @staticmethod 140 def config_write(dict): 141 """ 142 配置文件全部写入 143 :param dict: 144 :return: 145 """ 146 with open(PersonInfo.ConfigDir + 'user_config', 'w') as f: 147 pickle.dump(dict,f) 148 return True

def ensure_directory(directory):
directory = os.path.expanduser(directory)
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise e

2. MNIST手写识别测试

整个导入,训练,验证和测试的代码如下,详细解释可以在上述教程中得到。

import tensorflowas tf

import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x = tf.placeholder("float", [None, 784])

W = tf.Variable(tf.zeros([784,10]))

b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x,W)+b)

y_ = tf.placeholder("float", [None,10])

cross_entropy = -tf.reduce_sum(y_*tf.log(y))

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

init = tf.initialize_all_variables()

sess = tf.Session()

sess.run(init)

for iin range(1000):

batch_xs, batch_ys = mnist.train.next_batch(100)

sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

print sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})

执行代码后可得:

训练结果为0.9137,符合教程的结果,测试成功。

图片 1

这次我们将要搭建一个较复杂的卷积神经网络结构去对CIFAR-10进行训练和识别。

 

def download(url, directory, filename=None):
if not filename:
_, filename = os.path.split
directory = os.path.expanduser(directory)
ensure_directory(directory)
filepath = os.path.join(directory, filename)
if os.path.isfile:
return filepath
print('Download', filepath)
with urlopen as response, open(filepath, 'wb') as file_:
shutil.copyfileobj(response, file_)
return filepath

1. load 一些必要的库和 start a graph session:

  • 客户端:server_client.py

磁盘缓存修饰器,较大规模数据集处理中间结果保存磁盘公共位置,缓存加载函数修饰器。Python pickle功能实现函数返回值序列化、反序列化。只适合能纳入主存数据集。@disk_cache修饰器,函数实参传给被修饰函数。函数参数确定参数组合是否有缓存。散列映射为文件名数字。如果是'method',跳过第一参数,缓存filepath,'directory/basename-hash.pickle'。方法method=False参数通知修饰器是否忽略第一个参数。

import os

import sys

import tarfile

import matplotlib.pyplot as plt

import numpy as np

import tensorflow as tf

from six.moves import urllib

sess = tf. Session()

 

import functools
import os
import pickle

2. 定义一些模型参数

#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述:

import socket,os
import time
TAG =True

DIR = os.path.dirname(os.path.abspath(__file__))
DIR = DIR+'/Folder/'
HOST = 'localhost'
PORT = 8888


def Recvfile(s,filename):
    """
    接收文件方法函数
    :param s: 套接字封装对象
    :param filename: 目标文件名
    :return:
    """
    print ("开始下载文件...")
    buffer = []
    while TAG:
        d = s.recv(4096)
        if d == 'exit':
            break
        buffer.append(d)
    data = ''.join(buffer)
    with open(DIR+filename,'w') as f:
        f.write(data)
    print ("文件下载完毕!")


def Sendfile(s,filename):
    """
    放送文件方法函数
    :param s: 套接字封装对象
    :param filename: 目标文件名
    :return:
    """
    print ("开始上传文件!")
    if os.path.exists(DIR+filename):
        with open(DIR+filename,'r') as f:
            while TAG:
                data = f.read(4096)
                if not data:
                    break
                s.sendall(data)
        time.sleep(1)
        s.send('exit')
        print ("文件上传完毕")
    else:
        print ("你的目录里没有这个文件")
        time.sleep(1)
        s.send('exit')




def Confirm(s,command):
    """
    验证与服务器连接是否正常;
    把用户命令发过去,让服务器做好相应准备准备
    :param s: 套接字封装对象
    :param command: 用户输入的命令
    :return:
    """
    s.sendall(command)
    re = s.recv(4096)
    if re == 'Ready!':
        return True
    elif re == 'False!':
        return False
    else:
        print ("与服务器连接出现异常!")


def File_transfer(s):
    """
    用户指令函数
    :param s:
    :return:
    """
    while TAG:
        command = raw_input("请输入你想执行的命令>>")
        if not command:
            continue
        if command.lower().strip() == 'help':
            print ("请用'put'+'空格'+'文件名'的格式上传文件")
            print ("请用'get'+'空格'+'文件名'的格式下载文件")
            print ("输入'ls'查看用户服务器家目录")
            continue
        if command.lower().strip() == 'ls':
            s.send('ls')
            data = s.recv(4096)
            print (data)
            continue
        try:
            action,filename = command.strip().split()
            action = action.lower()
        except:
            print ("您的输入有误!输入help查看帮助文档")
            continue
        if action == 'put':
            re = Confirm(s,command)
            if re == True:
                Sendfile(s, filename)
            else:
                print ("对方服务器没有准备好!")
                break
        elif action == 'get':
            re = Confirm(s,command)
            if re == True:
                Recvfile(s, filename)
            elif re == False:
                print ("服务器家目录没有这个文件")
            else:
                print ("对方服务器没有准备好!")
                break
        else:
            print ("你输入的命令有误!输入help查看帮助文档")



def Login(s):
    """
    用户登录
    :param s:
    :return:
    """
    name = raw_input("请输入你的用户名:")
    password = raw_input("请输入你的密码:")
    command = 'login'+' '+ name + ',' + password
    re = Confirm(s, command)
    if re == True:
        print ("登陆成功!")
        File_transfer(s)
    elif re == False:
        print ("您的输入有误,请重新输入!")
        Login(s)
    else:
        print ("与服务器连接出现异常!")


def Register(s):
    """
    用户注册
    :param s:
    :return:
    """
    name = raw_input("请输入你的用户名:")
    password = raw_input("请输入你的密码:")
    Password = raw_input("请再次输入密码:")
    if password != Password:
        print ("你的密码两次输入不一致,请重新输入!")
        Register(s)
    command = 'register' + ' ' + name + ',' + password
    print (command)
    re = Confirm(s,command)
    if re == True:
        File_transfer(s)
    elif re == False:
        print ("用户名重复,请重新输入!")
        Register(s)
    else:
        print ("与服务器连接出现异常!")

def Main(s,log = '未联通主机...'):
    """
    用户登陆界面
    :param s:
    :param log:
    :return:
    """
    text = """
            用户登陆界面      {0}

            1,用户登陆
            2,用户注册
    """.format(log)
    print (text)
    choose = raw_input("请输入索引进行选择:")
    if choose == '1':
        Login(s)
    elif choose == '2':
        Register(s)
    else:
        print ("你的选择有误!")


if __name__ == "__main__":

    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        s.connect((HOST,PORT))
        Main(s,s.recv(1024))
    except Exception,e:
        print "服务器连接不上....",e
    finally:
        s.close()

def disk_cache(basename, directory, method=False):
directory = os.path.expanduser(directory)
ensure_directory(directory)

batch_size = 128

output_every = 50

generations = 20000

eval_every = 500

image_height = 32

image_width = 32

crop_height = 24

crop_width = 24

num_channels = 3

num_targets = 10

data_dir = 'temp'

extract_folder = 'cifar-10-batches-bin'

 

def wrapper:
@functools.wraps
def wrapped(*args, **kwargs):
key = (tuple, tuple(kwargs.items
if method and key:
key = key[1:]
filename = '{}-{}.pickle'.format(basename, hash
filepath = os.path.join(directory, filename)
if os.path.isfile:
with open(filepath, 'rb') as handle:
return pickle.load
result = func(*args, **kwargs)
with open(filepath, 'wb') as handle:
pickle.dump(result, handle)
return result
return wrapped

3. 定义训练学习率等几个参数

return wrapper
@disk_cache('dataset', '/home/user/dataset/')
def get_dataset(one_hot=True):
dataset = Dataset('')
dataset = Tokenize
if one_hot:
dataset = OneHotEncoding
return dataset

learning_rate = 0.1

lr_decay = 0.9

num_gens_to_wait = 250

属性字典。继承自内置dict类,可用属性语法访问悠已有元素。传入标准字典。内置函数locals,返回作用域所有局部变量名值映射。

4. 现在我们建立可以读取二进制 CIFAR-10图片的参数

class AttrDict:

image_vec_length = image_height * image_width * num_channels

record_length = 1 + image_vec_length

def __getattr__(self, key):
if key not in self:
raise AttributeError
return self[key]

5. 建立数据的路径及下载CIFAR-10数据集图片

本文由必威发布于必威-编程,转载请注明出处:基于tensorflow搭建一个简单的CNN模型(code),下载函

TAG标签:
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。