深度学习基础之《TensorFlow框架(7)—变量》

一、什么是变量

1、TensorFlow变量是表示程序处理的共享持久状态的最佳方法。变量通过tf.Variable OP类进行操作
这里的变量和传统认知里存储值或者返回值不一样,他是TensorFlow里的一个组件

2、变量的特点
(1)存储持久化
把程序中定义的数据以变量的形式保存下来
(2)可修改值
有时候存储一些数据,希望它能够被迭代更新
(3)可指定被训练
可以不断的迭代更新

3、变量很适合保存模型参数
深度学习目的:训练很好的模型解决问题

二、创建变量

1、tf.Variable(initial_value=None, trainable=True, collections=None, name=None)
说明:
(1)initial_value:初始化的值
(2)trainable:是否可以被训练
(3)collections:新变量将添加到列出的图的集合中collections
    默认为[GraphKeys.GLOBAL_VARIABLES],如果trainable是True,变量也被添加到图形集合[GraphKeys.TRAINABLE_VARIABLES]

2、变量需要显示初始化,才能运行值(TensorFlow2.0版本不需要)
tf.global_variables_initializer()

3、例子

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tfdef tensorflow_demo():"""TensorFlow的基本结构"""# TensorFlow实现加减法运算a_t = tf.constant(2)b_t = tf.constant(3)c_t = a_t + b_tprint("TensorFlow加法运算结果:\n", c_t)print(c_t.numpy())# 2.0版本不需要开启会话,已经没有会话模块了return Nonedef graph_demo():"""图的演示"""# TensorFlow实现加减法运算a_t = tf.constant(2)b_t = tf.constant(3)c_t = a_t + b_tprint("TensorFlow加法运算结果:\n", c_t)print(c_t.numpy())# 查看默认图# 方法1:调用方法default_g = tf.compat.v1.get_default_graph()print("default_g:\n", default_g)# 方法2:查看属性# print("a_t的图属性:\n", a_t.graph)# print("c_t的图属性:\n", c_t.graph)# 自定义图new_g = tf.Graph()# 在自己的图中定义数据和操作with new_g.as_default():a_new = tf.constant(20)b_new = tf.constant(30)c_new = a_new + b_newprint("c_new:\n", c_new)print("a_new的图属性:\n", a_new.graph)print("b_new的图属性:\n", b_new.graph)# 开启new_g的会话with tf.compat.v1.Session(graph=new_g) as sess:c_new_value = sess.run(c_new)print("c_new_value:\n", c_new_value)print("我们自己创建的图为:\n", sess.graph)# 可视化自定义图# 1)创建一个writerwriter = tf.summary.create_file_writer("./tmp/summary")# 2)将图写入with writer.as_default():tf.summary.graph(new_g)return Nonedef session_run_demo():"""feed操作"""tf.compat.v1.disable_eager_execution()# 定义占位符a = tf.compat.v1.placeholder(tf.float32)b = tf.compat.v1.placeholder(tf.float32)sum_ab = tf.add(a, b)print("a:\n", a)print("b:\n", b)print("sum_ab:\n", sum_ab)# 开启会话with tf.compat.v1.Session() as sess:print("占位符的结果:\n", sess.run(sum_ab, feed_dict={a: 1.1, b: 2.2}))return Nonedef tensor_demo():"""张量的演示"""tensor1 = tf.constant(4.0)tensor2 = tf.constant([1, 2, 3, 4])linear_squares = tf.constant([[4], [9], [16], [25]], dtype=tf.int32)print("tensor1:\n", tensor1)print("tensor2:\n", tensor2)print("linear_squares:\n", linear_squares)# 张量类型的修改l_cast = tf.cast(linear_squares, dtype=tf.float32)print("before:\n", linear_squares)print("l_cast:\n", l_cast)return Nonedef variable_demo():"""变量的演示"""a = tf.Variable(initial_value=50)b = tf.Variable(initial_value=40)c = tf.add(a, b)print("a:\n", a)print("b:\n", b)print("c:\n", c)return Noneif __name__ == "__main__":# 代码1:TensorFlow的基本结构# tensorflow_demo()# 代码2:图的演示#graph_demo()# feed操作#session_run_demo()# 代码4:张量的演示#tensor_demo()# 代码5:变量的演示variable_demo()

