Author: saqibkhan

  • Node.js Buffers

    Node.js provides Buffer class to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. Buffer class is used because pure JavaScript is not nice to binary data. So, when dealing with TCP streams or the file system, it’s necessary to handle octet streams.

    Buffer class is a global class. It can be accessed in application without importing buffer module.

    Node.js Creating Buffers

    There are many ways to construct a Node buffer. Following are the three mostly used methods:

    1. Create an uninitiated buffer: Following is the syntax of creating an uninitiated buffer of 10 octets:
    var buf = new Buffer(10);  
    1. Create a buffer from array: Following is the syntax to create a Buffer from a given array:
    var buf = new Buffer([10, 20, 30, 40, 50]);   
    1. Create a buffer from string: Following is the syntax to create a Buffer from a given string and optionally encoding type:
    var buf = new Buffer("Simply Easy Learning", "utf-8");   

    Node.js Writing to buffers

    Following is the method to write into a Node buffer:

    Syntax:

    buf.write(string[, offset][, length][, encoding])  

    Parameter explanation:

    string: It specifies the string data to be written to buffer.

    offset: It specifies the index of the buffer to start writing at. Its default value is 0.

    length: It specifies the number of bytes to write. Defaults to buffer.length

    encoding: Encoding to use. ‘utf8’ is the default encoding.

    Return values from writing buffers:

    This method is used to return number of octets written. In the case of space shortage for buffer to fit the entire string, it will write a part of the string.

    Let’s take an example:

    Create a JavaScript file named “main.js” having the following code:

    File: main.js

    buf = new Buffer(256);  
    
    len = buf.write("Simply Easy Learning");  
    
    console.log("Octets written : "+  len); 

      Open the Node.js command prompt and execute the following code:

      node main.js  

      Output:

      Node.js buffers 1

      Node.js Reading from buffers

      Following is the method to read data from a Node buffer.

      Syntax:

      buf.toString([encoding][, start][, end])  

      Parameter explanation:

      encoding: It specifies encoding to use. ‘utf8’ is the default encoding

      start: It specifies beginning index to start reading, defaults to 0.

      end: It specifies end index to end reading, defaults is complete buffer.

      Return values reading from buffers:

      This method decodes and returns a string from buffer data encoded using the specified character set encoding.

      Let’s take an example:

      File: main.js

      buf = new Buffer(26);  
      
      for (var i = 0 ; i < 26 ; i++) {  
      
        buf[i] = i + 97;  
      
      }  
      
      console.log( buf.toString('ascii'));       // outputs: abcdefghijklmnopqrstuvwxyz  
      
      console.log( buf.toString('ascii',0,5));   // outputs: abcde  
      
      console.log( buf.toString('utf8',0,5));    // outputs: abcde  
      
      console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde 

        Open Node.js command prompt and execute the following code:

        node main.js  

        Output:

        Node.js buffers 2
      1. Who is the Creator of Keras?

        François Chollet, He is currently working as an AI Researcher at Google

      2. What is keras?

        is a high-level neural networks API, capable of running on top of Tensorflow, Theano, and CNTK. It enables fast experimentation through a high-level, user-friendly, modular, and extensible API. Keras can also be run on both CPU and GPU.
        Keras was developed and is maintained by Francois Chollet and is part of the Tensorflow core, which makes it Tensorflows preferred high-level API.

        Keras is a deep learning API written in Python, running on top of the machine learning platform TensorFlow. It was developed with a focus on enabling fast experimentation. Being able to go from idea to result as fast as possible is key to doing good research.

        Keras is the high-level API of TensorFlow 2: an approachable, highly-productive interface for solving machine learning problems, with a focus on modern deep learning. It provides essential abstractions and building blocks for developing and shipping machine learning solutions with high iteration velocity.

        Keras empowers engineers and researchers to take full advantage of the scalability and cross-platform capabilities of TensorFlow 2: you can run Keras on TPU or on large clusters of GPUs, and you can export your Keras models to run in the browser or on a mobile device.

      3. Name the types of inputs in the Keras model.

        Keras models accept three types of inputs: Firstly, NumPy arrays, just like Scikit-Learn and many other Python-based libraries. This is a good option if your data fits in memory. Secondly, TensorFlow Dataset objects. This is a high-performance option that is more suitable for datasets that do not fit in memory and that are streamed from a disk or from a distributed filesystem. Lastly, Python generators that yield batches of data (such as custom subclasses of the keras.utils.Sequence class).

      4. Types are layers in Keras?

        • Core Layers
        • Convolutional Layers
        • Pooling Layers
        • Locally-connected Layers
        • Recurrent Layers
        • Embedding Layers
        • Merge Layers
        • Advanced Activations Layers
        • Normalization Layers
        • Noise layers
      5. How do you implement a custom callback in Keras?

        A custom callback in Keras is a powerful tool to customize the behavior of a model during training, evaluation, or inference, and to implement early stopping, model checkpointing, and other custom metrics or visualizations.

        To implement a custom callback in Keras, you need to create a class that inherits from the keras.callbacks.Callback class. This class should contain the methods that you want to customize, such as on_train_begin, on_train_end, on_epoch_begin, on_epoch_end, on_batch_begin, on_batch_end, and so on.

        In each of these methods, you can define the behavior that you want to customize. For example, in the on_train_begin method, you can define the code that you want to execute when the training begins. Similarly, in the on_epoch_end method, you can define the code that you want to execute when an epoch ends.

        Once you have defined the methods, you can instantiate the class and pass it to the fit() method of the model. This will enable the custom callback to be executed during training.

        For example, if you want to implement early stopping, you can define a custom callback that checks the validation loss after each epoch and stops the training if the validation loss does not improve for a certain number of epochs.

        In summary, to implement a custom callback in Keras, you need to create a class that inherits from the keras.callbacks.Callback class and define the methods that you want to customize. Then, you can instantiate the class and pass it to the fit() method of the model.

      6. How do you implement a custom layer in Keras?

        To implement a custom layer in Keras, you need to create a class that extends the tf.keras.layers.Layer class. This class should contain the logic for the layer’s forward pass, as well as any trainable weights.

        The class should also contain the following methods:

        – __init__: This method is used to define the layer’s properties, such as the number of inputs and outputs, the type of data it accepts, and any other parameters.

        – build: This method is used to create the layer’s weights.

        – call: This method is used to define the layer’s forward pass.

        – compute_output_shape: This method is used to define the shape of the output tensor.

        – get_config: This method is used to define the layer’s configuration, which can be used to recreate the layer.

        Once the class is defined, it can be used to create a layer instance, which can then be added to a model.

      7. How do you implement a custom metric in Keras?

        To implement a custom metric in Keras, you need to create a function that takes in two arguments: y_true and y_pred. The y_true argument is an array of true labels, and the y_pred argument is an array of predicted labels. The function should return a single scalar value that represents the custom metric.

        Once the custom metric function is created, it can be passed to the compile() method of the Keras model. The compile() method takes in a metrics argument, which is a list of metrics to be evaluated by the model during training and testing. The custom metric function can be added to this list.

        For example, if you wanted to implement a custom metric called ‘my_metric’, you could do the following:

        def my_metric(y_true, y_pred): # code to calculate custom metric return metric_value

        model.compile(optimizer=’adam’, loss=’binary_crossentropy’, metrics=[my_metric])

        The custom metric will then be evaluated during training and testing, and the results will be available in the history object returned by the fit() and evaluate() methods.

      8. How do you implement a custom loss function in Keras?

        A custom loss function can be implemented in Keras by creating a function that takes two arguments: y_true and y_pred. The function should return a single tensor value representing the loss.

        The function should be written using TensorFlow operations so that it can be used in the Keras model. The function should also be written to accept the same arguments as the standard Keras losses, such as mean_squared_error or binary_crossentropy.

        Once the function is written, it can be used in the model by passing it to the model.compile() method as the loss argument. For example:

        model.compile(optimizer=’adam’, loss=custom_loss_function)

        The custom loss function can also be used in the model.fit() method by passing it as the loss argument. For example:

        model.fit(x_train, y_train, loss=custom_loss_function)

        Finally, the custom loss function can be used in the model.evaluate() method by passing it as the loss argument. For example:

        model.evaluate(x_test, y_test, loss=custom_loss_function)

      9. Node.js Debugger

        Node.js provides a simple TCP based protocol and built-in debugging client. For debugging your JavaScript file, you can use debug argument followed by the js file name you want to debug.

        Syntax:

        node debug [script.js | -e "script" | <host>:<port>]  

        Example:

        node debug main.js  
        Node.js debugger example 1

        If you make any error:

        If you make any error in your js file source code or provide a wrong path on the Node.js command prompt then you will get the following result.

        Node.js debugger example 2