Tensorflow lesson 3---变量Variable

Tensorflow中的变量就是一个放在内存中的tensor结构,用于在计算过程中保存数据,变量的数值可以保存到文件中,也可以从文件中读取

1.变量的初始化

import tensorflow as tf

Weights=tf.Variable(tf.random_normal([3,2],stddev=0.35),name="weights")#声明一个Weights的变量

print(Weights)#打印Weights变量结构
init=tf.global_variables_initializer()#初始化变量

with tf.Session() as sess:#执行session任务
    sess.run(init)#初始化认为
    print(sess.run(Weights))#打印Weights的值

tensorflow中的变量必须被初始化,否则其内容是空的,以上代码执行完后会打印出一个3行2列的矩阵,值随机的,执行的输出结果如下

<tf.Variable 'weights:0' shape=(3, 2) dtype=float32_ref>
[[ 0.01990979 -0.26959115]
 [ 0.32198292 -0.09266231]
 [-0.32708889  0.3107968 ]]

2.变量保存到文件

import tensorflow as tf

Weights=tf.Variable(tf.random_normal([3,2],stddev=0.35),name="weights")

print(Weights)

saver = tf.train.Saver()#声明Saver
init=tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(Weights))
    save_path = saver.save(sess, "/Users/william/tmp/model.ckpt")#保存到文件
    print("Model saved in file: %s" % save_path)#打印保存的路径

tensorflow是可以将变量保存到文件的,要用到的是tf.train.Saver,以上这段代码执行完成后,就会在tmp文件夹下身材变量保存的文件
这里写图片描述

3.变量的读取
可以保存到文件,就可以从文件中把变量读取出来

import tensorflow as tf

Weights=tf.Variable(tf.random_normal([3,2],stddev=0.35),name="weights")

print(Weights)

saver = tf.train.Saver()

with tf.Session() as sess:
    saver.restore(sess, "/Users/william/tmp/model.ckpt")
    print("the restore variable Weights= %s" % sess.run(Weights))

以上代码把变量读取出来,并打印出来,其输出如下:

<tf.Variable 'weights:0' shape=(3, 2) dtype=float32_ref>
the restore variable Weights= [[ 0.01990979 -0.26959115]
 [ 0.32198292 -0.09266231]
 [-0.32708889  0.3107968 ]]

如果变量是从文件中读取出来,就不需要初始化,只需要声明就可以了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DiegoRobot

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值