《深度学习——Andrew Ng》第五课第一周编程作业_2_dinosaurus island

这篇博客介绍了在Andrew Ng的深度学习课程中,使用RNN进行恐龙名字生成的编程作业。通过训练,RNN能够创造类似恐龙名字的新名称。文章强调了模型中RNN细胞的计算流程以及应用clip函数来防止梯度爆炸,确保训练稳定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第二课的作业是给恐龙起名,训练集是一系列恐龙的名字,经过训练后,RNN网络可以生成新的恐龙的名字,随着训练次数的迭代,可以发现得到的名字越来越像是正常的恐龙名字。

这里有两点需要注意一下:

使用的模型RNN

图中的每个cell都把计算流程标清楚了
这里写图片描述

clip剪枝函数

使用梯度下降进行后向传播,所以存在单次迭代梯度过大的情况,这里使用函数进行梯度数值的约束,让每次的梯度值在一个阈值内。(剪枝可能不太准确,叫梯度正则化可能会好一点。。。)
这里写图片描述

程序Pycharm版

# dinosaurus island

import numpy as np
from utils import *
import random
from random import shuffle


### GRADED FUNCTION: clip
def clip(gradients, maxValue):
    '''
    Clips the gradients' values between minimum and maximum.

    Arguments:
    gradients -- a dictionary containing the gradients "dWaa", "dWax", "dWya", "db", "dby"
    maxValue -- everything above this number is set to this number, and everything less than -maxValue is set to -maxValue

    Returns:
    gradients -- a dictionary with the clipped gradients.
    '''

    dWaa, dWax, dWya, db, dby = gradients['dWaa'], gradients['dWax'], gradients['dWya'], gradients['db'], gradients[
        'dby']

    ### START CODE HERE ###
    # clip to mitigate exploding gradients, loop over [dWax, dWaa, dWya, db, dby]. (≈2 lines)
    for gradient in [dWax, dWaa, dWya, db, dby]:
        np.clip(gradient, -1*maxValue, maxValue, out=gradient)               # 这里想要保存clip后的值要设置out参数,不能用 gradient = np.clip(gradient, -1*maxValue, maxValue)

    ### END CODE HERE ###

    gradients = {
  "dWaa": dWaa, "dWax": dWax, "dWya": dWya, "db": db, "dby": dby}

    return gradients


# GRADED FUNCTION: sample
def sample(parameters, char_to_ix, seed):
    """
    Sample a sequence of characters according to a sequence of probability distributions output of the RNN

    Arguments:
    parameters -- python dictionary containing the parameters Waa, Wax, Wya, by, and b.
    char_to_ix -- python dictionary mapping each character to an index.
    seed -- used for grading purposes. Do not worry about it.

    Returns:
    indices -- a list of length n containing the indices of the sampled characters.
    """

    # Retrieve parameters and relevant shapes from "parameters" dictionary
    Waa, Wax, Wya, by, b = parameters['Waa'], parameters['Wax'], parameters['Wya'], parameters[
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值