-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCNN-02
45 lines (38 loc) · 1.56 KB
/
CNN-02
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
#CNN_02
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_length, embedding_dim, weights=[embedding_matrix], input_length=max_len, trainable=False),
tf.keras.layers.Conv1D(64, 5, activation='relu'),
tf.keras.layers.MaxPooling1D(2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy', tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
# Define early stopping callback
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
# Train the model
history = model.fit(X_train, Y_train, epochs=30, batch_size=64, validation_data=(X_test, Y_test), callbacks=[early_stop])
# Evaluate the model
test_loss, test_acc, test_precision, test_recall = model.evaluate(X_test, Y_test)
print('Test Loss:', test_loss)
print('Test Accuracy:', test_acc)
# Plot the training and validation accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# Plot the training and validation loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
y_pred_prob = model.predict(X_test)
y_pred = (y_pred_prob >= 0.5).astype(int)
print(classification_report(y_test, y_pred))