TensorFlow(2) 基本操作

创建变量

import tensorflow as tf
#创建变量
w = tf.Variable([[0.5,1.0]]) #行向量
x = tf.Variable([[2.0],[1.0]]) #列向量
y = tf.matmul(w,x) #矩阵乘法
print(y) #输出的是tensor的格式

#变量运行前必须做初始化操作
init_op = tf.global_variables_initializer()
with tf.Session() as sess: #创建运行会话
    sess.run(init_op)
    print(y.eval())

特殊矩阵和常量

# 零矩阵   
t1 = tf.zeros([3,4],tf.float32)
t2 = tf.zeros_like(t1)
# 单位矩阵
t3 = tf.ones([2,3],tf.int32)
t4 = tf.ones_like(t3)
# 创建一维常量
t5 = tf.constant([1,2,3,4,5,6,7])
# 创建二维常量
t6 = tf.constant(-1.0,shape=[2,3])
# 等差数列
t7 = tf.linspace(10.0,12.0,3,name="linspace") #[10.0,11.0,12.0]

(start,limit,delta) = (3,18,3)
t8 = tf.range(start,limit,delta)  #[3,6,9,12,15]

sess = tf.Session()
print(sess.run(t1))
print(sess.run(t2))
print(sess.run(t3))
print(sess.run(t4))
print(sess.run(t5))
print(sess.run(t6))
print(sess.run(t7))
print(sess.run(t8))
sess.close()

创建随机值

#创建高斯分布
norm = tf.random_normal([2,3],mean=-1,stddev=4)  #2行3列矩阵,均值为-1,方差为4

# 乱序洗牌操作
c = tf.constant([[1,2],[3,4],[5,6]])
shuff = tf.random_shuffle(c)

sess = tf.Session()
print(sess.run(norm))
print(sess.run(shuff))

示例程序

state = tf.Variable(0)
new_value = tf.add(state,tf.constant(1))
update = tf.assign(state,new_value)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(state))
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

保存模型

# 保存训练模型 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.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(init_op)
    save_path = saver.save(sess,"D://ml//model//test")
    print("Model saved in file:",save_path)

NumPy数据转换成TensorFlow数据

import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
    print(sess.run(ta))

tf.placeholder

  • 作用:申请session会话的一个空间,为未来计算流使用
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
    print(sess.run([output],feed_dict={input1:[7.],input2:[2.]})) # 数据以字典形式输入

你可能感兴趣的:(TensorFlow(2) 基本操作)