我正在尝试在tensorflow python中创建一个SavedModel(*。pb)文件。我将在Java中使用这个protobuf文件。但是,运行以下代码会给我一个权限被拒绝的错误。我在Windows机器上运行tensorflow-gpu。
import cv2
import tensorflow as tf
import os
import numpy as np
from imutils import paths
from keras.preprocessing.image import img_to_array
def load_data(data_dir):
imagePaths = sorted(list(paths.list_images(data_dir)))
print("[INFO] loading images...")
data = []
labels = []
for imagePath in imagePaths:
# load the image, pre-process it, and store it in the data list
image = cv2.imread(imagePath)
reimage = cv2.resize(image, (64,16))
reimage=reimage.astype(np.float32)
reimage=np.multiply(reimage,1.0/255.0)
data.append(reimage)
label = imagePath.split(os.path.sep)[-2]
if label=="classa":
label=0
if label=="classb":
label=1
if label=="classc":
label=2
ll=int(label)
labels.append(ll)
data=np.array(data)
print(data.shape)
labels=np.array(labels)
print(labels.shape)
return data, labels
images_a,labels_a=load_data("ttt")
graph=tf.Graph()
with graph.as_default():
images_ph=tf.placeholder(tf.float32,[None,16,64,3],name='input')
labels_ph=tf.placeholder(tf.int32,[None],name='labels')
dataset=tf.data.Dataset.from_tensor_slices((images_a,labels_a)).repeat().batch(100)
iter=dataset.make_one_shot_iterator()
next_element=iter.get_next()
conv1 = tf.layers.conv2d(
inputs=images_ph,
filters=32,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
pool2_flat = tf.reshape(pool1, [-1,32*8*32])
dense = tf.layers.dense(inputs=pool2_flat, units=1000, activation=tf.nn.relu)
dropout = tf.layers.dropout(inputs=dense, rate=0.4)
logits = tf.layers.dense(inputs=dropout, units=3)
predicted_labels=tf.argmax(logits,1)
loss=tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels_ph,logits=logits))
train=tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
init=tf.global_variables_initializer()
with tf.Session(graph=graph) as session:
session.run(init)
for i in range(101):
x,y=session.run(next_element)
loss_values=session.run([train,loss],feed_dict={images_ph:x,labels_ph:y})
if i%10==0:
print("Loss: ",loss_values)
builder=tf.saved_model.builder.SavedModelBuilder("/pModel")
builder.add_meta_graph_and_variables(session,[tf.saved_model.tag_constants.SERVING],
signature_def_map={
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:tf.saved_model.signature_def_utils.build_signature_def(
inputs={"input":tf.saved_model.utils.build_tensor_info(images_ph)},
outputs={"output":tf.saved_model.utils.build_tensor_info(logits)})
})
builder.save()
test_images,test_labels=load_data("test")
predicted=session.run(predicted_labels,feed_dict={images_ph:test_images})
match_count=sum([int(y==y_) for y,y_ in zip (test_labels, predicted)])
accuracy=match_count/len(test_labels)
print("Accuracy: {:.3f}".format(accuracy))
print(tf.saved_model.tag_constants.SERVING)
运行时会出现以下错误:
2018-04-19 13:32:10.043715: W C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\35\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES failed at save_restore_v2_ops.cc:220 : Permission denied: Failed to create a directory: /; Permission denied
Traceback (most recent call last):
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1361, in _do_call
return fn(*args)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _run_fn
target_list, status, run_metadata)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 516, in __exit__
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.PermissionDeniedError: Failed to create a directory: /; Permission denied
[[Node: save/MergeV2Checkpoints = MergeV2Checkpoints[delete_old_dirs=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](save/MergeV2Checkpoints/checkpoint_prefixes, _arg_save/Const_0_0)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "tensorv4.py", line 94, in <module>
outputs={"output":tf.saved_model.utils.build_tensor_info(logits)})
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\saved_model\builder_impl.py", line 392, in add_meta_graph_and_variables
saver.save(sess, variables_path, write_meta_graph=False, write_state=False)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1654, in save
{self.saver_def.filename_tensor_name: checkpoint_file})
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 905, in run
run_metadata_ptr)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1137, in _run
feed_dict_tensor, options, run_metadata)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1355, in _do_run
options, run_metadata)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1374, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.PermissionDeniedError: Failed to create a directory: /; Permission denied
[[Node: save/MergeV2Checkpoints = MergeV2Checkpoints[delete_old_dirs=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](save/MergeV2Checkpoints/checkpoint_prefixes, _arg_save/Const_0_0)]]
Caused by op 'save/MergeV2Checkpoints', defined at:
File "tensorv4.py", line 94, in <module>
outputs={"output":tf.saved_model.utils.build_tensor_info(logits)})
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\saved_model\builder_impl.py", line 386, in add_meta_graph_and_variables
allow_empty=True)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1293, in __init__
self.build()
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1302, in build
self._build(self._filename, build_save=True, build_restore=True)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1339, in _build
build_save=build_save, build_restore=build_restore)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 787, in _build_internal
save_tensor = self._AddShardedSaveOps(filename_tensor, per_device)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 411, in _AddShardedSaveOps
return self._AddShardedSaveOpsForV2(filename_tensor, per_device)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 393, in _AddShardedSaveOpsForV2
sharded_prefixes, checkpoint_prefix, delete_old_dirs=True)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 379, in merge_v2_checkpoints
delete_old_dirs=delete_old_dirs, name=name)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 3271, in create_op
op_def=op_def)
File "C:\Users\MoWHS\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1650, in __init__
self._traceback = self._graph._extract_stack() # pylint: disable=protected-access
PermissionDeniedError (see above for traceback): Failed to create a directory: /; Permission denied
[[Node: save/MergeV2Checkpoints = MergeV2Checkpoints[delete_old_dirs=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](save/MergeV2Checkpoints/checkpoint_prefixes, _arg_save/Const_0_0)]]
对于出了什么问题的任何想法。我尝试使用管理员权限运行但无济于事