gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:58:44 26 4
gpt4 key购买 nike

我正在尝试对狗和猫进行分类;为此,我使用 CNN 模型,但是当我将图像矩阵设置为 tf.placeholder 时,我收到错误“placeholder return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)”,但我不明白问题所在。

我该如何解决这个问题?

我的代码:

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

最佳答案

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

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

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

X=tf.placeholder(tf.float32,shape=[None,56,56],name='input_image')

参见What are the contraints for tensorflow scope names?

关于python - 占位符返回 gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com