运行结果:

a:<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=50>
b:<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=40>
c:tf.Tensor(90, shape=(), dtype=int32)

a和b是tf.Variable
c是Tensor对象

三、修改变量的命名空间

1、使用tf.variable_scope()修改变量的命名空间
会在OP的名字前面增加命名空间的指定名字
TensorFlow 2.0版本用,tf.compat.v1.variable_scope()

2、例子

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tfdef tensorflow_demo():"""TensorFlow的基本结构"""# TensorFlow实现加减法运算a_t = tf.constant(2)b_t = tf.constant(3)c_t = a_t + b_tprint("TensorFlow加法运算结果:\n", c_t)print(c_t.numpy())# 2.0版本不需要开启会话,已经没有会话模块了return Nonedef graph_demo():"""图的演示"""# TensorFlow实现加减法运算a_t = tf.constant(2)b_t = tf.constant(3)c_t = a_t + b_tprint("TensorFlow加法运算结果:\n", c_t)print(c_t.numpy())# 查看默认图# 方法1:调用方法default_g = tf.compat.v1.get_default_graph()print("default_g:\n", default_g)# 方法2:查看属性# print("a_t的图属性:\n", a_t.graph)# print("c_t的图属性:\n", c_t.graph)# 自定义图new_g = tf.Graph()# 在自己的图中定义数据和操作with new_g.as_default():a_new = tf.constant(20)b_new = tf.constant(30)c_new = a_new + b_newprint("c_new:\n", c_new)print("a_new的图属性:\n", a_new.graph)print("b_new的图属性:\n", b_new.graph)# 开启new_g的会话with tf.compat.v1.Session(graph=new_g) as sess:c_new_value = sess.run(c_new)print("c_new_value:\n", c_new_value)print("我们自己创建的图为:\n", sess.graph)# 可视化自定义图# 1)创建一个writerwriter = tf.summary.create_file_writer("./tmp/summary")# 2)将图写入with writer.as_default():tf.summary.graph(new_g)return Nonedef session_run_demo():"""feed操作"""tf.compat.v1.disable_eager_execution()# 定义占位符a = tf.compat.v1.placeholder(tf.float32)b = tf.compat.v1.placeholder(tf.float32)sum_ab = tf.add(a, b)print("a:\n", a)print("b:\n", b)print("sum_ab:\n", sum_ab)# 开启会话with tf.compat.v1.Session() as sess:print("占位符的结果:\n", sess.run(sum_ab, feed_dict={a: 1.1, b: 2.2}))return Nonedef tensor_demo():"""张量的演示"""tensor1 = tf.constant(4.0)tensor2 = tf.constant([1, 2, 3, 4])linear_squares = tf.constant([[4], [9], [16], [25]], dtype=tf.int32)print("tensor1:\n", tensor1)print("tensor2:\n", tensor2)print("linear_squares:\n", linear_squares)# 张量类型的修改l_cast = tf.cast(linear_squares, dtype=tf.float32)print("before:\n", linear_squares)print("l_cast:\n", l_cast)return Nonedef variable_demo():"""变量的演示"""a = tf.Variable(initial_value=50)b = tf.Variable(initial_value=40)c = tf.add(a, b)print("a:\n", a)print("b:\n", b)print("c:\n", c)with tf.compat.v1.variable_scope("my_scope"):d = tf.Variable(initial_value=30)e = tf.Variable(initial_value=20)f = tf.add(d, e)print("d:\n", d)print("e:\n", e)print("f:\n", f)return Noneif __name__ == "__main__":# 代码1:TensorFlow的基本结构# tensorflow_demo()# 代码2:图的演示#graph_demo()# feed操作#session_run_demo()# 代码4:张量的演示#tensor_demo()# 代码5:变量的演示variable_demo()

运行结果:

a:<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=50>
b:<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=40>
c:tf.Tensor(90, shape=(), dtype=int32)
d:<tf.Variable 'my_scope/Variable:0' shape=() dtype=int32, numpy=30>
e:<tf.Variable 'my_scope/Variable:0' shape=() dtype=int32, numpy=20>
f:tf.Tensor(50, shape=(), dtype=int32)

