Tensorflow基本操作(一)

本文详细介绍了TensorFlow中图和会话的基本概念及使用方法。通过具体案例展示了如何创建张量、执行运算,并利用会话进行计算。此外,还讲解了图和会话的相关属性及其操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

图和会话的操作

什么是图

案例

查看图对象

# 查看默认图的属性
import tensorflow as tf

a = tf.constant(5.0)  # 第一个张量
b = tf.constant(1.0)
c = tf.add(a, b)  # 执行两个张量的相加

gragh = tf.get_default_graph()  # 获取默认的图
print(gragh)

with tf.Session() as sess:
    print(sess.run(c))
    print(a.graph)  # 打印张量的gragh属性
    print(c.graph)  # 打印c操作的gragh属性
    print(sess.graph)  # 打印session的gragh属性

会话及相关操作

图相当于菜单,会话相当于厨师

 

 创建一个新的图

# 查看默认图的属性
import tensorflow as tf

a = tf.constant(5.0)  # 第一个张量
b = tf.constant(1.0)
c = tf.add(a, b)  # 执行两个张量的相加

gragh = tf.get_default_graph()  # 获取默认的图
print("gragh2:",gragh)

# 新创建一个图
gragh2 = tf.Graph()
print("gragh2:", gragh2)

with tf.Session() as sess:  # 括号里没有带任何的参数,它是执行默认的gragh
    print(sess.run(c))
    print(a.graph)  # 打印张量的gragh属性
    print(c.graph)  # 打印c操作的gragh属性
    print(sess.graph)  # 打印session的gragh属性

 新创建图

# 查看默认图的属性
import tensorflow as tf

a = tf.constant(5.0)  # 第一个张量
b = tf.constant(1.0)
c = tf.add(a, b)  # 执行两个张量的相加

graph = tf.get_default_graph()  # 获取默认的图
print("gragh2:",graph)

# 新创建一个图
graph2 = tf.Graph()
print("gragh2:", graph2)
with graph2.as_default():  # 将gragh2设置为默认图 是默认的主图 主图里有三个操作
    d = tf.constant(11.0)  # 操作d属于gragh2

with tf.Session(graph=graph2) as sess:  # 括号里没有带任何的参数,它是执行默认的gragh
    print(sess.run(d))
    print(a.graph)  # 打印张量的gragh属性
    print(c.graph)  # 打印c操作的gragh属性
    print(sess.graph)  # 打印session的gragh属性

会话常见的错误及原因

 张量的阶和形状

# 查看默认图的属性
import tensorflow as tf

a = tf.constant(5.0)  # 第一个张量
print(a)

 张量的数据类型

 

 张量的常用属性

查看张量属性 

# 查看张量属性的示例

import tensorflow as tf

a = tf.constant(5.0)  # 标量

with tf.Session() as sess:
    print(sess.run(a)) # 执行的结果
    print("name:", a.name)  # name属性 系统自动给它起的名字
    print("dtype:", a.shape)  # shape
    print("op:", a.op)  # op
    print("gragh:", a.graph)  # gragh

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值