Tensorflow學習記錄9 一些函數

"""
用tensorflow來實現或使用人工智能領域中的一些函數

@author: ronny
"""

import tensorflow as tf
import numpy as np


def linear_function():
    """
    用tensorflow來實現人工智能領域中著名的線性函數:  Z=𝑊𝑋+B

    return: Z
    """
    np.random.seed(1)   # 設置seed,每次運行隨機數都是一樣的

    # 設W的維度是(4,3),X的維度是(3,1)以及b的是(4,1)。它們裏面填充的都是隨機數。
    W = tf.constant(np.random.rand(4, 3))
    X = tf.constant(np.random.rand(3, 1))
    B = tf.constant(np.random.rand(4, 1))

    # 矩陣運算Y=WX+B
    Z = tf.add(tf.matmul(W, X), B)

    # 創建會話運行公式
    sess = tf.Session()
    result = sess.run(Z)
    sess.close()

    return result


def sigmoid(z):
    """
    通過placeholder使用tensorflow自帶的sigmoid

    param z: WX+B的結果
    return a: 通過sigmoid激活的預測值
    """
    #
    # 調用佔位符
    x = tf.placeholder(tf.float32, name='x')

    # 定義公式的名字
    sigmoid = tf.sigmoid(x)

    # 在會話中運行
    with tf.Session() as sess:
        # 用run來執行上面定義的sigmoid操作
        a = sess.run(sigmoid, feed_dict={x: z})

        return a


def cost(z_in, y_in):
    """
    成本函數

    :param z_in:  WX+B的結果
    :param y_in:  真實標籤矩陣Y
    :return: 成本(總損失的均值)
    """
    # 輸入z,y;輸出cost
    z = tf.placeholder(tf.float32, name='z')
    y = tf.placeholder(tf.float32, name='y')

    cost = tf.nn.softmax_cross_entropy_with_logits(logits=z, labels=y)

    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        cost = sess.run(cost, feed_dict={z: z_in, y: y_in})

    return cost


def one_hot_matrix(labels, C_in):
    """
    將多類別標籤用統一的01編碼矩陣輸出

    :param labels: 真實標籤y向量
    :param C_in: 標籤類別數
    :return:one_hot 矩陣
    """

    C = tf.constant(C_in, name='C')

    one_hot_matrix = tf.one_hot(indices=labels, depth=C, axis=0)

    sess = tf.Session()

    # run
    result = sess.run(one_hot_matrix)

    sess.close()

    return result


def ones(shape):
    """

    :param shape: 矩陣維度
    :return: 全1矩陣
    """

    shape = tf.constant(shape)

    ones = tf.ones(shape=shape)

    sess = tf.Session()

    ones = sess.run(ones)

    sess.close()

    return ones

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章