"""
用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