Cannot evaluate tensor using eval No default session is registered 错误问题的解决

今天下午遇到一个神奇的现象

# life is short, you need use python to create something!
# author    TuringEmmy
# time      11/29/18 3:25 PM
# project   DeepLearing

import os
print(os.listdir("./"))

import tensorflow as tf
ret=tf.one_hot([[13, 45, 18, 18], [19, 16, 15, 89]], depth=26, axis=1, on_value=1.0).eval()
# depth编码之后的数量
# on_value是就写1.0
print(ret)

然后就报下面的错误

/home/python/.virtualenvs/DeepLearning/bin/python /mnt/hgfs/WorkSpace/DeepLearingStudy/TensorFlowStudy/tensorflow08/demo.py
['CaptchaRecognize', 'demo.py', 'review.md', '__init__.py', '验证码的识别原理.py', '验验证码识别程序的流程以及图片的处理.py']
Traceback (most recent call last):
  File "/mnt/hgfs/WorkSpace/DeepLearingStudy/TensorFlowStudy/tensorflow08/demo.py", line 10, in <module>
    ret=tf.one_hot([[13, 45, 18, 18], [19, 16, 15, 89]], depth=26, axis=1, on_value=1.0).eval()
  File "/home/python/.virtualenvs/DeepLearning/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 567, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "/home/python/.virtualenvs/DeepLearning/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 3715, in _eval_using_default_session
    raise ValueError("Cannot evaluate tensor using `eval()`: No default "
ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an explicit session to `eval(session=sess)`

Process finished with exit code 1

经过网上搜集答案最终解决
添加会话即可:

with tf.Session() as sess:

原来代码修改如下:

import tensorflow as tf
with tf.Session() as sess:
    ret=tf.one_hot([[13, 45, 18, 18], [19, 16, 15, 89]], depth=26, axis=1, on_value=1.0).eval()
    # depth编码之后的数量
    # on_value是就写1.0
    print(ret)

最终刚运行结果如下:

[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [1. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 1. 1.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 1. 0.]
  [0. 1. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [1. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值