参考博文:http://blog.csdn.net/phdat101/article/details/52442738
<nobr aria-hidden="true"> </nobr> <math xmlns="http://www.w3.org/1998/Math/MathML"> </math>正常情况下,使用tf.initialize_all_variables()初始化变量,在完全构建好模型并加载之后才运行这个操作。生成数据的主要方法如下:
<nobr aria-hidden="true"> </nobr> <math xmlns="http://www.w3.org/1998/Math/MathML"> </math>1:如果需要利用已经初始化的参数给其他变量赋值,TF的变量有个initialized_value()属性,就是初始化的值,使用方法如下:
# 原始的变量
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),name="weights")
# 创造相同内容的变量
w2 = tf.Variable(weights.initialized_value(), name="w2")
# 也可以直接乘以比例
w_twice = tf.Variable(weights.initialized_value() * 0.2, name="w_twice")
<nobr aria-hidden="true"> </nobr> <math xmlns="http://www.w3.org/1998/Math/MathML"> </math>生成tensor,序列,随机数的一些方法:
# -*- coding: utf-8 -*-:
import tensorflow as tf
import numpy as np
#生成0和1矩阵
v1 = tf.Variable(tf.zeros([3,3,3]), name="v1")
v2 = tf.Variable(tf.ones([10,5]), name="v2")
#填充单值矩阵
v3 = tf.Variable(tf.fill([2,3],9))
#常量矩阵
v4_1 = tf.constant([1,2,3,4,5,6,7])
v4_2 = tf.constant(-1.0, shape=[2,3])
#生成等差数列
v6_1 = tf.linspace(10.0, 12.0, 30, name="linspace")
v7_1 = tf.range(10, 20, 3)#just int32
#生成各种随机数据矩阵
v8_1 = tf.Variable(tf.random_uniform([2,4],minval=0.0,maxval=2.0,dtype=tf.float32,seed=1234,name="v8_1"))
v8_2 = tf.Variable(tf.random_normal([2,3],mean=0.0,stddev=1.0,dtype=tf.float32,seed=1234,name="v8_2"))
v8_3 = tf.Variable(tf.random_normal([2,3],mean=0.0,stddev=1.0,dtype=tf.float32,seed=1234,name="v8_3"))
v8_4 = tf.Variable(tf.random_uniform([2,3], maxval=1.0, dtype=tf.float32, seed=1234, name="v8_4"))
v8_5 = tf.random_shuffle([[1,2,3],[4,5,6],[6,6,6]],seed=134,name="v8_5")
#初始化
init_op = tf.initialize_all_variables()
#保存变量,也可以指定保存的内容
saver = tf.train.Saver
#运行
with tf.Session() as sess:
sess.run(init_op)
#输出形状和值
print tf.Variable.get_shape(v1)#shape
print sess.run(v1)#value
#numpy保存文件
np.save("v1.npy",sess.run(v1))
test_a = np.load("v1.npy")
print test_a[1,2]
#一些输出
print(sess.run(v3))
v5 = tf.zeros_like(sess.run(v1))
print sess.run(v6_1)
print sess.run(v7_1)
print sess.run(v8_5)
运行结果如下:
(3, 3, 3)
[[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]
[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]
[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]]
[0. 0. 0.]
[[9 9 9] [9 9 9]]
[10. 10.068966 10.137931 10.206897 10.275862 10.344828
10.413794 10.4827585 10.551724 10.620689 10.689655 10.75862
10.827586 10.896552 10.965517 11.034483 11.103448 11.172414
11.241379 11.310345 11.379311 11.448276 11.5172415 11.586206
11.655172 11.724138 11.793103 11.862069 11.931034 12. ]
[10 13 16 19]
[[4 5 6] [6 6 6] [1 2 3]]
按照结果也是比较容易推测这些方法实现的功能