alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

【484】Book - Deep Learning with Python 相关说明与代码

目录:


一、相关函数说明

1. imdb.load_data()

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 将所有索引赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 构建

1
2
3
4
5
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 来对比两个列表相似性

1
2
3
4
5
6
7
8
9
10
11
12
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([ TrueTrue, FalseTrue, False])
3

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

6. numpy 求 mean 与 sum

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
a = np.arange(12)
a
array([ 0123456789, 10, 11])
 
a = a.reshape((3, 4))
a
array([[ 0123],
       [ 4567],
       [ 89, 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 权重正则化  
1
2
3
4
5
6
7
8
9
10
11
12
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 层如下:

1
2
3
4
5
6
7
8
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 反而效果更好

posted on   McDelfino  阅读(221)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示