Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

lstm_embedding.py 5.2 KB

You have to be logged in to leave a comment. Sign In
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
  1. # -*- coding: utf-8 -*-
  2. """LSTM-embedding.ipynb
  3. Automatically generated by Colaboratory.
  4. Original file is located at
  5. https://colab.research.google.com/drive/1up_JyJBZ1VnlidzHKtpGMGMRc1W9uXG5
  6. """
  7. import matplotlib as mpl
  8. import matplotlib.pyplot as plt
  9. import numpy as np
  10. import pandas as pd
  11. import tensorflow as tf
  12. from tensorflow import keras
  13. import sklearn
  14. import os
  15. import sys
  16. import time
  17. print(tf.__version__)
  18. print(sys.version_info)
  19. for module in mpl,np,pd,sklearn,tf,keras:
  20. print(module.__name__,module.__version__)
  21. imdb=keras.datasets.imdb
  22. vocab_size=10000
  23. index_from=3
  24. (train_data,train_labels),(test_data,test_labels)=imdb.load_data(num_words=vocab_size,index_from=index_from)
  25. word_index=imdb.get_word_index()
  26. print(len(word_index))
  27. word_index={k:(v+3) for k,v in word_index.items()}
  28. word_index['<PAD>']=0
  29. word_index['<START>']=1
  30. word_index['<UNK>']=2
  31. word_index['<END>']=3
  32. reverse_word_index=dict([
  33. (value,key) for key,value in word_index.items()
  34. ])
  35. def decode_review(text_ids):
  36. return ' '.join([reverse_word_index.get(word_id,'<UNK>') for word_id in text_ids])
  37. decode_review(train_data[0])
  38. max_length=500
  39. train_data=keras.preprocessing.sequence.pad_sequences(
  40. train_data,value=word_index['<PAD>'],
  41. padding='post',maxlen=max_length
  42. )
  43. test_data=keras.preprocessing.sequence.pad_sequences(
  44. test_data,value=word_index['<PAD>'],
  45. padding='post',maxlen=max_length
  46. )
  47. print(train_data[0])
  48. # 单向LSTM
  49. embedding_dim=16
  50. batch_size=512
  51. # 把DNN的全局平均换成单向RNN,时间变长,不断修改效果变好
  52. # return_sequences:Boolean. Whether to return the last output in the output sequence, or the full sequence 文本生成、机器翻译是要返回所有序列的True,只要最后一个序列False
  53. # 这里的变量名字应该改成model_LSTM的(代码从单向RNN复制过来正在训练,就不改了)
  54. single_rnn_model=keras.models.Sequential([
  55. keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length),
  56. keras.layers.LSTM(units=64,return_sequences=False),
  57. # w=64,b=64
  58. keras.layers.Dense(64,activation='relu'),
  59. keras.layers.Dense(1,activation='sigmoid'),
  60. ])
  61. single_rnn_model.summary()
  62. single_rnn_model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
  63. # 全连接层参数是4160 wx+b:x是一维的64
  64. history_single_rnn=single_rnn_model.fit(
  65. train_data,train_labels,
  66. epochs=30,
  67. batch_size=batch_size,
  68. validation_split=0.2
  69. )
  70. def plot_learning_curves(history,label,epochs,min_value,max_value):
  71. data={}
  72. data[label]=history.history[label]
  73. data['val_'+label]=history.history['val_'+label]
  74. pd.DataFrame(data).plot(figsize=(8,5))
  75. plt.grid(True)
  76. plt.axis([0,epochs,min_value,max_value])
  77. plt.show()
  78. # 训练集、验证集上的准确率
  79. plot_learning_curves(history_single_rnn,'accuracy',30,0,1)
  80. # 训练集、验证集上的损失
  81. plot_learning_curves(history_single_rnn,'loss',30,0,1)
  82. """过拟合-验证集上效果差一些"""
  83. single_rnn_model.evaluate(
  84. test_data,test_labels,
  85. batch_size=batch_size,
  86. verbose=0
  87. )
  88. # 双向双层LSTM
  89. embedding_dim=16
  90. batch_size=512
  91. # return_sequences:Boolean. Whether to return the last output in the output sequence, or the full sequence 文本生成、机器翻译是要返回所有序列的True,只要最后一个序列False
  92. model=keras.models.Sequential([
  93. keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length),
  94. keras.layers.Bidirectional(keras.layers.LSTM(units=64,return_sequences=True)),
  95. keras.layers.Bidirectional(keras.layers.LSTM(units=64,return_sequences=False)),
  96. # w=64,b=64
  97. keras.layers.Dense(64,activation='relu'),
  98. keras.layers.Dense(1,activation='sigmoid'),
  99. ])
  100. model.summary()
  101. model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
  102. # 全连接层参数是4160 wx+b:x是一维的64
  103. history=single_rnn_model.fit(
  104. train_data,train_labels,
  105. epochs=30,
  106. batch_size=batch_size,
  107. validation_split=0.2
  108. )
  109. # 训练集、验证集上的准确率
  110. plot_learning_curves(history,'accuracy',30,0,1)
  111. # 训练集、验证集上的损失
  112. plot_learning_curves(history,'loss',30,0,1)
  113. # 双向单层LSTM
  114. embedding_dim=16
  115. batch_size=512
  116. # return_sequences:Boolean. Whether to return the last output in the output sequence, or the full sequence 文本生成、机器翻译是要返回所有序列的True,只要最后一个序列False
  117. bi_lstm_model=keras.models.Sequential([
  118. keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length),
  119. keras.layers.Bidirectional(keras.layers.LSTM(units=32,return_sequences=False)),
  120. # w=64,b=64
  121. keras.layers.Dense(64,activation='relu'),
  122. keras.layers.Dense(1,activation='sigmoid'),
  123. ])
  124. bi_lstm_model.summary()
  125. bi_lstm_model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
  126. # 全连接层参数是4160 wx+b:x是一维的64
  127. history=bi_lstm_model.fit(
  128. train_data,train_labels,
  129. epochs=30,
  130. batch_size=batch_size,
  131. validation_split=0.2
  132. )
  133. # 训练集、验证集上的准确率
  134. plot_learning_curves(history,'accuracy',30,0,1)
  135. # 训练集、验证集上的损失
  136. plot_learning_curves(history,'loss',30,0,1)
  137. bi_lstm_model.evaluate(test_data,test_labels,batch_size=batch_size,verbose=0)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...