Python Can';t计算张量流的精度

Python Can';t计算张量流的精度,python,numpy,tensorflow,deep-learning,data-science,Python,Numpy,Tensorflow,Deep Learning,Data Science,我创建了一个卷积神经网络。它预测mnist数据集的位数。它的工作没有任何错误,没有辍学。当我加上辍学,它给出了错误。由于错误,我无法计算准确度。 这是您的代码: import numpy as np from matplotlib.pyplot import imshow import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist=input_data.read_data_set

我创建了一个卷积神经网络。它预测mnist数据集的位数。它的工作没有任何错误,没有辍学。当我加上辍学,它给出了错误。由于错误,我无法计算准确度。 这是您的代码:

import numpy as np
from matplotlib.pyplot import imshow
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("data/mnist",one_hot=True,reshape=False)
def get_val(in_):
    for i in range(len(in_)):
        if round(_list[i])==1.:
            return i
        else:
            continue
X=tf.placeholder(tf.float32,[None,28,28,1])
Y=tf.placeholder(tf.float32,[None,10])
pkeep=Y=tf.placeholder(tf.float32)

wc1=tf.Variable(tf.random.truncated_normal([6,6,1,16],stddev=0.2))
bc1=tf.Variable(tf.random.truncated_normal([16],stddev=0.2))

wc2=tf.Variable(tf.random.truncated_normal([5,5,16,32],stddev=0.2))
bc2=tf.Variable(tf.random.truncated_normal([32],stddev=0.2))

wd1=tf.Variable(tf.random.truncated_normal([1568,256],stddev=0.2))
bd1=tf.Variable(tf.random.truncated_normal([256],stddev=0.2))

wd2=tf.Variable(tf.random.truncated_normal([256,64],stddev=0.2))
bd2=tf.Variable(tf.random.truncated_normal([64],stddev=0.2))

wdo=tf.Variable(tf.random.truncated_normal([64,10],stddev=0.2))
bdo=tf.Variable(tf.random.truncated_normal([10],stddev=0.2))

