6.7 KiB
6.7 KiB
AITech — Uczenie maszynowe — laboratoria
11. Sieci neuronowe (Keras)
Keras to napisany w języku Python interfejs do platformy TensorFlow, służącej do uczenia maszynowego.
Aby z niego korzystać, trzeba zainstalować bibliotekę TensorFlow:
Przykład implementacji sieci neuronowej do rozpoznawania cyfr ze zbioru MNIST, według https://keras.io/examples/vision/mnist_convnet
# Konieczne importy
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
# Przygotowanie danych
num_classes = 10
input_shape = (28, 28, 1)
# podział danych na zbiory uczący i testowy
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# skalowanie obrazów do przedziału [0, 1]
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# upewnienie się, że obrazy mają wymiary (28, 28, 1)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
print("x_train shape:", x_train.shape)
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")
# konwersja danych kategorycznych na binarne
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 1s 0us/step x_train shape: (60000, 28, 28, 1) 60000 train samples 10000 test samples
# Stworzenie modelu
model = keras.Sequential(
[
keras.Input(shape=input_shape),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(num_classes, activation="softmax"),
]
)
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 26, 26, 32) 320 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 13, 13, 32) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 11, 11, 64) 18496 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 5, 5, 64) 0 _________________________________________________________________ flatten (Flatten) (None, 1600) 0 _________________________________________________________________ dropout (Dropout) (None, 1600) 0 _________________________________________________________________ dense (Dense) (None, 10) 16010 ================================================================= Total params: 34,826 Trainable params: 34,826 Non-trainable params: 0 _________________________________________________________________
# Uczenie modelu
batch_size = 128
epochs = 15
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
model.fit(x_train, y_train, epochs=1, batch_size=batch_size, epochs=epochs, validation_split=0.1)
422/422 [==============================] - 38s 91ms/step - loss: 0.0556 - accuracy: 0.9826 - val_loss: 0.0412 - val_accuracy: 0.9893
<tensorflow.python.keras.callbacks.History at 0x1a50b35a070>
# Ewaluacja modelu
score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
Test loss: 0.03675819933414459 Test accuracy: 0.988099992275238