Source From Here
Question
As title.
HowTo
First step, let's prepare some fake training/test data:
Check dataset shape:
Output:
Next is to generate a NN model:
Output:
It is time for training and collect evaluation result:
Output:
Now we can check out accuracy trending chart:
And then the loss trending chart:
For the complete example, refer to this notebook.
Supplement
* How to Use ROC Curves and Precision-Recall Curves for Classification in Python
* How to make inline plots in Jupyter Notebook larger?
As title.
HowTo
First step, let's prepare some fake training/test data:
- from sklearn.datasets import make_classification
- from sklearn.linear_model import LogisticRegression
- from sklearn.model_selection import train_test_split
- from sklearn.metrics import roc_curve
- from sklearn.metrics import roc_auc_score
- from matplotlib import pyplot
- # Generate 2 class dataset
- X, y = make_classification(n_samples=1000, n_classes=2, random_state=1)
- # Split into train/test sets
- trainX, testX, trainy, testy = train_test_split(X, y, test_size=0.2, random_state=2)
- print(f"trainX.shape={trainX.shape}")
Next is to generate a NN model:
- import keras
- import tensorflow as tf
- from keras.models import Sequential
- from keras.layers import Dense
- from keras.wrappers.scikit_learn import KerasClassifier
- from keras import regularizers
- from keras.optimizers import SGD
- from keras.layers import Dropout
- from keras.models import model_from_json
- from keras import backend as K
- from keras.callbacks import Callback
- def get_nn(input_shape):
- # Initialising the ANN
- classifier = Sequential()
- # Adding the dropout layer
- classifier.add(Dropout(0.01, input_shape=(input_shape,)))
- # Adding the input layer and the first hidden layer
- classifier.add(Dense(input_shape, kernel_initializer='uniform', activation='sigmoid'))
- # Adding the input layer and the first hidden layer
- classifier.add(Dense(input_shape*2, kernel_initializer='uniform', activation='sigmoid'))
- # Adding the second hidden layer
- classifier.add(
- Dense(
- units=int(input_shape),
- kernel_initializer = 'uniform',
- activation = 'sigmoid',
- activity_regularizer=regularizers.l1(10e-5)
- )
- )
- # Adding the third hidden layer
- classifier.add(
- Dense(
- units=int(input_shape/2),
- kernel_initializer = 'uniform',
- activation = 'sigmoid',
- activity_regularizer=regularizers.l1(10e-5)
- )
- )
- # Adding the output layer
- classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
- # Compiling the ANN
- # https://keras.io/api/optimizers/
- # opt = SGD(lr=0.01, momentum=0.9)
- m_preccision = keras.metrics.Precision()
- m_recall = keras.metrics.Recall()
- # classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = [m_preccision, m_recall])
- classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy', tf.keras.metrics.Precision()])
- return classifier
- nn_model = get_nn(trainX.shape[1])
- nn_model.summary()
- Model: "sequential_5"
- _________________________________________________________________
- Layer (type) Output Shape Param #
- =================================================================
- dropout_5 (Dropout) (None, 20) 0
- _________________________________________________________________
- dense_23 (Dense) (None, 20) 420
- _________________________________________________________________
- dense_24 (Dense) (None, 40) 840
- _________________________________________________________________
- dense_25 (Dense) (None, 20) 820
- _________________________________________________________________
- dense_26 (Dense) (None, 10) 210
- _________________________________________________________________
- dense_27 (Dense) (None, 1) 11
- =================================================================
- Total params: 2,301
- Trainable params: 2,301
- Non-trainable params: 0
- from matplotlib import pyplot as plt
- history = nn_model.fit(trainX, trainy, validation_split=0.1, epochs=50, batch_size=4)
- print(f"history.history.key()={history.history.keys()}")
Now we can check out accuracy trending chart:
- plt.rcParams['figure.figsize'] = [10, 5]
- plt.plot(history.history['accuracy'])
- plt.plot(history.history['val_accuracy'])
- plt.title('model accuracy')
- plt.ylabel('accuracy')
- plt.xlabel('epoch')
- plt.legend(['train', 'val'], loc='upper left')
- plt.show()
And then the loss trending chart:
- plt.plot(history.history['loss'])
- plt.plot(history.history['val_loss'])
- plt.title('model loss')
- plt.ylabel('loss')
- plt.xlabel('epoch')
- plt.legend(['train_loss', 'val_loss'], loc='upper left')
- plt.show()
For the complete example, refer to this notebook.
Supplement
* How to Use ROC Curves and Precision-Recall Curves for Classification in Python
* How to make inline plots in Jupyter Notebook larger?
沒有留言:
張貼留言