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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值