Python调用TensorFlow出现“Cannot evaluate tensor using `eval()`: No default session is registered”错误问题的解决

转载请注明出处:http://blog.csdn.net/dongdong9223/article/details/78968824 >本文出自【我是干勾鱼的博客】

Python如下代码:

#coding=utf-8

import tensorflow as tf
# NumPy是一个科学计算的工具包,这里通过NumPy工具包生成模拟数据集,
from numpy.random import RandomState

v = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])

'''
#这段代码之前如果没有添加session,会报错:Cannot evaluate tensor using `eval()`: No default session is registered
print tf.clip_by_value(v, 2.5, 4.5).eval()

为避免报错应该使用下面的方式:
with tf.Session() as sess:
    print tf.clip_by_value(v, 2.5, 4.5).eval()

'''

with tf.Session() as sess:
    print tf.clip_by_value(v, 2.5, 4.5).eval()

会报如下错误:

Traceback (most recent call last):
File “constant_eval.py”, line 10, in
print tf.clip_by_value(v, 2.5, 4.5).eval()
File “/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py”, line 575, in eval
return _eval_using_default_session(self, feed_dict, self.graph, session)
File “/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py”, line 3619, 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)

如图所示:

Python调用TensorFlow出现“Cannot evaluate tensor using `eval()`: No default session is registered”错误问题的解决_第1张图片

可以如代码所示增加session的定义:

with tf.Session() as sess:

让print在其中运行就可以了,如图所示:

这里写图片描述

你可能感兴趣的:(Python)