目标
本文旨在介绍 tensorflow 入门知识点及实战示例,希望各位新手能在学习之后熟练 tensorflow 相关操作
简单的常量运算代码
import tensorflow as tf
v1 = tf.constant([[5,6]])
v2 = tf.constant([[2],[4]])
p1 = tf.matmul(v1, v2)
p2 = tf.matmul(v2, v1)
with tf.Session() as sess: # 因为这里没有变量,都是常量,所以直接可以进行运算,输出值
print(sess.run(p1))
print(sess.run(p2))
复制代码
输出结果
[[34]]
[[10 12]
[20 24]]
简单的变量运算
import tensorflow as tf
x = tf.Variable([9,10])
y = tf.constant([4,4])
sub = tf.subtract(x, y)
add = tf.add(x, y)
init = tf.global_variables_initializer() # 这里因为 graph 中有变量 x ,所以要有一个操作对 graph 中的变量进行初始化
with tf.Session() as sess:
sess.run(init)
print(sess.run([sub, add]))
复制代码
输出结果
[array([5, 6], dtype=int32), array([13, 14], dtype=int32)]
复制代码
进阶—变量自增
import tensorflow as tf
state = tf.Variable(0, name='state')
add = tf.add(state, 2) # 为 state 加 2
update = tf.assign(state, add) # 将变化之后的 add 赋值给 state 完成值的更新
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(state)) # 输出原始的 state 值
for _ in range(3):
sess.run(update) # update 操作中已经包含了加法和赋值两个操作
print(sess.run(state)) # 输出变化之后的 state 值
复制代码
输出结果
0
2
4
6
大家有不懂的可以在下方留言或者关注crmeb公众号咨询
最后
如果你觉得这篇文章对你有点用的话,麻烦请给我们的开源项目点点star:http://github.crmeb.net/u/defu不胜感激 !
免费获取源码地址:http://www.crmeb.com
PHP学习手册:https://doc.crmeb.com
技术交流论坛:https://q.crmeb.com
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。