import tensorflow as tf
创建变量和执行
w = tf.Variable([[0.5, 2.0]]) #行向量
x = tf.Variable([[2.0], [1.0]]) #列向量
y = tf.matmul(w, x)
执行之前必须对变量进行初始化, 创建Session()
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(y.eval())
[[3.]]
一些常见的初始化操作
a = tf.zeros([2,3], float)
b = tf.ones([3,4], float)
c = tf.zeros_like(a)
d = tf.ones_like(b)
e = tf.constant([1,2,3,4,5])
f = tf.constant(-2, shape=[2,3])
g = tf.linspace(4.0,6.0,3, name='linspace')
h = tf.range(1,10,3)
shuffle洗牌
#生成2行3列符合均值为-1,且方差为4的正态分布数据
norm = tf.random_normal([2,3],mean=-1, stddev=9)
c = tf.constant([[1, 2], [3, 4], [5, 6]])
shuffle = tf.random_shuffle(c)
sess = tf.Session()
print(sess.run(norm))
print(sess.run(shuffle))
[[ 5.744781 4.8351593 -3.1881056]
[-9.752258 8.690398 -8.590118 ]]
[[3 4]
[5 6]
[1 2]]
赋值操作
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))
0
1
2
3
数据保存 tf.train.Saver()
w = tf.Variable([[0.5, 2.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, 'F://PythonAI//DeepLearning')
print ('Model saved in file:', save_path)
Model saved in file: F://PythonAI//DeepLearning
import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
print(sess.run(ta))
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
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.]}))
[array([14.], dtype=float32)]