机器学习2--week3

一:Tensorflow简单教程及简单教程

之前一直都是用numpy创建神经网络,并手动实现正向传播,损失,反向传播等等,这在构建一个小型简单的神经网络还可以,也可以帮助我们理解神经网络的原理及相关算法,但是一旦神经网络变得复杂,那么自己手动实现不仅难度大,而且容易出错,运行速度慢,如果采用现有的框架,如Tensorflow,我们只要做好数据的处理,前向传播就可以了,其他的诸如损失,优化都可以交于Tensorflow去完成。大大提高了工作效率和程序的正确性

1 - Exploring the Tensorflow Library

用TensorFlow实现如下的损失函数:
l o s s = L ( y ^ , y ) = ( y ^ ( i ) − y ( i ) ) 2 loss=\mathcal{L}(\hat{y}, y)=\left(\hat{y}^{(i)}-y^{(i)}\right)^{2} loss=L(y^,y)=(y^(i)y(i))2
代码:

import tensorflow as tf
import numpy as tf


y_hat = tf.constant(36, name='y_hat')            # Define y_hat constant. Set to 36.
y = tf.constant(39, name='y')                    # Define y. Set to 39

loss = tf.Variable((y - y_hat)**2, name='loss')  # Create a variable for the loss

init = tf.global_variables_initializer()         # When init is run later (session.run(init)),
                                                 # the loss variable will be initialized and ready to be computed
with tf.Session() as session:                    # Create a session and print the output
    session.run(init)                            # Initializes the variables
    print(session.run(loss))

输出:9

在TensorFlow中编写和运行程序有以下步骤:

  1. 创建尚未执行/计算的张量(变量)
  2. 写出这些张量之间的运算
  3. 初始化你的张量
  4. 创建一个会话
  5. 运行会话
    因此,当为损失创建一个变量(tf.Variable)时,只是简单地将损失定义为其他量的函数,但没有计算它的值。为了计算它,必须运行init=tf.global_variables_initializer()。初始化了loss变量后,最后一行才能够计算loss的值并打印它的值。

另外一个例子

a = tf.constant(2)
b = tf.constant(10)
c = tf.multiply(a,b)
print(c)

输出:
Tensor(“Mul:0”, shape=(), dtype=int32)

正如所料,看不到20,但是得到一个张量,结果是一个没有形状属性的张量,类型为int32。我们所做的就是把它放入“计算图”中,但是还没有运行这个计算。为了将这两个数字相乘,必须创建一个会话并运行它。

sess = tf.Session()
print(sess.run(c))

输出:20

总之,记住初始化变量、创建会话并在会话中运行操作。

2 - 占位符(placeholder)

占位符是一个对象,只能在稍后指定其值。要为占位符指定值,可以使用feed_dict变量传入值,这是一个字典类型变量。

# Change the value of x in the feed_dict

x = tf.placeholder(tf.int64, name = 'x')
print(sess.run(2 * x, feed_dict = {x: 3}))
sess.close()

输出:6
当第一次定义x时,不必为它指定值。占位符只是一个变量,会在稍后运行会话时将数据分配给该变量。

3 - 线性函数

利用Tensorflow计算线性函数: Y = W X + b Y = WX + b Y=WX+b, W W W X X X 是随机的正态分布 矩阵 b b b 是一个随机向量
W. shape =(4, 3), X .shape=(3,1),b.shape= (4,1).使用下面的函数创建:

X = tf.constant(np.random.randn(3,1), name = "X")

可用到下三个函数:

  • tf.matmul(…, …)计算矩阵乘法
  • tf.add(…, …) 计算加法
  • np.random.randn(…) 初始化一个正态分布数据
# GRADED FUNCTION: linear_function