2、命名空间好处,使得结构更加清晰

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/757322.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Springboot+vue的仓库管理系统(有报告)。Javaee项目,springboot vue前后端分离项目。

演示视频&#xff1a; Springbootvue的仓库管理系统&#xff08;有报告&#xff09;。Javaee项目&#xff0c;springboot vue前后端分离项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层…

Leetcode 62. 不同路径

心路历程&#xff1a; 这道题基本就是Q-learning经典迷宫问题的简化版本&#xff0c;所以肯定是用动态规划了&#xff0c;毕竟RL中的时序差分估计法的本身也是来自于MC和动态规划的结合。如果正常正向思维思考的话&#xff0c;首先看不到问题明显的循环结构&#xff0c;考虑递…

秒级生图,大模型 SDXL-turbo、LCM-SDXL 实战案例来了

最近一个月&#xff0c;快速生图成为文生图领域的热点&#xff0c;其中比较典型的两种方式的代表模型分别为SDXL-turbo 和 LCM-SDXL。 SDXL-turbo 模型是 SDXL 1.0 的蒸馏版本&#xff0c;SDXL-Turbo 基于一种称之为对抗扩散蒸馏&#xff08;ADD&#xff09;的新颖的训练方法&…

Go 1.22 - 更加强大的 Go 执行跟踪

原文&#xff1a;Michael Knyszek - 2024.03.14 runtime/trace 包含了一款强大的工具&#xff0c;用于理解和排查 Go 程序。这个功能可以生成一段时间内每个 goroutine 的执行追踪。然后&#xff0c;你可以使用 go tool trace 命令&#xff08;或者优秀的开源工具 gotraceui&a…

c++11 标准模板(STL)本地化库 - std::iscntrl(std::locale) 检查字符是否被本地环境分类为控制字符

本地化库 本地环境设施包含字符分类和字符串校对、数值、货币及日期/时间格式化和分析&#xff0c;以及消息取得的国际化支持。本地环境设置控制流 I/O 、正则表达式库和 C 标准库的其他组件的行为。 检查字符是否被本地环境分类为控制字符 std::iscntrl(std::locale) templa…

Spring Cloud 整合 GateWay

目录 第一章 微服务架构图 第二章 Spring Cloud整合Nacos集群 第三章 Spring Cloud GateWay 第四章 Spring Cloud Alibaba 整合Sentinel 第五章 Spring Cloud Alibaba 整合SkyWalking链路跟踪 第六章 Spring Cloud Alibaba 整合Seata分布式事务 第七章 Spring Cloud 集成Auth用…

[Qt学习笔记]Release后的exe程序在新的电脑上出现“找不到MSVCP140.dll”的错误

1、背景介绍 我们在打包程序的时候一般都会把相关依赖库整体打包&#xff0c;这样程序在新的电脑和环境下就不需要再去配置对应的环境&#xff0c;但是有时候新程序在一台新的电脑运行时会出现“找不到MSVCP140.dll”这种错误&#xff0c;其原因就是在新电脑的操作系统中缺少一…

倒计时 7 天 | 立即加入 GDE 成长计划,飞跃成为谷歌开发者专家

