Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Keras Basics Tutorial

Introduction to Keras

Keras is a powerful and easy-to-use open-source library for developing and evaluating deep learning models. It is written in Python and is capable of running on top of other deep learning libraries like TensorFlow, Theano, and Microsoft Cognitive Toolkit (CNTK). Keras makes it simple to build and train deep learning models with a minimal amount of code.

Installing Keras

To get started with Keras, you need to have Python installed on your system. You can install Keras using pip. Open your terminal or command prompt and run the following command:

pip install keras

Importing Libraries

Once Keras is installed, you can start by importing the necessary libraries. Here is a basic example:

import keras
from keras.models import Sequential
from keras.layers import Dense
                

Creating a Simple Neural Network

Let's create a simple neural network using Keras. We'll start by initializing a Sequential model and then add layers to it.

# Initialize the model
model = Sequential()

# Add an input layer with 12 nodes
model.add(Dense(12, input_dim=8, activation='relu'))

# Add a hidden layer with 8 nodes
model.add(Dense(8, activation='relu'))

# Add an output layer with 1 node
model.add(Dense(1, activation='sigmoid'))
                

Compiling the Model

After defining the model, the next step is to compile it. During compilation, you specify the loss function, optimizer, and metrics.

# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
                

Training the Model

Now, let's train the model using the fit method. You need to provide the training data and the number of epochs.

# Assume X_train and y_train are your training data and labels
history = model.fit(X_train, y_train, epochs=150, batch_size=10, validation_split=0.2)
                

Evaluating the Model

After training the model, you can evaluate its performance on test data using the evaluate method.

# Assume X_test and y_test are your test data and labels
loss, accuracy = model.evaluate(X_test, y_test)
print(f'Loss: {loss}, Accuracy: {accuracy}')
                

Making Predictions

You can use the trained model to make predictions on new data using the predict method.

# Assume X_new is your new data
predictions = model.predict(X_new)
print(predictions)
                

Saving and Loading the Model

You can save your trained model to a file for later use and load it back when needed.

# Save the model
model.save('model.h5')

# Load the model
from keras.models import load_model
loaded_model = load_model('model.h5')
                

Conclusion

In this tutorial, we covered the basics of using Keras to build, compile, train, evaluate, and save a deep learning model. Keras provides a high-level interface that makes it easy to develop powerful deep learning models with minimal code. Happy learning!