占位符返回gen_array_ops._placeholder(dtype = dtype,shape = shape,name = name)

时间:2018-03-05 17:49:47

标签: python python-3.x tensorflow machine-learning deep-learning

我正在尝试对狗和猫进行分类;对于这个我使用CNN模型,但是当我将Image矩阵放到tf.placeholder时,我得到一个错误,"占位符返回gen_array_ops._placeholder(dtype = dtype,shape = shape,name = name)& #34;,但我不明白这个问题。

我该如何解决这个问题?

我的代码:

import os
import warnings
import glob
import h5py
import tensorflow as tf
import math as mt
import numpy as np
import cv2 as cv
from matplotlib import pyplot
from tflearn.data_utils import image_preloader
from random import shuffle
import tflearn as tfl
warnings.simplefilter("ignore")
path="E:\data\minimum"
path1='E:\data\\train.txt'
path2='E:\data\\testing.txt'
path3='E:\data\\validation.txt'
training=0.7
testing=0.2
validation=0.1
list=os.listdir(path)
shuffle(list)
lenght=len(list)
file=open(path1,'w')
train=list[0: int(training*lenght)]
for i in train:
    if(i[0:3]=='cat'):
        file.write(path + '/'+ i + ' 0\n')
    elif(i[0:3]=='dog'):
        file.write(path + '/'+ i + ' 1\n')
file.close()
file=open(path3,'w')
train=list[0: int(validation*lenght)]
for i in train:
    if(i[0:3]=='cat'):
        file.write(path + '/'+ i + ' 0\n')
    elif(i[0:3]=='dog'):
        file.write(path + '/'+ i + ' 1\n')
file.close()
file=open(path2,'w')
train=list[0: int(testing*lenght)]
for i in train:
    if(i[0:3]=='cat'):
        file.write(path + '/'+ i + ' 0\n')
    elif(i[0:3]=='dog'):
        file.write(path + '/'+ i + ' 1\n')
file.close()

X_train, Y_train =image_preloader(path1, image_shape=(50,50),mode='file', categorical_labels=True,normalize=True)
X_test, Y_test =image_preloader(path2, image_shape=(50,50),mode='file', categorical_labels=True,normalize=True)
X_val, Y_val =image_preloader(path3, image_shape=(50,50),mode='file', categorical_labels=True,normalize=True)
print ("Dataset")
print ("Number of training images {}".format(len(X_train)))
print ("Number of testing images {}".format(len(X_test)))
print ("Number of validation images {}".format(len(X_val)))
print ("Shape of an image {}" .format(X_train[1].shape))
print ("Shape of label:{} ,number of classes: {}".format(Y_train[1].shape,len(Y_train[1])))

pyplot.imshow(X_train[1])
pyplot.axis('off')
pyplot.title('Sample image with label {}'.format(Y_train[1]))
pyplot.show()


X=tf.placeholder(tf.float32,shape=[None,56,56],name='input image')
Y=tf.placeholder(tf.float32,shape=[None,56,56],name='label')
## convulotion layer started code starting from this point
input_layer=X

CLayer1=tfl.layers.conv.conv_2d(input_layer,nb_filter=64,filter_size=5,strides=[1,1,1,1],padding='same',activation='relu',regularizer='L2',name='layer1')
outlayer1=tfl.layers.conv.max_pool_2d(CLayer1,2)

CLayer2=tfl.layers.conv.conv_2d(outlayer1,nb_filter=128,filter_size=5,strides=[1,1,1,1],padding='same',activation='relu',regularizer='L2',name='layer2')
outlayer2=tfl.layers.conv.max_pool_2d(CLayer2,2)

CLayer3=tfl.layers.conv.conv_2d(outlayer2,nb_filter=128,filter_size=5,strides=[1,1,1,1],padding='same',activation='relu',regularizer='L2',name='layer3')
outlayer3=tfl.layers.conv.max_pool_2d(CLayer3,2)

ConnectedL1=tfl.layers.fully_connected(outlayer3,4096)
dropout1 = tfl.layers.core.dropout(ConnectedL1, 0.8)

ConnectedL2=tfl.layers.fully_connected(dropout1,4096)
dropout2 = tfl.layers.core.dropout(ConnectedL2, 0.8)

prediction = tfl.layers.core.fully_connected(dropout2, 2, activation='softmax', name='output')

#loss
cross_entropy = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(prediction+np.exp(-10)), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# session parameters
sess = tf.InteractiveSession()
#initialising variables
sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=False))
init = tf.global_variables_initializer()
sess.run(init)
saver = tf.train.Saver()
save_path="/Users/Enkay/Documents/Viky/python/img-classification/mark3.ckpt"
# grabbing the default graph
g = tf.get_default_graph()

# every operations in our graph
[op.name for op in g.get_operations()]

epoch=5
batch_size=4
no_itr_per_epoch=len(X_train)
n_test=len(X_test)
n_val=len(X_val)

