一,tensorflow中有一類在tensor的某一維度上求值的函數(shù)蜜徽。如:
求最大值tf.reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None)
求平均值tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)
參數(shù)1--input_tensor:待求值的tensor票摇。
參數(shù)2--reduction_indices:在哪一維上求解。
參數(shù)(3)(4)可忽略
舉例說明:
'x' is [[1., 2.]
[3., 4.]]
x是一個2維數(shù)組盆色,分別調(diào)用reduce_*函數(shù)如下:
首先求平均值:
tf.reduce_mean(x) ==> 2.5 #如果不指定第二個參數(shù)祟剔,那么就在所有的元素中取平均值
tf.reduce_mean(x, 0) ==> [2., 3.] #指定第二個參數(shù)為0,則第一維的元素取平均值宣旱,即每一列求平均值
tf.reduce_mean(x, 1) ==> [1.5, 3.5] #指定第二個參數(shù)為1叛薯,則第二維的元素取平均值,即每一行求平均值
同理耗溜,還可用tf.reduce_max()求最大值等。
二燎字。 tf.square(x) 對x內(nèi)所有的元素進行平方操作
三。tf.global_variables
tf.global_variables或者tf.all_variables都是獲取程序中的變量轩触,不同的版本是不同的,目前的tensorflow版本應該用前面的那個伐弹,返回的值是變量的一個列表
例如:
import tensorflow as tf;
import numpy as np;
import matplotlib.pyplot as plt;
v = tf.Variable(tf.constant(0.0, shape=[1], dtype=tf.float32), name='v')
v1 = tf.Variable(tf.constant(5, shape=[1], dtype=tf.float32), name='v1')
variables = tf.global_variables()
print variables[0].name
print variables[1].name
輸出:
v:0
v1:0
四榨为。 tf.train.Saver函數(shù)的用法之保存全部變量和模型
用于保存模型,以后再用就可以直接導入模型進行計算矩乐,方便。
例如:
[python] view plain copy
import tensorflow as tf;
import numpy as np;
import matplotlib.pyplot as plt;
v1 = tf.Variable(tf.constant(1, shape=[1]), name='v1')
v2 = tf.Variable(tf.constant(2, shape=[1]), name='v2')
result = v1 + v2
init = tf.initialize_all_variables()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
saver.save(sess, "/home/penglu/Desktop/lp/model.ckpt")
# saver.restore(sess, "/home/penglu/Desktop/lp/model.ckpt")
# print sess.run(result)
結果:
下次需要使用模型就可以用下面的代碼:
[python] view plain copy
import tensorflow as tf;
import numpy as np;
import matplotlib.pyplot as plt;
v1 = tf.Variable(tf.constant(1, shape=[1]), name='v1')
v2 = tf.Variable(tf.constant(2, shape=[1]), name='v2')
result = v1 + v2
init = tf.initialize_all_variables()
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, "/home/penglu/Desktop/lp/model.ckpt")
print sess.run(result)
[python] view plain copy
[python] view plain copy
或者這個代碼:
[python] view plain copy
import tensorflow as tf;
import numpy as np;
import matplotlib.pyplot as plt;
[python] view plain copy
saver = tf.train.import_meta_graph('/home/penglu/Desktop/lp/model.ckpt.meta')
with tf.Session() as sess:
<span style="white-space:pre"> </span>saver.restore(sess, "/home/penglu/Desktop/lp/model.ckpt")
<span style="white-space:pre"> </span>print sess.run(tf.get_default_graph().get_tensor_by_name('add:0'))
[python] view plain copy
輸出:
三。np.expand_dims()加維
四职抡。np.mean(data)求data的平均數(shù) np.std(data)計算標準差 np.median(data)計算中位數(shù)