Trending November 2023 # Guide To Javascript Instanceof With Samplecode # Suggested December 2023 # Top 17 Popular

You are reading the article Guide To Javascript Instanceof With Samplecode updated in November 2023 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 Guide To Javascript Instanceof With Samplecode

Introduction to JavaScript instanceof

The instanceof operator in JavaScript is used to dynamically check the type of an object against a specified type at runtime. It allows you to determine whether an object is an instance of a particular class or a subtype of it. JavaScript instanceof operator returns 2 values true or Whenever an instance of an object comparison type both are same then returns true otherwise return false.

Start Your Free Software Development Course

Real-Time Scenario: If we have 1000’s user-defined class objects, but we need to work only with particular type objects, then we simply use instanceof operator to decide which objects belong to the desired class object, and then we will work with that objects without any hurdle.

How does instanceof operator work in JavaScript?

While checking whether the object belongs to the object type or not by using instanceof operator, on the left side of the instanceof operator, specify the object name, and on the right side of the instanceof operator, specify the object type. If the left-hand side object name and the right-hand side object type both right belong to a similar instance, then it will return a true value, otherwise returns a false.


var instanceOfOperator = nameOfObject instanceof typeOfObject; Examples to Implement JavaScript instanceof

See the examples below.

Example #1 – Operator with Array


