Author: saqibkhan

  • MongoDB Create Database

    To create a database in MongoDB, First create a MongoClient object and specify a connection URL with the correct ip address and the name of the database which you want to create.

    Note: MongoDB will automatically create the database if it does not exist, and make a connection to it.

    Example

    Create a folder named “MongoDatabase” as a database. Suppose you create it on Desktop. Create a js file named “createdatabase.js” within that folder and having the following code:

    var MongoClient = require('mongodb').MongoClient;  
    
    var url = "mongodb://localhost:27017/MongoDatabase";  
    
    MongoClient.connect(url, function(err, db) {  
    
    if (err) throw err;  
    
    console.log("Database created!");  
    
    db.close();  
    
    });  

      Now open the command terminal and set the path where MongoDatabase exists. Now execute the following command:

      Node createdatabase.js  
      Node.js Create database 1
    1. Create Connection with MongoDB

      MongoDb is a NoSQL database. It can be used with Node.js as a database to insert and retrieve data.

      Download MongoDB

      Open the Linux Command Terminal and execute the following command:

      apt-get install mongodb  

      It will download the latest MongoDB according to your system requirement.

      Node.js Create connection 1

      Install MongoDB

      After the complete download, use the following command to install MogoDB.

      npm install mongodb --save   

      Use the following command to start MongoDb services:

      service mongodb start  
      Node.js Create connection 2
    2. Use Data Augmentation to Avoid Overfitting

      • Data augmentation can improve generalization and avoid overfitting, especially when your dataset is small.pythonCopy codefrom tensorflow.keras.preprocessing.image import ImageDataGenerator datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest' )
    3. Node.js MySQL Drop Table

      The DROP TABLE command is used to delete or drop a table.

      Let’s drop a table named employee2.

      Create a js file named “delete” in DBexample folder and put the following data into it:

      var mysql = require('mysql');  
      
      var con = mysql.createConnection({  
      
      host: "localhost",  
      
      user: "root",  
      
      password: "12345",  
      
      database: "javatpoint"  
      
      });  
      
      con.connect(function(err) {  
      
      if (err) throw err;  
      
      var sql = "DROP TABLE employee2";  
      
      con.query(sql, function (err, result) {  
      
      if (err) throw err;  
      
      console.log("Table deleted");  
      
      });  
      
      });  

        Now open command terminal and run the following command:

        Node drop.js  
        Node.js drop table 1

        Verify that the table employee2 is no more in the database.

        Node.js drop table 2
      1. Leverage Pretrained Models

        • Keras offers many pretrained models that can save you time and resources when working on tasks like image classification or feature extraction.pythonCopy codefrom tensorflow.keras.applications import VGG16 base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
      2. Node.js MySQL SELECT Unique Record

        (WHERE Clause)

        Retrieve a unique data from the table “employees”.

        Create a js file named selectwhere.js having the following data in DBexample folder.

        var mysql = require('mysql');  
        
        var con = mysql.createConnection({  
        
        host: "localhost",  
        
        user: "root",  
        
        password: "12345",  
        
        database: "javatpoint"  
        
        });  
        
        con.connect(function(err) {  
        
        if (err) throw err;  
        
        con.query("SELECT * FROM employees WHERE id = '1'", function (err, result) {  
        
        if (err) throw err;  
        
        console.log(result);  
        
        });  
        
        }); 

          Now open command terminal and run the following command:

          Node selectwhere.js  
          Node.js unique record 1

          Node.js MySQL Select Wildcard

          Retrieve a unique data by using wildcard from the table “employees”.

          Create a js file named selectwildcard.js having the following data in DBexample folder.

          var mysql = require('mysql');  
          
          var con = mysql.createConnection({  
          
          host: "localhost",  
          
          user: "root",  
          
          password: "12345",  
          
          database: "javatpoint"  
          
          });  
          
          con.connect(function(err) {  
          
          if (err) throw err;  
          
          con.query("SELECT * FROM employees WHERE city LIKE 'A%'", function (err, result) {  
          
          if (err) throw err;  
          
          console.log(result);  
          
          });  
          
          });  

            Now open command terminal and run the following command:

            Node selectwildcard.js  

            It will retrieve the record where city start with A.

            Node.js unique record 2
          1. Node.js MySQL Select Records

            Example

            Retrieve all data from the table “employees”.

            Create a js file named select.js having the following data in DBexample folder.

            var mysql = require('mysql');  
            
            var con = mysql.createConnection({  
            
            host: "localhost",  
            
            user: "root",  
            
            password: "12345",  
            
            database: "javatpoint"  
            
            });  
            
            con.connect(function(err) {  
            
            if (err) throw err;  
            
            con.query("SELECT * FROM employees", function (err, result) {  
            
            if (err) throw err;  
            
            console.log(result);  
            
            });  
            
            }); 

              Now open command terminal and run the following command:

              Node select.js  
              Node.js select record 1

              You can also use the statement:

              SELECT * FROM employees;  
              Node.js select record 2
            1. Use Callbacks

              • Callbacks can help improve your training process, monitor metrics, and avoid overfitting.
              • Common callbacks include:
                • EarlyStopping: Stop training when a monitored metric has stopped improving.
                • ModelCheckpoint: Save the best model during training.
                • ReduceLROnPlateau: Reduce the learning rate when a metric has stopped improving.
                pythonCopy codefrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau callbacks = [ EarlyStopping(monitor='val_loss', patience=3), ModelCheckpoint('best_model.h5', save_best_only=True), ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2) ] model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=50, callbacks=callb
            2. Set Random Seed for Reproducibility

              • To ensure that your results are reproducible, you can set a random seed at the start of your code:pythonCopy codeimport numpy as np import tensorflow as tf np.random.seed(42) tf.random.set_seed(42)
            3. Graph Neural Networks (GNN):

              • Graph Convolutional Networks (GCNs): Using GCNs for node classification, link prediction, and other graph-based tasks. GNNs operate directly on graph structures, learning from node features and their neighbors.
              pythonCopy codeimport tensorflow as tf
              from tensorflow.keras import layers
              
              class GraphConvolution(layers.Layer):
              
              def call(self, inputs):
                  adjacency_matrix, features = inputs
                  aggregated_features = tf.matmul(adjacency_matrix, features)
                  return aggregated_features
              inputs = layers.Input(shape=(num_nodes, feature_dim)) adj_matrix = layers.Input(shape=(num_nodes, num_nodes)) gcn_layer = GraphConvolution()([adj_matrix, inputs]) output = layers.Dense(num_classes, activation='softmax')(gcn_layer) model = models.Model([inputs, adj_matrix], output)