Python 尝试使用MNIST进行训练时出现ResourceExhausterRor

Python 尝试使用MNIST进行训练时出现ResourceExhausterRor,python,tensorflow,machine-learning,deep-learning,mnist,Python,Tensorflow,Machine Learning,Deep Learning,Mnist,当我试图训练MNIST时,我感到资源枯竭 我发现我可以更改批处理大小以避免出现问题,但不幸的是,我不知道在我的代码中该在哪里执行该操作 回溯: ResourceExhustederRor(回溯见上文):当使用形状[238305,32,28,28]和类型float on/job:localhost/replica:0/task:0/device:GPU:0分配程序GPU\U bfc分配张量时,OOM [[Node:Conv2D=Conv2D[T=DT\u FLOAT,data\u format=“

当我试图训练MNIST时,我感到资源枯竭 我发现我可以更改批处理大小以避免出现问题,但不幸的是,我不知道在我的代码中该在哪里执行该操作

回溯:

ResourceExhustederRor(回溯见上文):当使用形状[238305,32,28,28]和类型float on/job:localhost/replica:0/task:0/device:GPU:0分配程序GPU\U bfc分配张量时,OOM [[Node:Conv2D=Conv2D[T=DT\u FLOAT,data\u format=“NCHW”,dillations=[1,1,1],padding=“SAME”,strips=[1,1,1],在\u gpu=true上使用\u cudnn\u,\u device=“/job:localhost/replica:0/task:0/device:gpu:0”](Conv2D-0-transpsenhwctonchw-layoutuoptimizer,Variable/read)]] 提示:如果您想在OOM发生时查看已分配的张量列表,请在OOM上添加report_tensor_allocations_on_to RunOptions以获取当前分配信息。 [[Node:add_3/\u 39=\u Recvclient_terminated=false,recv_device=“/job:localhost/replica:0/task:0/device:CPU:0”,send_device=“/job:localhost/replica:0/task:0/device:GPU:0”,send_device_化身=1,tensor_name=“edge_51_add_3”,tensor_type=DT_FLOAT,\u device=“/job:localhost/replica:0/task:0/device:CPU:0”]

我的CNN模型:

from __future__ import print_function
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 


# number 1 to 10 data


# from tensorflow.examples.tutorials.mnist import input_data
# mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
import mnist2.mnist as mn
mnist = mn.read_data_sets('MNIST/', one_hot=True, num_classes=9)

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_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
    return result

def weight_variable(shape):
    inital = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(inital)

def bias_variable(shape):
    inital = tf.constant(0.1, shape=shape)
    return tf.Variable(inital)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')


# define placeholder for inputs to network

xs = tf.placeholder(tf.float32, [None, 784, 1]) # 28x28

ys = tf.placeholder(tf.float32, [None, 9])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])

## conv1 layer ##

W_conv1 = weight_variable([5, 5, 1, 32]) #patch 5x5, in channel size 1, out size 32

## pool1 layer ##

b_conv1 = bias_variable([32])
#Combine

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #output size 28x28x32

h_pool1 = max_pool_2x2(h_conv1) #output size 14x14x32



## conv2 layer ##

W_conv2 = weight_variable([5, 5, 32, 64]) #patch 5x5, in channel size 32, out size 64

## pool2 layer ##

b_conv2 = bias_variable([64])
#Combine

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #output size 14x14x64

h_pool2 = max_pool_2x2(h_conv2) #output size 7x7x64

## fc1 layer ##

W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #[n_samples, 7,7,64]  => [n_samples, 7*7*64]

h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

## output layer ##

W_fc2 = weight_variable([1024, 9])
b_fc2 = bias_variable([9])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)


cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                              reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)


sess = tf.Session()
sess.run(tf.initialize_all_variables())
for i in range(10001):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob:0.5})
    if i % 50 == 0:
        print(compute_accuracy(
            mnist.test.images, mnist.test.labels))
我的MNIST代码:

# Copyright 2016 The TensorFlow Authors. 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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 numpy
from six.moves import xrange  # pylint: disable=redefined-builtin

from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed

# CVDF mirror of http://yann.lecun.com/exdb/mnist/
SOURCE_URL = 'https://storage.googleapis.com/cvdf-datasets/mnist/'


def _read32(bytestream):
  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]


def extract_images(f, channels=1):
  """Extract the images into a 4D uint8 numpy array [index, y, x, depth].

  Args:
    f: A file object that can be passed into a gzip reader.

  Returns:
    data: A 4D uint8 numpy array [index, y, x, depth].

  Raises:
    ValueError: If the bytestream does not start with 2051.

  """
  print('Extracting', f.name)
  with gzip.GzipFile(fileobj=f) as bytestream:
    magic = _read32(bytestream)
    if magic != 2051:
      raise ValueError('Invalid magic number %d in MNIST image file: %s' %
                       (magic, f.name))
    num_images = _read32(bytestream)
    rows = _read32(bytestream)
    cols = _read32(bytestream)
    buf = bytestream.read(rows * cols * num_images * channels)
    data = numpy.frombuffer(buf, dtype=numpy.uint8)
    data = data.reshape(num_images, rows, cols, channels)
    return data