h1 { text-align:center; color:blue; } .i { color:red; border-style:solid; border-color:brown; border-width:2px; font-size:22px; } var courses = [“Java”, “Python”, “C#”,”HTML”,”CSS”,”JavaScript”];



Line1, we have created a courses array with some course values.

Line2, we have checked courses object is an instance of Array type; as courses are array type, then it has given us true value.

Line3, we have checked course object is an instance of an object type, as all objects are inherited from the Object type, so the course array is also one of the inherited types, so it has given true value.

Line4, we have checked courses object is an instance of String type; as courses are not string type, then it has given us a false value.

Line5, we have checked courses object is an instance of Number type; as courses are not Number type, then it has given us a false value.

Example #2 – Operator with String

h1 { text-align:center; color:pink; } .i { color:green; border-style:solid; border-color:maroon; border-width:2px; font-size:22px; } var educbaString=new String(“EDUCBA”); 



Line1, we have created educbaString String with the new operator.

Line2, we have checked educbaString object is an instance of String type; as educbaString is a String type, then it has given us true value.

Line3, we have checked educbaString object is an instance of the Object type, as all objects are inherited from the Object type, so the educbaString String is also one of the inherited types, so it has given true value.

Line4, we have checked educbaString object is an instance of Array type; as educbaString is not an Array type, then it has given us a false value.

Line5, we have checked educbaString object is an instance of Number type; as educbaString is not a Number type, then it has given us a false value.

Line6, we have checked educbaString object is an instance of Date type; as educbaString is not a Date type, then it has given us a false value.

Example #3 – Operator with Date


h1 { text-align:center; color:fuchsia; } .i { color:orange; border-style:solid; border-color:red; border-width:2px; font-size:22px; } var dateValue=new Date(“03/15/2023”); 


Line1, we have created dateValue Date with the new operator.

Line2, we have checked dateValue object is an instance of String type; as dateValue is Date type, then it has given us a true value.

Line3, we have checked dateValue object is an instance of an object type, as all objects are inherited from the Object type, so dateValue Date is also one of the inherited types, so it has given true value.

Line4, we have checked dateValue object is an instance of Array type; as dateValue is not an Array type, then it has given us a false value.

Line5, we have checked dateValue object is an instance of a Number type; as dateValue is not a Number type, then it has given us a false value.

Line6, we have checked dateValue object is an instance of Date type; as dateValue is not Date type, then it has given us a false value.

Example #4 – Operator with Number


h1 { text-align:center; color:orange; } .i { color:navy; border-style:solid; border-color:yellow; border-width:2px; font-size:22px; } var numbers=new Number(10.10); 



Line1, we have created numbers Number with the new operator.

Line2, we have checked numbers object is an instance of Number type; as numbers are Number type, then it has given us true value.

Line3, we have checked numbers object is an instance of an object type, as all objects are inherited from the Object type, so numbers Number is also one of the inherited types, so it has given true value.

Line4, we have checked numbers object is an instance of Array type, as numbers are not Array type, then it has given us a false value.

Line5, we have checked numbers object is an instance of String type; as numbers are not String type, then it has given us a false value.

Line6, we have checked numbers object is an instance of Date type; as numbers are not Date type, then it has given us a false value.


JavaScript instanceof operator is used for comparing object names with the desired object type for validating the actual object instance.

Recommended Articles

This is a guide to JavaScript instanceof. Here we discuss an introduction to JavaScript instanceof with appropriate syntax, working, and respective programming examples. You can also go through our other related articles to learn more –

You're reading Guide To Javascript Instanceof With Samplecode

How To Detect Mobile Browsers With Javascript

Mobile detection has always been a crucial aspect of app development. It is relevant both for apps, but also software and websites. There are countless reasons to check for mobile browser agents. Most importantly, the ability to render a unique user experience.

Sometimes you might just want a simple solution that does the job without any libraries. And in this article, I am gonna lay out for you a handful of JavaScript techniques for detecting mobile users. Let me know if I missed any!


The holy grail of browser detection is the navigator.UserAgent property.


// an alternative structure to check individual matches if ( navigator.userAgent.match(/iPhone/i) ) { }

This is, of course, a very primitive way of doing it. It can easily be manipulated as the User-Agent property can be spoofed. But, you can still use it in various projects because it does the job. E.g. Landing pages or making a custom redirect to a mobile version.

How to display a warning message if the user uses an unsupported or outdated browser?

One way this property can be used is to check whether or not the user is using a specific version of a browser, and, if not – perform an action.

In this example, it’s a simple alert message:

var userAgent = navigator.userAgent; var browserVersion = userAgent.substring(userAgent.indexOf("Chrome") + 7); if (parseFloat(browserVersion) < 107) { alert("Your browser is outdated and not supported. Please upgrade to the latest version."); }

☰ What does the “+ 7” do?

In this case, the number 7 in the browserVersion string is used to specify the index at which to start extracting the substring from the userAgent string. The userAgent string is a property of the navigator object in JavaScript that contains information about the user’s browser, such as its name and version number.

In this case, the code is using the indexOf method to find the index of the first occurrence of the string "Chrome" within the userAgent string. This method returns the index of the string’s first character that it is searching for. The number 7 is added to this value, which means that the substring extraction will start at the 8th character of the userAgent string (since array indexes in JavaScript start at 0). This allows the code to skip the first seven characters of the userAgent string (i.e. the characters “Chrome” plus the space after it) and start extracting the substring at the character immediately following the space.

How to redirect users to a mobile version of the site if they’re browsing from mobile?

To detect mobile devices and serve a mobile-optimized version of the website, you can use the navigator.userAgent property to check for common mobile user agents. For example:


How to use navigator.userAgent to detect browser type and display content based on the specific browser?

Alright, so, there might be a unique use case where you want to detect a specific browser, such as Chrome and Firefox (or in this case, Android and iPhone), and then use that data to display specific content. This approach is often used to provide/change download links for specific browsers.

In such a case, you can use the following function.

function detectBrowser() { let userAgent = navigator.userAgent; let browserName; browserName = "Chrome"; browserName = "Firefox"; } else if (userAgent.match(/safari/i)) { browserName = "Safari"; } else if (userAgent.match(/opr//i)) { browserName = "Opera"; } else if (userAgent.match(/edg/i)) { browserName = "Edge"; } else if (userAgent.match(/android/i)) { browserName = "Android"; } else if (userAgent.match(/iphone/i)) { browserName = "iPhone"; } else { browserName = "Unknown"; } document.querySelector("div.form-style h3").innerText = "You are browsing with: " + browserName + ""; }


One method to detect mobile users is to check if the device has a touch screen.

Using the GlobalEventHandlers.ontouchstart property you can make a simple check to see how the user interacted with your app. If the interaction came from a touch screen, you can then return a mobile version of the app or page.

if ("ontouchstart" in document.documentElement) { } else { }

Touch-screen devices like Surface do not have this property. So, users coming from desktop-based touch devices will still see the desktop version of your pages.


The Window.matchMedia() is one of the best properties for detecting mobile users with JavaScript. And it is so because it lets you interact with CSS directly.

In a lot of cases, media queries are superior because they have built-in mobile detection tools. For example, you can make a call to check if “pointer:coarse” is true.

This specific statement validates whether the device’s pointer is fine or coarse.

let isMobile = window.matchMedia("(pointer:coarse)").matches;

Alternatively, the device might have both a fine and coarse pointer. For this use case, we can check if any pointers are coarse.

let isMobile = window.matchMedia("(any-pointer:coarse)").matches;

Keep in mind that this only validates the query as true or false. A more refined way to check for mobile devices is to use media queries directly.

let isMobile = window.matchMedia("only screen and (max-width: 480px)").matches;

This query will directly check the max-width of the device and assert whether it matches the criteria. Again, this is quite a lot of work for getting all devices correctly. As such, it’s easier to use a pre-built library with all the device types already defined.

Useful in certain contexts

Over the years, there have been many JavaScript properties for detecting device types. Many of them got deprecated, but most others got integrated into libraries. Which also happens to be the best way to do proper mobile detection.

Last but not least, most modern frameworks already include mobile detection as part of the framework itself. It’s worth looking into if you don’t want to do all the legwork.

Libraries for Detecting Mobile Devices

This section will list the most popular JavaScript libraries for detecting mobile devices. Again, I emphasize that these are specific to JavaScript. Refer to the docs for proper implementation in your app.


However, what makes it so popular is the fact that you can parse hundreds of device variations. And, all of it is very well documented. You can go from practical device vendors to more intricate detection patterns like CPU architecture.


This is a fairly straightforward port of the Mobile Detect library for PHP, provided to the community by Heinrich Goebl. The library itself uses User-Agent for detection, so as we discussed earlier – not the best option.

Still, it should do the job when it comes to practical HTML templates or portfolio projects.


Here we have another take on the User-Agent Navigator property from Kai Mallea. While still a simplistic solution, I like that isMobile provides a variety of specifications. For example, you can test for any mobile devices or specific ones like phone or tablet.


Are you a chúng tôi developer?

Then this library from Michael Laktionov is for you. It works as you would expect – first the library detects device type, then renders the view based on that type. Works flawlessly with component integration, and can be further customized through API calls.

One interesting fact is the number of selectors this library includes. It covers devices like smart TVs, wearables, a variety of iPhone devices, and much more. This gives you a broad selection of design choices when building an app for a specific device.

How To Use Spread Syntax With Arguments In Javascript Functions?

We use the Spread Syntax of JavaScript to expand an array, string, or object in place. Such types of values are called iterable. This is similar to destructuring the iterable in place. Its utility in a function call allows us to extract function parameters from an iterable. In this tutorial, we learn how to use Spread Syntax with arguments in JavaScript functions.

Spread operator in JavaScript

A Spread operator, denoted with (…) followed by the name of the iterable expands the iterable into its constituent elements.


const [x, y, ...z] = [1, 2, 3, 4, 5]

This creates three variables x, y, and z. The first two values are stored in the corresponding variables. So, x = 1, y = 2, and z = [3, 4, 5].

The spread operator stores the rest of the iterable into the z variable.

It is most commonly used in function calls to expand the iterable at the time of parameter initialization.

Example 1

Here we are going to show the use of the spread operator in the function call. We will create an array of strings and pass it as a function argument for printing. Let’s look at the code for the same.


























In the above code, the variables take the corresponding values from the array. This happens in order. So a = arr[0], b = arr[1] and c = arr[2].

The spread operator can be used to handle cases in which only some part of the iterable list is useful, and the rest can be ignored. The example from the beginning emphasizes that use case.

Let us look at an example to see this use case.

Example 2

Here we are going to show the use of the spread operator in the function call. We will create an array of strings and pass it as a function argument for printing. In this example, however, we will emphasize only the first element in the list.


























Only the first element is put to use, and the rest of the elements can be put into a different variable using the spread operator. This also provides us the utility of handling cases in which we have no information on the upper bound of the size of the iterable, but we know the lowest size.

The spread operator can also be used with objects. Note however that the spread operator provides an easy way to copy an iterable. This copy is separate from the original iterable, and any changes in the new copy are not reflected in the original one.

The spread operator can also concatenate iterable in the function call.

Here’s an example −

Example 3

Here we will create two separate lists of strings and use the spread operator to concatenate the two lists when calling the function.














































































Here we are passing a concatenated list of the two arrays as the argument for the function call print(). The spread operator expands both lists and creates a new list that acts as a single complete argument.


The Spread operator is pretty useful for single-dimensional arrays or iterable but is unsuitable for multidimensional iterable. It can also be used with objects.

Guide To Types Of Php Annotations With Examples

Introduction to PHP Annotations

PHP annotations are basically metadata which can be included in the source code and also in between classes, functions, properties and methods. They are to be started with the prefix @ wherever they are declared and they indicate something specific. This information they provide is very useful to coders, helpful for documentation purposes and also an IDE may use this to display certain popup hint kind of things. The same annotation can also be used for other purposes besides validation such as to determine what kind of input needs to be given in a form and also for automation purposes. There are various kinds of annotations like the @var and @int types which can be used for specific uses as their name itself suggests.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax class Example { public $new; }

Annotation is @var here and whenever it is encountered just before the piece of any code (public $new here for example) it indicates that the $new is to have a value of type integer as told by the annotation.

class Example { public $shop; }

Annotations can also be used for specifying the range where it displays the maximum and the minimum values that are to be accepted as integer values for the function and the label gives the purpose of this function.

Types of PHP Annotations

Given below are the types:

1. Built-in Annotations

There are 2 built-in functions in annotations which are as follows:

a. Compiled: This annotation indicates that if the method/function should be JIT compiled or not. It is also a function scope type of annotation.

b. SuppressWarnings: This is another built-in annotation which means that any warnings thrown as part of the execution of the succeeding code below it must be suppressed.

2. Meta Annotations

These are those type of annotations which can be used to apply for other annotations. They are used for configuration of annotations.

a. @Annotations

There is a kind of annotation classes which will contain @annotation.


[@Annotation] class MyAnnoExample { }

b. @Target

As the name suggests, this annotation indicates those types of class elements or a method upon which the annotation will be applicable.

Property annotation is just before the property class declaration.

Class which is allowed before the declaration of class.

Function is declared before the function declaration.

Method annotation allows proceeding the method declaration.

Annotation is allowed for proceeding to declaration of annotation class.

c. @Repeatable

This annotation means that it may be repeated any number of times when being used.

d. @Inherited

This can also be used on the other user defined annotation classes as a meta-annotation. These inherited annotations are automatically inherited to the respective sub-classes when they are used upon a superclass.

3. Custom Annotations

These are very similar to declarations of the normal class. Each element of the annotation type is defined by each of the property declarations.

Examples of PHP Annotations

Given below are the examples mentioned:

Example #1


[@Annotation] [@Target("class")] class MyAnnoEx { [@Required] public string $prop; public array $arrayProp = []; public embedAnno $embed; } [@Annotation] [@Target(["class", "annotation"])] class embedAnno { } [@Annotation] [@Target("property")] class propAnno { } @Annotation @Target("method") class methodAnno { public string $val; public function __construct(string $val) { } }

This is just a basic example showing the usage of all the different types of annotations which are shown above. All the ones in the example like embed annotation, property annotation, method annotation are custom annotations.

Example #2

<?php /** * @Replace(“exmaple”, “for”, “annotation”) */ class MyNamedComponent { } echo str_replace(“First”, “Second”, “First Example”);


In this example we are naming the annotation as replace since the below code represents the usage of string replace function which is str_replace, an inbuilt function of PHP. Using this function, the first parameter passed in the function is replaced by the second one.

Example #3


<!–Declaring First name for the form First_Name: <!–Declaring Last_Name for the form Last_Name: <!–Declaring Location for the form Stay location: <!–Declaring EMAILID for the form EmailID: <!–Declaring Password for the form Password: <!–Declaring Password for the form Gender: <input type=”radio” value=”Male” <input type=”radio” value=”Female” <?php if(example($_POST[‘confirm’])) { if(!example($error)) { } }


In this example, we are showing annotations in combination with the form validation in PHP. Using annotations we are labeling all the parameters which are required as input parameters to the form such as first and last name, email, location and password.


With the above examples we have noticed how annotations are a powerful tool to use and express metadata about our methods, classes or properties. We have also seen how to combine different kinds of annotations to declare workers who will perform certain tasks by writing some metadata about them. This makes them easy to find and gives actual information on whether or not they can be used.

Recommended Articles

This is a guide to PHP Annotations. Here we discuss the introduction to PHP annotations with types of annotations and respective examples. You may also have a look at the following articles to learn more –

Delete Revolut Account With This Guide

Delete Revolut account with this guide






Try Outbyte Driver Updater to resolve driver issues entirely:

This software will simplify the process by both searching and updating your drivers to prevent various malfunctions and enhance your PC stability. Check all your drivers now in 3 easy steps:

Download Outbyte Driver Updater.

Launch it on your PC to find all the problematic drivers.

OutByte Driver Updater has been downloaded by


readers this month.

Revolut is a popular financial startup that operates as a bank but purely on a digital basis through an app. Being a fully digital service, opening a Revolut bank account is easy and takes no more than 10 minutes. However, what if you want to delete Revolut account or currency account?

You may have several reasons to close your Revolut account. You probably don’t like the service, you are not actively using it and don’t want to keep your details with the financial firm. Irrespective of the reason, closing your Revolut account is easy.

In this article, we take you through the process to successfully delete Revolut account with ease.

Steps to delete Revolut account 1. Delete Revolut currency account

If you only want to delete an inactive currency account, do the following.

Login to your Revolut App.

Go to your Profile and tap on Account Details.

Tap on Deactivate and then confirm.

Need a secure browser for banking? Here are 5 great choices

Before deleting your Revolut account, you need to do a couple of things so that you don’t lose any of your money in the process.

According to Revolut, before closing the account, the users should withdraw all currency balances in their account. All transactions (card payments, transfer) must be completed.

This is important because once the account is closed, all the cards linked to the account will be terminated.

Once you have made sure that all the currencies are withdrawn from the account, you need to contact Revolut live agent.

You can find more details about contacting the live agent on the Revolut website or on the app.

The live agents will ask you some security questions before closing the account.

 What’s not Deleted?

According to Revolut, the company keeps the user data for 6 years due to financial regulations. However, your account is completely deleted and no transaction can be made through the concerned account.

 What to consider before deleting your account?

As discussed earlier, deleting Revolut account is easy if you follow the procedure correctly. However, there are a few things to consider before deleting your account.

According to Revolut, it can be difficult to reopen another Revolut account if the Mobile number is already associated with a closed account.

Additionally, it does not cost anything to keep your standard Revolut account active. So, even if you are not using Revolut service actively, you can still keep the account active without paying any fee.

In case you are using premium Revolut account with a monthly subscription, you can change the account bank to standard plan to avoid paying any fees. However, Revolut may charge a small delivery fee for the physical Revolut card.


That’s it. We have discussed all the steps that you need to take to delete Revolut account safely without any hassle. However, make sure you consider other points in the article before deleting your account.


Was this page helpful?


Start a conversation

Practical Guide To Deal With Imbalanced Classification Problems In R


We have several machine learning algorithms at our disposal for model building. Doing data based prediction is now easier like never before. Whether it is a regression or classification problem, one can effortlessly achieve a reasonably high accuracy using a suitable algorithm. But, this is not the case everytime. Classification problems can sometimes get a bit tricky.

ML algorithms tend to tremble when faced with imbalanced classification data sets. Moreover, they result in biased predictions and misleading accuracies. But, why does it happen ? What factors deteriorate their performance ?

The answer is simple. With imbalanced data sets, an algorithm doesn’t get the necessary information about the minority class to make an accurate prediction. Hence, it is desirable to use ML algorithms with balanced data sets. Then, how should we deal with imbalanced data sets ? The methods are simple but tricky as described in this article.

In this article, I’ve shared the important things you need to know to tackle imbalanced classification problems. In particular, I’ve kept my focus on imbalance in binary classification problems. As usual, I’ve kept the explanation simple and informative. Towards the end, I’ve provided a practical view of dealing with such data sets in R with ROSE package.

What is Imbalanced Classification ?

Imbalanced classification is a supervised learning problem where one class outnumbers other class by a large proportion. This problem is faced more frequently in binary classification problems than multi-level classification problems.

The term imbalanced refer to the disparity encountered in the dependent (response) variable. Therefore, an imbalanced classification problem is one in which the dependent variable has imbalanced proportion of classes. In other words, a data set that exhibits an unequal distribution between its classes is considered to be imbalanced.

For example: Consider a data set with 100,000 observations. This data set consist of candidates who applied for Internship in Harvard. Apparently, harvard is well-known for its extremely low acceptance rate. The dependent variable represents if a candidate has been shortlisted (1) or not shortlisted (0). After analyzing the data, it was found ~ 98% did not get shortlisted and only ~ 2% got lucky. This is a perfect case of imbalanced classification.

In real life, does such situations arise more ? Yes! For better understanding, here are some real life examples. Please note that the degree of imbalance varies per situations:

An automated inspection machine which detect products coming off manufacturing assembly line may find number of defective products significantly lower than non defective products.

A test done to detect cancer in residents of a chosen area may find the number of cancer affected people significantly less than unaffected people.

In credit card fraud detection, fraudulent transactions will be much lower than legitimate transactions.

A manufacturing operating under six sigma principle may encounter 10 in a million defected products.

There are many more real life situations which result in imbalanced data set. Now you see, the chances of obtaining an imbalanced data is quite high. Hence, it’s important to learn to deal with such problems for every analyst.

Why do standard ML algorithms struggle with accuracy on imbalanced data?

This is an interesting experiment to do. Try it! This way you will understand the importance of learning the ways to restructure imbalanced data. I’ve shown this in the practical section below.

ML algorithms struggle with accuracy because of the unequal distribution in dependent variable.

This causes the performance of existing classifiers to get biased towards majority class.

The algorithms are accuracy driven i.e. they aim to minimize the overall error to which the minority class contributes very little.

ML algorithms assume that the data set has balanced class distributions.

They also assume that errors obtained from different classes have same cost (explained below in detail).

What are the methods to deal with imbalanced data sets ?

The methods are widely known as ‘Sampling Methods’. Generally, these methods aim to modify an imbalanced data into balanced distribution using some mechanism. The modification occurs by altering the size of original data set and provide the same proportion of balance.

These methods have acquired higher importance after many researches have proved that balanced data results in improved overall classification performance compared to an imbalanced data set. Hence, it’s important to learn them.

Below are the methods used to treat imbalanced datasets:



Synthetic Data Generation

Cost Sensitive Learning

Let’s understand them one by one.

1. Undersampling

This method works with majority class. It reduces the number of observations from majority class to make the data set balanced. This method is best to use when the data set is huge and reducing the number of training samples helps to improve run time and storage troubles.

Undersampling methods are of 2 types: Random and Informative.

Random undersampling method randomly chooses observations from majority class which are eliminated until the data set gets balanced. Informative undersampling follows a pre-specified selection criterion to remove the observations from majority class.

Within informative undersampling, EasyEnsemble and BalanceCascade algorithms are known to produce good results. These algorithms are easy to understand and straightforward too.

EasyEnsemble: At first, it extracts several subsets of independent sample (with replacement) from majority class. Then, it develops multiple classifiers based on combination of each subset with minority class. As you see, it works just like a unsupervised learning algorithm.

BalanceCascade: It takes a supervised learning approach where it develops an ensemble of classifier and systematically selects which majority class to ensemble.

Do you see any problem with undersampling methods? Apparently, removing observations may cause the training data to lose important information pertaining to majority class.

2. Oversampling

This method works with minority class. It replicates the observations from minority class to balance the data. It is also known as upsampling. Similar to undersampling, this method also can be divided into two types: Random Oversampling and Informative Oversampling.

Random oversampling balances the data by randomly oversampling the minority class. Informative oversampling uses a pre-specified criterion and synthetically generates minority class observations.

3. Synthetic Data Generation

In simple words, instead of replicating and adding the observations from the minority class, it overcome imbalances by generates artificial data. It is also a type of oversampling technique.

In regards to synthetic data generation, synthetic minority oversampling technique (SMOTE) is a powerful and widely used method. SMOTE algorithm creates artificial data based on feature space (rather than data space) similarities from minority samples. We can also say, it generates a random set of minority class observations to shift the classifier learning bias towards minority class.

To generate artificial data, it uses bootstrapping and k-nearest neighbors. Precisely, it works this way:

Take the difference between the feature vector (sample) under consideration and its nearest neighbor.

Multiply this difference by a random number between 0 and 1

Add it to the feature vector under consideration

This causes the selection of a random point along the line segment between two specific features

R has a very well defined package which incorporates this techniques. We’ll look at it in practical section below.

4. Cost Sensitive Learning (CSL)

It is another commonly used method to handle classification problems with imbalanced data. It’s an interesting method. In simple words, this method evaluates the cost associated with misclassifying observations.

It does not create balanced data distribution. Instead, it highlights the imbalanced learning problem by using cost matrices which describes the cost for misclassification in a particular scenario. Recent researches have shown that cost sensitive learning have many a times outperformed sampling methods. Therefore, this method provides likely alternative to sampling methods.

Let’s understand it using an interesting example: A data set of passengers in given. We are interested to know if a person has bomb. The data set contains all the necessary information. A person carrying bomb is labeled as positive class. And, a person not carrying a bomb in labeled as negative class. The problem is to identify which class a person belongs to. Now, understand the cost matrix.

There in no cost associated with identifying a person with bomb as positive and a person without negative. Right ? But, the cost associated with identifying a person with bomb as negative (False Negative) is much more dangerous than identifying a person without bomb as positive (False Positive).

Cost Matrix is similar of confusion matrix. It’s just, we are here more concerned about false positives and false negatives (shown below). There is no cost penalty associated with True Positive and True Negatives as they are correctly identified.

Cost Matrix

The goal of this method is to choose a classifier with lowest total cost.

Total Cost = C(FN)xFN + C(FP)xFP


FN is the number of positive observations wrongly predicted

FP is the number of negative examples wrongly predicted

Using clustering, divide the majority class into K distinct cluster. There should be no overlap of observations among these clusters. Train each of these cluster with all observations from minority class. Finally, average your final prediction.

Collect more data. Aim for more data having higher proportion of minority class. Otherwise, adding more data will not improve the proportion of class imbalance.

Which performance metrics to use to evaluate accuracy ?

Choosing a performance metric is a critical aspect of working with imbalanced data. Most classification algorithms calculate accuracy based on the percentage of observations correctly classified. With imbalanced data, the results are high deceiving since minority classes hold minimum effect on overall accuracy.

Confusion Matrix

The difference between confusion matrix and cost matrix is that, cost matrix provides information only about the misclassification cost, whereas confusion matrix describes the entire set of possibilities using TP, TN, FP, FN. In a cost matrix, the diagonal elements are zero. The most frequently used metrics are Accuracy & Error Rate.

Accuracy: (TP + TN)/(TP+TN+FP+FN)

Error Rate = 1 - Accuracy = (FP+FN)/(TP+TN+FP+FN)

As mentioned above, these metrics may provide deceiving results and are highly sensitive to changes in data. Further, various metrics can be derived from confusion matrix. The resulting metrics provide a better measure to calculate accuracy while working on a imbalanced data set:

Precision: It is a measure of correctness achieved in positive prediction i.e. of observations labeled as positive, how many are actually labeled positive.

Precision = TP / (TP + FP)

Recall: It is a measure of actual observations which are labeled (predicted) correctly i.e. how many observations of positive class are labeled correctly. It is also known as ‘Sensitivity’.

Recall = TP / (TP + FN)

F measure: It combines precision and recall as a measure of effectiveness of classification in terms of ratio of weighted importance on either recall or precision as determined by β coefficient.

F measure = ((1 + β)² × Recall × Precision) / ( β² × Recall + Precision )

β is usually taken as 1.

Though, these methods are better than accuracy and error metric, but still ineffective in answering the important questions on classification. For example: precision does not tell us about negative prediction accuracy. Recall is more interesting in knowing actual positives. This suggest, we can still have a better metric to cater to our accuracy needs.

Fortunately, we have a ROC (Receiver Operating Characteristics) curve to measure the accuracy of a classification prediction. It’s the most widely used evaluation metric. ROC Curve is formed by plotting TP rate (Sensitivity) and FP rate (Specificity).

Specificity = TN / (TN + FP)

Any point on ROC graph, corresponds to the performance of a single classifier on a given distribution. It is useful because if provides a visual representation of benefits (TP) and costs (FP) of a classification data. The larger the area under ROC curve, higher will be the accuracy.

There may be situations when ROC fails to deliver trustworthy performance. It has few shortcomings such as.

It may provide overly optimistic performance results of highly skewed data.

It does not provide confidence interval on classifier’s performance

It fails to infer the significance of different classifier performance.

As alternative methods, we can use other visual representation metrics include PR curve, cost curves as well. Specifically, cost curves are known to possess the ability to describe a classifier’s performance over varying misclassification costs and class distributions in a visual format. In more than 90% instances, ROC curve is known to perform quite well.

Imbalanced Classification in R

Till here, we’ve learnt about some essential theoretical aspects of imbalanced classification. It’s time to learn to implement these techniques practically.  In R, packages such as ROSE and DMwR helps us to perform sampling strategies quickly. We’ll work on a problem of binary classification.

ROSE (Random Over Sampling Examples) package helps us to generate artificial data based on sampling methods and smoothed bootstrap approach. This package has well defined accuracy functions to do the tasks quickly.

Let’s get started

The package ROSE comes with an inbuilt imbalanced data set named as hacide. It comprises of two files: hacide.train and hacide.test. Let’s load it in R environment:

$ x2 : num 0.678 1.5766 -0.5595 -0.0938 -0.2984 ...

As you can see, the data set contains 3 variable of 1000 observations. cls is the response variable. x1 and x2 are dependent variables. Let’s check the severity of imbalance in this data set:

980    20

0.98   0.02

As we see, this data set contains only 2% of positive cases and 98% of negative cases. This is a severely imbalanced data set. So, how badly can this affect our prediction accuracy ? Let’s build a model on this data. I’ll be using decision tree algorithm for modeling purpose.

Let’s check the accuracy of this prediction. To check accuracy, ROSE package has a function names accuracy.meas, it computes important metrics such as precision, recall & F measure.

   Examples are labelled as positive when predicted is greater than 0.5 

   F: 0.167

These metrics provide an interesting interpretation. With threshold value as 0.5, Precision = 1 says there are no false positives. Recall = 0.20 is very much low and indicates that we have higher number of false negatives. Threshold values can be altered also. F = 0.167 is also low and suggests weak accuracy of this model.

We’ll check the final accuracy of this model using ROC curve. This will give us a clear picture, if this model is worth. Using the function roc.curve available in this package:

Area under the curve (AUC): 0.600

AUC = 0.60 is a terribly low score. Therefore, it is necessary to balanced data before applying a machine learning algorithm. In this case, the algorithm gets biased toward the majority class and fails to map minority class.

We’ll use the sampling techniques and try to improve this prediction accuracy. This package provides a function named ovun.sample which enables oversampling, undersampling in one go.

Let’s start with oversampling and balance the data.

980 980

In the code above, method over instructs the algorithm to perform over sampling. N refers to number of observations in the resulting balanced set. In this case, originally we had 980 negative observations. So, I instructed this line of code to over sample minority class until it reaches 980 and the total data set comprises of 1960 samples.

Similarly, we can perform undersampling as well. Remember, undersampling is done without replacement.

20  20

Now the data set is balanced. But, you see that we’ve lost significant information from the sample. Let’s do both undersampling and oversampling on this imbalanced data. This can be achieved using method = “both“. In this case, the minority class is oversampled with replacement and majority class is undersampled without replacement.

520 480

p refers to the probability of positive class in newly generated sample.

520 480

This generated data has size equal to the original data set (1000 observations). Now, we’ve balanced data sets using 4 techniques. Let’s compute the model using each data and evaluate its accuracy.

It’s time to evaluate the accuracy of respective predictions. Using inbuilt function roc.curve allows us to capture roc metric.

Area under the curve (AUC): 0.989

Area under the curve (AUC): 0.798

Area under the curve (AUC): 0.867

Area under the curve (AUC): 0.798

Here is the resultant ROC curve where:

Black color represents ROSE curve

Red color represents oversampling curve

Green color represents undersampling curve

Blue color represents both sampling curve

Hence, we get the highest accuracy from data obtained using ROSE algorithm. We see that the data generated using synthetic methods result in high accuracy as compared to sampling methods. This technique combined with a more robust algorithm (random forest, boosting) can lead to exceptionally high accuracy.

This package also provide us methods to check the model accuracy using holdout and bagging method. This helps us to ensure that our resultant predictions doesn’t suffer from high variance.

seed = 1)

Holdout estimate of auc: 0.985

We see that our accuracy retains at ~ 0.98 and shows that our predictions aren’t suffering from high variance. Similarly, you can use bootstrapping by setting method.assess to “BOOT”. The parameter chúng tôi is a function which extracts the column of probabilities belonging to positive class.

End Notes

In this article, I’ve discussed the important things one should know to deal with imbalanced data sets. For R users, dealing with such situations isn’t difficult since we are blessed with some powerful and awesome packages.

You can test your skills and knowledge. Check out Live Competitions and compete with best Data Scientists from all over the world.


Update the detailed information about Guide To Javascript Instanceof With Samplecode on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!