# Now iterate over our dataset n_epoch times
for iteration in range(epoch):
    print("Iteration no: {} ".format(iteration))

    previous_batch = 0
    # Do our mini batches:
    for i in range(no_itr_per_epoch):
        current_batch = previous_batch + batch_size
        x_input = X_train[previous_batch:current_batch]
        x_images = np.reshape(x_input, [batch_size, 50, 50, 3])

        y_input = Y_train[previous_batch:current_batch]
        y_label = np.reshape(y_input, [batch_size, 2])
        previous_batch = previous_batch + batch_size

        _, loss = sess.run([train_step, cross_entropy], feed_dict={X: x_images,Y: y_label})
        if i % 100 == 0:
            print("Training loss : {}".format(loss))

    x_test_images = np.reshape(X_test[0:n_test], [n_test, 50, 50, 3])
    y_test_labels = np.reshape(Y_test[0:n_test], [n_test, 2])
    Accuracy_test = sess.run(accuracy,
                             feed_dict={
                                 X: x_test_images,
                                 Y: y_test_labels
                             })
    Accuracy_test = round(Accuracy_test * 100, 2)

    x_val_images = np.reshape(X_val[0:n_val], [n_val, 50, 50, 3])
    y_val_labels = np.reshape(Y_val[0:n_val], [n_val, 2])
    Accuracy_val = sess.run(accuracy,
                            feed_dict={
                                X: x_val_images,
                                Y: y_val_labels
                            })
    Accuracy_val = round(Accuracy_val * 100, 2)
    print("Accuracy ::  Test_set {} % , Validation_set {} % ".format(Accuracy_test, Accuracy_val))

错误:

File "E:/pythonproject2/TASK/__init__.py", line 67, in <module>
    X=tf.placeholder(tf.float32,shape=[None,56,56],name='input image')
  File "C:\Users\salma\Anaconda4\envs\lib\site-packages\tensorflow\python\ops\array_ops.py", line 1746, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "C:\Users\salma\Anaconda4\envs\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 4026, in _placeholder
    "Placeholder", dtype=dtype, shape=shape, name=name)
  File "C:\Users\salma\Anaconda4\envs\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 394, in _apply_op_helper
    with g.as_default(), ops.name_scope(name) as scope:
  File "C:\Users\salma\Anaconda4\envs\lib\site-packages\tensorflow\python\framework\ops.py", line 5621, in __enter__
    return self._name_scope.__enter__()
  File "C:\Users\salma\Anaconda4\envs\lib\contextlib.py", line 81, in __enter__
    return next(self.gen)
  File "C:\Users\salma\Anaconda4\envs\lib\site-packages\tensorflow\python\framework\ops.py", line 3949, in name_scope
    raise ValueError("'%s' is not a valid scope name" % name)
ValueError: 'input image' is not a valid scope name

1 个答案:

答案 0 :(得分:2)

您不能使用任意范围名称。问题在于

#include <functional>
#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>

template <class value_t,
          typename std::enable_if<std::is_floating_point<value_t>::value,
                                  int>::type = 0>
struct Calculator {
  Calculator() = default;

  explicit operator bool() {
    while (true) {
      std::cout << "Valid operations: +, -, *, /, 0 (exit)\n";
      std::cout << "What would you like to do: ";
      if (!getUserInput(operation)) {
        std::cerr << "Wrong input for operation\n";
        continue;
      }

      switch (operation) {
      case '0':
        return false;
      case '+':
      case '-':
      case '*':
      case '/':
        break;
      default:
        std::cerr << "Wrong input for operation\n";
        continue;
      }

      std::cout << "Please enter v1: ";
      if (!getUserInput(v1)) {
        std::cerr << "Wrong input for v1\n";
        continue;
      }

      std::cout << "Please enter v2: ";
      if (!getUserInput(v2)) {
        std::cerr << "Wrong input for v2\n";
        continue;
      }

      calculate();
      return true;
    }
  }
  friend std::ostream &operator<<(std::ostream &os, const Calculator &c) {
    os << "v1 " << c.operation << " v2 = " << c.result;
    return os;
  }

private:
  char operation;
  value_t v1, v2, result;
  std::string line;

  void calculate() {
    switch (operation) {
    case '+':
      return calculate(std::plus<value_t>{});
    case '-':
      return calculate(std::minus<value_t>{});
    case '*':
      return calculate(std::multiplies<value_t>{});
    case '/':
      return calculate(std::divides<value_t>{});
    case '0':
      return;
    }
  }
  template <class Func> void calculate(Func &&f) { result = f(v1, v2); }

  template <class T> bool getUserInput(T &t) {
    std::cin >> line;
    std::istringstream ss{line};
    return (ss >> t) && (ss >> std::ws).eof();
  }
};

int main() {
  Calculator<double> c;
  while (c)
    std::cout << c << '\n';
  return 0;
}

您不能在范围名称字符串中使用空格,您可以通过修改范围

来修复它
X=tf.placeholder(tf.float32,shape=[None,56,56],name='input image')

请参阅this one