def linear_function():
    """
    Implements a linear function: 
            Initializes W to be a random tensor of shape (4,3)
            Initializes X to be a random tensor of shape (3,1)
            Initializes b to be a random tensor of shape (4,1)
    Returns: 
    result -- runs the session for 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='Y')
    Y = tf.matmul(W, X) + b
     
    sess = tf.Session()
    result = sess.run(Y)
    
    # close the session 
    sess.close()
    return result
print( "result = " + str(linear_function()))

输出:
result = [[-2.15657382]
[ 2.95891446]
[-1.08926781]
[-0.84538042]]

4 - 计算sigmoid

采用Tensorflow内置函数tf.sigmoid

# GRADED FUNCTION: sigmoid

def sigmoid(z):
    """
    Computes the sigmoid of z
    
    Arguments:
    z -- input value, scalar or vector
    
    Returns: 
    results -- the sigmoid of z
    """
    # Create a placeholder for x. Name it 'x'.
    x = tf.placeholder(tf.float32, name='x')

    # compute sigmoid(x)
    sigmoid = tf.sigmoid(x)

    with tf.Session() as sess:
        # Run session and call the output "result"
        result = sess.run(sigmoid, feed_dict={x:z})    
    return result
print ("sigmoid(12) = " + str(sigmoid(12)))

输出:sigmoid(12) = 0.9999938

5 - 计算cost

Tensorflow提供了内置函数来帮助计算损失,之前再使用numpy计算损失,采用的对输出样本做累加取平均的方式:
(2) J = − 1 m ∑ i = 1 m ( y ( i ) log ⁡ a [ 2 ] ( i ) + ( 1 − y ( i ) ) log ⁡ ( 1 − a [ 2 ] ( i ) ) ) J = - \frac{1}{m} \sum_{i = 1}^m \large ( \small y^{(i)} \log a^{ [2] (i)} + (1-y^{(i)})\log (1-a^{ [2] (i)} )\large )\small\tag{2} J=m1i=1m(y(i)loga[2](i)+(1y(i))log(1a[2](i)))(2)

使用Tensorflow的方式变成:
直接调用交叉熵接口进行计算,只要传入相应的Z和Y即可,这个函数进行了两步处理:
1.计算输出层sigmoid激活值
2.计算损失

tf.nn.sigmoid_cross_entropy_with_logits(logits = ...,  labels = ...)`

公式可以写成:
(2) − 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 )\small\tag{2} m1i=1m(y(i)logσ(z[2](i))+(1y(i))log(1σ(z[2](i)))(2)

# GRADED FUNCTION: cost

def cost(logits, labels):
    """
    Computes the cost using the sigmoid cross entropy
    
    Arguments:
    logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
    labels -- vector of labels y (1 or 0) 
    
    Note: What we've been calling "z" and "y" in this class are respectively called "logits" and "labels" 
    in the TensorFlow documentation. So logits will feed into z, and labels into y. 
    
    Returns:
    cost -- runs the session of the cost (formula (2))
    """   
    # Create the placeholders for "logits" (z) and "labels" (y) (approx. 2 lines)
    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)
    with tf.Session() as tf:
    	cost = sess.run(cost, feed_dict={z:logits, y:labels})
    return cost
logits = sigmoid(np.array([0.2,0.4,0.7,0.9]))
cost = cost(logits, np.array([0,0,1,1]))
print ("cost = " + str(cost))

输出:
cost = [1.0053872 1.0366408 0.41385433 0.39956617]

6 - 使用one-hot方式编码

很多时候,在深度学习中,你会得到一个y向量,它的数字从0到C-1不等,其中C是类的数量。如果C是例4,那么你可能有如下的y向量,你需要将其转换如下:
在这里插入图片描述

这被称为“one hot”编码,因为在转换后的表示中,每一列只有一个元素是“hot”(意思是设置为1)。在tensorflow中,可以使用一行代码:

tf.one_hot(labels, depth, axis) 

代码

# GRADED FUNCTION: one_hot_matrix

def one_hot_matrix(labels, C):
    """
    Creates a matrix where the i-th row corresponds to the ith class number and the jth column
                     corresponds to the jth training example. So if example j had a label i. Then entry (i,j) 
                     will be 1. 
                     
    Arguments:
    labels -- vector containing the labels 
    C -- number of classes, the depth of the one hot dimension
    
    Returns: 
    one_hot -- one hot matrix
    """
    
    # Create a tf.constant equal to C (depth), name it 'C'.
    C = tf.constant(C, name='C')
    
    # Use tf.one_hot, be careful with the axis
    one_hot_matrix = tf.one_hot(labels, C, axis=0)    
    with tf.Session() as sess:
    	one_hot = sess.run(one_hot_matrix)   
    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))

输出:
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.]]

7 - 初始化全0矩阵和全1矩阵

用1初始化,调用函数tf.ones()。用0初始化,可以使用tf.zeros()。这些函数呈现一个形状,并分别返回一个包含0和1的维度形状数组。

  • tf.ones(shape)
  • tf.zeros(shape)
# GRADED FUNCTION: ones

def ones(shape):
    """
    Creates an array of ones of dimension shape
    
    Arguments:
    shape -- shape of the array you want to create
        
    Returns: 
    ones -- array containing only ones
    """
    
    # Create "ones" tensor using tf.ones(...). (approx. 1 line)
    ones = tf.ones(shape)
    
    with tf.Session() as sess:
    	ones = sess.run(ones)
    return ones
print ("ones = " + str(ones([3])))

输出:
ones = [1. 1. 1.]

未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值