美文网首页
Tensorflow 学习 (1)

Tensorflow 学习 (1)

作者: 法号无涯 | 来源:发表于2017-11-21 18:27 被阅读16次

跟着谷歌总是没错的,学一学tensorflow

TF 是谷歌出得第二个机器学习框架。你可以用 tensorflow 做数字计算,没有任何区别。只不过这些计算是由数据流图来完成的。其中节点代表着某种运算,边则代表着数据,一般情况下会是多维的数组或tensors。所以从名字也可以看出这是tensors们的计算流。至于什么是tensor,呵呵,我也不知道

对于tensor,在知乎上找到一个回答,有时间细读
https://www.zhihu.com/question/20695804
简单看了下,说tensor和向量一样,是某种物理的量,貌似在相对论等领域是很基础的内容。先跳过。

constant

因为深度学习一般都是对向量的操作,因此定义了几个向量常量,并用tf.multiply() 操作得出其积,但是结果print出来后不是想象的那样

# Import `tensorflow`
import tensorflow as tf

# Initialize two constants
x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

# Multiply
result = tf.multiply(x1, x2)

# Print the result
print(result)

输出结果为 Tensor("Mul:0", shape=(4,), dtype=int32)
看来tf.multiply() 只是把这个操作或者模型定义了出来,并没有实际执行。这个称之为lazy evaluation。

session

上面print的结果被称之为computation graph里的虚拟张量,为了得到运算的结果,这个操作必须要经过session执行。一下两块代码都可以

1

# Import `tensorflow` 
import tensorflow as tf

# Initialize two constants
x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

# Multiply
result = tf.multiply(x1, x2)

# Intialize the Session
sess = tf.Session()

# Print the result
print(sess.run(result))

# Close the session
sess.close()

2

# Import `tensorflow`
import tensorflow as tf

# Initialize two constants
x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

# Multiply
result = tf.multiply(x1, x2)

# Initialize Session and run `result`
with tf.Session() as sess:
  output = sess.run(result)
  print(output)

以上是两种定义session的方法,也可以使用config和ConfigProto对session进行配置。接下来把注意力暂时转移到数据上看看。

相关文章

网友评论

      本文标题:Tensorflow 学习 (1)

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