y=tf.nn.relu(tf.nn.conv2d(X,wc1,strides=[1,1,1,1],padding="SAME")+bc1)
y=tf.nn.max_pool(y,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
y=tf.nn.relu(tf.nn.conv2d(y,wc2,strides=[1,1,1,1],padding="SAME")+bc2)
y=tf.nn.max_pool(y,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
y=tf.reshape(y,(-1,1568))
y=tf.nn.tanh(tf.linalg.matmul(y,wd1)+bd1)
y=tf.nn.dropout(y,pkeep)
y=tf.nn.tanh(tf.linalg.matmul(y,wd2)+bd2)
y=tf.nn.dropout(y,pkeep)
y_pred=tf.nn.softmax(tf.linalg.matmul(y,wdo)+bdo)

xent=-tf.reduce_sum(Y*tf.math.log(y_pred))
l2=tf.reduce_sum(tf.math.square(Y-y_pred))

correct_pred=tf.equal(tf.argmax(Y,-1),tf.argmax(y_pred,-1))
accuracy=tf.reduce_mean(tf.cast(correct_pred,tf.float32))

optimizer=tf.train.AdamOptimizer(1e-3).minimize(xent)
images=[]

saver=tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(3001):
        bx,by=mnist.train.next_batch(50)
        sess.run(optimizer,feed_dict={X:bx,Y:by,pkeep:0.75})
        acc,x_l,l2_l=sess.run([accuracy,xent,l2],feed_dict={X:bx,Y:by,pkeep:1})
        print("Iteration",i,"Accuracy="+str(acc),"Cross Entropy Loss="+str(x_l),"Mean Squared Error="+str(l2_l))
        test_acc,test_x,test_l=sess.run([accuracy,xent,l2],feed_dict={X:mnist.test.images,Y:mnist.test.labels,pkeep:1})
        print("Train Accuracy="+str(test_acc),"Cross Entropy Loss="+str(test_x),"Mean Squared Error="+str(test_l),"\n\n")

    print("Model is trained with",test_acc,"accuracy")
    save_path = saver.save(sess, "tmp/model.ckpt")
    print("Model saved in path: %s" % save_path)  
这是你的错误。我在
tf.argmax()函数中得到错误。
---------------------------------------------------------------------------
InvalidArgumentError回溯(最后一次最近调用)
/调用中的usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py(self,fn,*args)
1355尝试:
->1356返回fn(*args)
1357除错误外。操作错误为e:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1340       return self._call_tf_sessionrun(
-> 1341           options, feed_dict, fetch_list, target_list, run_metadata)
   1342 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1428         self._session, options, feed_dict, fetch_list, target_list,
-> 1429         run_metadata)
   1430 

InvalidArgumentError: Expected dimension in the range [0, 0), but got -1
     [[{{node ArgMax_8}}]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-8-4c94f5a440b2> in <module>()
     56         bx,by=mnist.train.next_batch(50)
     57         sess.run(optimizer,feed_dict={X:bx,Y:by,pkeep:0.75})
---> 58         acc,x_l,l2_l=sess.run([accuracy,xent,l2],feed_dict={X:bx,Y:by,pkeep:1})
     59         print("Iteration",i,"Accuracy="+str(acc),"Cross Entropy Loss="+str(x_l),"Mean Squared Error="+str(l2_l))
     60         test_acc,test_x,test_l=sess.run([accuracy,xent,l2],feed_dict={X:mnist.test.images,Y:mnist.test.labels,pkeep:1})

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    948     try:
    949       result = self._run(None, fetches, feed_dict, options_ptr,
--> 950                          run_metadata_ptr)
    951       if run_metadata:
    952         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1171     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1172       results = self._do_run(handle, final_targets, final_fetches,
-> 1173                              feed_dict_tensor, options, run_metadata)
   1174     else:
   1175       results = []

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1348     if handle is None:
   1349       return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1350                            run_metadata)
   1351     else:
   1352       return self._do_call(_prun_fn, handle, feeds, fetches)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1368           pass
   1369       message = error_interpolation.interpolate(message, self._graph)
-> 1370       raise type(e)(node_def, op, message)
   1371 
   1372   def _extend_graph(self):

InvalidArgumentError: Expected dimension in the range [0, 0), but got -1
     [[node ArgMax_8 (defined at <ipython-input-8-4c94f5a440b2>:46) ]]

Errors may have originated from an input operation.
Input Source operations connected to node ArgMax_8:
 Placeholder_17 (defined at <ipython-input-8-4c94f5a440b2>:15)

Original stack trace for 'ArgMax_8':
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python3.6/dist-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python3.6/dist-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 450, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 480, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 432, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python3.6/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/python3.6/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-8-4c94f5a440b2>", line 46, in <module>
    correct_pred=tf.equal(tf.argmax(Y,-1),tf.argmax(y_pred,-1))
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py", line 138, in argmax
    return argmax_v2(input, axis, output_type, name)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py", line 175, in argmax_v2
    return gen_math_ops.arg_max(input, axis, name=name, output_type=output_type)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 948, in arg_max
    name=name)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py", line 788, in _apply_op_helper
    op_def=op_def)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 3616, in create_op
    op_def=op_def)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 2005, in __init__
    self._traceback = tf_stack.extract_stack()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in\u run\fn(feed\u dict、fetch\u list、target\u list、options、run\u元数据)