谷歌开发者专家 (Google Developer Experts&#xff0c;GDE)&#xff0c;又称谷歌开发者专家项目&#xff0c;是由一群经验丰富的技术专家、具有社交影响力的开发者和思想领袖组成的全球性社区。通过在各项活动演讲以及各个平台上发布优质内容来积极助力开发者、企业和技术社区…

机器学习 - 线性问题

矩阵做 transpose import torch tensor_Matrix_A torch.tensor([[1,2],[4,5],[7,8] ], dtypetorch.float32) print(tensor_Matrix_A.T)# 结果 tensor([[1., 4., 7.],[2., 5., 8.]])torch.nn.Linear() 模块也被称为 “feed-forward layer"或者"fully connected laye…

如何防御XSS攻击

上篇讲解了XSS的危害&#xff0c;name在开发网站时就要做好防御措施&#xff0c;具体措施如下&#xff1a; 可以从浏览器的执行来进行预防&#xff0c;一种是使用纯前端的方式&#xff0c;不用服务器端拼接后返回&#xff08;不适用服务器端渲染&#xff09;。另一种是对需要插…

安卓面试题多线程 91-95

91. 简述java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用?有两种实现方法,分别是继承Thread类与实现Runnable接口 用synchronized关键字修饰同步方法 反对使用stop(),是因为它不安全。它会解除由线程获取的所有锁定,而…

AI助手 - 月之暗面 Kimi.ai

前言 这是 AI工具专栏 下的第四篇&#xff0c;这一篇所介绍的AI&#xff0c;也许是截至今天&#xff08;204-03-19&#xff09;国内可访问的实用性最强的一款。 今年年初&#xff0c;一直看到有人推荐 Kimi&#xff0c;不过面对雨后春笋般的各类品质的AI&#xff0c;说实话也有…

windows 多网卡情况dns解析超时问题的排查

最近遇到一个问题 多网卡&#xff0c;多网络环境下&#xff0c;dns解析总是超时。 排查之后发现是dns配置的问题&#xff0c;一个有线网络配置的内网dns&#xff0c;一个无线网络配置的公网dns 访问公网时莫名的时不时出现超时现象 初步排查是dns解析的耗时太长&#xff0c;…

ChatGPT-4 VS 文心一言4.0

在线体验 地址&#xff08;含 gpt 3.5 / 4.0&#xff0c;文心 3.5 / 4.0&#xff09;&#xff1a;https://chat.tool4j.com 点击访问 文心一言和ChatGPT-4都是非常强大的自然语言处理模型&#xff0c;它们都能够在对话系统和其他NLP应用中发挥巨大的作用。然而&#xff0c;它们…

【Go语言】Go语言中的函数

Go语言中的函数 Go语言中&#xff0c;函数主要有三种类型&#xff1a; 普通函数 匿名函数&#xff08;闭包&#xff09; 类方法 1 函数定义 Go语言函数的基本组成包括&#xff1a;关键字func、函数名、参数列表、返回值、函数体和返回语句。Go语言是强类型语言&#xff0…

【MySQL | 第五篇】MySQL事务总结

文章目录 5.MySQL事务5.1什么是事务&#xff1f;5.2什么是数据库事务&#xff1f;5.3数据库事务四大特性5.4并发事务带来的问题及解决方案&#xff1f;5.4.1脏读/不可重复读/幻读5.4.2不可重复读和幻读有什么区别&#xff1f;5.4.3解决并发事务带来的问题&#xff08;1&#xf…

springboot实战笔记

springboot实战笔记 用户模块开发用户登录接口实现根据token获取用户信息检查账号是否可用用户注册接口实现 首页模块开发查询首页分类分页查询首页头条信息查询头条详情 头条模块开发登陆检查头条发布和登录保护拦截器头条根据id回显头条修改头条删除 用户模块开发 用户登录接…

springboot/ssm医院病历管理系统Java医院住院病历信息管理系统web

springboot/ssm医院病历管理系统Java医院住院病历信息管理系统web 基于springboot(可改ssm)vue项目 开发语言&#xff1a;Java 框架&#xff1a;springboot/可改ssm vue JDK版本&#xff1a;JDK1.8&#xff08;或11&#xff09; 服务器&#xff1a;tomcat 数据库&#xf…

聚观早报 | 阅文去年净利增三成;iQOO Z9系列官宣

聚观早报每日整理最值得关注的行业重点事件&#xff0c;帮助大家及时了解最新行业动态&#xff0c;每日读报&#xff0c;就读聚观365资讯简报。 整理丨Cutie 3月20日消息 阅文去年净利增三成 iQOO Z9系列官宣 英伟达发布全新构架 一加Ace 3V设计细节 小米Civi 4 Pro核心…

章鱼网络 Community Call #19|​开启与 Eigenlayer 的合作

香港时间2024年3月8日12点&#xff0c;章鱼网络举行第19期 Community Call。 在过去的一个月&#xff0c;章鱼网络在成功完成 $NEAR Restaking 功能的安全审计之后&#xff0c;一直在稳步吸引关注。事实上&#xff0c;在整个行业中&#xff0c;我们是极少数已经推出 Restaking …