gpt4 book ai didi

python - 如何将 tensorflow 图中的中间结果作为 [inp] 输入到 tf.py_func 中?

转载 作者:行者123 更新时间:2023-11-30 09:00:13 32 4
gpt4 key购买 nike

我已经使用 numpy 实现了自定义池层,如下所示:

def pooling_np(input):
#input:[batch,h,v,channel]
#output:[batch,h/2,v/2,channel]
pooling = np.empty([input.shape[0], input.shape[1]/2, input.shape[2]/2, input.shape[3]])
for i_batch in range(input.shape[0]):
for j_channel in range(input.shape[-1]):
max_id = np.argmax(input[i_batch,:,:,j_channel])
#[i_batch,max_h,max_v,j_channel]
max_h = max_id / input.shape[1]
max_v = max_id % input.shape[1]
#begin point:(left,up)
left = max(min(max_h - input.shape[1]/4, input.shape[1]/2), 0)
up = max(min(max_v - input.shape[2]/4, input.shape[2]/2), 0)
pooling[i_batch,:,:,j_channel] = input[i_batch,left:left+input.shape[1]/2,up:up+input.shape[2]/2,j_channel]
return pooling

然后我想使用 tf.py_func 将这个新的池化层合并到 tensorflow alexnet 图中,如下所示:

with graph.as_default():
...
#conv5
#conv(3, 3, 256, 1, 1, group=2, name='conv5')
k_h = 3; k_w = 3; c_o = 256; s_h = 1; s_w = 1; group = 2
conv5W = tf.Variable(net_data["conv5"][0])
conv5b = tf.Variable(net_data["conv5"][1])
conv5_in = conv(conv4, conv5W, conv5b, k_h, k_w, c_o, s_h, s_w, padding="SAME", group=group)
conv5 = tf.nn.relu(conv5_in)

#newpool5:custom a new pooling layer
newpool5 = tf.py_func(adaptive_pooling_np, [conv5], tf.float32)
adaptivepool5.set_shape([conv5.get_shape()[0],conv5.get_shape()[1]/2,conv5.get_shape()[2]/2,conv5.get_shape()[-1]])
adaptivepool5 = tf.cast(adaptivepool5, tf.float32)

#fc6
#fc(4096, name='fc6')
fc6W = tf.Variable(net_data["fc6"][0])
fc6b = tf.Variable(net_data["fc6"][1])
fc6 = tf.nn.relu_layer(tf.reshape(newpool5, [-1, int(prod(newpool5.get_shape()[1:]))]), fc6W, fc6b)
...
with tf.Session(graph=graph, config = config) as session:
tf.global_variables_initializer().run()
print('Initialized')
t = time.time()
feed_dict = {x:testset}
output = session.run(prob, feed_dict = feed_dict)

我想使用 conv5 作为 tf.py_func 的 [inp],因为我无法创建 tf.placeholder 并在 tf session 开始时提供图形的中间值(此处:conv5)。

但是,出现这样的错误:

    Initialized
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
<ipython-input-19-2b38ea266e1a> in <module>()
6 t = time.time()
7 feed_dict = {x:testset}
----> 8 output = session.run(prob, feed_dict = feed_dict)
9 #adaptivepooling5 = session.run(adappool5, feed_dict = feed_dict)
10 print(conv5.shape)

/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
765 try:
766 result = self._run(None, fetches, feed_dict, options_ptr,
--> 767 run_metadata_ptr)
768 if run_metadata:
769 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
963 if final_fetches or final_targets:
964 results = self._do_run(handle, final_targets, final_fetches,
--> 965 feed_dict_string, options, run_metadata)
966 else:
967 results = []

/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1013 if handle is None:
1014 return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1015 target_list, options, run_metadata)
1016 else:
1017 return self._do_call(_prun_fn, self._session, handle, feed_dict,

/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
1033 except KeyError:
1034 pass
-> 1035 raise type(e)(node_def, op, message)
1036
1037 def _extend_graph(self):

InvalidArgumentError: 0-th value returned by pyfunc_8 is double, but expects float
[[Node: PyFunc = PyFunc[Tin=[DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_8", _device="/job:localhost/replica:0/task:0/cpu:0"](Relu_4/_3)]]
[[Node: PyFunc/_5 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_86_PyFunc", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

Caused by op u'PyFunc', defined at:
File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py", line 3, in <module>
app.launch_new_instance()
File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 658, in launch_instance
app.start()
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 474, in start
ioloop.IOLoop.instance().start()
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 887, in start
handler_func(fd_obj, events)
File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 276, in dispatcher
return self.dispatch_shell(stream, msg)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
handler(stream, idents, msg)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 390, in execute_request
user_expressions, allow_stdin)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/zmqshell.py", line 501, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
if self.run_code(code, result):
File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-17-90b8573e003c>", line 91, in <module>
adaptivepool5 = tf.py_func(adaptive_pooling_np, [conv5], tf.float32)
File "/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/script_ops.py", line 189, in py_func
input=inp, token=token, Tout=Tout, name=name)
File "/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_script_ops.py", line 40, in _py_func
name=name)
File "/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op
op_def=op_def)
File "/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2327, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/yifan/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1226, in __init__
self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): 0-th value returned by pyfunc_8 is double, but expects float
[[Node: PyFunc = PyFunc[Tin=[DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_8", _device="/job:localhost/replica:0/task:0/cpu:0"](Relu_4/_3)]]
[[Node: PyFunc/_5 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_86_PyFunc", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

如何在tensorflow中使用这个numpy函数?

最佳答案

您的 py_func 返回一个 tf.float64 而不是 tf.float32,这是声明的类型。

换行说

newpool5 = tf.py_func(adaptive_pooling_np, [conv5], tf.float64)

一切都会好起来的。

关于python - 如何将 tensorflow 图中的中间结果作为 [inp] 输入到 tf.py_func 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084137/

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