1. 程式人生 > >tf.argmax() tf.equal() tf.nn.softmax() eval tf.random_normal tf.reduce_mean tf.reduce_sum

tf.argmax() tf.equal() tf.nn.softmax() eval tf.random_normal tf.reduce_mean tf.reduce_sum

先講幾個 函式 然後用程式碼測試一下

tf.reduce_sum

input_tensor沿著給定的尺寸縮小axis。除非keepdims是真的,否則每個條目的張量等級減少1 axis。如果keepdims為真,則縮小尺寸將保留長度為1。
如果axis為None,則減小所有尺寸,並返回具有單個元素的張量。

    tf.reduce_sum(
        input_tensor,
        axis=None,
        keepdims=None,
        name=None,
        reduction_indices=None,
        keep_dims=
None ) x = tf.constant([[1, 1, 1], [1, 1, 1]]) tf.reduce_sum(x) # 6 tf.reduce_sum(x, 0) # [2, 2, 2] tf.reduce_sum(x, 1) # [3, 3] tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]] tf.reduce_sum(x, [0, 1]) # 6 引數: axis:要減少的尺寸。如果None(預設值),則減少所有尺寸。 keepdims:如果為true,則保留尺寸減小的長度為1。 name:操作的名稱(可選)。 reduction_indices: 軸的舊(已棄用)名稱。 等價與 axis keep_dims 等價於 keepdims。 返回: 計算後的張量,與input_tensor具有相同的dtype。 類似於 np.
sum

tf.reduce_mean

就是計算沿著某個axis的平均值 和 tf.reduce_sum很類似 這裡不再贅述

tf.reduce_mean(
    input_tensor,
    axis=None,
    keepdims=None,
    name=None,
    reduction_indices=None,
    keep_dims=None
)

x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x)  # 1.5
tf.reduce_mean(x, 0)  # [1.5, 1.5]
tf.
reduce_mean(x, 1) # [1., 2.]

tf.random_normal

tf.random_normal(
    shape,
    mean=0.0,
    stddev=1.0,
    dtype=tf.float32,
    seed=None,
    name=None
)

引數:
shape: [d1,d2...] 必須是一個一維的 類似與 list
seed: 一個隨機種子 整數
name: A name for the operation (optional).
Returns:
   A tensor of the specified shape filled with random normal values.

eval:

eval(
    feed_dict=None,
    session=None
)


呼叫此方法將執行所有先前的操作(這些操作僅僅是生成此張量的操作所需的輸入。)

注意:在呼叫Tensor.eval()之前,其圖形必須已在會話中啟動,並且預設會話必須可用,或者session必須明確指定。

ARGS:
feed_dict:為了獲取該tensor的值,所需要的輸入
session:(可選。)Session用於評估此張量。如果不是,則使用預設會話。
返回:
以numpy陣列的形式返回此張量的值。

tf.nn.softmax()

該函式就是將一個tensor的值轉換成概率分佈
此函式執行相當於
softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)
tf.nn.softmax(
    logits,
    axis=None,
    name=None,
    dim=None
)

引數:
logits:一個非空的Tensor。必須是下列型別之一:half, float32,float64。
axis:將執行維度softmax。預設值為-1,表示最後一個維度。
name:操作的名稱(可選)。
dim:等價於axis。
返回:
一Tensor。具有相同的型別和形狀logits。

tf.equal() 等價於 tf.math.equal()

# 別名:

tf.equal
tf.math.equal
tf.math.equal(
    x,
    y,
    name=None
)

==**Returns the truth value of (x == y) element-wise。**==
**注意:math.equal支援廣播。更多關於這裡的廣播**
引數:
x:A Tensor。必須是下列型別之一:bfloat16,half,float32,float64,uint8,int8,int16,int32,int64,complex64,quint8,qint8,qint32,string,bool,complex128。
y:A Tensor。必須與x相同的型別。
name:操作的名稱(可選)。
返回:
      A Tensor  bool型別的。
          

tf.argmax()

返回張量沿著指定的軸上最大值的索引。

tf.argmax(
    input,
    axis=None,
    name=None,
    dimension=None,
    output_type=tf.int64
)

引數:
axis:A Tensor。必須是以下型別之一:int32,int64。int32或int64,必須在範圍內[-rank(input), rank(input))。描述輸入Tensor的哪個軸要減少。對於向量,使用axis = 0。
output_type:可選tf.DType來自:tf.int32, tf.int64。預設為tf.int64。
name:操作的名稱(可選)。
返回:
   A Tensor 型別是 output_type

以上所有知識點 都出現在下面的程式碼中:該程式碼就是簡單的實現一個邏輯迴歸

程式碼的源頭

程式碼用到的資料在這裡下載
Extracting ./…/mnist_data/train-images-idx3-ubyte.gz
Extracting ./…/mnist_data/train-labels-idx1-ubyte.gz
Extracting ./…/mnist_data/t10k-images-idx3-ubyte.gz
Extracting ./…/mnist_data/t10k-labels-idx1-ubyte.gz

import tensorflow as tf

# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./../mnist_data", one_hot=True)
# Parameters
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1

# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes

# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# Construct model
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax

# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
# Start training
with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            # Fit training using batch data
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
                                                          y: batch_ys})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))

    print("Optimization Finished!")

    # Test model
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy for 3000 examples
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print("Accuracy:", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]}))