如果您对机器学习与人工智能感兴趣,这里极力推荐学习教程:莫烦 python
教程以视频形式手把手敲代码,是我学习过的最好教程!
session 会话
1 2 3 4 5 6
| import tensorflow as tf
matrix1 = tf.constant([[3,3]])# 常量,1行2列矩阵 matrix2 = tf.constant([[2], [2]])# 常量2行1列矩阵 product = tf.matmul(matrix1,matrix2)# 矩阵乘法,matrix multiply----np.dot(m1,m2)
|
执行方式一
1 2 3 4
| sess = tf.Session() result = sess.run(product) print(result) sess.close()# 有此句更为规范
|
运行结果:
[[12]]
执行方式二
1 2 3
| with tf.Session() as sess: result2 = sess.run(product) print(result2)
|
运行结果:
[[12]]
variable 变量
1 2 3 4 5
| import tensorflow as tf
state = tf.Variable(0,name = 'counter')
print(state.name)
|
运行结果:
counter:0
1 2 3 4 5 6 7 8 9 10 11 12 13
| one = tf.constant(1)
new_value = tf.add(state,one)# 常量+变量=变量
updata = tf.assign(state,new_value)# 将new_value加载到state上
init = tf.global_variables_initializer()# 如果定义了变量,必须有此句
with tf.Session() as sess: sess.run(init) for _ in range(3): sess.run(updata) print(sess.run(state))
|
运行结果:
1
2
3
placeholder 传入值
该值随时可变,并可传入,类似于自变量
1 2 3 4 5 6 7 8 9
| import tensorflow as tf
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.]}))# run时传入值,使用feed_dict字典形式
|
运行结果:
[14.]