模块使用问题
问题1
AttributeError: module ‘tensorflow’ has no attribute ‘Session’
解析
当使用Session时,报错AttributeError: module ‘tensorflow’ has no attribute ‘Session’:
问题产生的原因:无法执行sess.run()的原因是tensorflow版本不同导致的,tensorflow版本2.0无法兼容版本1.0.
经过学习和测验,解决办法:
把代码语句 sess= tf.Session() 改为
sess= tf.compat.v1.Session() #版本2.0的函数
问题2
RuntimeError: The Session graph is empty. Add operations to the graph before calling run()。
解析
在程序开始部分添加以下代码:tf.compat.v1.disable_eager_execution()
tf.compat.v1.disable_eager_execution() #保证sess.run()能够正常运行,此函数只能在创建任何图、运算或张量之前调用。它可以用于从TensorFlow 1.x到2.x的复杂迁移项目的程序开头。
版本问题
tensorflow 版本与python版本有关系
- tensorflow == 1.1.0 在python 3.6及以上的版本中并无法安装,至少亲测在python 3.5.4版本中能使用。希望在使用时注意每个软件及工具的对应版本。
- 所以在使用tensorflow == 2.0.0及以上版本的时候,注意选择python的版本。最好做项目的时候根据项目的要求选择。
- python2.7 版本和 tensorflow 2.0 版本两个版本是比较具有分水岭意义的界定版本。
函数与模块
- tf.reduce_mean():对张量求均值
# 'x' is [[1., 1.] # [2., 2.]] tf.reduce_mean(x) ==> 1.5 tf.reduce_mean(x, 0) ==> [1.5, 1.5] tf.reduce_mean(x, 1) ==> [1., 2.]
- tf.square():计算张量中元素的平方
- tf.random_uniform():从均匀分布中输出随机值
- tf.random_shuffle():沿着张量的第一维度随机洗牌
[[1, 2], [[5, 6],
[3, 4], ==> [1, 2],
[5, 6]] [3, 4]]
-
tf.truncated_normal(shape,mean=0.0,stddev=1.0,dtype=dtypes.float32,
seed=None, name=None):从截断的正态分布中输出随机值。
生成的值遵循具有指定的均值和标准差的正态分布,除了那些与均值相差超过2个标准差的值会被删除,然后重新选取。截断的意义是指随机数与均值的差值若大于两倍的标准差,则重新生成。也就是说,生成的随机数取值范围: [ mean - 2 * stddev, mean + 2 * stddev ] 。
shape:一个一维整数张量或Python数组。输出张量的形状。
mean: 类型为dtype
的0-D张量或Python值。一个0-D Tensor或Python类型dtype
的值。截断的正态分布的平均值。
stddev: 0-D张量或类型为dtype
的Python值。截断正态分布的标准差。
dtype.输出的类型。输出的类型
seed:输出的类型。一个Python整数。用于为分布创建一个随机种子。 -
tf.Variable(tf.truncated_normal(shape=[INPUT_NODE, LAYER1_NODE], stddev=0.1))
使用Variable,一个Variable代表一个可修改的张量,它可以用于计算输入值,也可以在计算中被修改。 -
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32,
seed=None, name=None):输出正态分布的随机值。
参数简介:
shape.一个1-D整数Tensor或Python数组。一个1-D整数Tensor或Python数组。输出张量的形状。
mean: 一个0-D的类型为dtype
的张量或Python数值。0-D Tensor或Python类型dtype
的值。正态分布的平均值。
stddev: 0-D Tensor或Python类型dtype
的值。正态分布的标准差。
dtype.输出的类型。输出的类型
seed:输出的类型。一个Python整数。用于为分布创建一个随机种子。 -
tf.argmax():
tf.argmax是从一个 tensor中寻找最大值的序号, tf.argmax(y, 1)就是求各个预测的数字y中概率最大的一个,而 tf.argmax(y_, 1)则是找到样本的真实数字类别。而 tf.equal方法则是用来判断预测数字类别是否就是正确的类别,最后返回计算分类是否正确的操作。. -
tf.convert_to_tensor(y.eval()):把numpy转为tensor类数据
y = tf.nn.relu([1, 0, -0.2, 2, 3, -5])
print(y)
# Tensor("Relu:0", shape=(6,), dtype=float32)
with tf.Session() as sess:
print(y)
print(y.eval())
# Tensor("Relu:0", shape=(6,), dtype=float32)
# [1. 0. 0. 2. 3. 0.]
# 使用 tf.convert_to_tensor函数把numpy转为tensor类数据
res = tf.convert_to_tensor(y.eval())
print(res)
# Tensor("Const:0", shape=(6,), dtype=float32)
如何查看 tensor类型的数据的值。因为我们在建立图(Graph)的时候,只定义tensor的结构形状信息,并没有执行数据的操作,而print函数只能打印输出 tensor的 shape信息,而不能直接显示tensor的值。所以我们需要执行会话session,在会话中打印值,而是由.eval() 相当于把tensor类型数据转为numpy,再输出。
- tf.assign(ref, value,…) :通过给’ref’赋值来更新它。
参数介绍:
ref:一个可变化的Tensor
。应该来自一个Variable
节点。可以是未初始化的。
value:一个Tensor应该来自Variable节点。一个Tensor
。必须与ref
有相同的类型。要分配给变量的值。