首先,要知道在Tensorflow中,最主要的数据结构是张量;那么什么是张量呢,在线性代数中张量可以理解为矩阵和向量的泛化;先回顾一下线代的知识:
标量(scalar)
:一个单独的数
向量(vector)
: 一列数或一维数组
矩阵(matrix)
:一个二维数组
张量(tensor)
:高维度的数组,例如三维数组A,其坐标为(i,j,l)
创建张量
import numpy as np
import tensorflow as tf
tf.constant(4)
tf.constant(5)
tf.constant([1,2,3])
tf.constant(np.random.rand(5,5))
张量不可直接用于运算,例如
a = tf.constant(2)
b = tf.constant(10)
c = tf.multiply(a,b)
print(c)
#out: Tensor("Mul:0", shape=(), dtype=int32)
正如所料,不会得到20,而是得到一个张量,是一个没有shape属性的张量,并且类型为“int32”。 这里建立得算子只是放在’计算图’中,但还没有运行这个计算。 为了实际乘以这两个数字,必须创建一个会话并运行它。
占位符
占位符(placeholder)的作用可以理解为先占个位置,此时并不知道这里将会是什么值,但知道类型和形状等信息,先把这些信息填进去占个位置,后续再用feed
的方式来把这些数据“填”进去,返回一个tensor
。feed
在session
的run()
方法中,通过feed_dict
这个参数来实现,这个参数的内容就是把值“喂”给那个placeholder
。
例如:
x = tf.placeholder(tf.int64, name = 'x')
print(sess.run(2 * x, feed_dict = {x: 3}))
sess.close()
实现线性函数
实现神经网络中得线性函数: Y = W X + b Y = WX +b Y=WX+b
def linear_function():
"""
实现线性函数:
初始化W的维度为 (4,3)
初始化X的维度为 (3,1)
初始化b的维度为(4,1)
返回值:
result -- 运行计算 Y = WX + b
"""
np.random.seed(1)
X = tf.constant(np.random.randn(3,1), name = "X")
W = tf.constant(np.random.randn(4,3),name = "W")
b = tf.constant(np.random.randn(4,1), name = "b")
Y = tf.add(tf.matmul(W,X),b)
sess = tf.Session()
result = sess.run(Y)
sess.close()
return result
#out: result [[-2.15657382] [ 2.95891446] [-1.08926781] [-0.84538042]]
实现激活函数
def sigmoid(z):
x = tf.placeholder(tf.float32, name = "x")
sigmoid = tf.sigmoid(x)
with tf.Session() as sess:
result = sess.run(sigmoid, {x: z})
return result
计算交叉熵损失
− 1 m ∑ i = 1 m ( y ( i ) log σ ( z [ 2 ] ( i ) ) + ( 1 − y ( i ) ) log ( 1 − σ ( z [ 2 ] ( i ) ) ) - \frac{1}{m} \sum_{i = 1}^m \large ( \small y^{(i)} \log \sigma(z^{[2](i)}) + (1-y^{(i)})\log (1-\sigma(z^{[2](i)})\large ) −m1i=1∑m(y(i)logσ(z[2](i))+(1−y(i))log(1−σ(z[2](i)))
def cost(logits, labels):
"""
用sifmoid激活函数计算交叉熵损失
参数:
logits --向量z,上一个线性单元的值
labels -- y标签 (1 or 0)
Note: 在tensorflow中称z和y为logits和labels
"""
z = tf.placeholder(tf.float32,name="z")
y = tf.placeholder(tf.float32, name="y")
cost = tf.nn.sigmoid_cross_entropy_with_logits(logits = z,labels = y)
sess = tf.Session()
cost = sess.run(cost, {z:logits,y:labels})
sess.close()
return cost
one hot编码(用于多元分类)
很多时候,在深度学习中,得到一个y向量,其数字范围从0到C-1,其中C是类的数量(多元分类)。 如果C是4,那么需要转换以下y向量,如下所示:
使用以下代码即可实现转换
tf.one_hot(labels, depth, axis)
def one_hot_matrix(labels, C):
#C = tf.constant(C,name="C")
one_hot_matrix = tf.one_hot(labels,C,axis=0)# 注意axis参数的用法
sess = tf.Session()
one_hot = sess.run(one_hot_matrix)
sess.close()
return one_hot
labels = np.array([1,2,3,0,2,1])
one_hot = one_hot_matrix(labels, C = 4)
print ("one_hot = " + str(one_hot))
# out:
#one_hot = [[ 0. 0. 0. 1. 0. 0.]
# [ 1. 0. 0. 0. 0. 1.]
# [ 0. 1. 0. 0. 1. 0.]
# [ 0. 0. 1. 0. 0. 0.]]