• 【484】Book


    目录:


    一、相关函数说明

    1. imdb.load_data()

      在 jupyter notebook 中使用代码 imdb.load_data? 可以获取函数的帮助文件。

    Signature: imdb.load_data(path='imdb.npz', num_words=None, skip_top=0, maxlen=None, seed=113, start_char=1, oov_char=2, index_from=3, **kwargs)
    Docstring:
    Loads the IMDB dataset.
    
    # Arguments
        path: where to cache the data (relative to `~/.keras/dataset`).
        num_words: max number of words to include. Words are ranked
            by how often they occur (in the training set) and only
            the most frequent words are kept
            保留前 num_words 个最常出现的单词,低频单词将被舍弃
        skip_top: skip the top N most frequently occurring words
            (which may not be informative).
        maxlen: sequences longer than this will be filtered out.
            序列长度太大会被顾虑掉
        seed: random seed for sample shuffling.
        start_char: The start of a sequence will be marked with this character.
            Set to 1 because 0 is usually the padding character.
        oov_char: words that were cut out because of the `num_words`
            or `skip_top` limit will be replaced with this character.
        index_from: index actual words with this index and higher.
    
    # Returns
        Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
        训练和测试数据以上面的形式返回
    

    2. numpy array 可以通过 list 将所有索引赋值

    a = [1, 2, 3]
    b = np.zeros((4,4))
    
    b[1][a] = 1
    # b[1, a] = 1
    # 效果相同,将 a 列表中的所有索引一起赋值
    
    b
    
    output:
    
    array([[0., 0., 0., 0.],
           [0., 1., 1., 1.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.]])
    

    3. 善用 enumerate 函数

      可以同时获取索引值及对应的值,特比适合进行 one hot encoding 构建

    def to_one_hot(labels, dimension=46):
        results = np.zeros((len(labels), dimension))
        for i, label in enumerate(labels):
            results[i, label] = 1
        return results
    

    4. 通过 numpy.array 来对比两个列表相似性

    a = [1, 2, 3, 4, 5]
    b = [1, 2, 5, 4, 3]
    c = np.array(a) == np.array(b)
    # 对比对应的数值是否一致
    print(c)
    # 返回一致的元素个数
    print(np.sum(c))
    
    output:
    
    array([ True,  True, False,  True, False])
    3
    

    5. 标签为整数,用 sparse_categorical_crossentropy 损失函数

    6. numpy 求 mean 与 sum

      对于二维的 numpy array,在计算 mean 的时候有个 axis 可以选,对于 axis=0,是指计算行的平均值,axis=1,是计算列的平均值

    a = np.arange(12)
    a
    array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
    
    a = a.reshape((3, 4))
    a
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    
    a.mean(axis=0)
    array([4., 5., 6., 7.])
    
    a.mean(axis=1)
    array([1.5, 5.5, 9.5])
    
    a.sum(axis=0)
    array([12, 15, 18, 21])
    
    a.sum(axis=1)
    array([ 6, 22, 38])
    

    7. 添加正则化来防止 overfitting  

      一种常见的降低 overfitting 的方法就是强制让模型权重只能取较小的值,从而限制模型的复杂度,这使得权重值的分布更加规则(regular)。

    • 添加 L2 权重正则化
    • 添加 L1 权重正则化
    • 添加 L1 和 L2 权重正则化  
    from keras import regularizers
    
    model = models.Sequential()
    model.add(layers.Dense(8, kernel_regularizer=regularizers.l2(0.001),
                           activation='tanh', input_shape=(10000,)))
    
    ...
    
    or 
    
    kernel_regularizer=regularizers.l1(0.001)
    kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.001)
    

    8. 添加 dropout 正则化

      对某一层使用 dropout,就是在训练过程中随机将该层的一些输出特征舍弃(设置为 0)。

      dropout 比率(dropout rate)是被设为 0 的特征所占的比例,通常在 0.2~0.5 范围内。测试时没有单元被舍弃,而该层的输出值需要按照 dropout 比率缩小,因为这时比训练时有更多的单元被激活,需要加以平衡。

      灵感:from Hinton。银行的防欺诈系统就是,办理业务有很多人,每个人负责某一项工作,这样他们想要欺诈银行就需要很多人合作,只要其中一两个人不合作,这个事情就无法完成,就类似于权重值,他们会有些“阴谋”,将他们有些值设置为 0,就可以打乱这种“阴谋”。

      keras 里面添加 dropout 层如下:

    model = models.Sequential()
    model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
    model.add(layers.Dropout(0.5)
    model.add(layers.Dense(16, activation='relu'))
    model.add(layers.Dropout(0.5)
    model.add(layers.Dense(16, activation='relu'))
    model.add(layers.Dropout(0.5)
    ...
    

      

    二、具体案例分析

    1. imdb 电影评论情感分析

      本例包含数据预处理,one-hot encoding,Keras 模型简介,hyperparameter 参数调参,结论就是想要达到好的结果,就是要不停的调整参数,避免 overfitting。

    参考:deep-learning-with-python-notebooks/3.5-classifying-movie-reviews.ipynb

    结论:

    • 一个隐藏层反而得到更好的效果,因为隐藏层太多容易 overfitting
    • 隐藏层单元为 8 个的时候效果最好,太多容易 overfitting,太少容易 underfitting
    • optimizer 改为 mse 反而效果更好
    • activation 改为 tanh 反而效果更好
  • 相关阅读:
    纯html的table打印注意事项
    Silverlight:针式打印机文字模糊的改善办法
    C#执行XSL转换
    tomcat 新手上路
    跨浏览器的剪贴板访问解决方案
    打印机设置(PrintDialog)、页面设置(PageSetupDialog) 及 RDLC报表如何选择指定打印机
    利用ActiveX实现web页面设置本地默认打印机、纸张大小
    前端工程化的理解
    算法注意---3、分治的本质
    算法与数据结构---4.9、最大子段和-dp空间优化
  • 原文地址:https://www.cnblogs.com/alex-bn-lee/p/13732612.html
Copyright © 2020-2023  润新知