def dense_to_one_hot(labels_dense, num_classes):
  """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(f, one_hot=False, num_classes=10):
  """Extract the labels into a 1D uint8 numpy array [index].

  Args:
    f: A file object that can be passed into a gzip reader.
    one_hot: Does one hot encoding for the result.
    num_classes: Number of classes for the one hot encoding.

  Returns:
    labels: a 1D uint8 numpy array.

  Raises:
    ValueError: If the bystream doesn't start with 2049.
  """
  print('Extracting', f.name)
  with gzip.GzipFile(fileobj=f) as bytestream:
    magic = _read32(bytestream)
    if magic != 2049:
      raise ValueError('Invalid magic number %d in MNIST label file: %s' %
                       (magic, f.name))
    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, num_classes)
    return labels


class DataSet(object):

  def __init__(self,
               images,
               labels,
               fake_data=False,
               one_hot=False,
               dtype=dtypes.float32,
               reshape=True,
               seed=None):
    """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]`.  Seed arg provides for convenient deterministic testing.
    """
    seed1, seed2 = random_seed.get_seed(seed)
    # If op level seed is not set, use whatever graph level seed is returned
    numpy.random.seed(seed1 if seed is None else seed2)
    dtype = dtypes.as_dtype(dtype).base_dtype
    if dtype not in (dtypes.uint8, dtypes.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)
      if reshape:
        #iassert images.shape[3] == 1
        images = images.reshape(images.shape[0],
                                images.shape[1] * images.shape[2], images.shape[3])
      if dtype == dtypes.float32:
        # Convert from [0, 255] -> [0.0, 1.0].
        num, dim, channels = images.shape
        count = num * dim * channels
        images.setflags(write=1)
        index = 1000
        images = images.astype(numpy.float32)
        for i in range(0,count,index):
            if not (count - i) < index:
                images[i:i+index] = numpy.multiply(images[i:i+index], 1.0 / 255.0)
            else:
                images[i:count] = numpy.multiply(images[i:count], 1.0 / 255.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, shuffle=True):
    """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
    # Shuffle for the first epoch
    if self._epochs_completed == 0 and start == 0 and shuffle:
      perm0 = numpy.arange(self._num_examples)
      numpy.random.shuffle(perm0)
      self._images = self.images[perm0]
      self._labels = self.labels[perm0]
    # Go to the next epoch
    if start + batch_size > self._num_examples:
      # Finished epoch
      self._epochs_completed += 1
      # Get the rest examples in this epoch
      rest_num_examples = self._num_examples - start
      images_rest_part = self._images[start:self._num_examples]
      labels_rest_part = self._labels[start:self._num_examples]
      # Shuffle the data
      if shuffle:
        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 - rest_num_examples
      end = self._index_in_epoch
      images_new_part = self._images[start:end]
      labels_new_part = self._labels[start:end]
      return numpy.concatenate((images_rest_part, images_new_part), axis=0) , numpy.concatenate((labels_rest_part, labels_new_part), axis=0)
    else:
      self._index_in_epoch += batch_size
      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=dtypes.float32,
                   reshape=True,
                   validation_size=24,
                   seed=None,
                   num_classes=10,
                   channels=1):
  if fake_data:

    def fake():
      return DataSet(
          [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed)

    train = fake()
    validation = fake()
    test = fake()
    return base.Datasets(train=train, validation=validation, test=test)

  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'

  local_file = base.maybe_download(TRAIN_IMAGES, train_dir,
                                   SOURCE_URL + TRAIN_IMAGES)
  with open(local_file, 'rb') as f:
    train_images = extract_images(f, channels)

  local_file = base.maybe_download(TRAIN_LABELS, train_dir,
                                   SOURCE_URL + TRAIN_LABELS)
  with open(local_file, 'rb') as f:
    train_labels = extract_labels(f, one_hot=one_hot, num_classes=num_classes)

  local_file = base.maybe_download(TEST_IMAGES, train_dir,
                                   SOURCE_URL + TEST_IMAGES)
  with open(local_file, 'rb') as f:
    test_images = extract_images(f, channels)

  local_file = base.maybe_download(TEST_LABELS, train_dir,
                                   SOURCE_URL + TEST_LABELS)
  with open(local_file, 'rb') as f:
    test_labels = extract_labels(f, one_hot=one_hot, num_classes=num_classes)

  if not 0 <= validation_size <= len(train_images):
    raise ValueError(
        'Validation size should be between 0 and {}. Received: {}.'
        .format(len(train_images), validation_size))

  validation_images = train_images[:validation_size]
  validation_labels = train_labels[:validation_size]
  train_images = train_images[validation_size:]
  train_labels = train_labels[validation_size:]


  options = dict(dtype=dtype, reshape=reshape, seed=seed)

  train = DataSet(train_images, train_labels, **options)
  validation = DataSet(validation_images, validation_labels, **options)
  test = DataSet(test_images, test_labels, **options)

  return base.Datasets(train=train, validation=validation, test=test)


def load_mnist(train_dir='MNIST-data'):
  return read_data_sets(train_dir)
#TensorFlow作者版权所有2016。版权所有。
#
#根据Apache许可证2.0版(以下简称“许可证”)获得许可;
#除非遵守许可证,否则不得使用此文件。
#您可以通过以下方式获得许可证副本:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#除非适用法律要求或书面同意,软件
#根据许可证进行的分发是按“原样”进行分发的,
#无任何明示或暗示的保证或条件。
#请参阅许可证以了解管理权限和权限的特定语言
#许可证下的限制。
# ==============================================================================
“”“用于下载和读取MNIST数据的函数。”“”
从未来导入绝对导入
来自未来进口部
来自未来导入打印功能
导入gzip
进口numpy
from six.moves导入xrange#pylint:disable=重新定义的内置
从tensorflow.contrib.learn.python.learn.datasets导入库
从tensorflow.python.framework导入数据类型
从tensorflow.python.framework导入随机种子
#CVDF反射镜http://yann.lecun.com/exdb/mnist/
来源(URL)https://storage.googleapis.com/cvdf-datasets/mnist/'
def_read32(ByTestStream):
dt=numpy.dtype(numpy.uint32).newbyteorder(“>”)
返回numpy.frombuffer(bytestream.read(4),dtype=dt)[0]
def提取图像(f,通道=1):
“”“将图像提取到4D uint8 numpy数组中[索引,y,x,深度]。
Args:
f:可以传递到gzip读取器的文件对象。
返回:
数据:4D uint8 numpy数组[索引,y,x,深度]。
提出:
ValueError:如果ByTestStream不是从2051开始的。
"""
打印('提取',f.name)
使用gzip.gzip文件(fileobj=f)作为ByTestStream:
magic=_read32(bytestream)
如果有魔法!=2051:
raise VALUERROR('MNIST映像文件中无效的幻数%d:%s'%
(魔术,f.名字)
num_images=_read32(bytestream)
行=_read32(bytestream)
cols=_read32(bytestream)
buf=bytestream.read(行*cols*num_图像*通道)
data=numpy.frombuffer(buf,dtype=numpy.uint8)
数据=数据。重塑(图像、行、列、通道的数量)
返回数据
def densite_到one_hot(标签密集,num类):
“”“将类标签从标量转换为一个热向量。”“”
num\u labels=标签密度。形状[0]
索引偏移=numpy.arange(num\u标签)*num\u类
labels\u one\u hot=numpy.zero((num\u标签,num\u类))
labels\u one\u hot.flat[index\u offset+labels\u densite.ravel()]=1
返回标签\u一个\u热
def extract_标签(f,one_hot=False,num_classes=10):
“”“将标签提取到1D uint8 numpy数组[索引]中。”。
Args:
f:可以传递到gzip读取器的文件对象。
one_hot:对结果进行一次热编码。
num_classes:一个热编码的类数。
返回:
标签:一个1D uint8 numpy数组。
提出:
ValueError:如果bystream不是从2049开始的。
"""
打印('提取',f.name)
使用gzip.gzip文件(fileobj=f)作为ByTestStream:
magic=_read32(bytestream)
如果有魔法!=2049:
raise VALUERROR('MNIST标签文件中的无效幻数%d:%s'%
(魔术,f.名字)
num\u items=\u read32(bytestream)
buf=bytestream.read(num\u项)
labels=numpy.frombuffer(buf,dtype=numpy.uint8)
如果其中一个热:
返回稠密的\u到\u一个\u热(标签、num\u类)
退货标签
类数据集(对象):
定义初始化(自我,
图像,
标签,
假数据=假,
一热=假,
dtype=dtypes.float32,
重塑=真,
种子=无):
“”“构造数据集。
仅当伪数据为真时才使用一个热参数。`dtype`可以是
`uint8`将输入保留为“[0,255]”,或'float32`重新缩放到
`[0,1]`。Seed arg提供了方便的确定性测试。
"""
种子1,种子2=随机种子。获取种子(种子)
#如果未设置op级别种子,则使用返回的任何图形级别种子
numpy.random.seed(如果seed不是其他seed,则seed 1为seed 2)
dtype=dtypes.as\u dtype(dtype).base\u dtype
如果数据类型不在(dtypes.uint8,dtypes.float32):
raise TypeError('无效的图像数据类型%r,应为uint8或float32'%
数据类型)
如果数据是假的:
self.\u num\u示例=10000
self.one_hot=one_hot
其他:
断言图像。形状[0]==标签。形状[0](
'images.shape:%s labels.shape:%s'(images.shape,labels.shape))
self.\u num\u examples=images.shape[0]
#从[num示例、行、列、深度]转换形状
#至[num示例,行*列](假设深度==1)
如果重塑:
#最后一批
for i in range(10001):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob:0.5})
size_batch=50
for i in range(10001):
    batch_xs, batch_ys = mnist.train.next_batch(size_batch)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob:0.5})