Python专题, 语言

TensorFlow基础

TensorFlow基础:

import tensorflow as tf  # 导入tensorflow

greeting = tf.constant('Hello Google Tensorflow!')  # 定义一个常量

# 第一种方式
sess = tf.Session()  # 启动一个会话
result = sess.run(greeting)  # 使用会话执行greeting计算模块
print(result)  # 打印显示
sess.close()  # 关闭会话

# 第二种方式
with tf.Session() as sess:  # 启动一个会话
    print(sess.run(greeting))  # 打印显示


# 例子1:
matrix1 = tf.constant([[1., 3.]])  # 定义常数矩阵1  tf.constant()
matrix2 = tf.constant([[2.], [2.]])  # 定义常数矩阵2  tf.constant()
product = tf.matmul(matrix1, matrix2)  # 矩阵乘积  tf.matmul()
linear = tf.add(product, tf.constant(2.))  # 矩阵乘积后再加上一个常数  tf.add()
with tf.Session() as sess:  # 启动一个会话  tf.Session()
    print(sess.run(matrix1))  # 执行语句并打印显示  tf.Session().run
    print(sess.run(linear))  # 执行语句并打印显示  tf.Session().run
print(linear)  # 直接打印是不能看到计算结果的,因为还未执行,只是一个张量。这里打印显示的结果是:Tensor("Add:0", shape=(1, 1), dtype=float32)


# 例子2:变量tf.Variable()
state = tf.Variable(3, name='counter')  # 变量tf.Variable
init = tf.global_variables_initializer()  # 如果定义了变量,后面一定要有这个语句,用来初始化变量。
with tf.Session() as sess:
    sess.run(init)  # 变量一定要初始化变量
    print(sess.run(state))  # 执行语句并打印显示

# 例子3:占位符tf.placeholder(),用来临时占坑,需要用feed_dict来传入数值。
x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.float32)
y = x1 + x2
with tf.Session() as sess:
    print(sess.run(y, feed_dict={x1: 7, x2: 2}))

参考资料:

https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/2-3-session/

1,950 次浏览

【说明:本站主要是个人的一些笔记和代码分享,内容可能会不定期修改。为了使全网显示的始终是最新版本,这里的文章未经同意请勿转载。引用请注明出处:https://www.guanjihuan.com

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注