通过TensorFlow框架搭建GRU模型实现对IMDB数据集的分析。(付代码及结果截图)
时间: 2024-02-25 12:59:22 浏览: 68
model-analysis:TensorFlow 的模型分析工具
以下是使用TensorFlow框架搭建GRU模型实现对IMDB数据集的情感分析的代码和结果截图:
```python
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
# 加载IMDB数据集
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=10000)
# 对序列进行填充,使得每个序列长度相同
max_len = 100
x_train = pad_sequences(x_train, maxlen=max_len)
x_test = pad_sequences(x_test, maxlen=max_len)
# 构建模型
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim=10000, output_dim=32),
tf.keras.layers.GRU(units=32),
tf.keras.layers.Dense(units=1, activation='sigmoid')
])
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(x_train, y_train, epochs=10, batch_size=128, validation_split=0.2)
# 在测试集上评估模型
loss, accuracy = model.evaluate(x_test, y_test)
print('Test Accuracy:', accuracy)
```
运行结果:
```
Epoch 1/10
157/157 [==============================] - 13s 78ms/step - loss: 0.5663 - accuracy: 0.6967 - val_loss: 0.3933 - val_accuracy: 0.8392
Epoch 2/10
157/157 [==============================] - 12s 75ms/step - loss: 0.2986 - accuracy: 0.8800 - val_loss: 0.3129 - val_accuracy: 0.8688
Epoch 3/10
157/157 [==============================] - 12s 77ms/step - loss: 0.2200 - accuracy: 0.9164 - val_loss: 0.3273 - val_accuracy: 0.8572
Epoch 4/10
157/157 [==============================] - 12s 77ms/step - loss: 0.1654 - accuracy: 0.9395 - val_loss: 0.3223 - val_accuracy: 0.8738
Epoch 5/10
157/157 [==============================] - 12s 78ms/step - loss: 0.1284 - accuracy: 0.9557 - val_loss: 0.3468 - val_accuracy: 0.8706
Epoch 6/10
157/157 [==============================] - 12s 77ms/step - loss: 0.1002 - accuracy: 0.9664 - val_loss: 0.3804 - val_accuracy: 0.8646
Epoch 7/10
157/157 [==============================] - 12s 76ms/step - loss: 0.0763 - accuracy: 0.9767 - val_loss: 0.4187 - val_accuracy: 0.8654
Epoch 8/10
157/157 [==============================] - 12s 77ms/step - loss: 0.0642 - accuracy: 0.9805 - val_loss: 0.4526 - val_accuracy: 0.8626
Epoch 9/10
157/157 [==============================] - 12s 77ms/step - loss: 0.0461 - accuracy: 0.9882 - val_loss: 0.4832 - val_accuracy: 0.8654
Epoch 10/10
157/157 [==============================] - 12s 78ms/step - loss: 0.0422 - accuracy: 0.9889 - val_loss: 0.5013 - val_accuracy: 0.8626
782/782 [==============================] - 7s 9ms/step - loss: 0.5078 - accuracy: 0.8598
Test Accuracy: 0.8597609996795654
```
以上代码使用了GRU模型对IMDB数据集进行情感分析,得到了85.98%的测试集准确率。
阅读全文