Tutorial to Predict the Type of Glass using MongoDB
Tags: beginners, mindsdb, ai, mongodb
Published: 2023-02-20 18:23:01

## What is MindsDB?
Data that lives in your database is a valuable asset. MindsDB enables you to use your data and make forecasts. It speeds up the ML development process by bringing machine learning into the database.

With MindsDB, you can build, train, optimize, and deploy your ML models without the need for other platforms. And to get the forecasts, simply query your data and ML models. Read along to see some examples.

## What are AI Tables?
MindsDB brings machine learning into databases by employing the concept of AI Tables.

AI Tables are machine learning models stored as virtual tables inside a database. They facilitate making predictions based on your data. You can perform time series, regression, and classification predictions within your database and get the output almost instantly by querying an AI Table with simple SQL statements.

## What will we be learning in this tutorial?
**Part 1 : Setting up the requirements**

First and foremost, we will prepare our setup that is essential to start forecasting with MindsDB and MongoAPI.

1. Download MongoDB and MongoDB Compass
2. Getting started with MindsDB
3. Integrating MindsDB with MongoDB

**Part 2 : Generating ML Models**

We will see how to create and train ML models in our database. In this tutorial, we will be classifying glass using [this dataset](https://www.kaggle.com/datasets/danushkumarv/glass-identification-data-set).

1. Preparing the database
2. Understanding our Problem Statement
3. Creating the Predictor Model
4. Querying the Predictor Model

## Part 1 : Setting up the requirements
We will be explaining this section briefly, so that we can move on to our predictions.

**Download MongoDB and MongoDB Compass**

To get started we must have both [MongoDB Community Edition](https://www.mongodb.com/try/download/community) and [MongoDB Compass](https://www.mongodb.com/try/download/compass) installed and working in our systems.

Once you are done with the installation of both MongoDB and MongoDB Compass we can get going with our tutorial.

**Getting started with MindsDB**

MindsDB provides all users with a free MindsDB Cloud version that they can access to generate predictions on their database. You can sign up for the free [MindsDB Cloud Version](https://cloud.mindsdb.com/) by following the [setup guide](https://docs.mindsdb.com/setup/cloud/). Verify your email and log into your account and you are ready to go. Once done, you should be seeing a page like this :

![MindsDB Cloud dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yoq08e49oj0a1vzaiwzg.png)

If you wish, you can choose to install MindsDB on your local system using docker image or by using [PyPI](https://pypi.org/project/MindsDB/). However, we will be working with Minds DB Cloud in this tutorial.

**Integrating MindsDB with MongoDB**

MindsDB provides us the ability to integrate with MongoDB using the MongoAPI. We can do so by following the given steps.

Open your MongoDB Compass. On the left navigation panel, You will have an option for a New Connection. Click on that Option and you will be provided with the details of your connection.

In the URI Section enter the following :

```
mongodb://cloud.mindsdb.com/
```

Click on the Advanced Connection Options dropdown. Here your host will be detected as MindsDB Cloud.

In the Authentication option enter your MindsDB Username and Password. Then click on Save and Connect, give your connection a name and select and color.

![MongoDB Compass](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yj9ek5pzofn0lxajpawt.png)

If you successfully create a connection you will be displayed a page similar to this :

![MongoDB Compass  Connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tk4gdzwj5816fcxl189g.png)

In the bottom panel of this page, you will see the the Mongo Shell bar, enlarge it and type the following queries and click Enter.

```
> use mindsdb
> show collections
```

![Mongo Shell Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z5e1kv1qa81mn30fi04f.png)

If you get a result like this, it means that we have succeeded in integrating MindsDB with MongoDB. Now let us move to the second part of our tutorial where we will be generating an ML model.

## Part 2 : Generating ML Models
**Preparing the database**

We will be preparing our database on which we can run our queries and perform our forecasts. On the MindsDB Cloud console, click on the last icon in the left navigation bar. You will see a 'Select Your Data Sources' page. We can add a variety of data sources, however, for this tutorial we will be working with .csv files.

Go to the files section and click on Import File. Import your csv file and provide a name for your database table in which the contents of the .csv file will be stored. Click on Save and Continue.

![Database Upload](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rknt9h4me0jlw7vv1fpr.png)

We need to import the data to our MongoDB database. We can use the databases.insertOne() command for this purpose.

To do so, go to the Mongo Shell and type the following command :

```
db.databases.insertOne({
    name: "glass_db", // database name
    engine: "mongodb", // database engine 
    connection_args: {
        "port": 27017, // default connection port
        "host": "mongodb+srv://readonly:6CKCDJFzLIxOtKhu@cluster0.uhsuhui.mongodb.net/test", // connection host
        "database": "glass_db" // database connection          
    }
});
```

On clicking Enter, you must receive the following response :

```
{
  acknowledged: true,
  insertedId: ObjectId("63f3b457011bd9118e88fa8c")
}
```

If you get such a response, that means your database is successfully created!

**Understanding our Problem Statement**

We saw earlier that we will be classifying glass using this [Kaggle dataset](https://www.kaggle.com/datasets/danushkumarv/glass-identification-data-set). Let us take a closer look into our database that we have set up. Our database consists of the following fields :

Id number: 1 to 214
RI: refractive index
Na: Sodium (unit measurement: weight percent in the corresponding oxide, as
are attributes 4-10)
Mg: Magnesium
Al: Aluminum
Si: Silicon
K: Potassium
Ca: Calcium
Ba: Barium
Fe: Iron
Type of glass: (class attribute)
1 building_windows_float_processed
2 building_windows_non_float_processed
3 vehicle_windows_float_processed
4 vehicle_windows_non_float_processed (none in this database)
5 containers
6 tableware
7 headlamps

We can run the following query in our MindsDB Console to see our database where we can see all our fields :

```
SELECT * FROM files.glass LIMIT 10;
```

This is what will be displayed :

![Database fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yslwm34bpb4ae7x1mz5l.png)

Now let us understand what we are trying to predict. We have been given a database consisting of various fields and we want to predict whether something is glass according to its features. We are going to train an ML model that learns how to recognize glass according to the features. And once we have trained our model, we can input the details of a house and our ML Model will predict if it's glass.

Sounds like a difficult task? Let us see how MindsDB can do that for us in a simple query!

**Creating the Predictor Model**

Now that our database is ready, we can go ahead and create our ML Model. As we have seen, The Predictor Model is basically a trained Machine Learning Model that can be used to predict or forecast a particular value known as the target variable or target value.

go to the Mongo Shell and type the following command :

```
db.predictors.insert({ name: "glass_predictor", predict: "Type of glass", connection: "glass_db", "select_data_query": "db.glass.find()" }); 
```

What do those parameters mean?

- name: name by which mindsdb identifies the predictor
- predict: name of the column in the database which values we want to predict
- connection: name we created previously by which Mindsdb identifies the connection
- select_data_query: this allows to specify specific rows in the database by using standard MongoDB queries. For this example, we will use all rows.

If there are no hiccups, we will get a Query Successfully Completed message.

```
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("63f3b501011bd9118e88fa8d")
  }
}
```

And that’s it! We have created and trained a Machine Learning model by a single query! That is the magic of MindsDB!

**Querying the Predictor Model**

We can see our machine learning model specifications by typing the following command in our Mongo Shell :
 
```
db.predictors.find({name:"glass_predictor"})
```

When we press Enter we get all the details of our Predictor Model like its status, accuracy, target value and errors.

```
{
  NAME: 'glass_predictor',
  ENGINE: 'lightwood',
  PROJECT: 'mindsdb',
  VERSION: 1,
  STATUS: 'complete',
  ACCURACY: 0.667,
  PREDICT: 'Type of glass',
  UPDATE_STATUS: 'up_to_date',
  MINDSDB_VERSION: '23.1.3.2',
  ERROR: null,
  SELECT_DATA_QUERY: 'db.glass.find()',
  TRAINING_OPTIONS: "{'target': 'Type of glass', 'using': {}}",
  TAG: null
}
```


Now finally we can query our ML model to predict the target value of a particular entry.

The query for that is :


```
db.glass_predictor.find({
_id: "63f3b3d488ca3f8488ea95c4",
Id: "2",
RI: "1.7435747",
Na: "11.5",
Mg: "3.2",
Al: "1.30",
Si: "67.81",
K: "0.5",
Ca: "7.01",
Ba: "0",
Fe: "0"})
```


And lo and behold! Our model predicts the type of glass according to its attributes entered by us :

```
{
  RI: '1.7435747',
  Na: '11.5',
  Mg: '3.2',
  Al: '1.30',
  Si: '67.81',
  K: '0.5',
  Ca: '7.01',
  Ba: '0',
  Fe: '0',
  'Type of glass': '2',
  select_data_query: null,
  when_data: null,
  'Type of glass_original': null,
  'Type of glass_confidence': 0.9047619047619048,
  'Type of glass_explain': '{"predicted_value": "2", "confidence": 0.9047619047619048, "anomaly": null, "truth": null, "probability_class_2": 0.8632, "probability_class_1": 0.0581, "probability_class_7": 0.0598, "probability_class_3": 0.0085, "probability_class_5": 0.0054, "probability_class_6": 0.005}',
  'Type of glass_anomaly': null,
  _id: '63f3b3d488ca3f8488ea95c4',
  '`Id`': '2'
}
```

## Conclusion :
Using MindsDB we have successfully created and trained a Machine Learning model in our database and unlocked the ability to generate in-database forecasts. You can visit the [MindsDB Documentation](https://docs.mindsdb.com/) to know the various features of MindsDB.

## What’s Next?
If you enjoyed following along to this tutorial, make sure to Sign Up for a free [MindsDB Cloud account](https://cloud.mindsdb.com/) and continue exploring! [Kaggle](https://www.kaggle.com/) is a great resource to find similar datasets and you can create and train an ML model of your own with the help of MindsDB. You can also check them out on [GitHub](https://github.com/mindsdb/mindsdb).