How to run and fit data with keras model?

This recipe helps you run and fit data with keras model

Recipe Objective

In machine learning, We have to first train the model on the data we have so that the model can learn and we can use that model to predict the further results.

So this recipe is a short example of how to run/fit data with keras model?

Build a Chatbot in Python from Scratch!

Step 1 - Import the library

import pandas as pd import numpy as np from keras.datasets import mnist from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout

We have imported pandas, numpy, mnist(which is the dataset), train_test_split, Sequential, Dense and Dropout. We will use these later in the recipe.

Step 2 - Loading the Dataset

Here we have used the inbuilt mnist dataset and stored the train data in X_train and y_train. We have used X_test and y_test to store the test data. (X_train, y_train), (X_test, y_test) = mnist.load_data()

Step 3 - Creating model and adding layers

We have created an object model for sequential model. We can use two args i.e layers and name. model = Sequential() Now, We are adding the layers by using 'add'. We can specify the type of layer, activation function to be used and many other things while adding the layer.
Here we have added four layers which will be connected one after other. model.add(Dense(512)) model.add(Dropout(0.3)) model.add(Dense(256, activation='relu')) model.add(Dropout(0.2))

Step 4 - Compiling the model

We can compile a model by using compile attribute. Let us first look at its parameters before using it.

  • optimizer : In this we can pass the optimizer we want to use. There are various optimizer like SGD, Adam etc.
  • loss : In this we can pass a loss function which we want for the model
  • metrics : In this we can pass the metric on which we want the model to be scored

model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])

Step 5 - Fitting the model

We can fit a model on the data we have and can use the model after that. Fitting a model means training our model on a data i.e. passing the data into the model so that the model can update its internal mathematical variables and get ready to make predictions. Here we are using the data which we have splitted i.e the training data for fitting the model.
While fitting we can pass various parameters like batch_size, epochs, verbose, validation_data and so on. model.fit(X_train, y_train, batch_size=128, epochs=2, verbose=1, validation_data=(X_test, y_test))

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

AWS MLOps Project for Gaussian Process Time Series Modeling
MLOps Project to Build and Deploy a Gaussian Process Time Series Model in Python on AWS

Build a Logistic Regression Model in Python from Scratch
Regression project to implement logistic regression in python from scratch on streaming app data.

Many-to-One LSTM for Sentiment Analysis and Text Generation
In this LSTM Project , you will build develop a sentiment detection model using many-to-one LSTMs for accurate prediction of sentiment labels in airline text reviews. Additionally, we will also train many-to-one LSTMs on 'Alice's Adventures in Wonderland' to generate contextually relevant text.

Customer Market Basket Analysis using Apriori and Fpgrowth algorithms
In this data science project, you will learn how to perform market basket analysis with the application of Apriori and FP growth algorithms based on the concept of association rule learning.

Deploy Transformer BART Model for Text summarization on GCP
Learn to Deploy a Machine Learning Model for the Abstractive Text Summarization on Google Cloud Platform (GCP)

Digit Recognition using CNN for MNIST Dataset in Python
In this deep learning project, you will build a convolutional neural network using MNIST dataset for handwritten digit recognition.

Build Deep Autoencoders Model for Anomaly Detection in Python
In this deep learning project , you will build and deploy a deep autoencoders model using Flask.

PyCaret Project to Build and Deploy an ML App using Streamlit
In this PyCaret Project, you will build a customer segmentation model with PyCaret and deploy the machine learning application using Streamlit.

AWS MLOps Project for ARCH and GARCH Time Series Models
Build and deploy ARCH and GARCH time series forecasting models in Python on AWS .