1340返回self.\u调用\u tf\u sessionrun(
->1341选项、提要、获取列表、目标列表、运行元数据)
1342
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in_call_tf_sessionrun(self、options、feed_dict、fetch_list、target_list、run_元数据)
1428自会话、选项、提要、获取列表、目标列表、,
->1429运行单元(元数据)
1430
InvalidArgumentError:预期维度在[0,0]范围内,但得到-1
[{{node ArgMax_8}}]]
在处理上述异常期间,发生了另一个异常:
InvalidArgumentError回溯(最后一次最近调用)
在()
56 bx,by=下一批(50)
57 sess.run(优化器,feed_dict={X:bx,Y:by,pkeep:0.75})
--->58 acc,x_l,l2_l=sess.run([accurity,xent,l2],feed_dict={x:bx,Y:by,pkeep:1})
59打印(“迭代”,i,“精度=”+str(acc),“交叉熵损失=”+str(x_l),“均方误差=”+str(l2_l))
60 test_acc,test_x,test_l=sess.run([accurity,xent,l2],feed_dict={x:mnist.test.images,Y:mnist.test.labels,pkeep:1})
/运行中的usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py(self、fetches、feed\u dict、options、run\u元数据)
948尝试:
949结果=self.\u运行(无、获取、馈送、选项、,
-->950运行(元数据(ptr)
951如果运行\u元数据:
952 proto_data=tf_session.tf_GetBuffer(运行元数据\u ptr)
/运行中的usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py(self、handle、fetches、feed、dict、options、run\u元数据)
1171如果final_获取或final_目标或(句柄和馈送dict_张量):
1172 results=self.\u do\u run(句柄、最终目标、最终获取、,
->1173提要(输入张量、选项、运行元数据)
1174其他:
1175结果=[]
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in_do_运行(self、handle、target_列表、fetch_列表、feed_dict、options、run_元数据)
1348如果句柄为“无”:
1349返回self.\u do\u call(\u run\u fn,feed,fetches,targets,options,
->1350运行单元(元数据)
1351其他:
1352返回self.\u do\u调用(\u prun\u fn、句柄、提要、获取)
/调用中的usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py(self,fn,*args)
1368通行证
1369 message=错误\u插值。插值(message,self.\u图形)
->1370提升类型(e)(节点定义、操作、消息)
1371
1372定义扩展图(自):
InvalidArgumentError:预期维度在[0,0]范围内,但得到-1
[[节点ArgMax_8(定义于:46)]]
错误可能源于输入操作。
连接到节点ArgMax_8的输入源操作:
占位符_17(定义于:15)
“ArgMax_8”的原始堆栈跟踪:
文件“/usr/lib/python3.6/runpy.py”,第193行,在“运行”模块中作为“主”
“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
文件“/usr/lib/python3.6/runpy.py”,第85行,在运行代码中
exec(代码、运行\全局)
文件“/usr/local/lib/python3.6/dist packages/ipykernel_launcher.py”,第16行,在
app.launch_new_instance()
文件“/usr/local/lib/python3.6/dist-packages/traitlets/config/application.py”,第658行,在launch_实例中
app.start()
文件“/usr/local/lib/python3.6/dist-packages/ipykernel/kernelapp.py”,第477行,开头
ioloop.ioloop.instance().start()
文件“/usr/local/lib/python3.6/dist-packages/tornado/ioloop.py”,第888行,开头
handler_func(fd_obj,事件)
文件“/usr/local/lib/python3.6/dist packages/tornado/stack\u context.py”,第277行,在空包装中
返回fn(*args,**kwargs)
文件“/usr/local/lib/python3.6/dist packages/zmq/eventloop/zmqstream.py”,第450行,在事件句柄中
self.\u handle\u recv()
文件“/usr/local/lib/python3.6/dist packages/zmq/eventloop/zmqstream.py”,第480行,在
self.\u运行\u回调(回调,消息)
文件“/usr/local/lib/python3.6/dist packages/zmq/eventloop/zmqstream.py”,第432行,在运行回调中
回调(*args,**kwargs)
文件“/usr/local/lib/python3.6/dist packages/tornado/stack\u context.py”,第277行,在空包装中
返回fn(*args,**kwargs)
dispatcher中的文件“/usr/local/lib/python3.6/dist packages/ipykernel/kernelbase.py”,第283行
返回self.dispatch\u shell(流,消息)
文件“/usr/local/lib/python3.6/dist packages/ipykernel/kernelbase.py”,第235行,在dispatch_shell中
处理程序(流、标识、消息)
文件“/usr/local/lib/python3.6/dist packages/ipykernel/kernelbase.py”,第399行,在执行请求中
用户\u表达式,允许\u stdin)
文件“/usr/local/lib/python3.6/dist packages/ipykernel/ipkernel.py”,第196行,在do_execute中
res=shell.run\u单元格(代码,store\u history=store\u history,silent=silent)
文件“/usr/local/lib/python3.6/dist packages/ipykernel/zmqshell.py”,第533行,在run_单元格中
返回超级(ZMQInteractiveShell,self)。运行单元格(*args,**kwargs)
文件“/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py”,第2718行,在运行单元中
交互性=交互性,编译器=com