Tensorflow 基础用法
- Tensorflow 基础用法
- tf.Variable(initializer,name)
- tf.matmul(w, x)
- tf.global_variables_initializer
- AttributeError: module 'tensorflow' has no attribute 'random_normal'
- AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'
- AttributeError: module 'tensorflow' has no attribute 'Session'
- 生成tensor
- 生成序列
- 生成随机数
- random_shuffle(value, seed=None, name=None)
- AttributeError: module 'tensorflow' has no attribute 'assign'
- AttributeError: module 'tensorflow_core._api.v2.train' has no attribute 'Saver'
- AttributeError: module 'tensorflow' has no attribute 'placeholder'
- AttributeError: module 'tensorflow' has no attribute 'mul'
Tensorflow 基础用法
# !pip install tensorflow
tf.Variable(initializer,name)
- 参数:initializer是初始化参数
- name:是可自定义的变量名称
- 推荐使用float32
tf.matmul(w, x)
- w ,x 的维度和类型必须一致。
- 输入w ,x 必须是矩阵或者维度大于2的tensor。
- 专门矩阵或者tensor乘法,而不是矩阵元素对应元素相乘。
tf.global_variables_initializer
- 在TensorFlow的世界里,变量的定义和初始化是分开的,所有关于图变量的赋值和计算都要通过tf.Session的run来进行。
- 想要将所有图变量进行集体初始化时应该使用tf.global_variables_initializer。
AttributeError: module ‘tensorflow’ has no attribute ‘random_normal’
tf.random_normal- tf.random.normal
tf.random.normal(shape=[4,3],mean=0,stddev=1)
<tf.Tensor 'random_normal_2:0' shape=(4, 3) dtype=float32>
AttributeError: module ‘tensorflow’ has no attribute ‘global_variables_initializer’
tf.global_variables_initializer()- tf.compat.v1.global_variables_initializer()
AttributeError: module ‘tensorflow’ has no attribute ‘Session’
-
tf.Session() -
tf.compat.v1.Session()
-
当eager execution开启的时候,loss应该是一个Python函数。
-
在Tensorflow 2.0 中,eager execution 是默认开启的。
-
所以,需要先关闭eager execution
-
tf.compat.v1.disable_eager_execution()
import tensorflow as tf
# 创建变量
v1=tf.Variable(tf.random.normal(shape=[4,3],mean=0,stddev=1),name='v1')
v2=tf.Variable(tf.constant(2),name='v2')
v3=tf.Variable(tf.ones([4,3]),name='v3')
# 个别变量初始化
# init_op = v3.initializer()
tf.compat.v1.disable_eager_execution()
# 将所有图变量进行集体初始化
init_op = tf.compat.v1.global_variables_initializer()
# 创建会话
with tf.compat.v1.Session() as sess:
sess.run(init_op)
# 输出变量值
print(sess.run(v1))
print(sess.run(v2))
print(sess.run(v3))
[[ 1.2573713 -0.21383092 0.2820194 ]
[ 1.3747884 -0.9983631 -0.75616807]
[-0.9669721 0.87451565 0.83416873]
[-0.47897404 -0.21675622 0.9892974 ]]
2
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
import tensorflow as tf
# python里创建变量
a = 3
# tensorflow里创建变量
# Create a variable.
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])
y = tf.matmul(w, x)
# 推荐写法
# variables have to be explicitly initialized before you can run Ops
init_op = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init_op)
# 输出变量值
print (y.eval())
# 不推荐
# sess.run(init_op)
[[2.]]
生成tensor
tf.zeros(shape, dtype=tf.float32, name=None)
tf.zeros_like(tensor, dtype=None, name=None)
tf.constant(value, dtype=None, shape=None, name='Const')
tf.fill(dims, value, name=None)
tf.ones_like(tensor, dtype=None, name=None)
tf.ones(shape, dtype=tf.float32, name=None)
生成序列
tf.range(start, limit, delta=1, name='range')
tf.linspace(start, stop, num, name=None)
生成随机数
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
tf.random_uniform(shape, minval=0.0, maxval=1.0, dtype=tf.float32, seed=None, name=None)
tf.random_shuffle(value, seed=None, name=None)
# 数据类型:推荐float32
# 与numpy类似
# 创建0填充矩阵
tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]]
tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]
# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.ones_like(tensor) ==> [[1, 1, 1], [1, 1, 1]]
# 创建常量
# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0 11.0 12.0]
# 'start' is 3
# 'limit' is 18
# 'delta' is 3
tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]
random_shuffle(value, seed=None, name=None)
参数:
- value:将被打乱的张量.
- seed:一个 Python 整数.用于为分布创建一个随机种子.查看 tf.set_random_seed 行为.
- name:操作的名称(可选).
返回:
- 与 value 具有相同的形状和类型的张量,沿着它的第一个维度打乱.
举例
随机地将张量沿其第一维度打乱.
张量沿着维度0被重新打乱,使得每个 value[j] 被映射到唯一一个 output[i].例如,一个 3x2 张量可能出现的映射是:
[[1, 2], [[5, 6],
[3, 4], ==> [1, 2],
[5, 6]] [3, 4]]
# 创建随机矩阵(2,3)
# mean:均值
# stddev:方差
norm = tf.random.normal([2, 3], mean=-1, stddev=4)
# 创建变量(3,2)
c = tf.constant([[1, 2], [3, 4], [5, 6]])
# Shuffle the first dimension of a tensor
shuff = tf.random.shuffle(c)
# 推荐使用with结构
# Each time we run these ops, different results are generated
sess = tf.compat.v1.Session()
print (sess.run(norm))
print (sess.run(shuff))
[[-2.4224548 0.9436902 -2.3370779]
[-5.3113627 -4.1880174 -3.6686687]]
[[1 2]
[5 6]
[3 4]]
AttributeError: module ‘tensorflow’ has no attribute ‘assign’
tf.assign()- tf.compat.v1.assign()
# 变量
state = tf.Variable(0)
# 常量
one = tf.constant(1)
# 对常量与变量进行简单的加法操作
# 这点需要说明的是: 在TensoorFlow中,所有的操作op,变量都视为节点
# tf.add() 的意思就是在tf的默认图中添加一个op,这个op是用来做加法操作的。
new_value = tf.add(state, one)
# 赋值操作。将new_value的值赋值给update变量。
update = tf.compat.v1.assign(state, new_value)
# 此处用于初始化变量。但是这句话仍然不会立即执行。
# 需要通过sess来将数据流动起来 。
# 切记:所有的运算都应在在session中进行。
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess: # 此处自动开启一个session
# 对变量进行初始化,执行(run)init语句
sess.run(init)
# 打印输出
print(sess.run(state))
for _ in range(3):
sess.run(update)
print(sess.run(state))
0
1
2
3
AttributeError: module ‘tensorflow_core._api.v2.train’ has no attribute ‘Saver’
tf.train.Saver()- tf.compat.v1.train.Saver()
# 保存变量,也可以指定保存的内容
#tf.train.Saver
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])
y = tf.matmul(w, x)
init_op = tf.compat.v1.global_variables_initializer()
saver = tf.compat.v1.train.Saver()
with tf.compat.v1.Session() as sess:
sess.run(init_op)
# Do some work with the model.
# Save the variables to disk.
save_path = saver.save(sess, "model/test")
print ("Model saved in file: ", save_path)
Model saved in file: model/test
# numpy 转换 tensorflow
# 不推荐
import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.compat.v1.Session() as sess:
print(sess.run(ta))
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
AttributeError: module ‘tensorflow’ has no attribute ‘placeholder’
tf.placeholder(tf.float32)- tf.compat.v1.placeholder(tf.float32)
AttributeError: module ‘tensorflow’ has no attribute ‘mul’
tf.mul(input1, input2)- tf.multiply(input1, input2)
# 占位
input1 = tf.compat.v1.placeholder(tf.float32)
input2 = tf.compat.v1.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.compat.v1.Session() as sess:
print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
[array([14.], dtype=float32)]