TensorFlow 基础(1)

作者 : 开心源码 本文共1184个字,预计阅读时间需要3分钟 发布时间: 2022-05-13 共191人阅读

awesome-tensorflow

参考《TensorFlow 深度学习》和 《TensorFlow 学习指南》等书籍

学习新语言也好、新框架也好,我们都喜欢写一个 Hello World 开始。

第一个 Hello TensorFlow

import tensorflow as tf

定义常量为 Hello TensorFlow

hello = tf.constant("Hello TensorFlow")sess = tf.Session()print(sess.run(hello))

在 TensorFlow 中所有的计算都需要在Session(会话)中完成。这个大家肯定要留心,否则就会出现问题得不到想要的效果。

第二个 Hello TensorFlow

h = tf.constant("Hello")t = tf.constant("TensorFlow")ht = h + twith tf.Session() as sess:    result = sess.run(ht)print(result)
h = tf.constant("Hello")w = tf.constant(" world")hw = tf.add(h,w)mul = tf.multiply(a,b)with tf.Session() as sess:    result = sess.run(hw)print(result)
mul = tf.multiply(a,b)with tf.Session() as sess:    result = sess.run(mul)print(result)

TensorFlow 的操作符

定义操作符

a = tf.constant(5)b = tf.constant(3)c = tf.constant(2)print(a)
Tensor("Const:0", shape=(), dtype=int32)

输出一个 a 的类型为 Tensor ,Tensor 相似一个对象,dtype 为数据类型。

mul = tf.multiply(a,b)

在 TensorFlow 中我们运算操作定义有区别于其余我们熟习语言,输出 mul 为一个对象,而非 a 和 b 乘积的结果,而是 Tensor 节点,需要执行运算后才能得到结果。假如写成 a * b 则是 tf.multiply(a,b) 缩写。

Tensor("Mul:0", shape=(), dtype=int32)

使用 with 语句打开会话能够保证一旦所有计算完成后会话将自动关闭。

a = tf.constant(5)b = tf.constant(3)c = tf.constant(2)# f =  (a + b) * cab = tf.add(a,b)f = tf.multiply(ab,c)with tf.Session() as sess:    result = sess.run(f)print(result)

当我们输入 Tensor(在这里可以叫张量或者者节点)到会话进行计算,方法调用时会完成一组运算,从该节点根据依赖进行计算出所有节点。

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » TensorFlow 基础(1)

发表回复