美文网首页TensorFlow简易教程
四、先来入门五个例子

四、先来入门五个例子

作者: Lornatang | 来源:发表于2018-11-20 16:18 被阅读1次
  • 例一:Hello World。
import tensorflow as tf
hw = tf.constant("Hello World")
with tf.Session() as sess:
 print(sess.run(hw))
  • 例二:两个矩阵相乘。
# Build a dataflow graph.
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)

# Construct a `Session` to execute the graph.
with tf.Session() as sess:
  # Execute the graph and store the value that `e` represents in `result`.
  result = sess.run(e)

print(result)
  • 例三:使用Feeding在执行时传入参数
import tensorflow as tf

# Build a dataflow graph.
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)

# Construct a `Session` to execute the graph.
sess = tf.Session()

# Execute the graph and store the value that `e` represents in `result`.
result = sess.run(e,feed_dict={c:[[0.0, 0.0], [3.0, 4.0]]})
print(result)
sess.close()

TensorFlow的一大特色时其图中的节点可以是带状态的。

  • 例四:带状态的图
import tensorflow as tf

# Build a dataflow graph.
count = tf.Variable([0],trainable=False);
init_op = tf.global_variables_initializer()
update_count = count.assign_add(tf.constant([2]))

# Construct a `Session` to execute the graph.
sess = tf.Session()
sess.run(init_op)

for step in range(10):
    result = sess.run(update_count)
    print("step %d: count = %g" % (step,result))

sess.close()
  • 例五:梯度计算
import tensorflow as tf

# Build a dataflow graph.
filename_queue = tf.train.string_input_producer(['1.txt'],num_epochs=1)
reader = tf.TextLineReader()
key,value = reader.read(filename_queue)
num = tf.decode_csv(value,record_defaults=[[0]])
x = tf.Variable([0])
loss = x * num
grads = tf.gradients([loss],x)
grad_x = grads[0]

def train_fn(sess):
  train_fn.counter += 1
  result = sess.run(grad_x)
  print("step %d: grad = %g" % (train_fn.counter,result))

train_fn.counter = 0

sv = tf.train.Supervisor()
tf.train.basic_train_loop(sv,train_fn)

相关文章

  • 四、先来入门五个例子

    例一:Hello World。 例二:两个矩阵相乘。 例三:使用Feeding在执行时传入参数 TensorFlo...

  • 四、官方文档入门例子

    看下官方文档入门例子,敲一下。熟悉代码与初步了解。官方例子 提前准备:npm建立项目,使用node express...

  • docker入门例子

    最近工作上刚好用到了docker ,所以作为入门学习,本文就以一个简单的例子展开。 推荐一个不错的入门资料 Do...

  • vuex入门例子

    vuex example 接着上一篇的vuex简单剖析,接下来主要来写一个简单的例子?,来操作一番。 store ...

  • 集合中的线程初体验

    java零基础入门-高级特性篇(四) HashSet 和 Collections 本章继续讲集合,先来看看Set集...

  • protobuf Python极简入门例子

    protbuf极简入门例子 Google官方的tutorial废话有点多, 而且例子也有点不直观. 自己在官方例子...

  • 正则表达式的语法分类

    转载自正则表达式30分钟入门教程 入门 学习正则表达式的最好方法是从例子开始,理解例子之后再自己对例子进行修改,实...

  • string变量在赋值时的空格问题

    我们先来看个例子: 当我们输入:this string 时.

  • TODO:Golang指针使用注意事项

    TODO:Golang指针使用注意事项 先来看简单的例子1: 输出: 11 例子2: 输出: 13 例子1是使用值...

  • beetl模板入门例子

    beetl初级用法 public class BeetlEngine { public static Strin...

网友评论

    本文标题:四、先来入门五个例子

    本文链接:https://www.haomeiwen.com/subject/jadxqqtx.html