title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to update DB2 table with a duplicate primary key?
|
To maintain the integrity of a DB2 table the primary key is always unique in the entire
table. For example, if we have a DB2 table ORDERS which stores all the orders and the
primary key of the table is column ORDER_ID. Then there can be only a single row having
a particular order id. This will be useful to identify an order distinctly.
If we try to insert or update a row in a DB2 table having duplicate primary key using a
COBOL-DB2 program, we will get DB2 error code -803. As per the IBM documentation -
803 error code states the followingβ
βUnique index violation. Try to insert duplicate record (Duplicate Error)β
|
[
{
"code": null,
"e": 1400,
"s": 1062,
"text": "To maintain the integrity of a DB2 table the primary key is always unique in the entire\ntable. For example, if we have a DB2 table ORDERS which stores all the orders and the\nprimary key of the table is column ORDER_ID. Then there can be only a single row having\na particular order id. This will be useful to identify an order distinctly."
},
{
"code": null,
"e": 1608,
"s": 1400,
"text": "If we try to insert or update a row in a DB2 table having duplicate primary key using a\nCOBOL-DB2 program, we will get DB2 error code -803. As per the IBM documentation -\n803 error code states the followingβ"
},
{
"code": null,
"e": 1683,
"s": 1608,
"text": "βUnique index violation. Try to insert duplicate record (Duplicate Error)β"
}
] |
How to get signal strength in android?
|
This example demonstrate about How to get signal strength in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken a text view to show signal strength information.
Step 3 β Add the following code to java/MainActivity.xml
package com.example.myapplication;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.READ_PHONE_NUMBERS;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.READ_SMS;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 100;
TextView textView;
TelephonyManager telephonyManager;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE,ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE);
} else {
textView.setText(""+telephonyManager.getSignalStrength());
}
}
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
textView.setText(""+telephonyManager.getSignalStrength());
}
}
}
}
Step 3 β Add the following code toAndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "This example demonstrate about How to get signal strength in android."
},
{
"code": null,
"e": 1261,
"s": 1132,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1326,
"s": 1261,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1894,
"s": 1326,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1976,
"s": 1894,
"text": "In the above code, we have taken a text view to show signal strength information."
},
{
"code": null,
"e": 2033,
"s": 1976,
"text": "Step 3 β Add the following code to java/MainActivity.xml"
},
{
"code": null,
"e": 4854,
"s": 2033,
"text": "package com.example.myapplication;\n\nimport android.Manifest;\nimport android.content.Context;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.TelephonyManager;\nimport android.widget.TextView;\n\nimport static android.Manifest.permission.ACCESS_COARSE_LOCATION;\nimport static android.Manifest.permission.READ_PHONE_NUMBERS;\nimport static android.Manifest.permission.READ_PHONE_STATE;\nimport static android.Manifest.permission.READ_SMS;\n\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_REQUEST_CODE = 100;\n TextView textView;\n TelephonyManager telephonyManager;\n\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);\n if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this, new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE,ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE);\n } else {\n textView.setText(\"\"+telephonyManager.getSignalStrength());\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n switch (requestCode) {\n case PERMISSION_REQUEST_CODE:\n if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n return;\n } else {\n textView.setText(\"\"+telephonyManager.getSignalStrength());\n }\n }\n }\n}"
},
{
"code": null,
"e": 4908,
"s": 4854,
"text": "Step 3 β Add the following code toAndroidManifest.xml"
},
{
"code": null,
"e": 5821,
"s": 4908,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.myapplication\">\n\n <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />\n <uses-permission android:name=\"android.permission.READ_PHONE_NUMBERS\" />\n <uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6168,
"s": 5821,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 6208,
"s": 6168,
"text": "Click here to download the project code"
}
] |
An AI agent plays tic-tac-toe (part 1): building the opponent to play against | by Paul Hiemstra | Towards Data Science
|
Where we build a brute force minimax tree search which will serve as the opponent to our reinforcement learning approach
This article is part of a series that lets a computer play tic-tac-toe using reinforcement learning. You can find all the articles here. The goal is to provide a complete implementation that you can really pick apart and learn reinforcement learning from. It is probably best to read the articles in order. The article including all the code can be found on Github
Reinforcement learning is the third modeling paradigm next to supervised and unsupervised modeling. It has seen great successes recently, including beating the worlds best Go player. This feat was considered impossible only a few years prior because of the enormous possible moveset in Go that dwarfs even that of chess. I will only briefly touch on how reinforcement learning works, but the following youtube movies should provide a more in depth introduction (Intro RL, Deep RL).
Reinforcement learning (RL) is based on the following key concepts:
There is a computer agent which takes actions (A) that act on an environment (E). That environment responds by providing a reward (R) for that action, and bringing the system to the next state (S). Take for example the following state:
Here we consider two options for the next action of the O player: the green and red option. Taking the green option yields a high reward, as we block the X player from winning. Alternatively, the red option yields a low reward as this allows the X player to win. By playing tic-tac-toe many times and receiving rewards the RL agent will slowly learn what action in a particular state provides a good long term value. The mapping of state to optimal action is known as a policy in RL jargon.
With the basics of RL out of the way, we can now focus on the goal of this article: building an opponent for our RL agent. Luckily for us, the game of tic-tac-toe is simple enough and can be solved in a brute force manner. This ensures that we end up with the optimal moves in tic-tac-toe, ensuring our RL agent can learn from the best.
The main idea is to store all the possible tic-tac-toe states in a tree, and determine for a given state what next move leads to a good result. This is done by recursively searching through the tree and finding rewards. The reward in the subtree below each possible next move informs us which move is optimal. To illustrate how this works, we start with a very simple tree (based on this youtube video):
In this game two players compete: one has the goal to maximize the score, one has the goal to minimize the score. First, the maximizing player can choose at the top of the tree, then the minimizing player can choose and so on. As the maximizing player our optimal move seems to be to go right, that is where the high score of 9 is present. However, the second player will then simply choose 2 when it has the choice. Therefore, in this case, the optimal choice is to go left and get a score of three.
Solving this kind of tree is done using a minimax algorithm. At each level in the tree the min or max player makes their optimal choice. If we express this tree in Python we get:
rootβββ β βββ 3β βββ 5βββ βββ 2 βββ 9
where we can solve the minimax problem by recusively going through the tree:
3
which indeed shows the correct maximum score the max player can get given this particular tree: 3. Making the recursion explicit in pseudo-code reveals what happens under the hood:
start-game: minmax('root') -> max-player: max([minmax('l1'), minmax('r1')]) -> min-player: max([min([minmax('l1-1), minmax('l1-2')]), min([minmax('r1-1'), minmax('r1-1')])]) ->end-tree : max([min([3, 5]), min([2, 9])]) -> max([3, 2]) -> 3
We can use the exact same minimax approach for tic-tac-toe using a much larger tree. First, we start at the top with nine possible moves for the max player, then we are left with eight moves for the min player, etcetera:
which leaves us with an enormous tree with all the possible combinations possible on the board. To store the tic-tac-toe state we assign a letter toe each of the fields on the board:
and create a Python class to store the state, allow updates to the board, check if the game is done, and return the value of our game depending on the outcome:
next we recursively create the giant tree and add the board state object at each node. The ID of each node is the sequence of steps taken, e.g. acig.
With the tree done, we can use minimax code very similar to the simple tree we first started with:
Using determine_move we can now get the next best move. Note that in case multiple moves have the same max value, we choose a random move here amongst those max moves. For example, when the max player plays the a square:
e2.986009120941162
Note that it picks the center e square, which is indeed a very strong move in tic-tac-toe. In addition, it takes around 3 seconds to determine this move.
So, now we have a worthy opponent for our RL agent. The only problem is that it is very slow, much too slow actually for our RL agent which will have to play a lot of games to learn tic-tac-toe. In part 2 we will use an advanced programming technique to massively speed up the tree search.
My name is Paul Hiemstra, and I work as a teacher and data scientist in the Netherlands. I am a mix between a scientist and a software engineer, and have a broad interest in everything related to data science. You can follow me here on medium, or on LinkedIn.
If you enjoyed this article, you might also enjoy some of my other articles:
There is no data science like applied data science
Altair plot deconstruction: visualizing the correlation structure of weather data
Advanced functional programming for data science: building code architectures with function operators
|
[
{
"code": null,
"e": 167,
"s": 46,
"text": "Where we build a brute force minimax tree search which will serve as the opponent to our reinforcement learning approach"
},
{
"code": null,
"e": 532,
"s": 167,
"text": "This article is part of a series that lets a computer play tic-tac-toe using reinforcement learning. You can find all the articles here. The goal is to provide a complete implementation that you can really pick apart and learn reinforcement learning from. It is probably best to read the articles in order. The article including all the code can be found on Github"
},
{
"code": null,
"e": 1014,
"s": 532,
"text": "Reinforcement learning is the third modeling paradigm next to supervised and unsupervised modeling. It has seen great successes recently, including beating the worlds best Go player. This feat was considered impossible only a few years prior because of the enormous possible moveset in Go that dwarfs even that of chess. I will only briefly touch on how reinforcement learning works, but the following youtube movies should provide a more in depth introduction (Intro RL, Deep RL)."
},
{
"code": null,
"e": 1082,
"s": 1014,
"text": "Reinforcement learning (RL) is based on the following key concepts:"
},
{
"code": null,
"e": 1318,
"s": 1082,
"text": "There is a computer agent which takes actions (A) that act on an environment (E). That environment responds by providing a reward (R) for that action, and bringing the system to the next state (S). Take for example the following state:"
},
{
"code": null,
"e": 1809,
"s": 1318,
"text": "Here we consider two options for the next action of the O player: the green and red option. Taking the green option yields a high reward, as we block the X player from winning. Alternatively, the red option yields a low reward as this allows the X player to win. By playing tic-tac-toe many times and receiving rewards the RL agent will slowly learn what action in a particular state provides a good long term value. The mapping of state to optimal action is known as a policy in RL jargon."
},
{
"code": null,
"e": 2146,
"s": 1809,
"text": "With the basics of RL out of the way, we can now focus on the goal of this article: building an opponent for our RL agent. Luckily for us, the game of tic-tac-toe is simple enough and can be solved in a brute force manner. This ensures that we end up with the optimal moves in tic-tac-toe, ensuring our RL agent can learn from the best."
},
{
"code": null,
"e": 2550,
"s": 2146,
"text": "The main idea is to store all the possible tic-tac-toe states in a tree, and determine for a given state what next move leads to a good result. This is done by recursively searching through the tree and finding rewards. The reward in the subtree below each possible next move informs us which move is optimal. To illustrate how this works, we start with a very simple tree (based on this youtube video):"
},
{
"code": null,
"e": 3051,
"s": 2550,
"text": "In this game two players compete: one has the goal to maximize the score, one has the goal to minimize the score. First, the maximizing player can choose at the top of the tree, then the minimizing player can choose and so on. As the maximizing player our optimal move seems to be to go right, that is where the high score of 9 is present. However, the second player will then simply choose 2 when it has the choice. Therefore, in this case, the optimal choice is to go left and get a score of three."
},
{
"code": null,
"e": 3230,
"s": 3051,
"text": "Solving this kind of tree is done using a minimax algorithm. At each level in the tree the min or max player makes their optimal choice. If we express this tree in Python we get:"
},
{
"code": null,
"e": 3279,
"s": 3230,
"text": "rootβββ β βββ 3β βββ 5βββ βββ 2 βββ 9"
},
{
"code": null,
"e": 3356,
"s": 3279,
"text": "where we can solve the minimax problem by recusively going through the tree:"
},
{
"code": null,
"e": 3358,
"s": 3356,
"text": "3"
},
{
"code": null,
"e": 3539,
"s": 3358,
"text": "which indeed shows the correct maximum score the max player can get given this particular tree: 3. Making the recursion explicit in pseudo-code reveals what happens under the hood:"
},
{
"code": null,
"e": 3836,
"s": 3539,
"text": "start-game: minmax('root') -> max-player: max([minmax('l1'), minmax('r1')]) -> min-player: max([min([minmax('l1-1), minmax('l1-2')]), min([minmax('r1-1'), minmax('r1-1')])]) ->end-tree : max([min([3, 5]), min([2, 9])]) -> max([3, 2]) -> 3"
},
{
"code": null,
"e": 4057,
"s": 3836,
"text": "We can use the exact same minimax approach for tic-tac-toe using a much larger tree. First, we start at the top with nine possible moves for the max player, then we are left with eight moves for the min player, etcetera:"
},
{
"code": null,
"e": 4240,
"s": 4057,
"text": "which leaves us with an enormous tree with all the possible combinations possible on the board. To store the tic-tac-toe state we assign a letter toe each of the fields on the board:"
},
{
"code": null,
"e": 4400,
"s": 4240,
"text": "and create a Python class to store the state, allow updates to the board, check if the game is done, and return the value of our game depending on the outcome:"
},
{
"code": null,
"e": 4550,
"s": 4400,
"text": "next we recursively create the giant tree and add the board state object at each node. The ID of each node is the sequence of steps taken, e.g. acig."
},
{
"code": null,
"e": 4649,
"s": 4550,
"text": "With the tree done, we can use minimax code very similar to the simple tree we first started with:"
},
{
"code": null,
"e": 4870,
"s": 4649,
"text": "Using determine_move we can now get the next best move. Note that in case multiple moves have the same max value, we choose a random move here amongst those max moves. For example, when the max player plays the a square:"
},
{
"code": null,
"e": 4889,
"s": 4870,
"text": "e2.986009120941162"
},
{
"code": null,
"e": 5043,
"s": 4889,
"text": "Note that it picks the center e square, which is indeed a very strong move in tic-tac-toe. In addition, it takes around 3 seconds to determine this move."
},
{
"code": null,
"e": 5333,
"s": 5043,
"text": "So, now we have a worthy opponent for our RL agent. The only problem is that it is very slow, much too slow actually for our RL agent which will have to play a lot of games to learn tic-tac-toe. In part 2 we will use an advanced programming technique to massively speed up the tree search."
},
{
"code": null,
"e": 5593,
"s": 5333,
"text": "My name is Paul Hiemstra, and I work as a teacher and data scientist in the Netherlands. I am a mix between a scientist and a software engineer, and have a broad interest in everything related to data science. You can follow me here on medium, or on LinkedIn."
},
{
"code": null,
"e": 5670,
"s": 5593,
"text": "If you enjoyed this article, you might also enjoy some of my other articles:"
},
{
"code": null,
"e": 5721,
"s": 5670,
"text": "There is no data science like applied data science"
},
{
"code": null,
"e": 5803,
"s": 5721,
"text": "Altair plot deconstruction: visualizing the correlation structure of weather data"
}
] |
Who Is Your Golden Goose?: Cohort Analysis | by Jiwon Jeong | Towards Data Science
|
Customer segmentation is the technique of diving customers into groups based on their purchase patterns to identify who are the most profitable groups. In segmenting customers, various criteria can also be used depending on the market such as geographic, demographic characteristics or behavior bases. This technique assumes that groups with different features require different approaches to marketing and wants to figure out the groups who can boost their profitability the most.
Today, we are going to discuss how to do customer segmentation analysis with the online retail dataset from UCI ML repo. This analysis will be focused on two steps getting the RFM values and making clusters with K-means algorithms. The dataset and the full code is also available on my Github. The original resource of this note is from the course βCustomer Segmentation Analysis in Python.β
RFM is an acronym of recency, frequency and monetary. Recency is about when was the last order of a customer. It means the number of days since a customer made the last purchase. If itβs a case for a website or an app, this could be interpreted as the last visit day or the last login time.
Frequency is about the number of purchase in a given period. It could be 3 months, 6 months or 1 year. So we can understand this value as for how often or how many a customer used the product of a company. The bigger the value is, the more engaged the customers are. Could we say them as our VIP? Not necessary. Cause we also have to think about how much they actually paid for each purchase, which means monetary value.
Monetary is the total amount of money a customer spent in that given period. Therefore big spenders will be differentiated with other customers such as MVP or VIP.
These three values are commonly used quantifiable factors in cohort analysis. Because of their simple and intuitive concept, they are popular among other customer segmentation methods.
So we are going to apply RFM to our cohort analysis today. The dataset we are going to use is the transaction history data occurring from Jan 2010 to Sep 2011. As this is a tutorial guideline for cohort analysis, Iβm going to use only the randomly selected fraction of the original dataset.
# Import dataonline = pd.read_excel('Online Retail.xlsx')# drop the row missing customer ID online = online[online.CustomerID.notnull()]online = online.sample(frac = .3).reset_index(drop = True)online.head()
The first thing weβre going to count is the recency value, the number of days since the last order of a customer. From which column could we get that value? InvoiceData. With this column, we can get when was the first purchase and when was the last purchase of a customer. Letβs call the first one as CohortDay. As InvoiceDate also contains additional time data, we need to extract the year, month and day part. After that, weβll get CohortDay which is the minimum of InvoiceDay.
# extract year, month and dayonline['InvoiceDay'] = online.InvoiceDate.apply(lambda x: dt.datetime(x.year, x.month, x.day))online.head()
As we randomly chose the subset of the data, we also need to know the time period of our data. Like what you can see below, the final day of our dataset is December 9th, 2011. Therefore set December 10th as our pining date and count backward the number of days from the latest purchase for each customer. That will be the recency value.
# print the time periodprint('Min : {}, Max : {}'.format(min(online.InvoiceDay), max(online.InvoiceDay)))
# pin the last datepin_date = max(online.InvoiceDay) + dt.timedelta(1)
Before getting the recency, letβs count one more value in advance, the total amount of money each customer spent. This is for counting the monetary value. How can we get that? Easy! Multiplying the product price and the quantity of the order in each row.
# Create total spend dataframeonline['TotalSum'] = online.Quantity * online.UnitPriceonline.head()
Now we are ready to get the three RFM values at once. Iβll group the data for each customer and aggregate it for each recency, frequency, and monetary value.
# calculate RFM valuesrfm = online.groupby('CustomerID').agg({ 'InvoiceDate' : lambda x: (pin_date - x.max()).days, 'InvoiceNo' : 'count', 'TotalSum' : 'sum'})# rename the columnsrfm.rename(columns = {'InvoiceDate' : 'Recency', 'InvoiceNo' : 'Frequency', 'TotalSum' : 'Monetary'}, inplace = True)rfm.head()
Now weβll group the customers based on RFM values. Cause these are continuous values, we can also use the quantile values and divide them into 4 groups.
# create labels and assign them to tree percentile groups r_labels = range(4, 0, -1)r_groups = pd.qcut(rfm.Recency, q = 4, labels = r_labels)f_labels = range(1, 5)f_groups = pd.qcut(rfm.Frequency, q = 4, labels = f_labels)m_labels = range(1, 5)m_groups = pd.qcut(rfm.Monetary, q = 4, labels = m_labels)
Please pay extra care for the r_labels. I gave the labels in descending order. Why is that? Because recency means how much time has elapsed since a customerβs last order. Therefore the smaller the value is, the more engaged a customer to that brand. Now letβs make a new column for indicating group labels.
# make a new column for group labelsrfm['R'] = r_groups.valuesrfm['F'] = f_groups.valuesrfm['M'] = m_groups.values# sum up the three columnsrfm['RFM_Segment'] = rfm.apply(lambda x: str(x['R']) + str(x['F']) + str(x['M']), axis = 1)rfm['RFM_Score'] = rfm[['R', 'F', 'M']].sum(axis = 1)rfm.head()
I attached all three labels in one cell as RFM_Segment. In this way, we can easily check what level or segment a customer belongs to. RFM_Score is the total sum of the three values. It doesnβt necessarily have to be the sum so the mean value is also possible. Moreover, we can catch further patterns with the mean or count values of recency, frequency and monetary grouped by this score like below.
# calculate averae values for each RFMrfm_agg = rfm.groupby('RFM_Score').agg({ 'Recency' : 'mean', 'Frequency' : 'mean', 'Monetary' : ['mean', 'count']})rfm_agg.round(1).head()
RFM_Score will be the total score of a customerβs engagement or loyalty. Summing up the three values altogether, we can finally categorize customers into βGold,β βSilver,β βBronze,β and βGreenβ.
# assign labels from total scorescore_labels = ['Green', 'Bronze', 'Silver', 'Gold']score_groups = pd.qcut(rfm.RFM_Score, q = 4, labels = score_labels)rfm['RFM_Level'] = score_groups.valuesrfm.head()
Great! Weβre done with one cohort analysis with RFM values. We identified who is our golden goose and where we should take extra care. Now why donβt we try a different method for customer segmentation and compare the two results?
K-Means clustering is one type of unsupervised learning algorithms, which makes groups based on the distance between the points. How? There are two concepts of distance in K-Means clustering. Within Cluster Sums of Squares (WSS) and Between Cluster Sums of Squares (BSS).
WSS means the sum of distances between the points and the corresponding centroids for each cluster and BSS means the sum of distances between the centroids and the total sample mean multiplied by the number of points within each cluster. So you can consider WSS as the measure of compactness and BSS as the measure of separation. For clustering to be successful, we need to get the lower WSS and the higher BSS.
By iterating and moving the cluster centroids, K-Means algorithm tries to get the optimized points of the centroid, which minimize the value of WSS and maximize the value of BSS. I wonβt go more in-depth with the basic concept, but you can find a further explanation from video.
Because K-means clustering uses the distance as the similarity factor, we need to scale the data. Suppose we have two different scales of features, say height and weight. Height is over 150cm and weight is below 100kg on average. So If we plot this data, the distance between the points will be highly dominated by height resulting in a biased analysis.
Therefore when it comes to K-means clustering, scaling and normalizing data is a critical step for preprocessing. If we check the distribution of RFM values, you can notice that they are right-skewed. Itβs not a good state to use without standardization. Letβs transform the RFM values into log scaled first and then normalize them.
# define function for the values below 0def neg_to_zero(x): if x <= 0: return 1 else: return x# apply the function to Recency and MonetaryValue column rfm['Recency'] = [neg_to_zero(x) for x in rfm.Recency]rfm['Monetary'] = [neg_to_zero(x) for x in rfm.Monetary]# unskew the datarfm_log = rfm[['Recency', 'Frequency', 'Monetary']].apply(np.log, axis = 1).round(3)
The values below or equal to zero go negative infinite when they are in log scale, I made a function to convert those values into 1 and applied it to Recency and Monetary column, using list comprehension like above. And then, a log transformation is applied for each RFM values. The next preprocessing step is scaling but itβs simpler than the previous step. Using StandardScaler(), we can get the standardized values like below.
# scale the datascaler = StandardScaler()rfm_scaled = scaler.fit_transform(rfm_log)# transform into a dataframerfm_scaled = pd.DataFrame(rfm_scaled, index = rfm.index, columns = rfm_log.columns)
The plot on the left is the distributions of RFM before preprocessing, and the plot on the right is the distributions of RFM after normalization. By making them in the somewhat normal distribution, we can give hints to our model to grasp the trends between values easily and accurately. Now, we are done with preprocessing.
What is the next? The next step will be selecting the right number of clusters. We have to choose how many groups weβre going to make. If there is prior knowledge, we can just give the number right ahead to the algorithm. But most of the case in unsupervised learning, there isnβt. So we need to choose the optimized number, and the Elbow method is one of the solutions where we can get the hints.
# the Elbow methodwcss = {}for k in range(1, 11): kmeans = KMeans(n_clusters= k, init= 'k-means++', max_iter= 300) kmeans.fit(rfm_scaled) wcss[k] = kmeans.inertia_# plot the WCSS valuessns.pointplot(x = list(wcss.keys()), y = list(wcss.values()))plt.xlabel('K Numbers')plt.ylabel('WCSS')plt.show()
Using for loop, I built the models for every number of clusters from 1 to 10. And then collect the WSS values for each model. Look at the plot below. As the number of clusters increases, the value of WSS decreases. There is no surprise cause the more clusters we make, the size of each cluster will decrease so the sum of the distances within each cluster will decrease. Then what is the optimal number?
The answer is at the βElbowβ of this line. Somewhere WSS dramatically decrease but not too much K. My choice here is three. What do you say? Doesnβt it really look like an elbow of the line?
Now we chose the number of clusters, we can build a model and make actual clusters like below. We can also check the distance between each point and the centroids or the labels of the clusters. Letβs make a new column and assign the labels to each customer.
# clusteringclus = KMeans(n_clusters= 3, init= 'k-means++', max_iter= 300)clus.fit(rfm_scaled)# Assign the clusters to datamartrfm['K_Cluster'] = clus.labels_rfm.head()
Now we made two kinds of segmentation, RFM quantile groups and K-Means groups. Letβs make visualization and compare the two methods.
Iβm going to make two kinds of plot, a line plot and a heat map. We can easily compare the differences of RFM values with these two plots. Firstly, Iβll make columns to assign the two clustering labels. And then reshape the data frame by melting the RFM values into one column.
# assign cluster column rfm_scaled['K_Cluster'] = clus.labels_rfm_scaled['RFM_Level'] = rfm.RFM_Levelrfm_scaled.reset_index(inplace = True)# melt the dataframerfm_melted = pd.melt(frame= rfm_scaled, id_vars= ['CustomerID', 'RFM_Level', 'K_Cluster'], var_name = 'Metrics', value_name = 'Value')rfm_melted.head()
This will make recency, frequency and monetary categories as observations, which allows us to plot the values in one plot. Put Metrics at x-axis and Value at y-axis and group the values by RFM_Level. Repeat the same code which groups the values by K_Cluster this time. The outcome would be like below.
# a snake plot with RFMsns.lineplot(x = 'Metrics', y = 'Value', hue = 'RFM_Level', data = rfm_melted)plt.title('Snake Plot of RFM')plt.legend(loc = 'upper right')# a snake plot with K-Meanssns.lineplot(x = 'Metrics', y = 'Value', hue = 'K_Cluster', data = rfm_melted)plt.title('Snake Plot of RFM')plt.legend(loc = 'upper right')
This kind of plots is called βSnake plotβ especially in marketing analysis. It seems Gold and Green groups on the left plot are similar with 1 and 2 clusters on the right plot. And the Bronze and Silver groups seem to be merged into group 0.
Letβs try again with a heat map. Heat maps are a graphical representation of data where larger values were colored in darker scales and smaller values in lighter scales. We can compare the variance between the groups quite intuitively by colors.
# the mean value in total total_avg = rfm.iloc[:, 0:3].mean()total_avg# calculate the proportional gap with total meancluster_avg = rfm.groupby('RFM_Level').mean().iloc[:, 0:3]prop_rfm = cluster_avg/total_avg - 1# heatmap with RFMsns.heatmap(prop_rfm, cmap= 'Oranges', fmt= '.2f', annot = True)plt.title('Heatmap of RFM quantile')plt.plot()
And then repeat the same code for K-clusters as we did before.
# calculate the proportional gap with total meancluster_avg_K = rfm.groupby('K_Cluster').mean().iloc[:, 0:3]prop_rfm_K = cluster_avg_K/total_avg - 1# heatmap with K-meanssns.heatmap(prop_rfm_K, cmap= 'Blues', fmt= '.2f', annot = True)plt.title('Heatmap of K-Means')plt.plot()
It could be seen unmatching, especially at the top of the plots. But Itβs just because of the different order. The Green group on the left will correspond to group 2. If you see the values inside each box, you can see the difference between the groups become significant for Gold and 1 group. And it could be easily recognized by the darkness of the color.
We talked about how to get RFM values from customer purchase data, and we made two kinds of segmentation with RFM quantiles and K-Means clustering methods. With this result, we can now figure out who are our βgoldenβ customers, the most profitable groups. This also tells us on which customer to focus on and to whom give special offers or promotions for fostering loyalty among customers. We can select the best communication channel for each segment and improve new marketing strategies.
A nice article about RFM analysis: https://clevertap.com/blog/rfm-analysis/
Another useful explanation for RFM analysis: https://www.optimove.com/learning-center/rfm-segmentation
Intuitive explanation on K-means clustering: https://www.youtube.com/watch?v=_aWzGGNrcic
Thank you for reading and hope you found this post interesting. If there is something need to be corrected, please share your insight! If youβd like to encourage an aspiring data scientist, please hit π π π! Iβm always open to talk so feel free to leave comments or contact me on LinkedIn. Iβll come back with another exciting project. Until then, happy machine learning!
|
[
{
"code": null,
"e": 653,
"s": 171,
"text": "Customer segmentation is the technique of diving customers into groups based on their purchase patterns to identify who are the most profitable groups. In segmenting customers, various criteria can also be used depending on the market such as geographic, demographic characteristics or behavior bases. This technique assumes that groups with different features require different approaches to marketing and wants to figure out the groups who can boost their profitability the most."
},
{
"code": null,
"e": 1045,
"s": 653,
"text": "Today, we are going to discuss how to do customer segmentation analysis with the online retail dataset from UCI ML repo. This analysis will be focused on two steps getting the RFM values and making clusters with K-means algorithms. The dataset and the full code is also available on my Github. The original resource of this note is from the course βCustomer Segmentation Analysis in Python.β"
},
{
"code": null,
"e": 1336,
"s": 1045,
"text": "RFM is an acronym of recency, frequency and monetary. Recency is about when was the last order of a customer. It means the number of days since a customer made the last purchase. If itβs a case for a website or an app, this could be interpreted as the last visit day or the last login time."
},
{
"code": null,
"e": 1757,
"s": 1336,
"text": "Frequency is about the number of purchase in a given period. It could be 3 months, 6 months or 1 year. So we can understand this value as for how often or how many a customer used the product of a company. The bigger the value is, the more engaged the customers are. Could we say them as our VIP? Not necessary. Cause we also have to think about how much they actually paid for each purchase, which means monetary value."
},
{
"code": null,
"e": 1921,
"s": 1757,
"text": "Monetary is the total amount of money a customer spent in that given period. Therefore big spenders will be differentiated with other customers such as MVP or VIP."
},
{
"code": null,
"e": 2106,
"s": 1921,
"text": "These three values are commonly used quantifiable factors in cohort analysis. Because of their simple and intuitive concept, they are popular among other customer segmentation methods."
},
{
"code": null,
"e": 2397,
"s": 2106,
"text": "So we are going to apply RFM to our cohort analysis today. The dataset we are going to use is the transaction history data occurring from Jan 2010 to Sep 2011. As this is a tutorial guideline for cohort analysis, Iβm going to use only the randomly selected fraction of the original dataset."
},
{
"code": null,
"e": 2605,
"s": 2397,
"text": "# Import dataonline = pd.read_excel('Online Retail.xlsx')# drop the row missing customer ID online = online[online.CustomerID.notnull()]online = online.sample(frac = .3).reset_index(drop = True)online.head()"
},
{
"code": null,
"e": 3085,
"s": 2605,
"text": "The first thing weβre going to count is the recency value, the number of days since the last order of a customer. From which column could we get that value? InvoiceData. With this column, we can get when was the first purchase and when was the last purchase of a customer. Letβs call the first one as CohortDay. As InvoiceDate also contains additional time data, we need to extract the year, month and day part. After that, weβll get CohortDay which is the minimum of InvoiceDay."
},
{
"code": null,
"e": 3222,
"s": 3085,
"text": "# extract year, month and dayonline['InvoiceDay'] = online.InvoiceDate.apply(lambda x: dt.datetime(x.year, x.month, x.day))online.head()"
},
{
"code": null,
"e": 3559,
"s": 3222,
"text": "As we randomly chose the subset of the data, we also need to know the time period of our data. Like what you can see below, the final day of our dataset is December 9th, 2011. Therefore set December 10th as our pining date and count backward the number of days from the latest purchase for each customer. That will be the recency value."
},
{
"code": null,
"e": 3665,
"s": 3559,
"text": "# print the time periodprint('Min : {}, Max : {}'.format(min(online.InvoiceDay), max(online.InvoiceDay)))"
},
{
"code": null,
"e": 3736,
"s": 3665,
"text": "# pin the last datepin_date = max(online.InvoiceDay) + dt.timedelta(1)"
},
{
"code": null,
"e": 3991,
"s": 3736,
"text": "Before getting the recency, letβs count one more value in advance, the total amount of money each customer spent. This is for counting the monetary value. How can we get that? Easy! Multiplying the product price and the quantity of the order in each row."
},
{
"code": null,
"e": 4090,
"s": 3991,
"text": "# Create total spend dataframeonline['TotalSum'] = online.Quantity * online.UnitPriceonline.head()"
},
{
"code": null,
"e": 4248,
"s": 4090,
"text": "Now we are ready to get the three RFM values at once. Iβll group the data for each customer and aggregate it for each recency, frequency, and monetary value."
},
{
"code": null,
"e": 4609,
"s": 4248,
"text": "# calculate RFM valuesrfm = online.groupby('CustomerID').agg({ 'InvoiceDate' : lambda x: (pin_date - x.max()).days, 'InvoiceNo' : 'count', 'TotalSum' : 'sum'})# rename the columnsrfm.rename(columns = {'InvoiceDate' : 'Recency', 'InvoiceNo' : 'Frequency', 'TotalSum' : 'Monetary'}, inplace = True)rfm.head()"
},
{
"code": null,
"e": 4762,
"s": 4609,
"text": "Now weβll group the customers based on RFM values. Cause these are continuous values, we can also use the quantile values and divide them into 4 groups."
},
{
"code": null,
"e": 5065,
"s": 4762,
"text": "# create labels and assign them to tree percentile groups r_labels = range(4, 0, -1)r_groups = pd.qcut(rfm.Recency, q = 4, labels = r_labels)f_labels = range(1, 5)f_groups = pd.qcut(rfm.Frequency, q = 4, labels = f_labels)m_labels = range(1, 5)m_groups = pd.qcut(rfm.Monetary, q = 4, labels = m_labels)"
},
{
"code": null,
"e": 5372,
"s": 5065,
"text": "Please pay extra care for the r_labels. I gave the labels in descending order. Why is that? Because recency means how much time has elapsed since a customerβs last order. Therefore the smaller the value is, the more engaged a customer to that brand. Now letβs make a new column for indicating group labels."
},
{
"code": null,
"e": 5667,
"s": 5372,
"text": "# make a new column for group labelsrfm['R'] = r_groups.valuesrfm['F'] = f_groups.valuesrfm['M'] = m_groups.values# sum up the three columnsrfm['RFM_Segment'] = rfm.apply(lambda x: str(x['R']) + str(x['F']) + str(x['M']), axis = 1)rfm['RFM_Score'] = rfm[['R', 'F', 'M']].sum(axis = 1)rfm.head()"
},
{
"code": null,
"e": 6066,
"s": 5667,
"text": "I attached all three labels in one cell as RFM_Segment. In this way, we can easily check what level or segment a customer belongs to. RFM_Score is the total sum of the three values. It doesnβt necessarily have to be the sum so the mean value is also possible. Moreover, we can catch further patterns with the mean or count values of recency, frequency and monetary grouped by this score like below."
},
{
"code": null,
"e": 6252,
"s": 6066,
"text": "# calculate averae values for each RFMrfm_agg = rfm.groupby('RFM_Score').agg({ 'Recency' : 'mean', 'Frequency' : 'mean', 'Monetary' : ['mean', 'count']})rfm_agg.round(1).head()"
},
{
"code": null,
"e": 6447,
"s": 6252,
"text": "RFM_Score will be the total score of a customerβs engagement or loyalty. Summing up the three values altogether, we can finally categorize customers into βGold,β βSilver,β βBronze,β and βGreenβ."
},
{
"code": null,
"e": 6647,
"s": 6447,
"text": "# assign labels from total scorescore_labels = ['Green', 'Bronze', 'Silver', 'Gold']score_groups = pd.qcut(rfm.RFM_Score, q = 4, labels = score_labels)rfm['RFM_Level'] = score_groups.valuesrfm.head()"
},
{
"code": null,
"e": 6877,
"s": 6647,
"text": "Great! Weβre done with one cohort analysis with RFM values. We identified who is our golden goose and where we should take extra care. Now why donβt we try a different method for customer segmentation and compare the two results?"
},
{
"code": null,
"e": 7149,
"s": 6877,
"text": "K-Means clustering is one type of unsupervised learning algorithms, which makes groups based on the distance between the points. How? There are two concepts of distance in K-Means clustering. Within Cluster Sums of Squares (WSS) and Between Cluster Sums of Squares (BSS)."
},
{
"code": null,
"e": 7561,
"s": 7149,
"text": "WSS means the sum of distances between the points and the corresponding centroids for each cluster and BSS means the sum of distances between the centroids and the total sample mean multiplied by the number of points within each cluster. So you can consider WSS as the measure of compactness and BSS as the measure of separation. For clustering to be successful, we need to get the lower WSS and the higher BSS."
},
{
"code": null,
"e": 7840,
"s": 7561,
"text": "By iterating and moving the cluster centroids, K-Means algorithm tries to get the optimized points of the centroid, which minimize the value of WSS and maximize the value of BSS. I wonβt go more in-depth with the basic concept, but you can find a further explanation from video."
},
{
"code": null,
"e": 8194,
"s": 7840,
"text": "Because K-means clustering uses the distance as the similarity factor, we need to scale the data. Suppose we have two different scales of features, say height and weight. Height is over 150cm and weight is below 100kg on average. So If we plot this data, the distance between the points will be highly dominated by height resulting in a biased analysis."
},
{
"code": null,
"e": 8527,
"s": 8194,
"text": "Therefore when it comes to K-means clustering, scaling and normalizing data is a critical step for preprocessing. If we check the distribution of RFM values, you can notice that they are right-skewed. Itβs not a good state to use without standardization. Letβs transform the RFM values into log scaled first and then normalize them."
},
{
"code": null,
"e": 8910,
"s": 8527,
"text": "# define function for the values below 0def neg_to_zero(x): if x <= 0: return 1 else: return x# apply the function to Recency and MonetaryValue column rfm['Recency'] = [neg_to_zero(x) for x in rfm.Recency]rfm['Monetary'] = [neg_to_zero(x) for x in rfm.Monetary]# unskew the datarfm_log = rfm[['Recency', 'Frequency', 'Monetary']].apply(np.log, axis = 1).round(3)"
},
{
"code": null,
"e": 9340,
"s": 8910,
"text": "The values below or equal to zero go negative infinite when they are in log scale, I made a function to convert those values into 1 and applied it to Recency and Monetary column, using list comprehension like above. And then, a log transformation is applied for each RFM values. The next preprocessing step is scaling but itβs simpler than the previous step. Using StandardScaler(), we can get the standardized values like below."
},
{
"code": null,
"e": 9535,
"s": 9340,
"text": "# scale the datascaler = StandardScaler()rfm_scaled = scaler.fit_transform(rfm_log)# transform into a dataframerfm_scaled = pd.DataFrame(rfm_scaled, index = rfm.index, columns = rfm_log.columns)"
},
{
"code": null,
"e": 9859,
"s": 9535,
"text": "The plot on the left is the distributions of RFM before preprocessing, and the plot on the right is the distributions of RFM after normalization. By making them in the somewhat normal distribution, we can give hints to our model to grasp the trends between values easily and accurately. Now, we are done with preprocessing."
},
{
"code": null,
"e": 10257,
"s": 9859,
"text": "What is the next? The next step will be selecting the right number of clusters. We have to choose how many groups weβre going to make. If there is prior knowledge, we can just give the number right ahead to the algorithm. But most of the case in unsupervised learning, there isnβt. So we need to choose the optimized number, and the Elbow method is one of the solutions where we can get the hints."
},
{
"code": null,
"e": 10564,
"s": 10257,
"text": "# the Elbow methodwcss = {}for k in range(1, 11): kmeans = KMeans(n_clusters= k, init= 'k-means++', max_iter= 300) kmeans.fit(rfm_scaled) wcss[k] = kmeans.inertia_# plot the WCSS valuessns.pointplot(x = list(wcss.keys()), y = list(wcss.values()))plt.xlabel('K Numbers')plt.ylabel('WCSS')plt.show()"
},
{
"code": null,
"e": 10968,
"s": 10564,
"text": "Using for loop, I built the models for every number of clusters from 1 to 10. And then collect the WSS values for each model. Look at the plot below. As the number of clusters increases, the value of WSS decreases. There is no surprise cause the more clusters we make, the size of each cluster will decrease so the sum of the distances within each cluster will decrease. Then what is the optimal number?"
},
{
"code": null,
"e": 11159,
"s": 10968,
"text": "The answer is at the βElbowβ of this line. Somewhere WSS dramatically decrease but not too much K. My choice here is three. What do you say? Doesnβt it really look like an elbow of the line?"
},
{
"code": null,
"e": 11417,
"s": 11159,
"text": "Now we chose the number of clusters, we can build a model and make actual clusters like below. We can also check the distance between each point and the centroids or the labels of the clusters. Letβs make a new column and assign the labels to each customer."
},
{
"code": null,
"e": 11586,
"s": 11417,
"text": "# clusteringclus = KMeans(n_clusters= 3, init= 'k-means++', max_iter= 300)clus.fit(rfm_scaled)# Assign the clusters to datamartrfm['K_Cluster'] = clus.labels_rfm.head()"
},
{
"code": null,
"e": 11719,
"s": 11586,
"text": "Now we made two kinds of segmentation, RFM quantile groups and K-Means groups. Letβs make visualization and compare the two methods."
},
{
"code": null,
"e": 11997,
"s": 11719,
"text": "Iβm going to make two kinds of plot, a line plot and a heat map. We can easily compare the differences of RFM values with these two plots. Firstly, Iβll make columns to assign the two clustering labels. And then reshape the data frame by melting the RFM values into one column."
},
{
"code": null,
"e": 12308,
"s": 11997,
"text": "# assign cluster column rfm_scaled['K_Cluster'] = clus.labels_rfm_scaled['RFM_Level'] = rfm.RFM_Levelrfm_scaled.reset_index(inplace = True)# melt the dataframerfm_melted = pd.melt(frame= rfm_scaled, id_vars= ['CustomerID', 'RFM_Level', 'K_Cluster'], var_name = 'Metrics', value_name = 'Value')rfm_melted.head()"
},
{
"code": null,
"e": 12610,
"s": 12308,
"text": "This will make recency, frequency and monetary categories as observations, which allows us to plot the values in one plot. Put Metrics at x-axis and Value at y-axis and group the values by RFM_Level. Repeat the same code which groups the values by K_Cluster this time. The outcome would be like below."
},
{
"code": null,
"e": 12939,
"s": 12610,
"text": "# a snake plot with RFMsns.lineplot(x = 'Metrics', y = 'Value', hue = 'RFM_Level', data = rfm_melted)plt.title('Snake Plot of RFM')plt.legend(loc = 'upper right')# a snake plot with K-Meanssns.lineplot(x = 'Metrics', y = 'Value', hue = 'K_Cluster', data = rfm_melted)plt.title('Snake Plot of RFM')plt.legend(loc = 'upper right')"
},
{
"code": null,
"e": 13181,
"s": 12939,
"text": "This kind of plots is called βSnake plotβ especially in marketing analysis. It seems Gold and Green groups on the left plot are similar with 1 and 2 clusters on the right plot. And the Bronze and Silver groups seem to be merged into group 0."
},
{
"code": null,
"e": 13427,
"s": 13181,
"text": "Letβs try again with a heat map. Heat maps are a graphical representation of data where larger values were colored in darker scales and smaller values in lighter scales. We can compare the variance between the groups quite intuitively by colors."
},
{
"code": null,
"e": 13768,
"s": 13427,
"text": "# the mean value in total total_avg = rfm.iloc[:, 0:3].mean()total_avg# calculate the proportional gap with total meancluster_avg = rfm.groupby('RFM_Level').mean().iloc[:, 0:3]prop_rfm = cluster_avg/total_avg - 1# heatmap with RFMsns.heatmap(prop_rfm, cmap= 'Oranges', fmt= '.2f', annot = True)plt.title('Heatmap of RFM quantile')plt.plot()"
},
{
"code": null,
"e": 13831,
"s": 13768,
"text": "And then repeat the same code for K-clusters as we did before."
},
{
"code": null,
"e": 14107,
"s": 13831,
"text": "# calculate the proportional gap with total meancluster_avg_K = rfm.groupby('K_Cluster').mean().iloc[:, 0:3]prop_rfm_K = cluster_avg_K/total_avg - 1# heatmap with K-meanssns.heatmap(prop_rfm_K, cmap= 'Blues', fmt= '.2f', annot = True)plt.title('Heatmap of K-Means')plt.plot()"
},
{
"code": null,
"e": 14464,
"s": 14107,
"text": "It could be seen unmatching, especially at the top of the plots. But Itβs just because of the different order. The Green group on the left will correspond to group 2. If you see the values inside each box, you can see the difference between the groups become significant for Gold and 1 group. And it could be easily recognized by the darkness of the color."
},
{
"code": null,
"e": 14954,
"s": 14464,
"text": "We talked about how to get RFM values from customer purchase data, and we made two kinds of segmentation with RFM quantiles and K-Means clustering methods. With this result, we can now figure out who are our βgoldenβ customers, the most profitable groups. This also tells us on which customer to focus on and to whom give special offers or promotions for fostering loyalty among customers. We can select the best communication channel for each segment and improve new marketing strategies."
},
{
"code": null,
"e": 15030,
"s": 14954,
"text": "A nice article about RFM analysis: https://clevertap.com/blog/rfm-analysis/"
},
{
"code": null,
"e": 15133,
"s": 15030,
"text": "Another useful explanation for RFM analysis: https://www.optimove.com/learning-center/rfm-segmentation"
},
{
"code": null,
"e": 15222,
"s": 15133,
"text": "Intuitive explanation on K-means clustering: https://www.youtube.com/watch?v=_aWzGGNrcic"
}
] |
Transfer Learning using ELMO Embeddings | by Sambit Mahapatra | Towards Data Science
|
Last year, the major developments in βNatural Language Processingβ were about Transfer Learning. Basically, Transfer Learning is the process of training a model on a large-scale dataset and then using that pre-trained model to process learning for another target task. Transfer Learning became popular in the field of NLP thanks to the state-of-the-art performance of different algorithms like ULMFiT, Skip-Gram, Elmo, BERT etc.
Elmo embedding, developed by Allen NLP, is a state-of-the-art pre-trained model available on Tensorflow Hub. Elmo embeddings are learned from the internal state of a bidirectional LSTM and represent contextual features of the input text. Itβs been shown to outperform previously existing pre-trained word embeddings like word2vec and glove on a wide variety of NLP tasks. Some of those tasks are Question Answering, Named Entity Extraction and Sentiment Analysis.
github.com
There is a pre-trained Elmo embedding module available in tensorflow-hub. This module supports both raw text strings or tokenized text strings as input. The module outputs fixed embeddings at each LSTM layer, a learnable aggregation of the 3 layers, and a fixed mean-pooled vector representation of the input (for sentences). To use this module first, letβs download it to the local.
#download the model to local so it can be used again and again!mkdir module/module_elmo2# Download the module, and uncompress it to the destination folder. !curl -L "https://tfhub.dev/google/elmo/2?tf-hub-format=compressed" | tar -zxvC module/module_elmo2
This module exposes 4 trainable scalar weights for layer aggregation. The output dictionary contains :
word_emb: the character-based word representations with shape [batch_size, max_length, 512].
lstm_outputs1: the first LSTM hidden state with shape [batch_size, max_length, 1024].
lstm_outputs2: the second LSTM hidden state with shape [batch_size, max_length, 1024].
elmo: the weighted sum of the 3 layers, where the weights are trainable. This tensor has shape [batch_size, max_length, 1024]
default: a fixed mean-pooling of all contextualized word representations with shape [batch_size, 1024].
To pass raw strings as input:
elmo = hub.Module("module/module_elmo2/", trainable=False)embeddings = elmo(["the cat is on the mat", "what are you doing in evening"],signature="default",as_dict=True)["elmo"]with tf.Session() as session: session.run([tf.global_variables_initializer(), tf.tables_initializer()]) message_embeddings = session.run(embeddings)
The output message_embeddings is of shape (2, 6, 1024), as there are 2 sentences with max length of 6 words and for each word 1D vector of length 1024 is generated. It internally tokenizes it based of spaces. If a string with less than 6 words would have been supplied, it would have appended spaces to it internally.
We can also supply tokenized strings to the module as shown below:
elmo = hub.Module("sentence_wise_email/module/module_elmo2/", trainable=False)tokens_input = [["the", "cat", "is", "on", "the", "mat"],["what", "are", "you", "doing", "in", "evening"]]tokens_length = [6, 5]embeddings = elmo(inputs={"tokens": tokens_input,"sequence_len": tokens_length},signature="tokens",as_dict=True)["elmo"]with tf.Session() as session: session.run([tf.global_variables_initializer(), tf.tables_initializer()]) message_embeddings = session.run(embeddings)
The output will be similar.
When using in REST API or backend for multiple inputs, rather than initializing sessions for each call, which is a overhead, one efficient way can be:
def embed_elmo2(module): with tf.Graph().as_default(): sentences = tf.placeholder(tf.string) embed = hub.Module(module) embeddings = embed(sentences) session = tf.train.MonitoredSession() return lambda x: session.run(embeddings, {sentences: x})embed_fn = embed_elmo2('module/module_elmo2')embed_fn(["i am sambit"]).shape
Here, by default it outputs a vector of size 1024 for each sentence which is a fixed mean-pooling of all contextualized word representations. Normally while using it in a classifier we can use this output.
Data Input
We will be using First GOP Debate Twitter Sentiment data, which contains around 14K tweets on the first 2016 GOP Presidential Debate. We are making a binary classifier, hence will ignore tweets with neutral sentiment.
df = pd.read_csv("sentence_wise_email/Sentiment.csv",encoding="latin")df = df[df["sentiment"]!="Neutral"]df.loc[df["sentiment"]=='Negative',"sentiment"]=0df.loc[df["sentiment"]=='Positive',"sentiment"]=1
Data Processing
We will perform some cleaning on the data like dealing with contractions like βIβllβ, βItβsβ etc. We will remove numbers, links, punctuations and e-mail addresses also. (The names also should be removed, but not done here as this model was actually getting developed for some other purpose and I got lazy to change in this case :-) )
import redef cleanText(text): text = text.strip().replace("\n", " ").replace("\r", " ") text = replace_contraction(text) text = replace_links(text, "link") text = remove_numbers(text) text = re.sub(r'[,!@#$%^&*)(|/><";:.?\'\\}{]',"",text) text = text.lower() return textX = np.array(df["text"].apply(cleanText))y = np.array(df["sentiment"])
Classifier Model Building
First, need to import the necessary modules for this. Then we need to make a function which will perform the pre-trained Elmo embedding on inputs.
embed = hub.Module("module/module_elmo2")def ELMoEmbedding(x): return embed(tf.squeeze(tf.cast(x, tf.string)), signature="default", as_dict=True)["default"]
Then, we need to build the architecture. Here we are building it using high level keras api as it is easier to use. We are using the functional approach to build a simple feed-forward neural network along with regularization to avoid over-fitting.
def build_model(): input_text = Input(shape=(1,), dtype="string") embedding = Lambda(ELMoEmbedding, output_shape=(1024, ))(input_text) dense = Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001))(embedding) pred = Dense(1, activation='sigmoid')(dense) model = Model(inputs=[input_text], outputs=pred) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return modelmodel_elmo = build_model()
The model summary is:
_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_2 (InputLayer) (None, 1) 0 _________________________________________________________________lambda_2 (Lambda) (None, 1024) 0 _________________________________________________________________dense_3 (Dense) (None, 256) 262400 _________________________________________________________________dense_4 (Dense) (None, 1) 257 =================================================================Total params: 262,657Trainable params: 262,657Non-trainable params: 0_________________________________________________________________
Now since the model architecture (compiled) and data both are ready, it is time to start training and saving the trained weights.
with tf.Session() as session: K.set_session(session) session.run(tf.global_variables_initializer()) session.run(tf.tables_initializer()) history = model_elmo.fit(X, y, epochs=5, batch_size=256, validation_split = 0.2) model_elmo.save_weights('./model_elmo_weights.h5')
Just to see how the learning was going on while training with respect to accuracy and loss function, we can draw a plot:
import matplotlib.pyplot as plt%matplotlib inlineacc = history.history['acc']val_acc = history.history['val_acc']loss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(acc) + 1)plt.plot(epochs, acc, 'g', label='Training Acc')plt.plot(epochs, val_acc, 'b', label='Validation Acc')plt.title('Training and validation Acc')plt.xlabel('Epochs')plt.ylabel('Acc')plt.legend()plt.show()
It seems after 4th epoch there is not much change in accuracy. You can draw the same for loss value also. To have a better idea when the model is achieving its destination, it has to be trained for more epochs (means added cost as it is very computationally intensive and require GPU :-) ).
Prediction with the trained model
Now to predict with the trained model, we need to first process the text and make an array of it.
new_text = ['RT @FrankLuntz: Before the #GOPDebate, 14 focus groupers said they did not have favorable view of Trump.', 'Chris Wallace(D) to be the 2nd worst partisan pontificating asshole "moderating" #GOPDebate @megynkelly' ]#the texts should go through clean text alsonew_text_pr = np.array(new_text, dtype=object)[:, np.newaxis]
Now we can start a tensorflow session, where we will call the model architecture first and then load the weights from the saved file. Calling the predict API call, it will give us the sentiment probability of each text. The less is the score, the more negative sentiment is embedded in the sentence.
with tf.Session() as session: K.set_session(session) session.run(tf.global_variables_initializer()) session.run(tf.tables_initializer()) model_elmo = build_model() model_elmo.load_weights('./model_elmo_weights.h5') import time t = time.time() predicts = model_elmo.predict(new_text_pr) print("time: ", time.time() - t) print(predicts)
The output is:
time: 0.6370120048522949[[0.17122008] [0.3037635 ]]
I have printed time just to show how much time is required, It took 0.63 seconds for two sentences in Tesla k80 gpu. In i5 processor cpu, it took 14.3 seconds. Since it is a very computationally intensive process especially due to highly complex architecture of Elmo Embedding, use of accelerator is required in real time.
If you see in above training we achieved an accuracy of 0.8094 on Elmo Embedding, while with pre-trained word2vec, glove and online embedding the accuracies were 0.7821, 0.7432 and 0.7213 respectively. These were the results with the same data processing after 5 epochs.
Train on 8583 samples, validate on 2146 samplesEpoch 1/58583/8583 [==============================] - 63s 7ms/step - loss: 0.8087 - acc: 0.7853 - val_loss: 0.6919 - val_acc: 0.7819Epoch 2/58583/8583 [==============================] - 62s 7ms/step - loss: 0.6015 - acc: 0.8265 - val_loss: 0.6359 - val_acc: 0.7651Epoch 3/58583/8583 [==============================] - 62s 7ms/step - loss: 0.5377 - acc: 0.8371 - val_loss: 0.5407 - val_acc: 0.8169Epoch 4/58583/8583 [==============================] - 62s 7ms/step - loss: 0.4946 - acc: 0.8401 - val_loss: 0.5016 - val_acc: 0.8071Epoch 5/58583/8583 [==============================] - 63s 7ms/step - loss: 0.4836 - acc: 0.8396 - val_loss: 0.4995 - val_acc: 0.8094
|
[
{
"code": null,
"e": 600,
"s": 171,
"text": "Last year, the major developments in βNatural Language Processingβ were about Transfer Learning. Basically, Transfer Learning is the process of training a model on a large-scale dataset and then using that pre-trained model to process learning for another target task. Transfer Learning became popular in the field of NLP thanks to the state-of-the-art performance of different algorithms like ULMFiT, Skip-Gram, Elmo, BERT etc."
},
{
"code": null,
"e": 1064,
"s": 600,
"text": "Elmo embedding, developed by Allen NLP, is a state-of-the-art pre-trained model available on Tensorflow Hub. Elmo embeddings are learned from the internal state of a bidirectional LSTM and represent contextual features of the input text. Itβs been shown to outperform previously existing pre-trained word embeddings like word2vec and glove on a wide variety of NLP tasks. Some of those tasks are Question Answering, Named Entity Extraction and Sentiment Analysis."
},
{
"code": null,
"e": 1075,
"s": 1064,
"text": "github.com"
},
{
"code": null,
"e": 1459,
"s": 1075,
"text": "There is a pre-trained Elmo embedding module available in tensorflow-hub. This module supports both raw text strings or tokenized text strings as input. The module outputs fixed embeddings at each LSTM layer, a learnable aggregation of the 3 layers, and a fixed mean-pooled vector representation of the input (for sentences). To use this module first, letβs download it to the local."
},
{
"code": null,
"e": 1715,
"s": 1459,
"text": "#download the model to local so it can be used again and again!mkdir module/module_elmo2# Download the module, and uncompress it to the destination folder. !curl -L \"https://tfhub.dev/google/elmo/2?tf-hub-format=compressed\" | tar -zxvC module/module_elmo2"
},
{
"code": null,
"e": 1818,
"s": 1715,
"text": "This module exposes 4 trainable scalar weights for layer aggregation. The output dictionary contains :"
},
{
"code": null,
"e": 1911,
"s": 1818,
"text": "word_emb: the character-based word representations with shape [batch_size, max_length, 512]."
},
{
"code": null,
"e": 1997,
"s": 1911,
"text": "lstm_outputs1: the first LSTM hidden state with shape [batch_size, max_length, 1024]."
},
{
"code": null,
"e": 2084,
"s": 1997,
"text": "lstm_outputs2: the second LSTM hidden state with shape [batch_size, max_length, 1024]."
},
{
"code": null,
"e": 2210,
"s": 2084,
"text": "elmo: the weighted sum of the 3 layers, where the weights are trainable. This tensor has shape [batch_size, max_length, 1024]"
},
{
"code": null,
"e": 2314,
"s": 2210,
"text": "default: a fixed mean-pooling of all contextualized word representations with shape [batch_size, 1024]."
},
{
"code": null,
"e": 2344,
"s": 2314,
"text": "To pass raw strings as input:"
},
{
"code": null,
"e": 2675,
"s": 2344,
"text": "elmo = hub.Module(\"module/module_elmo2/\", trainable=False)embeddings = elmo([\"the cat is on the mat\", \"what are you doing in evening\"],signature=\"default\",as_dict=True)[\"elmo\"]with tf.Session() as session: session.run([tf.global_variables_initializer(), tf.tables_initializer()]) message_embeddings = session.run(embeddings)"
},
{
"code": null,
"e": 2993,
"s": 2675,
"text": "The output message_embeddings is of shape (2, 6, 1024), as there are 2 sentences with max length of 6 words and for each word 1D vector of length 1024 is generated. It internally tokenizes it based of spaces. If a string with less than 6 words would have been supplied, it would have appended spaces to it internally."
},
{
"code": null,
"e": 3060,
"s": 2993,
"text": "We can also supply tokenized strings to the module as shown below:"
},
{
"code": null,
"e": 3541,
"s": 3060,
"text": "elmo = hub.Module(\"sentence_wise_email/module/module_elmo2/\", trainable=False)tokens_input = [[\"the\", \"cat\", \"is\", \"on\", \"the\", \"mat\"],[\"what\", \"are\", \"you\", \"doing\", \"in\", \"evening\"]]tokens_length = [6, 5]embeddings = elmo(inputs={\"tokens\": tokens_input,\"sequence_len\": tokens_length},signature=\"tokens\",as_dict=True)[\"elmo\"]with tf.Session() as session: session.run([tf.global_variables_initializer(), tf.tables_initializer()]) message_embeddings = session.run(embeddings)"
},
{
"code": null,
"e": 3569,
"s": 3541,
"text": "The output will be similar."
},
{
"code": null,
"e": 3720,
"s": 3569,
"text": "When using in REST API or backend for multiple inputs, rather than initializing sessions for each call, which is a overhead, one efficient way can be:"
},
{
"code": null,
"e": 4075,
"s": 3720,
"text": "def embed_elmo2(module): with tf.Graph().as_default(): sentences = tf.placeholder(tf.string) embed = hub.Module(module) embeddings = embed(sentences) session = tf.train.MonitoredSession() return lambda x: session.run(embeddings, {sentences: x})embed_fn = embed_elmo2('module/module_elmo2')embed_fn([\"i am sambit\"]).shape"
},
{
"code": null,
"e": 4281,
"s": 4075,
"text": "Here, by default it outputs a vector of size 1024 for each sentence which is a fixed mean-pooling of all contextualized word representations. Normally while using it in a classifier we can use this output."
},
{
"code": null,
"e": 4292,
"s": 4281,
"text": "Data Input"
},
{
"code": null,
"e": 4510,
"s": 4292,
"text": "We will be using First GOP Debate Twitter Sentiment data, which contains around 14K tweets on the first 2016 GOP Presidential Debate. We are making a binary classifier, hence will ignore tweets with neutral sentiment."
},
{
"code": null,
"e": 4715,
"s": 4510,
"text": "df = pd.read_csv(\"sentence_wise_email/Sentiment.csv\",encoding=\"latin\")df = df[df[\"sentiment\"]!=\"Neutral\"]df.loc[df[\"sentiment\"]=='Negative',\"sentiment\"]=0df.loc[df[\"sentiment\"]=='Positive',\"sentiment\"]=1"
},
{
"code": null,
"e": 4731,
"s": 4715,
"text": "Data Processing"
},
{
"code": null,
"e": 5065,
"s": 4731,
"text": "We will perform some cleaning on the data like dealing with contractions like βIβllβ, βItβsβ etc. We will remove numbers, links, punctuations and e-mail addresses also. (The names also should be removed, but not done here as this model was actually getting developed for some other purpose and I got lazy to change in this case :-) )"
},
{
"code": null,
"e": 5427,
"s": 5065,
"text": "import redef cleanText(text): text = text.strip().replace(\"\\n\", \" \").replace(\"\\r\", \" \") text = replace_contraction(text) text = replace_links(text, \"link\") text = remove_numbers(text) text = re.sub(r'[,!@#$%^&*)(|/><\";:.?\\'\\\\}{]',\"\",text) text = text.lower() return textX = np.array(df[\"text\"].apply(cleanText))y = np.array(df[\"sentiment\"])"
},
{
"code": null,
"e": 5453,
"s": 5427,
"text": "Classifier Model Building"
},
{
"code": null,
"e": 5600,
"s": 5453,
"text": "First, need to import the necessary modules for this. Then we need to make a function which will perform the pre-trained Elmo embedding on inputs."
},
{
"code": null,
"e": 5760,
"s": 5600,
"text": "embed = hub.Module(\"module/module_elmo2\")def ELMoEmbedding(x): return embed(tf.squeeze(tf.cast(x, tf.string)), signature=\"default\", as_dict=True)[\"default\"]"
},
{
"code": null,
"e": 6008,
"s": 5760,
"text": "Then, we need to build the architecture. Here we are building it using high level keras api as it is easier to use. We are using the functional approach to build a simple feed-forward neural network along with regularization to avoid over-fitting."
},
{
"code": null,
"e": 6481,
"s": 6008,
"text": "def build_model(): input_text = Input(shape=(1,), dtype=\"string\") embedding = Lambda(ELMoEmbedding, output_shape=(1024, ))(input_text) dense = Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001))(embedding) pred = Dense(1, activation='sigmoid')(dense) model = Model(inputs=[input_text], outputs=pred) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return modelmodel_elmo = build_model()"
},
{
"code": null,
"e": 6503,
"s": 6481,
"text": "The model summary is:"
},
{
"code": null,
"e": 7353,
"s": 6503,
"text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_2 (InputLayer) (None, 1) 0 _________________________________________________________________lambda_2 (Lambda) (None, 1024) 0 _________________________________________________________________dense_3 (Dense) (None, 256) 262400 _________________________________________________________________dense_4 (Dense) (None, 1) 257 =================================================================Total params: 262,657Trainable params: 262,657Non-trainable params: 0_________________________________________________________________"
},
{
"code": null,
"e": 7483,
"s": 7353,
"text": "Now since the model architecture (compiled) and data both are ready, it is time to start training and saving the trained weights."
},
{
"code": null,
"e": 7769,
"s": 7483,
"text": "with tf.Session() as session: K.set_session(session) session.run(tf.global_variables_initializer()) session.run(tf.tables_initializer()) history = model_elmo.fit(X, y, epochs=5, batch_size=256, validation_split = 0.2) model_elmo.save_weights('./model_elmo_weights.h5')"
},
{
"code": null,
"e": 7890,
"s": 7769,
"text": "Just to see how the learning was going on while training with respect to accuracy and loss function, we can draw a plot:"
},
{
"code": null,
"e": 8304,
"s": 7890,
"text": "import matplotlib.pyplot as plt%matplotlib inlineacc = history.history['acc']val_acc = history.history['val_acc']loss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(acc) + 1)plt.plot(epochs, acc, 'g', label='Training Acc')plt.plot(epochs, val_acc, 'b', label='Validation Acc')plt.title('Training and validation Acc')plt.xlabel('Epochs')plt.ylabel('Acc')plt.legend()plt.show()"
},
{
"code": null,
"e": 8595,
"s": 8304,
"text": "It seems after 4th epoch there is not much change in accuracy. You can draw the same for loss value also. To have a better idea when the model is achieving its destination, it has to be trained for more epochs (means added cost as it is very computationally intensive and require GPU :-) )."
},
{
"code": null,
"e": 8629,
"s": 8595,
"text": "Prediction with the trained model"
},
{
"code": null,
"e": 8727,
"s": 8629,
"text": "Now to predict with the trained model, we need to first process the text and make an array of it."
},
{
"code": null,
"e": 9084,
"s": 8727,
"text": "new_text = ['RT @FrankLuntz: Before the #GOPDebate, 14 focus groupers said they did not have favorable view of Trump.', 'Chris Wallace(D) to be the 2nd worst partisan pontificating asshole \"moderating\" #GOPDebate @megynkelly' ]#the texts should go through clean text alsonew_text_pr = np.array(new_text, dtype=object)[:, np.newaxis]"
},
{
"code": null,
"e": 9384,
"s": 9084,
"text": "Now we can start a tensorflow session, where we will call the model architecture first and then load the weights from the saved file. Calling the predict API call, it will give us the sentiment probability of each text. The less is the score, the more negative sentiment is embedded in the sentence."
},
{
"code": null,
"e": 9752,
"s": 9384,
"text": "with tf.Session() as session: K.set_session(session) session.run(tf.global_variables_initializer()) session.run(tf.tables_initializer()) model_elmo = build_model() model_elmo.load_weights('./model_elmo_weights.h5') import time t = time.time() predicts = model_elmo.predict(new_text_pr) print(\"time: \", time.time() - t) print(predicts)"
},
{
"code": null,
"e": 9767,
"s": 9752,
"text": "The output is:"
},
{
"code": null,
"e": 9820,
"s": 9767,
"text": "time: 0.6370120048522949[[0.17122008] [0.3037635 ]]"
},
{
"code": null,
"e": 10143,
"s": 9820,
"text": "I have printed time just to show how much time is required, It took 0.63 seconds for two sentences in Tesla k80 gpu. In i5 processor cpu, it took 14.3 seconds. Since it is a very computationally intensive process especially due to highly complex architecture of Elmo Embedding, use of accelerator is required in real time."
},
{
"code": null,
"e": 10414,
"s": 10143,
"text": "If you see in above training we achieved an accuracy of 0.8094 on Elmo Embedding, while with pre-trained word2vec, glove and online embedding the accuracies were 0.7821, 0.7432 and 0.7213 respectively. These were the results with the same data processing after 5 epochs."
}
] |
Convert character array to string in Arduino
|
In order to convert a character array to a string, the String() constructor can be used. An example is shown below β
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
char buf[10] = "Hello!";
Serial.print("Char array: ");
Serial.println(buf);
String s = String(buf);
Serial.print("String: ");
Serial.println(s);
}
void loop() {
// put your main code here, to run repeatedly:
}
The output of the Serial monitor is shown below β
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "In order to convert a character array to a string, the String() constructor can be used. An example is shown below β"
},
{
"code": null,
"e": 1515,
"s": 1179,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n char buf[10] = \"Hello!\";\n\n Serial.print(\"Char array: \");\n Serial.println(buf);\n String s = String(buf);\n Serial.print(\"String: \");\n Serial.println(s);\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 1565,
"s": 1515,
"text": "The output of the Serial monitor is shown below β"
}
] |
How to open new tab in same browser and switch between them using Selenium?
|
We can open new tabs in the same browser and switch between them using Selenium webdriver. Firstly, to open a new tab in the same browser we have to take the help of the methods β Keys.chord and sendKeys.
The parameters Keys.CONTROL and Keys.ENTER are passed to the Keys.chord method. This method yields a string value and in turn passed as a parameter to the sendKeys method.
String n = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.id("open-tab")).sendKeys(n);
Once the second tab is opened, the getWindowHandles method is used to hold all the window handle ids in a Set. To shift the focus of the webdriver object to the new tab, the method switchTo().window is used.
The window handle id of the new tab should be passed as a parameter to the switchTo().window to shift the driver focus to the new tab. The method getWindowHandle is used to obtain the window handle id of the browser window in focus.
Let us open the link Team in a new tab in the same browser β
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.Keys;
import java.util.ArrayList;
public class SwitchNewTab{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// method Keys.chord
String n = Keys.chord(Keys.CONTROL, Keys.ENTER);
//open link in new tab
driver.findElement(By.linkText("Team")).sendKeys(n);
Thread.sleep(8000);
// store window handle ids
ArrayList<String> w = new ArrayList<String>(driver.getWindowHandles());
//switch to open tab
driver.switchTo().window(w.get(1));
System.out.println("New tab title: " + driver.getTitle());
//switch to first tab
driver.switchTo().window(w.get(0));
System.out.println("First tab title: " + driver.getTitle());
driver.quit();
}
}
|
[
{
"code": null,
"e": 1267,
"s": 1062,
"text": "We can open new tabs in the same browser and switch between them using Selenium webdriver. Firstly, to open a new tab in the same browser we have to take the help of the methods β Keys.chord and sendKeys."
},
{
"code": null,
"e": 1439,
"s": 1267,
"text": "The parameters Keys.CONTROL and Keys.ENTER are passed to the Keys.chord method. This method yields a string value and in turn passed as a parameter to the sendKeys method."
},
{
"code": null,
"e": 1538,
"s": 1439,
"text": "String n = Keys.chord(Keys.CONTROL,Keys.ENTER);\ndriver.findElement(By.id(\"open-tab\")).sendKeys(n);"
},
{
"code": null,
"e": 1746,
"s": 1538,
"text": "Once the second tab is opened, the getWindowHandles method is used to hold all the window handle ids in a Set. To shift the focus of the webdriver object to the new tab, the method switchTo().window is used."
},
{
"code": null,
"e": 1979,
"s": 1746,
"text": "The window handle id of the new tab should be passed as a parameter to the switchTo().window to shift the driver focus to the new tab. The method getWindowHandle is used to obtain the window handle id of the browser window in focus."
},
{
"code": null,
"e": 2040,
"s": 1979,
"text": "Let us open the link Team in a new tab in the same browser β"
},
{
"code": null,
"e": 3325,
"s": 2040,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\nimport org.openqa.selenium.Keys;\nimport java.util.ArrayList;\npublic class SwitchNewTab{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // method Keys.chord\n String n = Keys.chord(Keys.CONTROL, Keys.ENTER);\n //open link in new tab\n driver.findElement(By.linkText(\"Team\")).sendKeys(n);\n Thread.sleep(8000);\n // store window handle ids\n ArrayList<String> w = new ArrayList<String>(driver.getWindowHandles());\n //switch to open tab\n driver.switchTo().window(w.get(1));\n System.out.println(\"New tab title: \" + driver.getTitle());\n //switch to first tab\n driver.switchTo().window(w.get(0));\n System.out.println(\"First tab title: \" + driver.getTitle());\n driver.quit();\n }\n}"
}
] |
How to implement Python __lt__ __gt__ custom (overloaded) operators?
|
Python has magic methods to define overloaded behaviour of operators. The comparison operators (<, <=, >, >=, == and !=) can be overloaded by providing definition to __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods. Following program overloads < and > operators to compare objects of distance class.
class distance:
def __init__(self, x=5,y=5):
self.ft=x
self.inch=y
def __eq__(self, other):
if self.ft==other.ft and self.inch==other.inch:
return "both objects are equal"
else:
return "both objects are not equal"
def __lt__(self, other):
in1=self.ft*12+self.inch
in2=other.ft*12+other.inch
if in1<in2:
return "first object smaller than other"
else:
return "first object not smaller than other"
def __gt__(self, other):
in1=self.ft*12+self.inch
in2=other.ft*12+other.inch
if in1<in2:
return "first object greater than other"
else:
return "first object not greater than other"
d1=distance(5,5)
d2=distance()
print (d1>d2)
d3=distance()
d4=distance(6,10)
print (d1<d2)
d5=distance(3,11)
d6=distance()
print(d5<d6)
Result shows implementation of __lt__ and _gt__ magic methods
first object not greater than other
first object not smaller than other
first object smaller than other
|
[
{
"code": null,
"e": 1379,
"s": 1062,
"text": "Python has magic methods to define overloaded behaviour of operators. The comparison operators (<, <=, >, >=, == and !=) can be overloaded by providing definition to __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods. Following program overloads < and > operators to compare objects of distance class. "
},
{
"code": null,
"e": 2187,
"s": 1379,
"text": "class distance:\n def __init__(self, x=5,y=5):\n self.ft=x\n self.inch=y\n\n def __eq__(self, other):\n if self.ft==other.ft and self.inch==other.inch:\n return \"both objects are equal\"\n else:\n return \"both objects are not equal\"\n\n def __lt__(self, other):\n in1=self.ft*12+self.inch\n in2=other.ft*12+other.inch\n if in1<in2:\n return \"first object smaller than other\"\n else:\n return \"first object not smaller than other\"\n\n def __gt__(self, other):\n in1=self.ft*12+self.inch\n in2=other.ft*12+other.inch\n if in1<in2:\n return \"first object greater than other\"\n else:\n return \"first object not greater than other\"\n\nd1=distance(5,5)\nd2=distance()\nprint (d1>d2)\nd3=distance()\nd4=distance(6,10)\nprint (d1<d2)\nd5=distance(3,11)\nd6=distance()\nprint(d5<d6)"
},
{
"code": null,
"e": 2249,
"s": 2187,
"text": "Result shows implementation of __lt__ and _gt__ magic methods"
},
{
"code": null,
"e": 2353,
"s": 2249,
"text": "first object not greater than other\nfirst object not smaller than other\nfirst object smaller than other"
}
] |
Using CNNs and RNNs for Music Genre Recognition | by Priya Dwivedi | Towards Data Science
|
Audio data is becoming an important part of machine learning. We are using audio to interact with smart agents like Siri and Alexa. Audio will also be important for self-driving cars so they can not only βseeβ their surroundings but βhearβ them as well. I wanted to explore deep learning techniques on audio files and music analysis seems to be an interesting area with lots of promising research. In this blog I have looked at architectures that combine CNNs and RNNs to classify music clips into 8 different genres. I have also visualized filter activations in different CNN layers. If you are new to deep learning and want to learn about CNNs and deep learning for computer vision, please checkout my blog here.
The code for this project is available on my Github. My hope here is that the techniques mentioned here have broader application than just on music. Hope you enjoy!
There are a few different datasets with music data β GTZan and Million Songs data set (MSD) are 2 of the ones most commonly used. But both of these data sets have limitations. GTZan only has 100 songs per genre and MSD has well 1 million songs but only their metadata, no audio files. I decided to use the Free Music Archive Small dataset. You can use their github link to download the small dataset (8 GB) which has raw audio files + metadata. The FMA small data set that I used had 8 genres and 1000 songs per genre evenly distributed. The eight genres are Electronic, Experimental, Folk, Hip-Hop, Instrumental, International, Pop and Rock.
Converting audio data into mel-spectogram
Each audio file was converted into a spectogram which is a visual representation of spectrum of frequencies over time. A regular spectogram is squared magnitude of the short term Fourier transform (STFT) of the audio signal. This regular spectogram is squashed using mel scale to convert theaudio frequencies into something a human is more able to understand. I used the built in function in the librosa library to convert the audio file directly into a mel-spectogram. The most important parameters used in the transformation are β window length which indicates the window of time to perform Fourier Transform on and hop length which is the number of samples between successive frames. The typical window length for this transformation is 2048 which converts to about 10ms, the shortest reasonable period a human ear can distinguish. I chose hop length of 512. Further more the Mel-spectrograms produced by Librosa were scaled by a log function. This mapsthe sound data to the normal logarithmic scale used to determine loudness in decibels (dB) as it relates to the human-perceived pitch. As a result of this transformation each audio file gets converted to a mel-spectogram of shape β 640, 128.
As seen in Figure 1, different genres have noticeable differences in their mel-spectogram which gives us confidence in using a CNN to do the classification.
Librosa makes it super easy to create spectograms. A 3 line code can convert an audio file into a spectogram!
y, sr = librosa.load(filename)spect = librosa.feature.melspectrogram(y=y, sr=sr,n_fft=2048, hop_length=512)spect = librosa.power_to_db(spect, ref=np.max)
To speed up training, I divided the data set into train, test and validation, converted their respective audio files into spectograms and picked the results so this pickled data could directly be loaded. You can find this data on the drive link.
Why use CNNs and RNNs?
One question that arises is why do we need to use both CNNs and RNNs. A spectogram is a visual representation of audio across frequency and time dimension. CNN makes sense since spectograms of a song are kind of like an image, each with their own distinct patterns. RNNs excel in understand sequential data by making the hidden state at time t dependent on hidden state at time t-1. The spectograms have a time component and RNNs can do a much better job of identifying the short term and longer term temporal features in the song.
I tried 2 interesting CNN-RNN architectures β Convolutional Recurrent Model and a Parallel CNN-RNN model. Both models were coded in Keras and you can find the code on my Github.
The inspiration of this model comes from the work by deep sound and from the paper by Keunwoo Choi et al. This model uses 1D CNNs that performconvolution operation just across the time dimension. Each 1D convolution layer extracts features from a small slice of the spectogram. RELU activationis applied after the Convolution operation. Batch normalization is done and finally 1D Max Pooling is performed which reduces spatial dimension of the image and prevents over fitting.This chain of operations β 1D Convolution β RELU β Batch Normalization β 1D Max Pooling is performed 3 times. The output from 1D Convolution Layer is fed into a LSTM which should find short term and long term structure of the song. The LSTM uses 96 hidden units. The output from LSTM is passed into aDense Layer of 64 units. The final output layer of the model is a dense layer with Softmax activation and 8 hidden units to assign probability to the 8 classes. Both dropout and L2 regularization were used between all the layers to reduce over fitting of the model. Figure below shows the overallarchitecture of the model.
The model was trained using Adam optimizer with a learning rate of 0.001 and the loss function was categorical cross entropy. The model was trained for 70 epochs and Learning Rate was reduced if the validation accuracy plateaued for at least 10 epochs.
See below the loss and accuracy curves for training and validation samples. As seen, the model has low bias but high variance implying the model is over fitting a bit to training even after using several regularization techniques.
Overall this model got to around 53% accuracy on the validation set.
Inspired by the work of Lin Fen and Shenlen Liu, I also tried a Parallel CNN-RNN Model. The key idea behind this network is that even though CRNN has RNNs to be the temporal summarizer, it can only summarize temporal information from the output of CNNs. The temporal relationships of original musical signals are not preserved during operations with CNNs. This model passes the input spectogram through both CNN and RNN layers in parallel, concatenating their output and then sending this through a dense layer with softmax activation to perform classification as shown below.
The convolutional block of the model consists of 2D convolution layer followed by a 2D Max pooling layer. This is in contrast to the CRNN model that uses 1D convolution and max pooling layers. There are 5 blocks of Convolution Max pooling layers. The final output is flattened and is a tensor of shape None , 256.The recurrent block starts with 2D max pooling layer of pool size 4,2 to reduce the size of the spectogram before LSTM operation. This feature reduction was done primarily to speed up processing. The reduced image is sent to a bidirectional GRU with 64 units. The output from this layer is atensor of shape None, 128.The outputs from the convolutional and recurrent blocks are then concatenated resulting in a tensor of shape, None, 384. Finally we have a dense layer with softmax activation. The model was trained using RMSProp optimizer with a learning rate of 0.0005 and the loss function was categorical cross entropy. The model was trained for 50 epochs and Learning Rate was reduced if the validation accuracy plateaued for at least 10 epochs.
Figure below shows the loss and accuracy curves from this model
This model had a validation loss of around 51%. Both models have very similar overall accuracies which is quite interesting but their class wise performance is very different. Parallel CNN-RNN model has a better performance for Experimental, Folk, Hip-Hop and Instrumental genres. The ensembling of both these models should produce even better results.
One question that I asked myself was why is the accuracy only around 51%. I think there are 2 reasons for this:
The sample size of 1000 spectograms is actually a very small sample for building a deep learning model from scratch. As seen by the loss curves, both models overfit quickly. Ideally we have a bigger training set or one thing that can be tried is breaking each song into 3 segments of 10 seconds each with the same label and using this to triple the size of the data set.
The FMA data set is challenging and in particular it has a few classes like experimental and international which are easy to confuse among. The top leader board score on FMA -Genre Recognition challenge has a test F1 score of only around 0.63
I explored the features learned by initial vs later layers of the convolution model. For this analysis I used the Keras Visualization package and selected Parallel CNN-RNN model as this uses the 2D CNN layers which were easier to visualize.
The first convolution block in this model has 16 filters and the fifth convolution block has 64 filters. To understand what the filter is focusing on, we look at what kind of input maximizes the activations in that filter. Figure below shows the filter activations of all 16 filters in the first convolution blocks vs the first 24 filters of the fifth convolution block.
What I observe here is that the filters for the first layer are relatively straightforward. There are looking at a small kernel size of 3,1. As such they are focusing on different patterns of fluctuations between primarily 50β200 db. In the fifth convolution block, the same filter is looking at a biggersize of the input image due to feature maps being shrunk as a result of convolution and max pooling operations. It is now able to focus on different features like sharp increases in amplitude to 250 db as well as periods of very low amplitude coloured as black region.
I hope you like this analysis and try the code for yourself.
I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at β http://deeplearninganalytics.org/.
You can also see my other writings at: https://medium.com/@priya.dwivedi
If you have a project that we can collaborate on, then please contact me through my website or at info@deeplearninganalytics.org
http://deepsound.io/music_genre_recognition.html
Free Music Archive β https://github.com/mdeff/fma
Librosa
Convolutional Recurrent Neural Networks for Music Classification
Music Genre Classification with Paralleling Recurrent Convolutional Neural Network
|
[
{
"code": null,
"e": 887,
"s": 172,
"text": "Audio data is becoming an important part of machine learning. We are using audio to interact with smart agents like Siri and Alexa. Audio will also be important for self-driving cars so they can not only βseeβ their surroundings but βhearβ them as well. I wanted to explore deep learning techniques on audio files and music analysis seems to be an interesting area with lots of promising research. In this blog I have looked at architectures that combine CNNs and RNNs to classify music clips into 8 different genres. I have also visualized filter activations in different CNN layers. If you are new to deep learning and want to learn about CNNs and deep learning for computer vision, please checkout my blog here."
},
{
"code": null,
"e": 1052,
"s": 887,
"text": "The code for this project is available on my Github. My hope here is that the techniques mentioned here have broader application than just on music. Hope you enjoy!"
},
{
"code": null,
"e": 1695,
"s": 1052,
"text": "There are a few different datasets with music data β GTZan and Million Songs data set (MSD) are 2 of the ones most commonly used. But both of these data sets have limitations. GTZan only has 100 songs per genre and MSD has well 1 million songs but only their metadata, no audio files. I decided to use the Free Music Archive Small dataset. You can use their github link to download the small dataset (8 GB) which has raw audio files + metadata. The FMA small data set that I used had 8 genres and 1000 songs per genre evenly distributed. The eight genres are Electronic, Experimental, Folk, Hip-Hop, Instrumental, International, Pop and Rock."
},
{
"code": null,
"e": 1737,
"s": 1695,
"text": "Converting audio data into mel-spectogram"
},
{
"code": null,
"e": 2935,
"s": 1737,
"text": "Each audio file was converted into a spectogram which is a visual representation of spectrum of frequencies over time. A regular spectogram is squared magnitude of the short term Fourier transform (STFT) of the audio signal. This regular spectogram is squashed using mel scale to convert theaudio frequencies into something a human is more able to understand. I used the built in function in the librosa library to convert the audio file directly into a mel-spectogram. The most important parameters used in the transformation are β window length which indicates the window of time to perform Fourier Transform on and hop length which is the number of samples between successive frames. The typical window length for this transformation is 2048 which converts to about 10ms, the shortest reasonable period a human ear can distinguish. I chose hop length of 512. Further more the Mel-spectrograms produced by Librosa were scaled by a log function. This mapsthe sound data to the normal logarithmic scale used to determine loudness in decibels (dB) as it relates to the human-perceived pitch. As a result of this transformation each audio file gets converted to a mel-spectogram of shape β 640, 128."
},
{
"code": null,
"e": 3092,
"s": 2935,
"text": "As seen in Figure 1, different genres have noticeable differences in their mel-spectogram which gives us confidence in using a CNN to do the classification."
},
{
"code": null,
"e": 3202,
"s": 3092,
"text": "Librosa makes it super easy to create spectograms. A 3 line code can convert an audio file into a spectogram!"
},
{
"code": null,
"e": 3356,
"s": 3202,
"text": "y, sr = librosa.load(filename)spect = librosa.feature.melspectrogram(y=y, sr=sr,n_fft=2048, hop_length=512)spect = librosa.power_to_db(spect, ref=np.max)"
},
{
"code": null,
"e": 3602,
"s": 3356,
"text": "To speed up training, I divided the data set into train, test and validation, converted their respective audio files into spectograms and picked the results so this pickled data could directly be loaded. You can find this data on the drive link."
},
{
"code": null,
"e": 3625,
"s": 3602,
"text": "Why use CNNs and RNNs?"
},
{
"code": null,
"e": 4157,
"s": 3625,
"text": "One question that arises is why do we need to use both CNNs and RNNs. A spectogram is a visual representation of audio across frequency and time dimension. CNN makes sense since spectograms of a song are kind of like an image, each with their own distinct patterns. RNNs excel in understand sequential data by making the hidden state at time t dependent on hidden state at time t-1. The spectograms have a time component and RNNs can do a much better job of identifying the short term and longer term temporal features in the song."
},
{
"code": null,
"e": 4335,
"s": 4157,
"text": "I tried 2 interesting CNN-RNN architectures β Convolutional Recurrent Model and a Parallel CNN-RNN model. Both models were coded in Keras and you can find the code on my Github."
},
{
"code": null,
"e": 5434,
"s": 4335,
"text": "The inspiration of this model comes from the work by deep sound and from the paper by Keunwoo Choi et al. This model uses 1D CNNs that performconvolution operation just across the time dimension. Each 1D convolution layer extracts features from a small slice of the spectogram. RELU activationis applied after the Convolution operation. Batch normalization is done and finally 1D Max Pooling is performed which reduces spatial dimension of the image and prevents over fitting.This chain of operations β 1D Convolution β RELU β Batch Normalization β 1D Max Pooling is performed 3 times. The output from 1D Convolution Layer is fed into a LSTM which should find short term and long term structure of the song. The LSTM uses 96 hidden units. The output from LSTM is passed into aDense Layer of 64 units. The final output layer of the model is a dense layer with Softmax activation and 8 hidden units to assign probability to the 8 classes. Both dropout and L2 regularization were used between all the layers to reduce over fitting of the model. Figure below shows the overallarchitecture of the model."
},
{
"code": null,
"e": 5687,
"s": 5434,
"text": "The model was trained using Adam optimizer with a learning rate of 0.001 and the loss function was categorical cross entropy. The model was trained for 70 epochs and Learning Rate was reduced if the validation accuracy plateaued for at least 10 epochs."
},
{
"code": null,
"e": 5918,
"s": 5687,
"text": "See below the loss and accuracy curves for training and validation samples. As seen, the model has low bias but high variance implying the model is over fitting a bit to training even after using several regularization techniques."
},
{
"code": null,
"e": 5987,
"s": 5918,
"text": "Overall this model got to around 53% accuracy on the validation set."
},
{
"code": null,
"e": 6564,
"s": 5987,
"text": "Inspired by the work of Lin Fen and Shenlen Liu, I also tried a Parallel CNN-RNN Model. The key idea behind this network is that even though CRNN has RNNs to be the temporal summarizer, it can only summarize temporal information from the output of CNNs. The temporal relationships of original musical signals are not preserved during operations with CNNs. This model passes the input spectogram through both CNN and RNN layers in parallel, concatenating their output and then sending this through a dense layer with softmax activation to perform classification as shown below."
},
{
"code": null,
"e": 7627,
"s": 6564,
"text": "The convolutional block of the model consists of 2D convolution layer followed by a 2D Max pooling layer. This is in contrast to the CRNN model that uses 1D convolution and max pooling layers. There are 5 blocks of Convolution Max pooling layers. The final output is flattened and is a tensor of shape None , 256.The recurrent block starts with 2D max pooling layer of pool size 4,2 to reduce the size of the spectogram before LSTM operation. This feature reduction was done primarily to speed up processing. The reduced image is sent to a bidirectional GRU with 64 units. The output from this layer is atensor of shape None, 128.The outputs from the convolutional and recurrent blocks are then concatenated resulting in a tensor of shape, None, 384. Finally we have a dense layer with softmax activation. The model was trained using RMSProp optimizer with a learning rate of 0.0005 and the loss function was categorical cross entropy. The model was trained for 50 epochs and Learning Rate was reduced if the validation accuracy plateaued for at least 10 epochs."
},
{
"code": null,
"e": 7691,
"s": 7627,
"text": "Figure below shows the loss and accuracy curves from this model"
},
{
"code": null,
"e": 8044,
"s": 7691,
"text": "This model had a validation loss of around 51%. Both models have very similar overall accuracies which is quite interesting but their class wise performance is very different. Parallel CNN-RNN model has a better performance for Experimental, Folk, Hip-Hop and Instrumental genres. The ensembling of both these models should produce even better results."
},
{
"code": null,
"e": 8156,
"s": 8044,
"text": "One question that I asked myself was why is the accuracy only around 51%. I think there are 2 reasons for this:"
},
{
"code": null,
"e": 8527,
"s": 8156,
"text": "The sample size of 1000 spectograms is actually a very small sample for building a deep learning model from scratch. As seen by the loss curves, both models overfit quickly. Ideally we have a bigger training set or one thing that can be tried is breaking each song into 3 segments of 10 seconds each with the same label and using this to triple the size of the data set."
},
{
"code": null,
"e": 8770,
"s": 8527,
"text": "The FMA data set is challenging and in particular it has a few classes like experimental and international which are easy to confuse among. The top leader board score on FMA -Genre Recognition challenge has a test F1 score of only around 0.63"
},
{
"code": null,
"e": 9011,
"s": 8770,
"text": "I explored the features learned by initial vs later layers of the convolution model. For this analysis I used the Keras Visualization package and selected Parallel CNN-RNN model as this uses the 2D CNN layers which were easier to visualize."
},
{
"code": null,
"e": 9382,
"s": 9011,
"text": "The first convolution block in this model has 16 filters and the fifth convolution block has 64 filters. To understand what the filter is focusing on, we look at what kind of input maximizes the activations in that filter. Figure below shows the filter activations of all 16 filters in the first convolution blocks vs the first 24 filters of the fifth convolution block."
},
{
"code": null,
"e": 9955,
"s": 9382,
"text": "What I observe here is that the filters for the first layer are relatively straightforward. There are looking at a small kernel size of 3,1. As such they are focusing on different patterns of fluctuations between primarily 50β200 db. In the fifth convolution block, the same filter is looking at a biggersize of the input image due to feature maps being shrunk as a result of convolution and max pooling operations. It is now able to focus on different features like sharp increases in amplitude to 250 db as well as periods of very low amplitude coloured as black region."
},
{
"code": null,
"e": 10016,
"s": 9955,
"text": "I hope you like this analysis and try the code for yourself."
},
{
"code": null,
"e": 10217,
"s": 10016,
"text": "I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at β http://deeplearninganalytics.org/."
},
{
"code": null,
"e": 10290,
"s": 10217,
"text": "You can also see my other writings at: https://medium.com/@priya.dwivedi"
},
{
"code": null,
"e": 10419,
"s": 10290,
"text": "If you have a project that we can collaborate on, then please contact me through my website or at info@deeplearninganalytics.org"
},
{
"code": null,
"e": 10468,
"s": 10419,
"text": "http://deepsound.io/music_genre_recognition.html"
},
{
"code": null,
"e": 10518,
"s": 10468,
"text": "Free Music Archive β https://github.com/mdeff/fma"
},
{
"code": null,
"e": 10526,
"s": 10518,
"text": "Librosa"
},
{
"code": null,
"e": 10591,
"s": 10526,
"text": "Convolutional Recurrent Neural Networks for Music Classification"
}
] |
Intersection of Two Linked Lists in C++
|
A Linked List is a linear data structure in which each node has two blocks such that one block contains the value or data of the node and the other block contains the address of the next field.
Let us assume that we have a linked list such that each node contains a random pointer which is pointing to the other nodes in the list. The task is to find the node at which two linked lists intersect each other. If they don't intersect, then return NULL or empty as output.
For Example
Input-1:
Output:
2
Explanation: Since the given linked list intersects at the node with the value '2', we will return the value '2' as the output.
Input-2:
Output:
NULL
Explanation: Since there are no common points, we will return NULL in this case.
We have two linked lists with a common point where they intersect each other. To find the intersection point, we will traverse both the linked lists till we find that they are equally pointing to the same value. At some point, the pointer to the next node of the linked list will be the same. Thus we will return the value of that point.
Take two linked lists with data and pointer to the next node.
A function commonPoint(listnode*headA, listnode*headB) takes two pointers of linked list respectively and returns the value of the common or intersection point of the linked list.
An integer function that finds the length of the linked list will return the length of both linked lists from the head of the list.
Now create a pointer to the head of both lists and traverse the list which is greater in its length till (length of first list β length of second list).
Now traverse the list till we find the next pointer is equal.
Return the value of that particular node where both the lists intersect.
Live Demo
#include <bits/stdc++.h>
using namespace std;
class listnode {
public:
int data;
listnode * next;
};
// Find the length of the linked list
int count(listnode * head) {
int count = 0;
while (head != NULL) {
count++;
head = head -> next;
}
return count;
}
//Function to get the common point of two linked list
int commonPoint(listnode * headA, listnode * headB) {
int len1 = count(headA);
int len2 = count(headB);
listnode * p1 = headA;
listnode * p2 = headB;
if (len1 > len2) {
for (int i = 0; i < len1 - len2; ++i) {
p1 = p1 -> next;
}
}
if (len1 < len2) {
for (int i = 0; i < len2 - len1; ++i) {
p2 = p2 -> next;
}
}
while (p1 != NULL and p2 != NULL) {
if (p1 == p2) {
return p1 -> data;
}
p1 = p1 -> next;
p2 = p2 -> next;
}
return -1;
}
int main() {
listnode * head;
listnode * headA = new listnode();
headA -> data = 5;
listnode * headB = new listnode();
headB -> data = 4;
head = new listnode();
head -> data = 9;
headB -> next = head;
head = new listnode();
head -> data = 2;
headB -> next -> next = head;
head = new listnode();
head -> data = 7;
headA -> next = head;
headB -> next -> next -> next = head;
head = new listnode();
head -> data = 3;
headA -> next -> next = head;
headA -> next -> next -> next = NULL;
cout << commonPoint(headA, headB) << endl;
}
Running the above code will generate the output as,
7
Explanation: The given linked lists are merging at '7'.
|
[
{
"code": null,
"e": 1256,
"s": 1062,
"text": "A Linked List is a linear data structure in which each node has two blocks such that one block contains the value or data of the node and the other block contains the address of the next field."
},
{
"code": null,
"e": 1532,
"s": 1256,
"text": "Let us assume that we have a linked list such that each node contains a random pointer which is pointing to the other nodes in the list. The task is to find the node at which two linked lists intersect each other. If they don't intersect, then return NULL or empty as output."
},
{
"code": null,
"e": 1544,
"s": 1532,
"text": "For Example"
},
{
"code": null,
"e": 1553,
"s": 1544,
"text": "Input-1:"
},
{
"code": null,
"e": 1575,
"s": 1567,
"text": "Output:"
},
{
"code": null,
"e": 1577,
"s": 1575,
"text": "2"
},
{
"code": null,
"e": 1705,
"s": 1577,
"text": "Explanation: Since the given linked list intersects at the node with the value '2', we will return the value '2' as the output."
},
{
"code": null,
"e": 1714,
"s": 1705,
"text": "Input-2:"
},
{
"code": null,
"e": 1722,
"s": 1714,
"text": "Output:"
},
{
"code": null,
"e": 1727,
"s": 1722,
"text": "NULL"
},
{
"code": null,
"e": 1808,
"s": 1727,
"text": "Explanation: Since there are no common points, we will return NULL in this case."
},
{
"code": null,
"e": 2146,
"s": 1808,
"text": "We have two linked lists with a common point where they intersect each other. To find the intersection point, we will traverse both the linked lists till we find that they are equally pointing to the same value. At some point, the pointer to the next node of the linked list will be the same. Thus we will return the value of that point."
},
{
"code": null,
"e": 2208,
"s": 2146,
"text": "Take two linked lists with data and pointer to the next node."
},
{
"code": null,
"e": 2388,
"s": 2208,
"text": "A function commonPoint(listnode*headA, listnode*headB) takes two pointers of linked list respectively and returns the value of the common or intersection point of the linked list."
},
{
"code": null,
"e": 2520,
"s": 2388,
"text": "An integer function that finds the length of the linked list will return the length of both linked lists from the head of the list."
},
{
"code": null,
"e": 2673,
"s": 2520,
"text": "Now create a pointer to the head of both lists and traverse the list which is greater in its length till (length of first list β length of second list)."
},
{
"code": null,
"e": 2735,
"s": 2673,
"text": "Now traverse the list till we find the next pointer is equal."
},
{
"code": null,
"e": 2808,
"s": 2735,
"text": "Return the value of that particular node where both the lists intersect."
},
{
"code": null,
"e": 2818,
"s": 2808,
"text": "Live Demo"
},
{
"code": null,
"e": 4289,
"s": 2818,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass listnode {\n public:\n int data;\n listnode * next;\n};\n// Find the length of the linked list\nint count(listnode * head) {\n int count = 0;\n while (head != NULL) {\n count++;\n head = head -> next;\n }\n return count;\n}\n//Function to get the common point of two linked list\nint commonPoint(listnode * headA, listnode * headB) {\n int len1 = count(headA);\n int len2 = count(headB);\n listnode * p1 = headA;\n listnode * p2 = headB;\n if (len1 > len2) {\n for (int i = 0; i < len1 - len2; ++i) {\n p1 = p1 -> next;\n }\n }\n if (len1 < len2) {\n for (int i = 0; i < len2 - len1; ++i) {\n p2 = p2 -> next;\n }\n }\n while (p1 != NULL and p2 != NULL) {\n if (p1 == p2) {\n return p1 -> data;\n }\n p1 = p1 -> next;\n p2 = p2 -> next;\n }\n return -1;\n}\nint main() {\n listnode * head;\n listnode * headA = new listnode();\n headA -> data = 5;\n listnode * headB = new listnode();\n headB -> data = 4;\n head = new listnode();\n head -> data = 9;\n headB -> next = head;\n head = new listnode();\n head -> data = 2;\n headB -> next -> next = head;\n head = new listnode();\n head -> data = 7;\n headA -> next = head;\n headB -> next -> next -> next = head;\n head = new listnode();\n head -> data = 3;\n headA -> next -> next = head;\n headA -> next -> next -> next = NULL;\n cout << commonPoint(headA, headB) << endl;\n}"
},
{
"code": null,
"e": 4341,
"s": 4289,
"text": "Running the above code will generate the output as,"
},
{
"code": null,
"e": 4343,
"s": 4341,
"text": "7"
},
{
"code": null,
"e": 4399,
"s": 4343,
"text": "Explanation: The given linked lists are merging at '7'."
}
] |
How to Set Classpath in Java? - GeeksforGeeks
|
20 Nov, 2020
CLASSPATH describes the location where all the required files are available which are used in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the required files. If the CLASSPATH is not set, Java Compiler will not be able to find the required files and hence will throw the following error.
Error: Could not find or load main class <class name> (e.g. GFG)
The above error is resolved when CLASSPATH is set.
Java
// If the following code is run when the CLASSPATH is not// set, it will throw the above error. // If it is set, we get the desired result import java.io.*; class GFG { public static void main(String[] args) { // prints GeeksForGeeks to the console System.out.println("GeekForGeeks!"); }}
GeekForGeeks!
Command Prompt:
set PATH=.;C:\Program Files\Java\JDK1.6.20\bin
Note: Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH in the above command.
1. Select Start
2. Go to the Control Panel
3. Select System and Security
4. Select Advanced System settings
5. Click on Environment Variables
6. Click on New under System Variables
7. Add CLASSPATH as variable name and path of files as a variable value.
8. Select OK.
Command Line:
Find out where you have installed Java, basically, itβs in /usr/lib/jvm path. Set the CLASSPATH in /etc/environment using
sudo <editor name> /etc/environment
Add the following lines,
JAVA_HOME = "/usr/lib/jvm/<java folder (eg. java-1.8.0-openjdk-amd64>)/bin"
export JAVA_HOME
CLASSPATH=".:/usr/lib/jvm/<java folder>/lib:/home/name/Desktop"
export CLASSPATH
Note: Colon (:) is used as a separate directory and dot (.) is the default value of CLASSPATH in the above command.
To check the current CLASSPATH, run
echo ${CLASSPATH}
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Overriding in Java
Collections in Java
Singleton Class in Java
Multithreading in Java
|
[
{
"code": null,
"e": 24354,
"s": 24326,
"text": "\n20 Nov, 2020"
},
{
"code": null,
"e": 24683,
"s": 24354,
"text": "CLASSPATH describes the location where all the required files are available which are used in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the required files. If the CLASSPATH is not set, Java Compiler will not be able to find the required files and hence will throw the following error."
},
{
"code": null,
"e": 24749,
"s": 24683,
"text": "Error: Could not find or load main class <class name> (e.g. GFG)\n"
},
{
"code": null,
"e": 24800,
"s": 24749,
"text": "The above error is resolved when CLASSPATH is set."
},
{
"code": null,
"e": 24805,
"s": 24800,
"text": "Java"
},
{
"code": "// If the following code is run when the CLASSPATH is not// set, it will throw the above error. // If it is set, we get the desired result import java.io.*; class GFG { public static void main(String[] args) { // prints GeeksForGeeks to the console System.out.println(\"GeekForGeeks!\"); }}",
"e": 25122,
"s": 24805,
"text": null
},
{
"code": null,
"e": 25138,
"s": 25122,
"text": "GeekForGeeks!\n\n"
},
{
"code": null,
"e": 25154,
"s": 25138,
"text": "Command Prompt:"
},
{
"code": null,
"e": 25202,
"s": 25154,
"text": "set PATH=.;C:\\Program Files\\Java\\JDK1.6.20\\bin\n"
},
{
"code": null,
"e": 25314,
"s": 25202,
"text": "Note: Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH in the above command."
},
{
"code": null,
"e": 25330,
"s": 25314,
"text": "1. Select Start"
},
{
"code": null,
"e": 25357,
"s": 25330,
"text": "2. Go to the Control Panel"
},
{
"code": null,
"e": 25387,
"s": 25357,
"text": "3. Select System and Security"
},
{
"code": null,
"e": 25422,
"s": 25387,
"text": "4. Select Advanced System settings"
},
{
"code": null,
"e": 25456,
"s": 25422,
"text": "5. Click on Environment Variables"
},
{
"code": null,
"e": 25495,
"s": 25456,
"text": "6. Click on New under System Variables"
},
{
"code": null,
"e": 25568,
"s": 25495,
"text": "7. Add CLASSPATH as variable name and path of files as a variable value."
},
{
"code": null,
"e": 25582,
"s": 25568,
"text": "8. Select OK."
},
{
"code": null,
"e": 25596,
"s": 25582,
"text": "Command Line:"
},
{
"code": null,
"e": 25719,
"s": 25596,
"text": "Find out where you have installed Java, basically, itβs in /usr/lib/jvm path. Set the CLASSPATH in /etc/environment using "
},
{
"code": null,
"e": 25756,
"s": 25719,
"text": "sudo <editor name> /etc/environment\n"
},
{
"code": null,
"e": 25781,
"s": 25756,
"text": "Add the following lines,"
},
{
"code": null,
"e": 25957,
"s": 25781,
"text": "JAVA_HOME = \"/usr/lib/jvm/<java folder (eg. java-1.8.0-openjdk-amd64>)/bin\"\nexport JAVA_HOME\nCLASSPATH=\".:/usr/lib/jvm/<java folder>/lib:/home/name/Desktop\"\nexport CLASSPATH\n\n"
},
{
"code": null,
"e": 26073,
"s": 25957,
"text": "Note: Colon (:) is used as a separate directory and dot (.) is the default value of CLASSPATH in the above command."
},
{
"code": null,
"e": 26110,
"s": 26073,
"text": "To check the current CLASSPATH, run "
},
{
"code": null,
"e": 26129,
"s": 26110,
"text": "echo ${CLASSPATH}\n"
},
{
"code": null,
"e": 26136,
"s": 26129,
"text": "Picked"
},
{
"code": null,
"e": 26141,
"s": 26136,
"text": "Java"
},
{
"code": null,
"e": 26146,
"s": 26141,
"text": "Java"
},
{
"code": null,
"e": 26244,
"s": 26146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26253,
"s": 26244,
"text": "Comments"
},
{
"code": null,
"e": 26266,
"s": 26253,
"text": "Old Comments"
},
{
"code": null,
"e": 26296,
"s": 26266,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26315,
"s": 26296,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26366,
"s": 26315,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26384,
"s": 26366,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26415,
"s": 26384,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26447,
"s": 26415,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26466,
"s": 26447,
"text": "Overriding in Java"
},
{
"code": null,
"e": 26486,
"s": 26466,
"text": "Collections in Java"
},
{
"code": null,
"e": 26510,
"s": 26486,
"text": "Singleton Class in Java"
}
] |
Main thread vs child thread in C#
|
The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created.
The threads created using the Thread class are called the child threads of the main thread.
Here is an example showing how to create a main and child thread β
Live Demo
using System;
using System.Threading;
namespace Demo {
class Program {
static void Main(string[] args) {
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
This is MainThread
|
[
{
"code": null,
"e": 1212,
"s": 1062,
"text": "The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created."
},
{
"code": null,
"e": 1304,
"s": 1212,
"text": "The threads created using the Thread class are called the child threads of the main thread."
},
{
"code": null,
"e": 1371,
"s": 1304,
"text": "Here is an example showing how to create a main and child thread β"
},
{
"code": null,
"e": 1382,
"s": 1371,
"text": " Live Demo"
},
{
"code": null,
"e": 1667,
"s": 1382,
"text": "using System;\nusing System.Threading;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n Thread th = Thread.CurrentThread;\n th.Name = \"MainThread\";\n Console.WriteLine(\"This is {0}\", th.Name);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 1686,
"s": 1667,
"text": "This is MainThread"
}
] |
Battleships in a Board in C++
|
Suppose we have an 2D board, we have to count how many battleships are in it. The battleships are represented with the symbol 'X', empty slots are represented with '.'s. We can assume these rules β
You receive a valid board, made of only battleships or empty slots.
You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
So if the board is like:
Then the output will be 2, as there are two battleships.
To solve this, we will follow these steps β
ans := 0, n := row count and m := column count
ans := 0, n := row count and m := column count
for ith rowfor jth columnif board[i, j] is dot, then go for the next iterationif i > 0 and board[i β 1, j] = βXβ, then go for the next iterationif j > 0 and board[i, j - 1] = βXβ, then go for the next iterationincrease ans by 1
for ith row
for jth columnif board[i, j] is dot, then go for the next iterationif i > 0 and board[i β 1, j] = βXβ, then go for the next iterationif j > 0 and board[i, j - 1] = βXβ, then go for the next iterationincrease ans by 1
for jth column
if board[i, j] is dot, then go for the next iteration
if board[i, j] is dot, then go for the next iteration
if i > 0 and board[i β 1, j] = βXβ, then go for the next iteration
if i > 0 and board[i β 1, j] = βXβ, then go for the next iteration
if j > 0 and board[i, j - 1] = βXβ, then go for the next iteration
if j > 0 and board[i, j - 1] = βXβ, then go for the next iteration
increase ans by 1
increase ans by 1
return ans
return ans
Let us see the following implementation to get better understanding β
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int ans = 0;
int n = board.size();
int m = board[0].size();
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(board[i][j] == '.')continue;
if(i > 0 && board[i - 1][j] == 'X')continue;
if(j > 0 && board[i][j - 1] == 'X')continue;
ans++;
}
}
return ans;
}
};
main(){
vector<vector<char>> v = {{'X','.','.','X'},{'.','.','.','X'},{'.','.','.','X'}};
Solution ob;
cout << (ob.countBattleships(v));
}
[["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
2
|
[
{
"code": null,
"e": 1260,
"s": 1062,
"text": "Suppose we have an 2D board, we have to count how many battleships are in it. The battleships are represented with the symbol 'X', empty slots are represented with '.'s. We can assume these rules β"
},
{
"code": null,
"e": 1328,
"s": 1260,
"text": "You receive a valid board, made of only battleships or empty slots."
},
{
"code": null,
"e": 1396,
"s": 1328,
"text": "You receive a valid board, made of only battleships or empty slots."
},
{
"code": null,
"e": 1584,
"s": 1396,
"text": "Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size."
},
{
"code": null,
"e": 1772,
"s": 1584,
"text": "Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size."
},
{
"code": null,
"e": 1884,
"s": 1772,
"text": "At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships."
},
{
"code": null,
"e": 1996,
"s": 1884,
"text": "At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships."
},
{
"code": null,
"e": 2021,
"s": 1996,
"text": "So if the board is like:"
},
{
"code": null,
"e": 2078,
"s": 2021,
"text": "Then the output will be 2, as there are two battleships."
},
{
"code": null,
"e": 2122,
"s": 2078,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 2169,
"s": 2122,
"text": "ans := 0, n := row count and m := column count"
},
{
"code": null,
"e": 2216,
"s": 2169,
"text": "ans := 0, n := row count and m := column count"
},
{
"code": null,
"e": 2444,
"s": 2216,
"text": "for ith rowfor jth columnif board[i, j] is dot, then go for the next iterationif i > 0 and board[i β 1, j] = βXβ, then go for the next iterationif j > 0 and board[i, j - 1] = βXβ, then go for the next iterationincrease ans by 1"
},
{
"code": null,
"e": 2456,
"s": 2444,
"text": "for ith row"
},
{
"code": null,
"e": 2673,
"s": 2456,
"text": "for jth columnif board[i, j] is dot, then go for the next iterationif i > 0 and board[i β 1, j] = βXβ, then go for the next iterationif j > 0 and board[i, j - 1] = βXβ, then go for the next iterationincrease ans by 1"
},
{
"code": null,
"e": 2688,
"s": 2673,
"text": "for jth column"
},
{
"code": null,
"e": 2742,
"s": 2688,
"text": "if board[i, j] is dot, then go for the next iteration"
},
{
"code": null,
"e": 2796,
"s": 2742,
"text": "if board[i, j] is dot, then go for the next iteration"
},
{
"code": null,
"e": 2863,
"s": 2796,
"text": "if i > 0 and board[i β 1, j] = βXβ, then go for the next iteration"
},
{
"code": null,
"e": 2930,
"s": 2863,
"text": "if i > 0 and board[i β 1, j] = βXβ, then go for the next iteration"
},
{
"code": null,
"e": 2997,
"s": 2930,
"text": "if j > 0 and board[i, j - 1] = βXβ, then go for the next iteration"
},
{
"code": null,
"e": 3064,
"s": 2997,
"text": "if j > 0 and board[i, j - 1] = βXβ, then go for the next iteration"
},
{
"code": null,
"e": 3082,
"s": 3064,
"text": "increase ans by 1"
},
{
"code": null,
"e": 3100,
"s": 3082,
"text": "increase ans by 1"
},
{
"code": null,
"e": 3111,
"s": 3100,
"text": "return ans"
},
{
"code": null,
"e": 3122,
"s": 3111,
"text": "return ans"
},
{
"code": null,
"e": 3192,
"s": 3122,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 3203,
"s": 3192,
"text": " Live Demo"
},
{
"code": null,
"e": 3851,
"s": 3203,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int countBattleships(vector<vector<char>>& board) {\n int ans = 0;\n int n = board.size();\n int m = board[0].size();\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n if(board[i][j] == '.')continue;\n if(i > 0 && board[i - 1][j] == 'X')continue;\n if(j > 0 && board[i][j - 1] == 'X')continue;\n ans++;\n }\n }\n return ans;\n }\n};\nmain(){\n vector<vector<char>> v = {{'X','.','.','X'},{'.','.','.','X'},{'.','.','.','X'}};\n Solution ob;\n cout << (ob.countBattleships(v));\n}"
},
{
"code": null,
"e": 3907,
"s": 3851,
"text": "[[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]"
},
{
"code": null,
"e": 3909,
"s": 3907,
"text": "2"
}
] |
Groovy - Object Oriented
|
In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain.
A class in Groovy declares the state (data) and the behavior of objects defined by that class. Hence, a Groovy class describes both the instance fields and methods for that class.
Following is an example of a class in Groovy. The name of the class is Student which has two fields β StudentID and StudentName. In the main function, we are creating an object of this class and assigning values to the StudentID and StudentName of the object.
class Student {
int StudentID;
String StudentName;
static void main(String[] args) {
Student st = new Student();
st.StudentID = 1;
st.StudentName = "Joe"
}
}
In any programming language, it always a practice to hide the instance members with the private keyword and instead provide getter and setter methods to set and get the values of the instance variables accordingly. The following example shows how this can be done.
class Student {
private int StudentID;
private String StudentName;
void setStudentID(int pID) {
StudentID = pID;
}
void setStudentName(String pName) {
StudentName = pName;
}
int getStudentID() {
return this.StudentID;
}
String getStudentName() {
return this.StudentName;
}
static void main(String[] args) {
Student st = new Student();
st.setStudentID(1);
st.setStudentName("Joe");
println(st.getStudentID());
println(st.getStudentName());
}
}
When we run the above program, we will get the following result β
1
Joe
Note the following key points about the above program β
In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class.
In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class.
Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName)
Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName)
Itβs normally a natural to include more methods inside of the class which actually does some sort of functionality for the class. In our student example, letβs add instance members of Marks1, Marks2 and Marks3 to denote the marks of the student in 3 subjects. We will then add a new instance method which will calculate the total marks of the student. Following is how the code would look like.
In the following example, the method Total is an additional Instance method which has some logic built into it.
class Student {
int StudentID;
String StudentName;
int Marks1;
int Marks2;
int Marks3;
int Total() {
return Marks1+Marks2+Marks3;
}
static void main(String[] args) {
Student st = new Student();
st.StudentID = 1;
st.StudentName="Joe";
st.Marks1 = 10;
st.Marks2 = 20;
st.Marks3 = 30;
println(st.Total());
}
}
When we run the above program, we will get the following result β
60
One can also create multiple objects of a class. Following is the example of how this can be achieved. In here we are creating 3 objects (st, st1 and st2) and calling their instance members and instance methods accordingly.
class Student {
int StudentID;
String StudentName;
int Marks1;
int Marks2;
int Marks3;
int Total() {
return Marks1+Marks2+Marks3;
}
static void main(String[] args) {
Student st = new Student();
st.StudentID = 1;
st.StudentName = "Joe";
st.Marks1 = 10;
st.Marks2 = 20;
st.Marks3 = 30;
println(st.Total());
Student st1 = new Student();
st.StudentID = 1;
st.StudentName = "Joe";
st.Marks1 = 10;
st.Marks2 = 20;
st.Marks3 = 40;
println(st.Total());
Student st3 = new Student();
st.StudentID = 1;
st.StudentName = "Joe";
st.Marks1 = 10;
st.Marks2 = 20;
st.Marks3 = 50;
println(st.Total());
}
}
When we run the above program, we will get the following result β
60
70
80
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
extends is the keyword used to inherit the properties of a class. Given below is the syntax of extends keyword. In the following example we are doing the following things β
Creating a class called Person. This class has one instance member called name.
Creating a class called Person. This class has one instance member called name.
Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class.
Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class.
In the Student class constructor, we are calling the base class constructor.
In the Student class constructor, we are calling the base class constructor.
In our Student class, we are adding 2 additional instance members of StudentID and Marks1.
In our Student class, we are adding 2 additional instance members of StudentID and Marks1.
class Example {
static void main(String[] args) {
Student st = new Student();
st.StudentID = 1;
st.Marks1 = 10;
st.name = "Joe";
println(st.name);
}
}
class Person {
public String name;
public Person() {}
}
class Student extends Person {
int StudentID
int Marks1;
public Student() {
super();
}
}
When we run the above program, we will get the following result β
Joe
Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes.
Following is an example of an Outer and Inner class. In the following example we are doing the following things β
Creating an class called Outer which will be our outer class.
Defining a string called name in our Outer class.
Creating an Inner or nested class inside of our Outer class.
Note that in the inner class we are able to access the name instance member defined in the Outer class.
class Example {
static void main(String[] args) {
Outer outobj = new Outer();
outobj.name = "Joe";
outobj.callInnerMethod()
}
}
class Outer {
String name;
def callInnerMethod() {
new Inner().methodA()
}
class Inner {
def methodA() {
println(name);
}
}
}
When we run the above program, we will get the following result β
Joe
Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses. Abstract classes must be declared with abstract keyword. Abstract methods must also be declared with abstract keyword.
In the following example, note that the Person class is now made into an abstract class and cannot be instantiated. Also note that there is an abstract method called DisplayMarks in the abstract class which has no implementation details. In the student class it is mandatory to add the implementation details.
class Example {
static void main(String[] args) {
Student st = new Student();
st.StudentID = 1;
st.Marks1 = 10;
st.name="Joe";
println(st.name);
println(st.DisplayMarks());
}
}
abstract class Person {
public String name;
public Person() { }
abstract void DisplayMarks();
}
class Student extends Person {
int StudentID
int Marks1;
public Student() {
super();
}
void DisplayMarks() {
println(Marks1);
}
}
When we run the above program, we will get the following result β
Joe
10
null
An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the methods implementation. An interface needs to be declared using the interface keyword. An interface only defines method signatures. Methods of an interface are always public. It is an error to use protected or private methods in interfaces.
Following is an example of an interface in groovy. In the following example we are doing the following things β
Creating an interface called Marks and creating an interface method called DisplayMarks.
Creating an interface called Marks and creating an interface method called DisplayMarks.
In the class definition, we are using the implements keyword to implement the interface.
In the class definition, we are using the implements keyword to implement the interface.
Because we are implementing the interface we have to provide the implementation for the DisplayMarks method.
Because we are implementing the interface we have to provide the implementation for the DisplayMarks method.
class Example {
static void main(String[] args) {
Student st = new Student();
st.StudentID = 1;
st.Marks1 = 10;
println(st.DisplayMarks());
}
}
interface Marks {
void DisplayMarks();
}
class Student implements Marks {
int StudentID
int Marks1;
void DisplayMarks() {
println(Marks1);
}
}
When we run the above program, we will get the following result β
10
null
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2600,
"s": 2238,
"text": "In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain."
},
{
"code": null,
"e": 2780,
"s": 2600,
"text": "A class in Groovy declares the state (data) and the behavior of objects defined by that class. Hence, a Groovy class describes both the instance fields and methods for that class."
},
{
"code": null,
"e": 3040,
"s": 2780,
"text": "Following is an example of a class in Groovy. The name of the class is Student which has two fields β StudentID and StudentName. In the main function, we are creating an object of this class and assigning values to the StudentID and StudentName of the object."
},
{
"code": null,
"e": 3236,
"s": 3040,
"text": "class Student {\n int StudentID;\n String StudentName;\n\t\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\" \n } \n}"
},
{
"code": null,
"e": 3501,
"s": 3236,
"text": "In any programming language, it always a practice to hide the instance members with the private keyword and instead provide getter and setter methods to set and get the values of the instance variables accordingly. The following example shows how this can be done."
},
{
"code": null,
"e": 4048,
"s": 3501,
"text": "class Student {\n private int StudentID;\n private String StudentName;\n\t\n void setStudentID(int pID) {\n StudentID = pID;\n }\n\t\n void setStudentName(String pName) {\n StudentName = pName;\n }\n\t\n int getStudentID() {\n return this.StudentID;\n }\n\t\n String getStudentName() {\n return this.StudentName;\n }\n\t\n static void main(String[] args) {\n Student st = new Student();\n st.setStudentID(1);\n st.setStudentName(\"Joe\");\n\t\t\n println(st.getStudentID());\n println(st.getStudentName());\n } \n}"
},
{
"code": null,
"e": 4114,
"s": 4048,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 4123,
"s": 4114,
"text": "1 \nJoe \n"
},
{
"code": null,
"e": 4179,
"s": 4123,
"text": "Note the following key points about the above program β"
},
{
"code": null,
"e": 4317,
"s": 4179,
"text": "In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class."
},
{
"code": null,
"e": 4455,
"s": 4317,
"text": "In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class."
},
{
"code": null,
"e": 4734,
"s": 4455,
"text": "Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName)"
},
{
"code": null,
"e": 5013,
"s": 4734,
"text": "Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName)"
},
{
"code": null,
"e": 5408,
"s": 5013,
"text": "Itβs normally a natural to include more methods inside of the class which actually does some sort of functionality for the class. In our student example, letβs add instance members of Marks1, Marks2 and Marks3 to denote the marks of the student in 3 subjects. We will then add a new instance method which will calculate the total marks of the student. Following is how the code would look like."
},
{
"code": null,
"e": 5520,
"s": 5408,
"text": "In the following example, the method Total is an additional Instance method which has some logic built into it."
},
{
"code": null,
"e": 5914,
"s": 5520,
"text": "class Student {\n int StudentID;\n String StudentName;\n\t\n int Marks1;\n int Marks2;\n int Marks3;\n\t\n int Total() {\n return Marks1+Marks2+Marks3;\n }\n\t\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.StudentName=\"Joe\";\n\t\t\n st.Marks1 = 10;\n st.Marks2 = 20;\n st.Marks3 = 30;\n\t\t\n println(st.Total());\n }\n}"
},
{
"code": null,
"e": 5980,
"s": 5914,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 5984,
"s": 5980,
"text": "60\n"
},
{
"code": null,
"e": 6208,
"s": 5984,
"text": "One can also create multiple objects of a class. Following is the example of how this can be achieved. In here we are creating 3 objects (st, st1 and st2) and calling their instance members and instance methods accordingly."
},
{
"code": null,
"e": 7001,
"s": 6208,
"text": "class Student {\n int StudentID;\n String StudentName;\n\t\n int Marks1;\n int Marks2;\n int Marks3;\n\t\n int Total() { \n return Marks1+Marks2+Marks3;\n } \n\t\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\";\n\t\t\n st.Marks1 = 10;\n st.Marks2 = 20;\n st.Marks3 = 30;\n\t\t\n println(st.Total()); \n \n Student st1 = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\";\n\t\t\n st.Marks1 = 10;\n st.Marks2 = 20;\n st.Marks3 = 40;\n\t\t\n println(st.Total()); \n \n Student st3 = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\";\n\t\t\n st.Marks1 = 10; \n st.Marks2 = 20;\n st.Marks3 = 50;\n\t\t\n println(st.Total());\n } \n} "
},
{
"code": null,
"e": 7067,
"s": 7001,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 7080,
"s": 7067,
"text": "60 \n70 \n80 \n"
},
{
"code": null,
"e": 7283,
"s": 7080,
"text": "Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order."
},
{
"code": null,
"e": 7478,
"s": 7283,
"text": "The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class)."
},
{
"code": null,
"e": 7651,
"s": 7478,
"text": "extends is the keyword used to inherit the properties of a class. Given below is the syntax of extends keyword. In the following example we are doing the following things β"
},
{
"code": null,
"e": 7731,
"s": 7651,
"text": "Creating a class called Person. This class has one instance member called name."
},
{
"code": null,
"e": 7811,
"s": 7731,
"text": "Creating a class called Person. This class has one instance member called name."
},
{
"code": null,
"e": 7989,
"s": 7811,
"text": "Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class."
},
{
"code": null,
"e": 8167,
"s": 7989,
"text": "Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class."
},
{
"code": null,
"e": 8244,
"s": 8167,
"text": "In the Student class constructor, we are calling the base class constructor."
},
{
"code": null,
"e": 8321,
"s": 8244,
"text": "In the Student class constructor, we are calling the base class constructor."
},
{
"code": null,
"e": 8412,
"s": 8321,
"text": "In our Student class, we are adding 2 additional instance members of StudentID and Marks1."
},
{
"code": null,
"e": 8503,
"s": 8412,
"text": "In our Student class, we are adding 2 additional instance members of StudentID and Marks1."
},
{
"code": null,
"e": 8877,
"s": 8503,
"text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n\t\t\n st.Marks1 = 10;\n st.name = \"Joe\";\n\t\t\n println(st.name);\n }\n} \n\nclass Person {\n public String name;\n public Person() {} \n} \n\nclass Student extends Person {\n int StudentID\n int Marks1;\n\t\n public Student() {\n super();\n } \n} "
},
{
"code": null,
"e": 8943,
"s": 8877,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 8948,
"s": 8943,
"text": "Joe\n"
},
{
"code": null,
"e": 9234,
"s": 8948,
"text": "Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes."
},
{
"code": null,
"e": 9348,
"s": 9234,
"text": "Following is an example of an Outer and Inner class. In the following example we are doing the following things β"
},
{
"code": null,
"e": 9410,
"s": 9348,
"text": "Creating an class called Outer which will be our outer class."
},
{
"code": null,
"e": 9460,
"s": 9410,
"text": "Defining a string called name in our Outer class."
},
{
"code": null,
"e": 9521,
"s": 9460,
"text": "Creating an Inner or nested class inside of our Outer class."
},
{
"code": null,
"e": 9625,
"s": 9521,
"text": "Note that in the inner class we are able to access the name instance member defined in the Outer class."
},
{
"code": null,
"e": 9970,
"s": 9625,
"text": "class Example { \n static void main(String[] args) { \n Outer outobj = new Outer(); \n outobj.name = \"Joe\"; \n outobj.callInnerMethod() \n } \n} \n\nclass Outer { \n String name;\n\t\n def callInnerMethod() { \n new Inner().methodA() \n } \n\t\n class Inner {\n def methodA() { \n println(name); \n } \n } \n\t\n} "
},
{
"code": null,
"e": 10036,
"s": 9970,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 10041,
"s": 10036,
"text": "Joe\n"
},
{
"code": null,
"e": 10439,
"s": 10041,
"text": "Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses. Abstract classes must be declared with abstract keyword. Abstract methods must also be declared with abstract keyword."
},
{
"code": null,
"e": 10749,
"s": 10439,
"text": "In the following example, note that the Person class is now made into an abstract class and cannot be instantiated. Also note that there is an abstract method called DisplayMarks in the abstract class which has no implementation details. In the student class it is mandatory to add the implementation details."
},
{
"code": null,
"e": 11269,
"s": 10749,
"text": "class Example { \n static void main(String[] args) { \n Student st = new Student(); \n st.StudentID = 1;\n\t\t\n st.Marks1 = 10; \n st.name=\"Joe\"; \n\t\t\n println(st.name); \n println(st.DisplayMarks()); \n } \n} \n\nabstract class Person { \n public String name; \n public Person() { } \n abstract void DisplayMarks();\n}\n \nclass Student extends Person { \n int StudentID \n int Marks1; \n\t\n public Student() { \n super(); \n } \n\t\n void DisplayMarks() { \n println(Marks1); \n } \n} "
},
{
"code": null,
"e": 11335,
"s": 11269,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 11350,
"s": 11335,
"text": "Joe \n10 \nnull\n"
},
{
"code": null,
"e": 11754,
"s": 11350,
"text": "An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the methods implementation. An interface needs to be declared using the interface keyword. An interface only defines method signatures. Methods of an interface are always public. It is an error to use protected or private methods in interfaces."
},
{
"code": null,
"e": 11866,
"s": 11754,
"text": "Following is an example of an interface in groovy. In the following example we are doing the following things β"
},
{
"code": null,
"e": 11955,
"s": 11866,
"text": "Creating an interface called Marks and creating an interface method called DisplayMarks."
},
{
"code": null,
"e": 12044,
"s": 11955,
"text": "Creating an interface called Marks and creating an interface method called DisplayMarks."
},
{
"code": null,
"e": 12133,
"s": 12044,
"text": "In the class definition, we are using the implements keyword to implement the interface."
},
{
"code": null,
"e": 12222,
"s": 12133,
"text": "In the class definition, we are using the implements keyword to implement the interface."
},
{
"code": null,
"e": 12331,
"s": 12222,
"text": "Because we are implementing the interface we have to provide the implementation for the DisplayMarks method."
},
{
"code": null,
"e": 12440,
"s": 12331,
"text": "Because we are implementing the interface we have to provide the implementation for the DisplayMarks method."
},
{
"code": null,
"e": 12787,
"s": 12440,
"text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.Marks1 = 10;\n println(st.DisplayMarks());\n } \n} \n\ninterface Marks { \n void DisplayMarks(); \n} \n\nclass Student implements Marks {\n int StudentID\n int Marks1;\n\t\n void DisplayMarks() {\n println(Marks1);\n }\n}"
},
{
"code": null,
"e": 12853,
"s": 12787,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 12862,
"s": 12853,
"text": "10\nnull\n"
},
{
"code": null,
"e": 12895,
"s": 12862,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 12913,
"s": 12895,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 12948,
"s": 12913,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12966,
"s": 12948,
"text": " Packt Publishing"
},
{
"code": null,
"e": 12973,
"s": 12966,
"text": " Print"
},
{
"code": null,
"e": 12984,
"s": 12973,
"text": " Add Notes"
}
] |
Enum in a class in Java
|
Yes, we can create Enum in a class in Java.
Set the enum inside the class. Here, we have an Enum with four constants β
enum Devices {
LAPTOP, MOBILE, TABLET, DESKTOP;
}
Now, create objects inside the main() method β
Devices d = Devices.MOBILE;
System.out.println(d);
d = Devices.DESKTOP;
System.out.println(d);
The following is the complete example β
Live Demo
public class Demo {
enum Devices {
LAPTOP, MOBILE, TABLET, DESKTOP;
}
public static void main(String[] args) {
Devices d = Devices.MOBILE;
System.out.println(d);
d = Devices.DESKTOP;
System.out.println(d);
d = Devices.TABLET;
System.out.println(d);
}
}
MOBILE
DESKTOP
TABLET
|
[
{
"code": null,
"e": 1106,
"s": 1062,
"text": "Yes, we can create Enum in a class in Java."
},
{
"code": null,
"e": 1181,
"s": 1106,
"text": "Set the enum inside the class. Here, we have an Enum with four constants β"
},
{
"code": null,
"e": 1231,
"s": 1181,
"text": "enum Devices {\nLAPTOP, MOBILE, TABLET, DESKTOP;\n}"
},
{
"code": null,
"e": 1278,
"s": 1231,
"text": "Now, create objects inside the main() method β"
},
{
"code": null,
"e": 1373,
"s": 1278,
"text": "Devices d = Devices.MOBILE;\nSystem.out.println(d);\nd = Devices.DESKTOP;\nSystem.out.println(d);"
},
{
"code": null,
"e": 1413,
"s": 1373,
"text": "The following is the complete example β"
},
{
"code": null,
"e": 1424,
"s": 1413,
"text": " Live Demo"
},
{
"code": null,
"e": 1731,
"s": 1424,
"text": "public class Demo {\n enum Devices {\n LAPTOP, MOBILE, TABLET, DESKTOP;\n }\n public static void main(String[] args) {\n Devices d = Devices.MOBILE;\n System.out.println(d);\n d = Devices.DESKTOP;\n System.out.println(d);\n d = Devices.TABLET;\n System.out.println(d);\n }\n}"
},
{
"code": null,
"e": 1753,
"s": 1731,
"text": "MOBILE\nDESKTOP\nTABLET"
}
] |
Distributed Data Pre-processing using Dask, Amazon ECS and Python (Part 2) | by Will Badr | Towards Data Science
|
In Part 1 of this series, I explained how to build a serverless cluster of Dask scheduler and workers on AWS Fargate. Scaling the number of workers up and down is quite simple. You can achieve that by running the below AWS CLI commands:
bash~# aws ecs update-service β service Dask-Workers β desired-count 10 β cluster Fargate-Dask-Cluster > /dev/nullbash~# aws ecs update-service β service Dask-Scheduler β desired-count 1 β cluster Fargate-Dask-Cluster > /dev/null
Now that I scaled up the serverless Fargate cluster, letβs try some exploratory data analysis (EDA). I am using the famous NY Yellow Taxi 2017 Dataset.
First, letβs load our dataframe into the cluster memory. To do so, simply import the dataframe class from the dask library then load the files using read_csv() function:
The client.persist() function works by persisting the data into memory asynchronously then it returns right away. It will submit the task graphs to the cluster and return a Future object. We can then run fast queries on the output dataframe. Letβs run some analytics:
Letβs get some descriptive statistics on the dataframe. The code should look exactly the same except that with Dask dataframes, you need to add a compute() function in order to get the results right away on the notebook. As you can see, it took about 7 seconds to do some complex computations on the dataframe such as: (Calculate quantiles, mean, count, min, max and standard deviation).
It took about 5.5 seconds to finish this groupby() statement. As you can see, vendor 2 did much more trips that vendor 1 and drove a lot more distance.
No missing values in the dataset.
There are some clear correlations like the high positive correlation between fare_amount and trip_distance, tip_amount and fare_amount. I will need to remove the highly correlated feature (total_amount) in order to avoid some problems like Multicollinearity problems.
Letβs try 1.2 again but this time, I will persist the data in memory and will let it work in the background while I do some other tasks. I will also print out the progress bar to see when the task is finished.
Notice that the prompt returns right away as the data is being loaded/computed in the background using the cluster workers.
When the progress bar is finished (all green), you can query the output of the data quickly. Notice that the prompt returns right away as the data is being loaded/computed in the background using the cluster workers.
One of the most computationally expensive tasks in machine learning is the hyperparameters optimization (HPO). HPO is a technique that is used to tune the ML parameters that are not learned during the training process such as learning rate, optimizer, regularization or number of hidden layers in a neural network. It works by exploring the search space of a pre-defined range for each of the hyperparameters you are going to tune. There are many libraries and techniques to carry out the HPO process but in this article, I will focus on tuning the hyperparameters using GridSearch technique and Scikit-Learn library in Python.
The Grid Search technique is an exhaustive searching bymanually specifying a subset of the hyperparameter space of a learning algorithm. The algorithm will then go through each and every combination of the hyperparameters aiming at (maximizing/minimizing) the objective metrics (Accuracy/Loss). It will end up giving the best results but the more hyperparameters you tune, the more complex the tuning process will get.
Since the HPO process is computationally expensive, we will run it on a Dask Cluster in order to take advantage of the scale and elasticity. Scikit-learn uses a very powerful library called joblib to parallelize processes across multiple CPU cores.
Joblib also provides an interface for other parallel systems to become an execution engine. We can achieve this by usingparallel_backend context manager to run with thousands of cores in a cluster:
First, we need to import joblib from sklearn externals then register Dask Distributed as a parallel backend engine for joblib.
from sklearn.externals.joblib import _dask, parallel_backendfrom sklearn.utils import register_parallel_backendfrom sklearn.externals.joblib import parallel_backendregister_parallel_backend('distributed',_dask.DaskDistributedBackend)
Then, we need to run the following line to start using the cluster as an execution engine:
with parallel_backend('distributed', scheduler_host='dask-Scheduler.local-dask:8786'): <Normal sklearn Code>
Then your sklearn code logic stays exactly the same with no changes.
Here is the full code for using GridSearch HPO to find the best hyperparameters for a Random Forest Classifier that will classify the handwritten digits from the MNIST dataset:
from sklearn import datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.model_selection import GridSearchCVfrom sklearn.ensemble import RandomForestClassifierimport numpy as npfrom time import timefrom sklearn.externals.joblib import _dask, parallel_backendfrom sklearn.utils import register_parallel_backendregister_parallel_backend('distributed', _dask.DaskDistributedBackend)# Loading the Digits datasetdigits = datasets.load_digits()# To apply an classifier on this data, we need to flatten the image, to# turn the data in a (samples, feature) matrix:n_samples = len(digits.images)X = digits.images.reshape((n_samples, -1))y = digits.target# Split the dataset in two equal partsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)clf = RandomForestClassifier(n_estimators=20)# use a full grid over all parametersparam_grid = {"max_depth": [3,4,5,6, None], "max_features": [1, 3, 10, None], "min_samples_split": [2, 3, 10], "bootstrap": [True, False], "criterion": ["gini", "entropy"]}# run grid searchgrid_search = GridSearchCV(clf, param_grid=param_grid, cv=8, iid=True)start = time()with parallel_backend('distributed', scheduler_host='dask-Scheduler.local-dask:8786'): grid_search.fit(X, y) clf.fit(X, y)print("GridSearchCV took %.2f seconds for %d candidate parameter settings." % (time() - start, len(grid_search.cv_results_['params'])))results = grid_search.cv_results_ # Return the index of the best validation scoreidx = np.flatnonzero(results['rank_test_score'] == 1 )print("The best score is: " + str(results['mean_test_score'][idx[0]])) #print the parameters for the best job print("Parameters: {0}".format(results['params'][idx[0]]))
It took about 40 seconds on a 10 nodes cluster to find the best combination of hyperparameters for the classifier, whereas on a single machine, (even with multiple cores/ multiple CPUs), it would take many minutes without the parallelization feature.
From my experience using Dask, it is a great library to preprocess large datasets in a distributed fashion. If you are a fan of Pandas and Numpy and have trouble fitting your data into memory then Dask should definitely be the way to go. It is absolutely a great solution when it comes to time and cost sensitive machine learning tasks such as HPO, data imputation, data preprocessing and exploratory analysis.
|
[
{
"code": null,
"e": 408,
"s": 171,
"text": "In Part 1 of this series, I explained how to build a serverless cluster of Dask scheduler and workers on AWS Fargate. Scaling the number of workers up and down is quite simple. You can achieve that by running the below AWS CLI commands:"
},
{
"code": null,
"e": 638,
"s": 408,
"text": "bash~# aws ecs update-service β service Dask-Workers β desired-count 10 β cluster Fargate-Dask-Cluster > /dev/nullbash~# aws ecs update-service β service Dask-Scheduler β desired-count 1 β cluster Fargate-Dask-Cluster > /dev/null"
},
{
"code": null,
"e": 790,
"s": 638,
"text": "Now that I scaled up the serverless Fargate cluster, letβs try some exploratory data analysis (EDA). I am using the famous NY Yellow Taxi 2017 Dataset."
},
{
"code": null,
"e": 960,
"s": 790,
"text": "First, letβs load our dataframe into the cluster memory. To do so, simply import the dataframe class from the dask library then load the files using read_csv() function:"
},
{
"code": null,
"e": 1228,
"s": 960,
"text": "The client.persist() function works by persisting the data into memory asynchronously then it returns right away. It will submit the task graphs to the cluster and return a Future object. We can then run fast queries on the output dataframe. Letβs run some analytics:"
},
{
"code": null,
"e": 1616,
"s": 1228,
"text": "Letβs get some descriptive statistics on the dataframe. The code should look exactly the same except that with Dask dataframes, you need to add a compute() function in order to get the results right away on the notebook. As you can see, it took about 7 seconds to do some complex computations on the dataframe such as: (Calculate quantiles, mean, count, min, max and standard deviation)."
},
{
"code": null,
"e": 1768,
"s": 1616,
"text": "It took about 5.5 seconds to finish this groupby() statement. As you can see, vendor 2 did much more trips that vendor 1 and drove a lot more distance."
},
{
"code": null,
"e": 1802,
"s": 1768,
"text": "No missing values in the dataset."
},
{
"code": null,
"e": 2070,
"s": 1802,
"text": "There are some clear correlations like the high positive correlation between fare_amount and trip_distance, tip_amount and fare_amount. I will need to remove the highly correlated feature (total_amount) in order to avoid some problems like Multicollinearity problems."
},
{
"code": null,
"e": 2280,
"s": 2070,
"text": "Letβs try 1.2 again but this time, I will persist the data in memory and will let it work in the background while I do some other tasks. I will also print out the progress bar to see when the task is finished."
},
{
"code": null,
"e": 2404,
"s": 2280,
"text": "Notice that the prompt returns right away as the data is being loaded/computed in the background using the cluster workers."
},
{
"code": null,
"e": 2621,
"s": 2404,
"text": "When the progress bar is finished (all green), you can query the output of the data quickly. Notice that the prompt returns right away as the data is being loaded/computed in the background using the cluster workers."
},
{
"code": null,
"e": 3249,
"s": 2621,
"text": "One of the most computationally expensive tasks in machine learning is the hyperparameters optimization (HPO). HPO is a technique that is used to tune the ML parameters that are not learned during the training process such as learning rate, optimizer, regularization or number of hidden layers in a neural network. It works by exploring the search space of a pre-defined range for each of the hyperparameters you are going to tune. There are many libraries and techniques to carry out the HPO process but in this article, I will focus on tuning the hyperparameters using GridSearch technique and Scikit-Learn library in Python."
},
{
"code": null,
"e": 3668,
"s": 3249,
"text": "The Grid Search technique is an exhaustive searching bymanually specifying a subset of the hyperparameter space of a learning algorithm. The algorithm will then go through each and every combination of the hyperparameters aiming at (maximizing/minimizing) the objective metrics (Accuracy/Loss). It will end up giving the best results but the more hyperparameters you tune, the more complex the tuning process will get."
},
{
"code": null,
"e": 3917,
"s": 3668,
"text": "Since the HPO process is computationally expensive, we will run it on a Dask Cluster in order to take advantage of the scale and elasticity. Scikit-learn uses a very powerful library called joblib to parallelize processes across multiple CPU cores."
},
{
"code": null,
"e": 4115,
"s": 3917,
"text": "Joblib also provides an interface for other parallel systems to become an execution engine. We can achieve this by usingparallel_backend context manager to run with thousands of cores in a cluster:"
},
{
"code": null,
"e": 4242,
"s": 4115,
"text": "First, we need to import joblib from sklearn externals then register Dask Distributed as a parallel backend engine for joblib."
},
{
"code": null,
"e": 4476,
"s": 4242,
"text": "from sklearn.externals.joblib import _dask, parallel_backendfrom sklearn.utils import register_parallel_backendfrom sklearn.externals.joblib import parallel_backendregister_parallel_backend('distributed',_dask.DaskDistributedBackend)"
},
{
"code": null,
"e": 4567,
"s": 4476,
"text": "Then, we need to run the following line to start using the cluster as an execution engine:"
},
{
"code": null,
"e": 4680,
"s": 4567,
"text": "with parallel_backend('distributed', scheduler_host='dask-Scheduler.local-dask:8786'): <Normal sklearn Code>"
},
{
"code": null,
"e": 4749,
"s": 4680,
"text": "Then your sklearn code logic stays exactly the same with no changes."
},
{
"code": null,
"e": 4926,
"s": 4749,
"text": "Here is the full code for using GridSearch HPO to find the best hyperparameters for a Random Forest Classifier that will classify the handwritten digits from the MNIST dataset:"
},
{
"code": null,
"e": 6724,
"s": 4926,
"text": "from sklearn import datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.model_selection import GridSearchCVfrom sklearn.ensemble import RandomForestClassifierimport numpy as npfrom time import timefrom sklearn.externals.joblib import _dask, parallel_backendfrom sklearn.utils import register_parallel_backendregister_parallel_backend('distributed', _dask.DaskDistributedBackend)# Loading the Digits datasetdigits = datasets.load_digits()# To apply an classifier on this data, we need to flatten the image, to# turn the data in a (samples, feature) matrix:n_samples = len(digits.images)X = digits.images.reshape((n_samples, -1))y = digits.target# Split the dataset in two equal partsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)clf = RandomForestClassifier(n_estimators=20)# use a full grid over all parametersparam_grid = {\"max_depth\": [3,4,5,6, None], \"max_features\": [1, 3, 10, None], \"min_samples_split\": [2, 3, 10], \"bootstrap\": [True, False], \"criterion\": [\"gini\", \"entropy\"]}# run grid searchgrid_search = GridSearchCV(clf, param_grid=param_grid, cv=8, iid=True)start = time()with parallel_backend('distributed', scheduler_host='dask-Scheduler.local-dask:8786'): grid_search.fit(X, y) clf.fit(X, y)print(\"GridSearchCV took %.2f seconds for %d candidate parameter settings.\" % (time() - start, len(grid_search.cv_results_['params'])))results = grid_search.cv_results_ # Return the index of the best validation scoreidx = np.flatnonzero(results['rank_test_score'] == 1 )print(\"The best score is: \" + str(results['mean_test_score'][idx[0]])) #print the parameters for the best job print(\"Parameters: {0}\".format(results['params'][idx[0]]))"
},
{
"code": null,
"e": 6975,
"s": 6724,
"text": "It took about 40 seconds on a 10 nodes cluster to find the best combination of hyperparameters for the classifier, whereas on a single machine, (even with multiple cores/ multiple CPUs), it would take many minutes without the parallelization feature."
}
] |
Ext.js - Themes
|
Ext.js provides a number of themes to be used in your applications. You can add a different theme in place of a classic theme and see the difference in the output. This is done simply by replacing the theme CSS file as explained ahead.
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Neptune theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result β
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Neptune theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result β
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Triton theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result β
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Gray theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result β
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2259,
"s": 2023,
"text": "Ext.js provides a number of themes to be used in your applications. You can add a different theme in place of a classic theme and see the difference in the output. This is done simply by replacing the theme CSS file as explained ahead."
},
{
"code": null,
"e": 2356,
"s": 2259,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 2462,
"s": 2356,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 2510,
"s": 2462,
"text": "Add the following CSS to use the Neptune theme."
},
{
"code": null,
"e": 2616,
"s": 2510,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\n"
},
{
"code": null,
"e": 2662,
"s": 2616,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 3419,
"s": 2662,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 3473,
"s": 3419,
"text": "The above program will produce the following result β"
},
{
"code": null,
"e": 3570,
"s": 3473,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 3676,
"s": 3570,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 3724,
"s": 3676,
"text": "Add the following CSS to use the Neptune theme."
},
{
"code": null,
"e": 3826,
"s": 3724,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css\n"
},
{
"code": null,
"e": 3872,
"s": 3826,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 4618,
"s": 3872,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 4672,
"s": 4618,
"text": "The above program will produce the following result β"
},
{
"code": null,
"e": 4769,
"s": 4672,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 4875,
"s": 4769,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 4922,
"s": 4875,
"text": "Add the following CSS to use the Triton theme."
},
{
"code": null,
"e": 5026,
"s": 4922,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css\n"
},
{
"code": null,
"e": 5072,
"s": 5026,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 5827,
"s": 5072,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 5881,
"s": 5827,
"text": "The above program will produce the following result β"
},
{
"code": null,
"e": 5978,
"s": 5881,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 6084,
"s": 5978,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 6129,
"s": 6084,
"text": "Add the following CSS to use the Gray theme."
},
{
"code": null,
"e": 6229,
"s": 6129,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css\n"
},
{
"code": null,
"e": 6275,
"s": 6229,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 7026,
"s": 6275,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 7080,
"s": 7026,
"text": "The above program will produce the following result β"
},
{
"code": null,
"e": 7087,
"s": 7080,
"text": " Print"
},
{
"code": null,
"e": 7098,
"s": 7087,
"text": " Add Notes"
}
] |
C++ Map Library - ~map() Function
|
The C++ destructor std::map::~map() destroys map object by deallocating it's memory.
Following is the declaration for std::map::~map() function form std::map header.
~map();
None
Destructor never returns value.
This member function never throws exception.
Linear i.e. O(n)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2688,
"s": 2603,
"text": "The C++ destructor std::map::~map() destroys map object by deallocating it's memory."
},
{
"code": null,
"e": 2769,
"s": 2688,
"text": "Following is the declaration for std::map::~map() function form std::map header."
},
{
"code": null,
"e": 2778,
"s": 2769,
"text": "~map();\n"
},
{
"code": null,
"e": 2783,
"s": 2778,
"text": "None"
},
{
"code": null,
"e": 2815,
"s": 2783,
"text": "Destructor never returns value."
},
{
"code": null,
"e": 2860,
"s": 2815,
"text": "This member function never throws exception."
},
{
"code": null,
"e": 2877,
"s": 2860,
"text": "Linear i.e. O(n)"
},
{
"code": null,
"e": 2884,
"s": 2877,
"text": " Print"
},
{
"code": null,
"e": 2895,
"s": 2884,
"text": " Add Notes"
}
] |
chr () in Python
|
This function return the string representing a character whose Unicode code point is the integer supplied as parameter to this function. For example, chr(65) returns the string 'A', while chr(126) returns the string '~'.
The syntax of the function is as below.
chr(n) where n is an integer value
The below program shows how the chr() is used. We supply various integer values as parameter and get back the respective characters.
Live Demo
# Printing the strings from chr() function
print(chr(84),chr(85),chr(84),chr(79),chr(82))
Running the above code gives us the following result β
T U T O R
We can take help of python data structures like lists to loop through a series of numbers and apply char function to create a required string. In the below example we see that we have used a list to
Live Demo
str = ""
series = [84,85,84,79,82,73,65,76,83]
for i in range(0,len(series)):
char = chr(series[i])
str = str + char
i=i+1
print(str)
Running the above code gives us the following result β
TUTORIALS
|
[
{
"code": null,
"e": 1283,
"s": 1062,
"text": "This function return the string representing a character whose Unicode code point is the integer supplied as parameter to this function. For example, chr(65) returns the string 'A', while chr(126) returns the string '~'."
},
{
"code": null,
"e": 1323,
"s": 1283,
"text": "The syntax of the function is as below."
},
{
"code": null,
"e": 1358,
"s": 1323,
"text": "chr(n) where n is an integer value"
},
{
"code": null,
"e": 1491,
"s": 1358,
"text": "The below program shows how the chr() is used. We supply various integer values as parameter and get back the respective characters."
},
{
"code": null,
"e": 1502,
"s": 1491,
"text": " Live Demo"
},
{
"code": null,
"e": 1592,
"s": 1502,
"text": "# Printing the strings from chr() function\nprint(chr(84),chr(85),chr(84),chr(79),chr(82))"
},
{
"code": null,
"e": 1647,
"s": 1592,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 1657,
"s": 1647,
"text": "T U T O R"
},
{
"code": null,
"e": 1856,
"s": 1657,
"text": "We can take help of python data structures like lists to loop through a series of numbers and apply char function to create a required string. In the below example we see that we have used a list to"
},
{
"code": null,
"e": 1867,
"s": 1856,
"text": " Live Demo"
},
{
"code": null,
"e": 2010,
"s": 1867,
"text": "str = \"\"\nseries = [84,85,84,79,82,73,65,76,83]\nfor i in range(0,len(series)):\n char = chr(series[i])\n str = str + char\n i=i+1\nprint(str)"
},
{
"code": null,
"e": 2065,
"s": 2010,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 2075,
"s": 2065,
"text": "TUTORIALS"
}
] |
How to limit Database Resources per Session in Oracle?
|
Problem:
You want to limit the amount of resources a user can consume in your database.
Solution
To limit the resources, we can follow below steps.
We can use below SQL statement to view the current setting of RESOURCE_LIMIT in our database.
select name, value from v$parameter where name='resource_limit';
Create a profile to limit the resources and assign it to a user. It wonβt limit the CPU utilization though.
CREATE PROFILE test_profile LIMIT
SESSIONS_PER_USER 2
CPU_PER_SESSION UNLIMITED
CPU_PER_CALL 300000
CONNECT_TIME 45
IDLE_TIME 15
LOGICAL_READS_PER_SESSION DEFAULT
LOGICAL_READS_PER_CALL 1000
PRIVATE_SGA 15K
FAILED_LOGIN_ATTEMPTS 5
PASSWORD_LIFE_TIME 60
PASSWORD_GRACE_TIME 10
PASSWORD_LOCK_TIME 1
PASSWORD_REUSE_TIME 10
PASSWORD_REUSE_MAX 1 ;
CREATE PROFILE test_profile LIMIT
SESSIONS_PER_USER 2
CPU_PER_SESSION UNLIMITED
CPU_PER_CALL 300000
CONNECT_TIME 45
IDLE_TIME 15
LOGICAL_READS_PER_SESSION DEFAULT
LOGICAL_READS_PER_CALL 1000
PRIVATE_SGA 15K
FAILED_LOGIN_ATTEMPTS 5
PASSWORD_LIFE_TIME 60
PASSWORD_GRACE_TIME 10
PASSWORD_LOCK_TIME 1
PASSWORD_REUSE_TIME 10
PASSWORD_REUSE_MAX 1 ;
SESSIONS_PER_USER -- Specify the number of concurrent sessions to which you want to limit the user.
CPU_PER_SESSION -- Specify the CPU time limit for a session, expressed in hundredth of seconds.
CPU_PER_CALL -- Specify the CPU time limit for a call (a parse, execute, or fetch), expressed in hundredths of seconds. Need to increase this or not required to mention
CONNECT_TIME -- Specify the total elapsed time limit for a session, expressed in minutes.
IDLE_TIME -- Specify the permitted periods of continuous inactive time during a session, expressed in minutes. Long-running queries and other operations are not subject to this limit.
LOGICAL_READS_PER_SESSION -- Specify the permitted number of data blocks read in a session, including blocks read from memory and disk.
PRIVATE_SGA -- Specify the amount of private space a session can allocate in the shared pool of the system global area (SGA). Please refer to size_clause for information on that clause.
FAILED_LOGIN_ATTEMPTS -- Specify the number of failed attempts to log in to the user account before the account is locked
PASSWORD_LIFE_TIME -- Specify the number of days the same password can be used for authentication.
PASSWORD_GRACE_TIME -- Specify the number of days after the grace period begins during which a warning is issued and login is allowed. If the password is not changed during the grace period, the password expires.
PASSWORD_LOCK_TIME -- Specify the number of days an account will be locked after the specified number of consecutive failed login attempts.
PASSWORD_REUSE_TIME --specifies the number of days before which a password cannot be reused.
PASSWORD_REUSE_MAX --specifies the number of password changes required before the current password can be reused
SESSIONS_PER_USER -- Specify the number of concurrent sessions to which you want to limit the user.
CPU_PER_SESSION -- Specify the CPU time limit for a session, expressed in hundredth of seconds.
CPU_PER_CALL -- Specify the CPU time limit for a call (a parse, execute, or fetch), expressed in hundredths of seconds. Need to increase this or not required to mention
CONNECT_TIME -- Specify the total elapsed time limit for a session, expressed in minutes.
IDLE_TIME -- Specify the permitted periods of continuous inactive time during a session, expressed in minutes. Long-running queries and other operations are not subject to this limit.
LOGICAL_READS_PER_SESSION -- Specify the permitted number of data blocks read in a session, including blocks read from memory and disk.
PRIVATE_SGA -- Specify the amount of private space a session can allocate in the shared pool of the system global area (SGA). Please refer to size_clause for information on that clause.
FAILED_LOGIN_ATTEMPTS -- Specify the number of failed attempts to log in to the user account before the account is locked
PASSWORD_LIFE_TIME -- Specify the number of days the same password can be used for authentication.
PASSWORD_GRACE_TIME -- Specify the number of days after the grace period begins during which a warning is issued and login is allowed. If the password is not changed during the grace period, the password expires.
PASSWORD_LOCK_TIME -- Specify the number of days an account will be locked after the specified number of consecutive failed login attempts.
PASSWORD_REUSE_TIME --specifies the number of days before which a password cannot be reused.
PASSWORD_REUSE_MAX --specifies the number of password changes required before the current password can be reused
When execute the test_profile would be have been created.
Once the profile is created, we can now assign it to a user. In the next example, user test is assigned the test_profile:
alter user test profile test_profile;
alter user test profile test_profile;
Oracle database profiles are used for couple of reasons, Setting resource limits and Enforcing password security settings.
When creating a user, if no profile is specified, the DEFAULT profile is assigned to the newly created user. We can modify a profile with the ALTER PROFILE statement. We can override the DEFAULT profile to limit the CPU_PER_SESSION to 360000 (in hundredths of seconds).
alter profile default limit cpu_per_session 360000;
alter profile default limit cpu_per_session 360000;
A profile is also used to enforce password security settings, For example, say you wanted to alter the DEFAULT profile so that there was a cap on the maximum number of days a password can be used. This next line of code sets the PASSWORD_LIFE_TIME of the DEFAULT profile to 90 days.
alter profile default limit password_life_time 90;
alter profile default limit password_life_time 90;
The PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX settings must be used in conjunction. If you specify an integer for one parameter and then UNLIMITED for the other parameter, the current password can never be reused.
If you want to specify that the DEFAULT profile password has to be changed 10 times within 100 days before it can be reused, use a line of code similar to this:
alter profile default limit password_reuse_time 100 password_reuse_max 10;
alter profile default limit password_reuse_time 100 password_reuse_max 10;
|
[
{
"code": null,
"e": 1071,
"s": 1062,
"text": "Problem:"
},
{
"code": null,
"e": 1150,
"s": 1071,
"text": "You want to limit the amount of resources a user can consume in your database."
},
{
"code": null,
"e": 1159,
"s": 1150,
"text": "Solution"
},
{
"code": null,
"e": 1210,
"s": 1159,
"text": "To limit the resources, we can follow below steps."
},
{
"code": null,
"e": 1304,
"s": 1210,
"text": "We can use below SQL statement to view the current setting of RESOURCE_LIMIT in our database."
},
{
"code": null,
"e": 1369,
"s": 1304,
"text": "select name, value from v$parameter where name='resource_limit';"
},
{
"code": null,
"e": 1477,
"s": 1369,
"text": "Create a profile to limit the resources and assign it to a user. It wonβt limit the CPU utilization though."
},
{
"code": null,
"e": 1999,
"s": 1477,
"text": "CREATE PROFILE test_profile LIMIT\n SESSIONS_PER_USER 2 \n CPU_PER_SESSION UNLIMITED \n CPU_PER_CALL 300000\n CONNECT_TIME 45 \n IDLE_TIME 15 \n LOGICAL_READS_PER_SESSION DEFAULT \n LOGICAL_READS_PER_CALL 1000\n PRIVATE_SGA 15K \n FAILED_LOGIN_ATTEMPTS 5 \n PASSWORD_LIFE_TIME 60 \n PASSWORD_GRACE_TIME 10 \n PASSWORD_LOCK_TIME 1\n PASSWORD_REUSE_TIME 10\n PASSWORD_REUSE_MAX 1 ;"
},
{
"code": null,
"e": 2521,
"s": 1999,
"text": "CREATE PROFILE test_profile LIMIT\n SESSIONS_PER_USER 2 \n CPU_PER_SESSION UNLIMITED \n CPU_PER_CALL 300000\n CONNECT_TIME 45 \n IDLE_TIME 15 \n LOGICAL_READS_PER_SESSION DEFAULT \n LOGICAL_READS_PER_CALL 1000\n PRIVATE_SGA 15K \n FAILED_LOGIN_ATTEMPTS 5 \n PASSWORD_LIFE_TIME 60 \n PASSWORD_GRACE_TIME 10 \n PASSWORD_LOCK_TIME 1\n PASSWORD_REUSE_TIME 10\n PASSWORD_REUSE_MAX 1 ;"
},
{
"code": null,
"e": 4363,
"s": 2521,
"text": "SESSIONS_PER_USER -- Specify the number of concurrent sessions to which you want to limit the user.\nCPU_PER_SESSION -- Specify the CPU time limit for a session, expressed in hundredth of seconds.\nCPU_PER_CALL -- Specify the CPU time limit for a call (a parse, execute, or fetch), expressed in hundredths of seconds. Need to increase this or not required to mention\nCONNECT_TIME -- Specify the total elapsed time limit for a session, expressed in minutes.\nIDLE_TIME -- Specify the permitted periods of continuous inactive time during a session, expressed in minutes. Long-running queries and other operations are not subject to this limit.\nLOGICAL_READS_PER_SESSION -- Specify the permitted number of data blocks read in a session, including blocks read from memory and disk.\nPRIVATE_SGA -- Specify the amount of private space a session can allocate in the shared pool of the system global area (SGA). Please refer to size_clause for information on that clause.\nFAILED_LOGIN_ATTEMPTS -- Specify the number of failed attempts to log in to the user account before the account is locked\nPASSWORD_LIFE_TIME -- Specify the number of days the same password can be used for authentication.\nPASSWORD_GRACE_TIME -- Specify the number of days after the grace period begins during which a warning is issued and login is allowed. If the password is not changed during the grace period, the password expires. \nPASSWORD_LOCK_TIME -- Specify the number of days an account will be locked after the specified number of consecutive failed login attempts. \nPASSWORD_REUSE_TIME --specifies the number of days before which a password cannot be reused.\nPASSWORD_REUSE_MAX --specifies the number of password changes required before the current password can be reused"
},
{
"code": null,
"e": 6205,
"s": 4363,
"text": "SESSIONS_PER_USER -- Specify the number of concurrent sessions to which you want to limit the user.\nCPU_PER_SESSION -- Specify the CPU time limit for a session, expressed in hundredth of seconds.\nCPU_PER_CALL -- Specify the CPU time limit for a call (a parse, execute, or fetch), expressed in hundredths of seconds. Need to increase this or not required to mention\nCONNECT_TIME -- Specify the total elapsed time limit for a session, expressed in minutes.\nIDLE_TIME -- Specify the permitted periods of continuous inactive time during a session, expressed in minutes. Long-running queries and other operations are not subject to this limit.\nLOGICAL_READS_PER_SESSION -- Specify the permitted number of data blocks read in a session, including blocks read from memory and disk.\nPRIVATE_SGA -- Specify the amount of private space a session can allocate in the shared pool of the system global area (SGA). Please refer to size_clause for information on that clause.\nFAILED_LOGIN_ATTEMPTS -- Specify the number of failed attempts to log in to the user account before the account is locked\nPASSWORD_LIFE_TIME -- Specify the number of days the same password can be used for authentication.\nPASSWORD_GRACE_TIME -- Specify the number of days after the grace period begins during which a warning is issued and login is allowed. If the password is not changed during the grace period, the password expires. \nPASSWORD_LOCK_TIME -- Specify the number of days an account will be locked after the specified number of consecutive failed login attempts. \nPASSWORD_REUSE_TIME --specifies the number of days before which a password cannot be reused.\nPASSWORD_REUSE_MAX --specifies the number of password changes required before the current password can be reused"
},
{
"code": null,
"e": 6263,
"s": 6205,
"text": "When execute the test_profile would be have been created."
},
{
"code": null,
"e": 6385,
"s": 6263,
"text": "Once the profile is created, we can now assign it to a user. In the next example, user test is assigned the test_profile:"
},
{
"code": null,
"e": 6423,
"s": 6385,
"text": "alter user test profile test_profile;"
},
{
"code": null,
"e": 6461,
"s": 6423,
"text": "alter user test profile test_profile;"
},
{
"code": null,
"e": 6584,
"s": 6461,
"text": "Oracle database profiles are used for couple of reasons, Setting resource limits and Enforcing password security settings."
},
{
"code": null,
"e": 6854,
"s": 6584,
"text": "When creating a user, if no profile is specified, the DEFAULT profile is assigned to the newly created user. We can modify a profile with the ALTER PROFILE statement. We can override the DEFAULT profile to limit the CPU_PER_SESSION to 360000 (in hundredths of seconds)."
},
{
"code": null,
"e": 6906,
"s": 6854,
"text": "alter profile default limit cpu_per_session 360000;"
},
{
"code": null,
"e": 6958,
"s": 6906,
"text": "alter profile default limit cpu_per_session 360000;"
},
{
"code": null,
"e": 7241,
"s": 6958,
"text": "A profile is also used to enforce password security settings, For example, say you wanted to alter the DEFAULT profile so that there was a cap on the maximum number of days a password can be used. This next line of code sets the PASSWORD_LIFE_TIME of the DEFAULT profile to 90 days."
},
{
"code": null,
"e": 7292,
"s": 7241,
"text": "alter profile default limit password_life_time 90;"
},
{
"code": null,
"e": 7343,
"s": 7292,
"text": "alter profile default limit password_life_time 90;"
},
{
"code": null,
"e": 7558,
"s": 7343,
"text": "The PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX settings must be used in conjunction. If you specify an integer for one parameter and then UNLIMITED for the other parameter, the current password can never be reused."
},
{
"code": null,
"e": 7719,
"s": 7558,
"text": "If you want to specify that the DEFAULT profile password has to be changed 10 times within 100 days before it can be reused, use a line of code similar to this:"
},
{
"code": null,
"e": 7794,
"s": 7719,
"text": "alter profile default limit password_reuse_time 100 password_reuse_max 10;"
},
{
"code": null,
"e": 7869,
"s": 7794,
"text": "alter profile default limit password_reuse_time 100 password_reuse_max 10;"
}
] |
Rexx - ADDRESS
|
This method returns the name of the environment in the which the Rexx commands are currently running in.
ADDRESS()
None
This method returns the name of the environment in the which the Rexx commands are currently running in.
/* Main program */
say ADDRESS()
When we run the above program we will get the following result.
bash
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2444,
"s": 2339,
"text": "This method returns the name of the environment in the which the Rexx commands are currently running in."
},
{
"code": null,
"e": 2456,
"s": 2444,
"text": "ADDRESS() \n"
},
{
"code": null,
"e": 2461,
"s": 2456,
"text": "None"
},
{
"code": null,
"e": 2566,
"s": 2461,
"text": "This method returns the name of the environment in the which the Rexx commands are currently running in."
},
{
"code": null,
"e": 2600,
"s": 2566,
"text": "/* Main program */ \nsay ADDRESS()"
},
{
"code": null,
"e": 2664,
"s": 2600,
"text": "When we run the above program we will get the following result."
},
{
"code": null,
"e": 2670,
"s": 2664,
"text": "bash\n"
},
{
"code": null,
"e": 2677,
"s": 2670,
"text": " Print"
},
{
"code": null,
"e": 2688,
"s": 2677,
"text": " Add Notes"
}
] |
std::basic_istream::gcount() in C++ with Examples - GeeksforGeeks
|
21 May, 2020
The std::basic_istream::gcount() is used to count the characters in the given string. It returns the number of characters extracted by the last unformatted input operation. The unformatted input operation is returned by these function: get(), getline(), ignore(), peek(), read(), etc.
Header File:
<iostream>
Syntax:
streamsize gcount() const
Parameter: This method doesnβt accepts any parameter.
Return Value: It returns the number of characters extracted by the last unformatted input operation.
Below is the program to illustrate std::basic_istream::gcount():
Program 1:
// C++ code to illustrate std::gcount() #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Initialise array of characters char arr[20]; // Declare string stream istringstream stream("GeeksforGeeks"); // Read the string in string stream stream.read(arr, sizeof arr); // Print the count of characters in // string "GeeksforGeeks" cout << "The count of characters" << " in the string " << " is " << stream.gcount() << endl; return 0;}
The count of characters in the string is 13
References: http://www.cplusplus.com/reference/istream/basic_istream/gcount/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 25628,
"s": 25343,
"text": "The std::basic_istream::gcount() is used to count the characters in the given string. It returns the number of characters extracted by the last unformatted input operation. The unformatted input operation is returned by these function: get(), getline(), ignore(), peek(), read(), etc."
},
{
"code": null,
"e": 25641,
"s": 25628,
"text": "Header File:"
},
{
"code": null,
"e": 25653,
"s": 25641,
"text": "<iostream>\n"
},
{
"code": null,
"e": 25661,
"s": 25653,
"text": "Syntax:"
},
{
"code": null,
"e": 25688,
"s": 25661,
"text": "streamsize gcount() const\n"
},
{
"code": null,
"e": 25742,
"s": 25688,
"text": "Parameter: This method doesnβt accepts any parameter."
},
{
"code": null,
"e": 25843,
"s": 25742,
"text": "Return Value: It returns the number of characters extracted by the last unformatted input operation."
},
{
"code": null,
"e": 25908,
"s": 25843,
"text": "Below is the program to illustrate std::basic_istream::gcount():"
},
{
"code": null,
"e": 25919,
"s": 25908,
"text": "Program 1:"
},
{
"code": "// C++ code to illustrate std::gcount() #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Initialise array of characters char arr[20]; // Declare string stream istringstream stream(\"GeeksforGeeks\"); // Read the string in string stream stream.read(arr, sizeof arr); // Print the count of characters in // string \"GeeksforGeeks\" cout << \"The count of characters\" << \" in the string \" << \" is \" << stream.gcount() << endl; return 0;}",
"e": 26440,
"s": 25919,
"text": null
},
{
"code": null,
"e": 26486,
"s": 26440,
"text": "The count of characters in the string is 13\n"
},
{
"code": null,
"e": 26563,
"s": 26486,
"text": "References: http://www.cplusplus.com/reference/istream/basic_istream/gcount/"
},
{
"code": null,
"e": 26577,
"s": 26563,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26581,
"s": 26577,
"text": "C++"
},
{
"code": null,
"e": 26585,
"s": 26581,
"text": "CPP"
},
{
"code": null,
"e": 26683,
"s": 26585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26711,
"s": 26683,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26731,
"s": 26711,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26764,
"s": 26731,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26788,
"s": 26764,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26813,
"s": 26788,
"text": "std::string class in C++"
},
{
"code": null,
"e": 26857,
"s": 26813,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26881,
"s": 26857,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 26926,
"s": 26881,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26979,
"s": 26926,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Print the nodes of Binary Tree having a grandchild
|
13 Aug, 2021
Given a Binary Tree, the task is to print the nodes that have grandchildren.
Examples:
Input:
Output: 20 8 Explanation: 20 and 8 are the grandparents of 4, 12 and 10, 14.
Input:
Output: 1 Explanation: 1 is the grandparent of 4, 5.
Approach: The idea uses Recursion. Below are the steps:
Traverse the given tree at every node.Check if each node has grandchildren node or not.For any tree node(say temp) if one of the below node exists then current node is the grandparent node: temp->left->left.temp->left->right.temp->right->left.temp->right->right.If any of the above exist for any node temp then the node temp is the grandparent node.
Traverse the given tree at every node.
Check if each node has grandchildren node or not.
For any tree node(say temp) if one of the below node exists then current node is the grandparent node: temp->left->left.temp->left->right.temp->right->left.temp->right->right.
temp->left->left.
temp->left->right.
temp->right->left.
temp->right->right.
If any of the above exist for any node temp then the node temp is the grandparent node.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct node { struct node *left, *right; int key;}; // Function to create new tree nodenode* newNode(int key){ node* temp = new node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Function to print the nodes of// the Binary Tree having a grandchildvoid cal(struct node* root){ // Base case to check // if the tree exists if (root == NULL) return; else { // Check if there is a left and // right child of the curr node if (root->left != NULL && root->right != NULL) { // Check for grandchildren if (root->left->left != NULL || root->left->right != NULL || root->right->left != NULL || root->right->right != NULL) { // Print the node's key cout << root->key << " "; } } // Check if the left child // of node is not null else if (root->left != NULL) { // Check for grandchildren if (root->left->left != NULL || root->left->right != NULL) { cout << root->key << " "; } } // Check if the right child // of node is not null else if (root->right != NULL) { // Check for grandchildren if (root->right->left != NULL || root->right->right != NULL) { cout << root->key << " "; } } // Recursive call on left and // right subtree cal(root->left); cal(root->right); }} // Driver Codeint main(){ // Given Tree struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // Function Call cal(root); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // A Binary Tree Nodestatic class node{ node left, right; int key;}; // Function to create new tree nodestatic node newNode(int key){ node temp = new node(); temp.key = key; temp.left = temp.right = null; return temp;} // Function to print the nodes of// the Binary Tree having a grandchildstatic void cal(node root){ // Base case to check // if the tree exists if (root == null) return; else { // Check if there is a left and // right child of the curr node if (root.left != null && root.right != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null || root.right.left != null || root.right.right != null) { // Print the node's key System.out.print(root.key + " "); } } // Check if the left child // of node is not null else if (root.left != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null) { System.out.print(root.key + " "); } } // Check if the right child // of node is not null else if (root.right != null) { // Check for grandchildren if (root.right.left != null || root.right.right != null) { System.out.print(root.key + " "); } } // Recursive call on left and // right subtree cal(root.left); cal(root.right); }} // Driver Codepublic static void main(String[] args){ // Given Tree node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // Function call cal(root);}} // This code is contributed by Amit Katiyar
# Python3 program for the# above approach # A Binary Tree Nodeclass newNode: def __init__(self, key): self.key = key self.left = None self.right = None # Function to print the nodes# of the Binary Tree having a# grandchilddef cal(root): # Base case to check # if the tree exists if (root == None): return else: # Check if there is a left # and right child of the # curr node if (root.left != None and root.right != None): # Check for grandchildren if (root.left.left != None or root.left.right != None or root.right.left != None or root.right.right != None): # Print the node's key print(root.key, end = " ") # Check if the left child # of node is not None elif (root.left != None): # Check for grandchildren if (root.left.left != None or root.left.right != None): print(root.key, end = " ") # Check if the right child # of node is not None elif(root.right != None): # Check for grandchildren if (root.right.left != None or root.right.right != None): print(root.key, end = " ") # Recursive call on left and # right subtree cal(root.left) cal(root.right) # Driver Codeif __name__ == '__main__': # Given Tree root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) # Function Call cal(root) # This code is contributed by SURENDRA_GANGWAR
// C# program for the// above approachusing System;class GFG{ // A Binary Tree Nodepublic class node{ public node left, right; public int key;}; // Function to create new// tree nodestatic node newNode(int key){ node temp = new node(); temp.key = key; temp.left = temp.right = null; return temp;} // Function to print the// nodes of the Binary Tree// having a grandchildstatic void cal(node root){ // Base case to check // if the tree exists if (root == null) return; else { // Check if there is a left and // right child of the curr node if (root.left != null && root.right != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null || root.right.left != null || root.right.right != null) { // Print the node's key Console.Write(root.key + " "); } } // Check if the left child // of node is not null else if (root.left != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null) { Console.Write(root.key + " "); } } // Check if the right child // of node is not null else if (root.right != null) { // Check for grandchildren if (root.right.left != null || root.right.right != null) { Console.Write(root.key + " "); } } // Recursive call on left and // right subtree cal(root.left); cal(root.right); }} // Driver Codepublic static void Main(String[] args){ // Given Tree node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // Function call cal(root);}} // This code is contributed by Princi Singh
<script> // Javascript program for the above approach // A Binary Tree Node class node { constructor(key) { this.left = null; this.right = null; this.key = key; } } // Function to create new tree node function newNode(key) { let temp = new node(key); return temp; } // Function to print the nodes of // the Binary Tree having a grandchild function cal(root) { // Base case to check // if the tree exists if (root == null) return; else { // Check if there is a left and // right child of the curr node if (root.left != null && root.right != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null || root.right.left != null || root.right.right != null) { // Print the node's key document.write(root.key + " "); } } // Check if the left child // of node is not null else if (root.left != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null) { document.write(root.key + " "); } } // Check if the right child // of node is not null else if (root.right != null) { // Check for grandchildren if (root.right.left != null || root.right.right != null) { document.write(root.key + " "); } } // Recursive call on left and // right subtree cal(root.left); cal(root.right); } } // Given Tree let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // Function call cal(root); // This code is contributed by mukesh07.</script>
1
Time Complexity: O(N), where N is the number of nodes. Auxiliary Space: O(N)
amit143katiyar
princi singh
SURENDRA_GANGWAR
mukesh07
pankajsharmagfg
Algorithms-Recursion
B-Tree
Binary Tree
Algorithms
Competitive Programming
Data Structures
Recursion
Tree
Data Structures
Recursion
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "Given a Binary Tree, the task is to print the nodes that have grandchildren."
},
{
"code": null,
"e": 116,
"s": 105,
"text": "Examples: "
},
{
"code": null,
"e": 125,
"s": 116,
"text": "Input: "
},
{
"code": null,
"e": 202,
"s": 125,
"text": "Output: 20 8 Explanation: 20 and 8 are the grandparents of 4, 12 and 10, 14."
},
{
"code": null,
"e": 211,
"s": 202,
"text": "Input: "
},
{
"code": null,
"e": 265,
"s": 211,
"text": "Output: 1 Explanation: 1 is the grandparent of 4, 5. "
},
{
"code": null,
"e": 322,
"s": 265,
"text": "Approach: The idea uses Recursion. Below are the steps: "
},
{
"code": null,
"e": 672,
"s": 322,
"text": "Traverse the given tree at every node.Check if each node has grandchildren node or not.For any tree node(say temp) if one of the below node exists then current node is the grandparent node: temp->left->left.temp->left->right.temp->right->left.temp->right->right.If any of the above exist for any node temp then the node temp is the grandparent node."
},
{
"code": null,
"e": 711,
"s": 672,
"text": "Traverse the given tree at every node."
},
{
"code": null,
"e": 761,
"s": 711,
"text": "Check if each node has grandchildren node or not."
},
{
"code": null,
"e": 937,
"s": 761,
"text": "For any tree node(say temp) if one of the below node exists then current node is the grandparent node: temp->left->left.temp->left->right.temp->right->left.temp->right->right."
},
{
"code": null,
"e": 955,
"s": 937,
"text": "temp->left->left."
},
{
"code": null,
"e": 974,
"s": 955,
"text": "temp->left->right."
},
{
"code": null,
"e": 993,
"s": 974,
"text": "temp->right->left."
},
{
"code": null,
"e": 1013,
"s": 993,
"text": "temp->right->right."
},
{
"code": null,
"e": 1101,
"s": 1013,
"text": "If any of the above exist for any node temp then the node temp is the grandparent node."
},
{
"code": null,
"e": 1152,
"s": 1101,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1156,
"s": 1152,
"text": "C++"
},
{
"code": null,
"e": 1161,
"s": 1156,
"text": "Java"
},
{
"code": null,
"e": 1169,
"s": 1161,
"text": "Python3"
},
{
"code": null,
"e": 1172,
"s": 1169,
"text": "C#"
},
{
"code": null,
"e": 1183,
"s": 1172,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct node { struct node *left, *right; int key;}; // Function to create new tree nodenode* newNode(int key){ node* temp = new node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Function to print the nodes of// the Binary Tree having a grandchildvoid cal(struct node* root){ // Base case to check // if the tree exists if (root == NULL) return; else { // Check if there is a left and // right child of the curr node if (root->left != NULL && root->right != NULL) { // Check for grandchildren if (root->left->left != NULL || root->left->right != NULL || root->right->left != NULL || root->right->right != NULL) { // Print the node's key cout << root->key << \" \"; } } // Check if the left child // of node is not null else if (root->left != NULL) { // Check for grandchildren if (root->left->left != NULL || root->left->right != NULL) { cout << root->key << \" \"; } } // Check if the right child // of node is not null else if (root->right != NULL) { // Check for grandchildren if (root->right->left != NULL || root->right->right != NULL) { cout << root->key << \" \"; } } // Recursive call on left and // right subtree cal(root->left); cal(root->right); }} // Driver Codeint main(){ // Given Tree struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // Function Call cal(root); return 0;}",
"e": 3122,
"s": 1183,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // A Binary Tree Nodestatic class node{ node left, right; int key;}; // Function to create new tree nodestatic node newNode(int key){ node temp = new node(); temp.key = key; temp.left = temp.right = null; return temp;} // Function to print the nodes of// the Binary Tree having a grandchildstatic void cal(node root){ // Base case to check // if the tree exists if (root == null) return; else { // Check if there is a left and // right child of the curr node if (root.left != null && root.right != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null || root.right.left != null || root.right.right != null) { // Print the node's key System.out.print(root.key + \" \"); } } // Check if the left child // of node is not null else if (root.left != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null) { System.out.print(root.key + \" \"); } } // Check if the right child // of node is not null else if (root.right != null) { // Check for grandchildren if (root.right.left != null || root.right.right != null) { System.out.print(root.key + \" \"); } } // Recursive call on left and // right subtree cal(root.left); cal(root.right); }} // Driver Codepublic static void main(String[] args){ // Given Tree node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // Function call cal(root);}} // This code is contributed by Amit Katiyar",
"e": 5214,
"s": 3122,
"text": null
},
{
"code": "# Python3 program for the# above approach # A Binary Tree Nodeclass newNode: def __init__(self, key): self.key = key self.left = None self.right = None # Function to print the nodes# of the Binary Tree having a# grandchilddef cal(root): # Base case to check # if the tree exists if (root == None): return else: # Check if there is a left # and right child of the # curr node if (root.left != None and root.right != None): # Check for grandchildren if (root.left.left != None or root.left.right != None or root.right.left != None or root.right.right != None): # Print the node's key print(root.key, end = \" \") # Check if the left child # of node is not None elif (root.left != None): # Check for grandchildren if (root.left.left != None or root.left.right != None): print(root.key, end = \" \") # Check if the right child # of node is not None elif(root.right != None): # Check for grandchildren if (root.right.left != None or root.right.right != None): print(root.key, end = \" \") # Recursive call on left and # right subtree cal(root.left) cal(root.right) # Driver Codeif __name__ == '__main__': # Given Tree root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) # Function Call cal(root) # This code is contributed by SURENDRA_GANGWAR",
"e": 6962,
"s": 5214,
"text": null
},
{
"code": "// C# program for the// above approachusing System;class GFG{ // A Binary Tree Nodepublic class node{ public node left, right; public int key;}; // Function to create new// tree nodestatic node newNode(int key){ node temp = new node(); temp.key = key; temp.left = temp.right = null; return temp;} // Function to print the// nodes of the Binary Tree// having a grandchildstatic void cal(node root){ // Base case to check // if the tree exists if (root == null) return; else { // Check if there is a left and // right child of the curr node if (root.left != null && root.right != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null || root.right.left != null || root.right.right != null) { // Print the node's key Console.Write(root.key + \" \"); } } // Check if the left child // of node is not null else if (root.left != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null) { Console.Write(root.key + \" \"); } } // Check if the right child // of node is not null else if (root.right != null) { // Check for grandchildren if (root.right.left != null || root.right.right != null) { Console.Write(root.key + \" \"); } } // Recursive call on left and // right subtree cal(root.left); cal(root.right); }} // Driver Codepublic static void Main(String[] args){ // Given Tree node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // Function call cal(root);}} // This code is contributed by Princi Singh",
"e": 8732,
"s": 6962,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // A Binary Tree Node class node { constructor(key) { this.left = null; this.right = null; this.key = key; } } // Function to create new tree node function newNode(key) { let temp = new node(key); return temp; } // Function to print the nodes of // the Binary Tree having a grandchild function cal(root) { // Base case to check // if the tree exists if (root == null) return; else { // Check if there is a left and // right child of the curr node if (root.left != null && root.right != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null || root.right.left != null || root.right.right != null) { // Print the node's key document.write(root.key + \" \"); } } // Check if the left child // of node is not null else if (root.left != null) { // Check for grandchildren if (root.left.left != null || root.left.right != null) { document.write(root.key + \" \"); } } // Check if the right child // of node is not null else if (root.right != null) { // Check for grandchildren if (root.right.left != null || root.right.right != null) { document.write(root.key + \" \"); } } // Recursive call on left and // right subtree cal(root.left); cal(root.right); } } // Given Tree let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // Function call cal(root); // This code is contributed by mukesh07.</script>",
"e": 10959,
"s": 8732,
"text": null
},
{
"code": null,
"e": 10961,
"s": 10959,
"text": "1"
},
{
"code": null,
"e": 11040,
"s": 10963,
"text": "Time Complexity: O(N), where N is the number of nodes. Auxiliary Space: O(N)"
},
{
"code": null,
"e": 11055,
"s": 11040,
"text": "amit143katiyar"
},
{
"code": null,
"e": 11068,
"s": 11055,
"text": "princi singh"
},
{
"code": null,
"e": 11085,
"s": 11068,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 11094,
"s": 11085,
"text": "mukesh07"
},
{
"code": null,
"e": 11110,
"s": 11094,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 11131,
"s": 11110,
"text": "Algorithms-Recursion"
},
{
"code": null,
"e": 11138,
"s": 11131,
"text": "B-Tree"
},
{
"code": null,
"e": 11150,
"s": 11138,
"text": "Binary Tree"
},
{
"code": null,
"e": 11161,
"s": 11150,
"text": "Algorithms"
},
{
"code": null,
"e": 11185,
"s": 11161,
"text": "Competitive Programming"
},
{
"code": null,
"e": 11201,
"s": 11185,
"text": "Data Structures"
},
{
"code": null,
"e": 11211,
"s": 11201,
"text": "Recursion"
},
{
"code": null,
"e": 11216,
"s": 11211,
"text": "Tree"
},
{
"code": null,
"e": 11232,
"s": 11216,
"text": "Data Structures"
},
{
"code": null,
"e": 11242,
"s": 11232,
"text": "Recursion"
},
{
"code": null,
"e": 11247,
"s": 11242,
"text": "Tree"
},
{
"code": null,
"e": 11258,
"s": 11247,
"text": "Algorithms"
},
{
"code": null,
"e": 11356,
"s": 11258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11394,
"s": 11356,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 11462,
"s": 11394,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 11489,
"s": 11462,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 11532,
"s": 11489,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 11599,
"s": 11532,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 11642,
"s": 11599,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 11685,
"s": 11642,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 11726,
"s": 11685,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 11753,
"s": 11726,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
printf command in Linux with Examples
|
18 Feb, 2021
βprintfβ command in Linux is used to display the given string, number or any other format specifier on the terminal window. It works the same way as βprintfβ works in programming languages like C.
Syntax:
$printf [-v var] format [arguments]
Note: printf can have format specifiers, escape sequences or ordinary characters.
Format Specifiers: The most commonly used printf specifiers are %s, %b, %d, %x and %f.
Examples:
%s specifier: It is basically a string specifier for string output.$printf "%s\n" "Hello, World!"
Output:
$printf "%s\n" "Hello, World!"
Output:
%b specifier: It is same as string specifier but it allows us to interpret escape sequences with an argument.Input: printf "%s\n" "Hello, World! \n" "From Geeks For Geeks\n"
Output: Hello, World! \n
From Geeks For Geeks\n
Note: The escape sequence β\nβ in the above lines has no special meaning when used with β%sβ specifier and is treated just like other characters. If we replace β%sβ with β%bβ, Then it will be interpreted as a newline character.Input : printf "%b\n" "Hello, World! \n" "From Geeks For Geeks\n"
Output: Hello, World!
From Geeks For Geeks
Example:$printf "%b\n" "Geeks" "for" "\nGeeks\n"
Output:
Input: printf "%s\n" "Hello, World! \n" "From Geeks For Geeks\n"
Output: Hello, World! \n
From Geeks For Geeks\n
Note: The escape sequence β\nβ in the above lines has no special meaning when used with β%sβ specifier and is treated just like other characters. If we replace β%sβ with β%bβ, Then it will be interpreted as a newline character.
Input : printf "%b\n" "Hello, World! \n" "From Geeks For Geeks\n"
Output: Hello, World!
From Geeks For Geeks
Example:
$printf "%b\n" "Geeks" "for" "\nGeeks\n"
Output:
%d specifier: It is an integer specifier for showing the integral values.$printf "%d\n" "213" "109"
Output:
$printf "%d\n" "213" "109"
Output:
%f specifier: It is used for output of floating point values.$printf "%f\n" "1.32" "3.14"
Output:
$printf "%f\n" "1.32" "3.14"
Output:
%x specifier: It is used for output of lowercase hexadecimal values for integers and for padding the output.$printf "%08x\n" "1024"
Output:
$printf "%08x\n" "1024"
Output:
Linux Tutorials | General Purpose Utilities | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | General Purpose Utilities | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:003:12 / 4:09β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=g6cPFj9ptdc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-Shell-Commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Cat command in Linux with examples
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 250,
"s": 53,
"text": "βprintfβ command in Linux is used to display the given string, number or any other format specifier on the terminal window. It works the same way as βprintfβ works in programming languages like C."
},
{
"code": null,
"e": 258,
"s": 250,
"text": "Syntax:"
},
{
"code": null,
"e": 295,
"s": 258,
"text": "$printf [-v var] format [arguments]\n"
},
{
"code": null,
"e": 377,
"s": 295,
"text": "Note: printf can have format specifiers, escape sequences or ordinary characters."
},
{
"code": null,
"e": 464,
"s": 377,
"text": "Format Specifiers: The most commonly used printf specifiers are %s, %b, %d, %x and %f."
},
{
"code": null,
"e": 474,
"s": 464,
"text": "Examples:"
},
{
"code": null,
"e": 580,
"s": 474,
"text": "%s specifier: It is basically a string specifier for string output.$printf \"%s\\n\" \"Hello, World!\"\nOutput:"
},
{
"code": null,
"e": 612,
"s": 580,
"text": "$printf \"%s\\n\" \"Hello, World!\"\n"
},
{
"code": null,
"e": 620,
"s": 612,
"text": "Output:"
},
{
"code": null,
"e": 1260,
"s": 620,
"text": "%b specifier: It is same as string specifier but it allows us to interpret escape sequences with an argument.Input: printf \"%s\\n\" \"Hello, World! \\n\" \"From Geeks For Geeks\\n\"\n\nOutput: Hello, World! \\n\n From Geeks For Geeks\\n\nNote: The escape sequence β\\nβ in the above lines has no special meaning when used with β%sβ specifier and is treated just like other characters. If we replace β%sβ with β%bβ, Then it will be interpreted as a newline character.Input : printf \"%b\\n\" \"Hello, World! \\n\" \"From Geeks For Geeks\\n\"\nOutput: Hello, World! \n\n From Geeks For Geeks \n\nExample:$printf \"%b\\n\" \"Geeks\" \"for\" \"\\nGeeks\\n\"\nOutput:"
},
{
"code": null,
"e": 1384,
"s": 1260,
"text": "Input: printf \"%s\\n\" \"Hello, World! \\n\" \"From Geeks For Geeks\\n\"\n\nOutput: Hello, World! \\n\n From Geeks For Geeks\\n\n"
},
{
"code": null,
"e": 1612,
"s": 1384,
"text": "Note: The escape sequence β\\nβ in the above lines has no special meaning when used with β%sβ specifier and is treated just like other characters. If we replace β%sβ with β%bβ, Then it will be interpreted as a newline character."
},
{
"code": null,
"e": 1737,
"s": 1612,
"text": "Input : printf \"%b\\n\" \"Hello, World! \\n\" \"From Geeks For Geeks\\n\"\nOutput: Hello, World! \n\n From Geeks For Geeks \n\n"
},
{
"code": null,
"e": 1746,
"s": 1737,
"text": "Example:"
},
{
"code": null,
"e": 1788,
"s": 1746,
"text": "$printf \"%b\\n\" \"Geeks\" \"for\" \"\\nGeeks\\n\"\n"
},
{
"code": null,
"e": 1796,
"s": 1788,
"text": "Output:"
},
{
"code": null,
"e": 1904,
"s": 1796,
"text": "%d specifier: It is an integer specifier for showing the integral values.$printf \"%d\\n\" \"213\" \"109\"\nOutput:"
},
{
"code": null,
"e": 1932,
"s": 1904,
"text": "$printf \"%d\\n\" \"213\" \"109\"\n"
},
{
"code": null,
"e": 1940,
"s": 1932,
"text": "Output:"
},
{
"code": null,
"e": 2038,
"s": 1940,
"text": "%f specifier: It is used for output of floating point values.$printf \"%f\\n\" \"1.32\" \"3.14\"\nOutput:"
},
{
"code": null,
"e": 2068,
"s": 2038,
"text": "$printf \"%f\\n\" \"1.32\" \"3.14\"\n"
},
{
"code": null,
"e": 2076,
"s": 2068,
"text": "Output:"
},
{
"code": null,
"e": 2216,
"s": 2076,
"text": "%x specifier: It is used for output of lowercase hexadecimal values for integers and for padding the output.$printf \"%08x\\n\" \"1024\"\nOutput:"
},
{
"code": null,
"e": 2241,
"s": 2216,
"text": "$printf \"%08x\\n\" \"1024\"\n"
},
{
"code": null,
"e": 2249,
"s": 2241,
"text": "Output:"
},
{
"code": null,
"e": 3153,
"s": 2249,
"text": "Linux Tutorials | General Purpose Utilities | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | General Purpose Utilities | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:003:12 / 4:09β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=g6cPFj9ptdc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 3167,
"s": 3153,
"text": "linux-command"
},
{
"code": null,
"e": 3188,
"s": 3167,
"text": "Linux-Shell-Commands"
},
{
"code": null,
"e": 3199,
"s": 3188,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3297,
"s": 3199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3332,
"s": 3297,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3368,
"s": 3332,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 3404,
"s": 3368,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 3442,
"s": 3404,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 3480,
"s": 3442,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3506,
"s": 3480,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3541,
"s": 3506,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3579,
"s": 3541,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 3615,
"s": 3579,
"text": "echo command in Linux with Examples"
}
] |
Python String rstrip() Method
|
19 Aug, 2021
Python String rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed). If no argument is passed, it removes trailing spaces.
Syntax:
string.rstrip([chars])
Parameters:
chars (optional) β a string specifying the set of characters to be removed.
Returns:
Returns a copy of the string with trailing characters stripped
Python3
# Python3 program to demonstrate the use of# rstrip() method using optional parameters # string which is to be strippedstring = "geekssss" # Removes given set of characters from# right.print(string.rstrip('s'))
Output:
geek
Python3
# Python3 program to demonstrate the use of# rstrip() method using optional parameters # string which is to be strippedstring = " for " # Leading whitespaces are removedprint("Geeks" + string.rstrip() + " Geeks ")
Output:
Geeks for Geeks
Python3
# string which is to be strippedstring = "geeks for geeks" # Argument doesn't contain trailing 's'# So, no characters are removedprint(string.rstrip('ek'))
Output:
geeks for geeks
Python3
# string which is to be strippedstring = "geeks for geeks" # Removes given set of characters from# right.print(string.rstrip('ske'))
Output:
geeks for g
AmiyaRanjanRout
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 238,
"s": 53,
"text": "Python String rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed). If no argument is passed, it removes trailing spaces."
},
{
"code": null,
"e": 247,
"s": 238,
"text": "Syntax: "
},
{
"code": null,
"e": 270,
"s": 247,
"text": "string.rstrip([chars])"
},
{
"code": null,
"e": 282,
"s": 270,
"text": "Parameters:"
},
{
"code": null,
"e": 358,
"s": 282,
"text": "chars (optional) β a string specifying the set of characters to be removed."
},
{
"code": null,
"e": 367,
"s": 358,
"text": "Returns:"
},
{
"code": null,
"e": 430,
"s": 367,
"text": "Returns a copy of the string with trailing characters stripped"
},
{
"code": null,
"e": 438,
"s": 430,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate the use of# rstrip() method using optional parameters # string which is to be strippedstring = \"geekssss\" # Removes given set of characters from# right.print(string.rstrip('s'))",
"e": 649,
"s": 438,
"text": null
},
{
"code": null,
"e": 658,
"s": 649,
"text": "Output: "
},
{
"code": null,
"e": 663,
"s": 658,
"text": "geek"
},
{
"code": null,
"e": 671,
"s": 663,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate the use of# rstrip() method using optional parameters # string which is to be strippedstring = \" for \" # Leading whitespaces are removedprint(\"Geeks\" + string.rstrip() + \" Geeks \")",
"e": 890,
"s": 671,
"text": null
},
{
"code": null,
"e": 899,
"s": 890,
"text": "Output: "
},
{
"code": null,
"e": 917,
"s": 899,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 925,
"s": 917,
"text": "Python3"
},
{
"code": "# string which is to be strippedstring = \"geeks for geeks\" # Argument doesn't contain trailing 's'# So, no characters are removedprint(string.rstrip('ek'))",
"e": 1081,
"s": 925,
"text": null
},
{
"code": null,
"e": 1090,
"s": 1081,
"text": "Output: "
},
{
"code": null,
"e": 1106,
"s": 1090,
"text": "geeks for geeks"
},
{
"code": null,
"e": 1114,
"s": 1106,
"text": "Python3"
},
{
"code": "# string which is to be strippedstring = \"geeks for geeks\" # Removes given set of characters from# right.print(string.rstrip('ske'))",
"e": 1247,
"s": 1114,
"text": null
},
{
"code": null,
"e": 1256,
"s": 1247,
"text": "Output: "
},
{
"code": null,
"e": 1268,
"s": 1256,
"text": "geeks for g"
},
{
"code": null,
"e": 1284,
"s": 1268,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 1298,
"s": 1284,
"text": "python-string"
},
{
"code": null,
"e": 1322,
"s": 1298,
"text": "Python-string-functions"
},
{
"code": null,
"e": 1329,
"s": 1322,
"text": "Python"
},
{
"code": null,
"e": 1427,
"s": 1329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1455,
"s": 1427,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1505,
"s": 1455,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1527,
"s": 1505,
"text": "Python map() function"
},
{
"code": null,
"e": 1545,
"s": 1527,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1589,
"s": 1545,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 1631,
"s": 1589,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1654,
"s": 1631,
"text": "Taking input in Python"
},
{
"code": null,
"e": 1676,
"s": 1654,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1711,
"s": 1676,
"text": "Read a file line by line in Python"
}
] |
Using Network Science to explore hashtag culture on Instagram | by Sam Ho | Towards Data Science
|
This project proposes that Network Science and graph theory can be used to effectively analyse hashtag culture on Instagram. The relational characteristics of Instagram hashtags can be realised through these techniques and this allows for deeper understanding of conversations and themes found across hashtags.
To demonstrate this idea I have written a practical and technical walkthrough of how to do this using Python and NetworkX.
Around 37,000 Instagram posts all containing at least one mention of #happiness were scraped from Instagram. All unique hashtags in the corpus (other than #happiness) represented nodes in the graph. Edges were formed between hashtags if they were mentioned together in the same post.
This yielded an undirected βHappinessβ graph which was then analysed using community detection and various centrality measures.
Community detection identified three clusters, interpreted as:
Aspects of happiness that seem to be about what people do and experience (e.g. β#photography, #summer, #travel,#family )
Aspects of happiness that broadly seem to be about how people think and feel (e.g #life, #motivation, #inspiration, #quotes)
A third very distinct cluster was entirely about #weddings, #celebrations and #parties
This approach has shown that graph theory can be a very intuitive and useful way to explore social media metadata such as hashtags. Its application could be in two immediate areas:
1. We might want to graph thematic entities e.g people posting about sustainability, Brexit, Coronavirus
2. We could use graphs to model and understand the conversation around specific brands, events and places
(We need to bear in mind the nature of content on Instagram as this will guide what could be a suitable application)
All code for the functionality to replicate this task can be found on my GitHub:
github.com
Instagram is huge
Hashtag culture: making life easier for a Data Scientist!
A picture is worth a thousand words ....or a handful of hashtags?
What does βhappinessβ mean to people on Instagram?
What is a Graph?
What aspects of Graph Theory can we use in our analysis?
Further Reading on Graphs
Search for hashtags on Instagram using Selenium WebDriver
Capture unique Instagram URLβs
Parse hashtags and other content from html using multi-thread processing
Feature Generation & Exploratory Analysis
Data Selection
Graph Building
Visualisation / Analysis & Interpretation
Instagram began life in 2006 as a niche place for creative expression. Early adopters flocked to the app keen to share their pictures of urban graffiti, soy lattes and bowls of ramen. iPhone 1 + Instagram was a stamp of coolness β a golden era for the digitally hip.
Alas, this didnβt last. Instagramβs gentrification was inevitable and when Facebook bought Instagram in 2012, they swiftly monetised it through advertising and turned Instagram into a cash cow of gigantic proportions.
In 2020 Instagram is no longer cool, itβs a commercial behemoth.
With an estimated 1 billion active monthly users and 500 million daily stories, the rise and reach of Instagram is nothing but impressive.
Subsequently, Instagram has in many ways become a reliable barometer of mainstream consumer culture and this means that it lends itself as a potentially useful tool to find stuff out about people.
Whilst it would be reasonable to assume that Instagramβs images and videos would be the primary βgo-toβ sources of data, Iβve found that analysing Instagramβs hashtag culture is a more fruitful way to get under the skin of themes and topics that occur on Instagram. Coupled with analytical techniques borrowed from Network Science means that the relationships between themes and topics can be more easily understood.
One of the more important parts of a Data Scientistβs job is being able to commit the time to ensure that our data is fit for purpose and this involves thorough cleaning of our data. This can take up a lot of time, especially with social media data that tends to be extremely unstructured and frequently littered with βnoiseβ.
Without sufficient pre-processing, the natural language processing techniques we use with social media data can lead to outputs that are hard to interpret and light on insight.
There are various methods we can use to clean and organise the raw language we find on social media but itβs made infinitely easier when users do it for us. Hashtag culture on Instagram β which by its very nature is organised, normalised and less noisy β is a cultural phenomenon that does all this hard work for us.
βA hashtag β introduced by the octothorpe symbol (#) β is a type of metadata tag used on social networks such as Twitter and other microblogging services. It lets users apply dynamic, user-generated tagging that helps other users easily find messages with a specific theme or contentβ
People often end an Instagram post with a series of hashtags. Hashtags can provide a succinct summary of what that person was thinking, feeling and observing in that moment. Hashtags provide context and meaning that the image alone is unable to.
Letβs find an example to illustrate this.
Social media is increasingly likely to get bashed as being something that makes people miserable....and sadly there is truth in this.
Letβs be contrarian, flip this truth and explore HAPPINESS on Instagram.
The following Instagram post contains #happiness in the body of the post. What can we interpret from this post by the image alone?
Not much. Maybe something to do with music?
Other than the obvious there is little to go on from the image alone. What else were they thinking/feeling when they posted this?
Now when we look at all the hashtags this person made alongside their post, we learn a lot more about this person and what they associated with #happiness at that moment in time.
For this person, happiness has an association with positivity, motivation, change and weight loss.
Whilst Instagram images can tell us something, the hashtags people use tell us considerably more.
Now, this is just one Instagram post containing #happiness. What happens when we look at the surrounding hashtags for other peopleβs posts mentioning #happiness?
What happens if we scale this analysis up and look at thousands upon thousands of posts containing #happiness?
Pretty soon we would be in a position where we have a vast number of hashtags to navigate. What scalable approach will allow us to make sense of all this data?
This is where we can use Network Science and Graph Theory to help us.
Network science is a thriving and increasingly important cross-disciplinary domain that focuses on the representation, analysis and modelling of complex social, biological and technological systems as networks or graphsβ
Source: http://tuvalu.santafe.edu/~aaronc/courses/5352/
I like to think of Network Science and graph theory as methods that allow us to understand how things are connected. We can borrow some basic principles from Network Science and graph theory to understand how hashtags on Instagram are connected.
The subject matter relating to Network Science and graph theory is incredibly dense and would take a very long time to cover. This would distract from the practical focus of the project. There are however some simple but fundamental concepts that need explaining.
A graph (G) is the abstract representation of a network. Graphs are made up of vertices (V) and edges (E) where G=(V,E)
Nodes (V) in a graph represent the unique data points that exist in our data. In the case of hashtag analysis, it makes sense for hashtags to represent the nodes in our network. So if our #happiness dataset only had two hashtags β #A and #B we would have two nodes
Edges (E) are connections that represent some kind of relationship between nodes. In the case of analysing hashtags, it might make sense to represent this relationship as some kind of occurrence i.e. if the hashtag #A was mentioned in the same post as #B, we would assume that there is a relationship between #A and #B and therefore we would create an edge between these two nodes
As we add hashtags from other posts to the graph and model their relationships with all previous posts we begin to see structure form.
Community Detection. We can use algorithms to identify and label clusters of topics/themes that are associated with #happiness. In this example we have 14 hashtags, all connected in various ways but with distinct clusters forming.
Degree Centrality / Betweenness Centrality. We can calculate what hashtags in the network are particularly important in linking the whole network. Much like Heathrow Airport links up a lot of the world, what hashtags link up the #happiness βlandscapeβ?
Visualisation. If we plot the network using scatterplots, itβs a very compelling way to visualise a huge amount of information about #happiness that would be cumbersome to do otherwise
MaeΜl Fabien has written a whole series which covers the content around graph theory really well. I strongly recommend you have a read of this at some point if you find this topic interesting.
towardsdatascience.com
Letβs now look at the practical steps we need to take to build our network.
I have built two Python classes that handle all the processes needed to go from capturing the data all the way through to building, visualising and analysing the #Happiness graph. The key pipelines within each class are outlined below.
class InstagramScraper()
Search for hashtags on Instagram using Selenium WebDriver
Capture unique Instagram URLβs
Parse hashtags and other content from post html using multi-thread processing
class InstagramGraph()
Feature generation & exploratory analysis
Data selection
Graph building
Visualisation
You can access the full code for these classes and their relevant readme documentation here:
https://github.com/kitsamho/Instagram_Scraper_Graph
class InstagramScraper()
Search for hashtags on Instagram using Selenium WebDriver
Capture unique Instagram URLβs
Parse hashtags and other content from html using multi-thread processing
This stage uses a combination of automated web browsing and html parsing to scrape content from Instagram posts. I have built a custom Python class InstagramScraper that contains a pipeline of scraping and data extraction methods that returns a Pandas DataFrame of scraped Instagram data.
I will walk you through the main processes below with a few example code blocks to highlight the main steps involved.
There is functionality on Instagram where a user can search for specific hashtags and Instagram returns all the posts that contain that hashtag. This is our first step in getting the data we need; get Instagram to do the work for us using Selenium webdriver.
Every post on Instagram has its own unique URL. After we have searched for all the posts containing a specific hashtag, the first step is to capture all of these unique URLβs for posts that contain that hashtag.
I found the best way to do this is through using a combination of Selenium WebDriver and parsing the html on the fly, extracting each posts href attributes to a data structure as we scroll through all the content.
As this part of the Instagram site is highly dynamic requiring consistent scrolling to load new images, using some kind of browser based automation such as Selenium WebDriver is the only feasible way of capturing the data. This means it can take a little while to get all the links.
Once you have a list of all the links, you can then use a combination of urlopen and html parsing (I use Beautiful Soup) to get the data for each Instagram post.
Once you have the html for each post and parse its content, you will find that data for Instagram posts has a consistent structure resembling a dictionary / JSON style format
The main output of the InstagramScraper class is a Pandas DataFrame containing a host of variables by post.
Most of these variables are self explanatory and offer all kinds of options for exploratory analysis beyond hashtags.
Now that we have our scraped data and have a nice and tidy Pandas DataFrame we can begin to think about processing our data in preparation for building our network and visualising our graph, which is where things get really fun.
I have built a second python class called InstagramGraph which also contains a pipeline of methods that allow you to analyse an Instagram dataset and ultimately model the hashtag data as an instance of a NetworkX graph object using Plotly visualisations.
class InstagramGraph()
The key processes within this class are:
Feature Generation & Exploratory Analysis
Data Selection
Graph Building
Visualisation / Analysis & Interpretation
The code block below outlines a pipeline from the InstagramGraph class which contains a suite of methods that create new features in our data.
There are several methods here, some are linguistic (e.g. determining the language of a post) although most of the processes within this method generate extra descriptive metrics such as median post count by user, total hashtag count by post and median hashtag use by user.
Whilst some of these new features/metrics arenβt directly related to graph building itβs alway worth generating more data points where you can as it offers a chance to do some exploratory analysis of the subject matter which might provide more context about what our graph model reveals. It also might inspire some other ideas for analysis that you hadnβt initially considered.
Letβs explore some of these.
The langdetect library in Python allows us to access the Google Translation library over an API and gives us the ability to identify language in our text.
Note β due to a limit on Google Cloud API requests this can run quite slow when processing a large volume of data. For the purposes of example, this is fine; if you want to productionise this you may want to think about a faster alternative and consider paying.
As we can see the majority of the Instagram posts for #happiness are in English β over 80% of our data set.
A look at some distributions show that the data on user post frequency is extremely positively skewed; there are handful of outlier accounts that post very frequently (up to 140 times) whereas the majority of posters are posting only once.
To extract our hashtags I have created two methods that do the job for us. One method takes a string input and returns a list of hashtags. If people have failed to include a space between their string of hashtags, the code can account for this and βunpackβ them into individual hashtags.
Analysis of hashtag frequency by post indicates that whilst frequency by post tends to follow a uniform distribution , there are some outlier posts that contain an unusually high number of hashtags. Further exploration shows that this partially seems to be driven by people who have posted multiple times across the dataset (high frequency posters). So broadly speaking, those that post more often also tend to use more hashtags in their posts.
A second method then takes this list of hashtags and looks to lemmatise the input, where appropriate. For those unfamiliar with lemmatisation, this is the process where we can reduce a word to its root lexical form. For instance if we have the hashtags #happiest and #happier β these are both inflections of the verb #happy. Therefore lemmatisation reduces these inflections back to #happy. Iβve used an instance of a spaCy model to perform the lemmatisation.
Ok, so the next step is to select the data we want to model. The code outlines a pipeline from the InstagramGraph class which contains a suite of methods that allow us to select the data we want.
Whilst Instagram is an international platform, for simplicity we might want to consider filtering out non-English posts. As we saw previously, over 80% of the data for #happiness is in English so it makes sense to focus on this subset of the data.
Verified users tend to be either brands, celebrities or online shops i.e. βpeopleβ who likely donβt represent the average Instagram user. Depending on your objectives for this analysis, you might want to consider removing verified users from your data.
A cursory inspection of high frequency posters reveals that these are sometimes unverified accounts that are using Instagram to sell stuff under a non-verified status. Do we feel this represents that audience we are interested in understanding? If so we can leave them in, if not β we can filter them out prior to building our graph.
I thought it made sense to have the option to lemmatise the scraped hashtags where possible as it reduces the amount of data needed to build the graph β we donβt necessarily need all that extra data.
Now that we we have selected the data we want to model, we can build the graph. The pipeline we use for this is below:
There are three main processes that take place in this pipeline:
This simply extracts hashtags from our DataFrame into a list of lists β each sub-list representing a post from our #Happiness data set. By having the input as a simple list of lists, we can easily re-purpose this graph building approach to other sources of data in future where we can wrangle the raw data in a similarly structured / list of list format
The next step is to take our list of lists and use this to generate the nodes and edges that exist across the entire data set. Remember the nodes are the unique hashtags in the dataset and an edge is created if any two hashtags are mentioned together in the same post.
The method saves two generated DataFrames as attributes β a DataFrame containing all the nodes and a DataFrame containing all the edges.
The next stage is to add these nodes and edges into an instance of a NetworkX graph object (G).
Once we have created our NetworkX graph object β we can then use various calculated graph attributes to enhance our node data even further.
Betweeness Centrality
Adjacency Frequency
Clustering Coefficient
Community
Now we have an instance of a NetworkX graph object that has been built with our node and edge data that we extracted from our #Happiness dataset.
We can now use Plotly to visualise the hashtag graph as a connected scatter plot.
There are a few arguments that I have set up that allow for a degree of customisation to the visualisation.
def plotGraph(node_size=βadjacency_frequencyβ,colorscale=βViridisβ)
I think it makes sense to use node size to convey some other variable β the default is βadjacency_frequencyβ i.e. how many other nodes a node has edge connections with. In this instance a smaller node would represent a hashtag with fewer edges and contrastingly a larger node would have more edges. We can emphasise this point even further by applying a colour scale that is correlated with node size.
def plotGraph(layout=nx.kamada_kawai_layout)
NetworkX has a few different graph layouts. The kamada kawai layout arranges nodes in a way so that there are as few overlapping edges as possible. Therefore this has a tendency for the nodes to be arranged in a way that conveys clusters ...but most importantly tends to be the easiest layout to interpret. There are alternatives such as the circular layout or random layout but these are harder to make sense of in my experience.
def plotGraph(light_theme=True)
There are two colour themes, light and dark.
We can see quite easily how there are several well connected hashtags in the #happiness graph(hashtags that have more node connections). Smile, life, family, motivation, party...these are all hashtags that are frequently mentioned across the network.
As we can see, the force directed layout has a tendency to push groups of hashtags together that are well connected . If we plot the graph again but colour nodes using their community label we can better visualise how communities fall out.
def plotGraph(community_plot=True)
There seems to be three easily identifiable communities in the #happiness network. We can explore which specific hashtags contribute to each of the communities using sunburst visualisations. Click on the wheel to interact with the clusters.
Community detection identified three clusters interpreted as:
Aspects of happiness that seem to be about what people do and experience (e.g. β#photography, #summer, #travel,#family ) (Segment 0)
Aspects of happiness that broadly seem to be about how people think and feel (e.g #life, #motivation, #inspiration, #quotes) (Segment 1)
A third very distinct cluster was entirely about #weddings, #celebrations and #parties (Segment 3)
I hope you enjoyed this practical walk through on how to extract hashtag data from Instagram and analyse it using principles borrowed from Network Science.
My main aims with this project were:
To try and demonstrate that there is an abundance of accessible and potentially insightful content buried in social media data.To show you that there are almost always interesting patterns in places you might not have expected
To try and demonstrate that there is an abundance of accessible and potentially insightful content buried in social media data.
To show you that there are almost always interesting patterns in places you might not have expected
I chose #happiness as a case study because hopefully this is something that we can all relate to. However the code works for any hashtag. As long as you can gather sufficient volumes of data to model β there are observable relationships for anything. You could consider brands, places, events and even people.
You donβt even need to use Instagram; the code can easily be repurposed to use all kinds of meta data beyond Instagram....Twitter, LinkedIn even TikTok could be a possibility.
As I mentioned before, the code is available on my GitHub so please feel free to take, use, evolve and improve. Iβd love to see what people do with this.
Until next time! π
Cheers Sam
My GitHub: https://github.com/kitsamho/Instagram_Scraper_Graph
Introduction to Graphs by MaeΜl Fabien: https://maelfabien.github.io/machinelearning/graph_1/#
Instagram: https://www.instagram.com
Selenium WebDriver: https://chromedriver.chromium.org/downloads
Beautiful Soup : https://www.crummy.com/software/BeautifulSoup/bs4/doc/
NetworkX : https://networkx.github.io/documentation/stable/
|
[
{
"code": null,
"e": 483,
"s": 172,
"text": "This project proposes that Network Science and graph theory can be used to effectively analyse hashtag culture on Instagram. The relational characteristics of Instagram hashtags can be realised through these techniques and this allows for deeper understanding of conversations and themes found across hashtags."
},
{
"code": null,
"e": 606,
"s": 483,
"text": "To demonstrate this idea I have written a practical and technical walkthrough of how to do this using Python and NetworkX."
},
{
"code": null,
"e": 890,
"s": 606,
"text": "Around 37,000 Instagram posts all containing at least one mention of #happiness were scraped from Instagram. All unique hashtags in the corpus (other than #happiness) represented nodes in the graph. Edges were formed between hashtags if they were mentioned together in the same post."
},
{
"code": null,
"e": 1018,
"s": 890,
"text": "This yielded an undirected βHappinessβ graph which was then analysed using community detection and various centrality measures."
},
{
"code": null,
"e": 1081,
"s": 1018,
"text": "Community detection identified three clusters, interpreted as:"
},
{
"code": null,
"e": 1202,
"s": 1081,
"text": "Aspects of happiness that seem to be about what people do and experience (e.g. β#photography, #summer, #travel,#family )"
},
{
"code": null,
"e": 1327,
"s": 1202,
"text": "Aspects of happiness that broadly seem to be about how people think and feel (e.g #life, #motivation, #inspiration, #quotes)"
},
{
"code": null,
"e": 1414,
"s": 1327,
"text": "A third very distinct cluster was entirely about #weddings, #celebrations and #parties"
},
{
"code": null,
"e": 1595,
"s": 1414,
"text": "This approach has shown that graph theory can be a very intuitive and useful way to explore social media metadata such as hashtags. Its application could be in two immediate areas:"
},
{
"code": null,
"e": 1700,
"s": 1595,
"text": "1. We might want to graph thematic entities e.g people posting about sustainability, Brexit, Coronavirus"
},
{
"code": null,
"e": 1806,
"s": 1700,
"text": "2. We could use graphs to model and understand the conversation around specific brands, events and places"
},
{
"code": null,
"e": 1923,
"s": 1806,
"text": "(We need to bear in mind the nature of content on Instagram as this will guide what could be a suitable application)"
},
{
"code": null,
"e": 2004,
"s": 1923,
"text": "All code for the functionality to replicate this task can be found on my GitHub:"
},
{
"code": null,
"e": 2015,
"s": 2004,
"text": "github.com"
},
{
"code": null,
"e": 2033,
"s": 2015,
"text": "Instagram is huge"
},
{
"code": null,
"e": 2091,
"s": 2033,
"text": "Hashtag culture: making life easier for a Data Scientist!"
},
{
"code": null,
"e": 2157,
"s": 2091,
"text": "A picture is worth a thousand words ....or a handful of hashtags?"
},
{
"code": null,
"e": 2208,
"s": 2157,
"text": "What does βhappinessβ mean to people on Instagram?"
},
{
"code": null,
"e": 2225,
"s": 2208,
"text": "What is a Graph?"
},
{
"code": null,
"e": 2282,
"s": 2225,
"text": "What aspects of Graph Theory can we use in our analysis?"
},
{
"code": null,
"e": 2308,
"s": 2282,
"text": "Further Reading on Graphs"
},
{
"code": null,
"e": 2366,
"s": 2308,
"text": "Search for hashtags on Instagram using Selenium WebDriver"
},
{
"code": null,
"e": 2397,
"s": 2366,
"text": "Capture unique Instagram URLβs"
},
{
"code": null,
"e": 2470,
"s": 2397,
"text": "Parse hashtags and other content from html using multi-thread processing"
},
{
"code": null,
"e": 2512,
"s": 2470,
"text": "Feature Generation & Exploratory Analysis"
},
{
"code": null,
"e": 2527,
"s": 2512,
"text": "Data Selection"
},
{
"code": null,
"e": 2542,
"s": 2527,
"text": "Graph Building"
},
{
"code": null,
"e": 2584,
"s": 2542,
"text": "Visualisation / Analysis & Interpretation"
},
{
"code": null,
"e": 2851,
"s": 2584,
"text": "Instagram began life in 2006 as a niche place for creative expression. Early adopters flocked to the app keen to share their pictures of urban graffiti, soy lattes and bowls of ramen. iPhone 1 + Instagram was a stamp of coolness β a golden era for the digitally hip."
},
{
"code": null,
"e": 3069,
"s": 2851,
"text": "Alas, this didnβt last. Instagramβs gentrification was inevitable and when Facebook bought Instagram in 2012, they swiftly monetised it through advertising and turned Instagram into a cash cow of gigantic proportions."
},
{
"code": null,
"e": 3134,
"s": 3069,
"text": "In 2020 Instagram is no longer cool, itβs a commercial behemoth."
},
{
"code": null,
"e": 3273,
"s": 3134,
"text": "With an estimated 1 billion active monthly users and 500 million daily stories, the rise and reach of Instagram is nothing but impressive."
},
{
"code": null,
"e": 3470,
"s": 3273,
"text": "Subsequently, Instagram has in many ways become a reliable barometer of mainstream consumer culture and this means that it lends itself as a potentially useful tool to find stuff out about people."
},
{
"code": null,
"e": 3887,
"s": 3470,
"text": "Whilst it would be reasonable to assume that Instagramβs images and videos would be the primary βgo-toβ sources of data, Iβve found that analysing Instagramβs hashtag culture is a more fruitful way to get under the skin of themes and topics that occur on Instagram. Coupled with analytical techniques borrowed from Network Science means that the relationships between themes and topics can be more easily understood."
},
{
"code": null,
"e": 4214,
"s": 3887,
"text": "One of the more important parts of a Data Scientistβs job is being able to commit the time to ensure that our data is fit for purpose and this involves thorough cleaning of our data. This can take up a lot of time, especially with social media data that tends to be extremely unstructured and frequently littered with βnoiseβ."
},
{
"code": null,
"e": 4391,
"s": 4214,
"text": "Without sufficient pre-processing, the natural language processing techniques we use with social media data can lead to outputs that are hard to interpret and light on insight."
},
{
"code": null,
"e": 4708,
"s": 4391,
"text": "There are various methods we can use to clean and organise the raw language we find on social media but itβs made infinitely easier when users do it for us. Hashtag culture on Instagram β which by its very nature is organised, normalised and less noisy β is a cultural phenomenon that does all this hard work for us."
},
{
"code": null,
"e": 4993,
"s": 4708,
"text": "βA hashtag β introduced by the octothorpe symbol (#) β is a type of metadata tag used on social networks such as Twitter and other microblogging services. It lets users apply dynamic, user-generated tagging that helps other users easily find messages with a specific theme or contentβ"
},
{
"code": null,
"e": 5239,
"s": 4993,
"text": "People often end an Instagram post with a series of hashtags. Hashtags can provide a succinct summary of what that person was thinking, feeling and observing in that moment. Hashtags provide context and meaning that the image alone is unable to."
},
{
"code": null,
"e": 5281,
"s": 5239,
"text": "Letβs find an example to illustrate this."
},
{
"code": null,
"e": 5415,
"s": 5281,
"text": "Social media is increasingly likely to get bashed as being something that makes people miserable....and sadly there is truth in this."
},
{
"code": null,
"e": 5488,
"s": 5415,
"text": "Letβs be contrarian, flip this truth and explore HAPPINESS on Instagram."
},
{
"code": null,
"e": 5619,
"s": 5488,
"text": "The following Instagram post contains #happiness in the body of the post. What can we interpret from this post by the image alone?"
},
{
"code": null,
"e": 5663,
"s": 5619,
"text": "Not much. Maybe something to do with music?"
},
{
"code": null,
"e": 5793,
"s": 5663,
"text": "Other than the obvious there is little to go on from the image alone. What else were they thinking/feeling when they posted this?"
},
{
"code": null,
"e": 5972,
"s": 5793,
"text": "Now when we look at all the hashtags this person made alongside their post, we learn a lot more about this person and what they associated with #happiness at that moment in time."
},
{
"code": null,
"e": 6071,
"s": 5972,
"text": "For this person, happiness has an association with positivity, motivation, change and weight loss."
},
{
"code": null,
"e": 6169,
"s": 6071,
"text": "Whilst Instagram images can tell us something, the hashtags people use tell us considerably more."
},
{
"code": null,
"e": 6331,
"s": 6169,
"text": "Now, this is just one Instagram post containing #happiness. What happens when we look at the surrounding hashtags for other peopleβs posts mentioning #happiness?"
},
{
"code": null,
"e": 6442,
"s": 6331,
"text": "What happens if we scale this analysis up and look at thousands upon thousands of posts containing #happiness?"
},
{
"code": null,
"e": 6602,
"s": 6442,
"text": "Pretty soon we would be in a position where we have a vast number of hashtags to navigate. What scalable approach will allow us to make sense of all this data?"
},
{
"code": null,
"e": 6672,
"s": 6602,
"text": "This is where we can use Network Science and Graph Theory to help us."
},
{
"code": null,
"e": 6893,
"s": 6672,
"text": "Network science is a thriving and increasingly important cross-disciplinary domain that focuses on the representation, analysis and modelling of complex social, biological and technological systems as networks or graphsβ"
},
{
"code": null,
"e": 6949,
"s": 6893,
"text": "Source: http://tuvalu.santafe.edu/~aaronc/courses/5352/"
},
{
"code": null,
"e": 7195,
"s": 6949,
"text": "I like to think of Network Science and graph theory as methods that allow us to understand how things are connected. We can borrow some basic principles from Network Science and graph theory to understand how hashtags on Instagram are connected."
},
{
"code": null,
"e": 7459,
"s": 7195,
"text": "The subject matter relating to Network Science and graph theory is incredibly dense and would take a very long time to cover. This would distract from the practical focus of the project. There are however some simple but fundamental concepts that need explaining."
},
{
"code": null,
"e": 7579,
"s": 7459,
"text": "A graph (G) is the abstract representation of a network. Graphs are made up of vertices (V) and edges (E) where G=(V,E)"
},
{
"code": null,
"e": 7844,
"s": 7579,
"text": "Nodes (V) in a graph represent the unique data points that exist in our data. In the case of hashtag analysis, it makes sense for hashtags to represent the nodes in our network. So if our #happiness dataset only had two hashtags β #A and #B we would have two nodes"
},
{
"code": null,
"e": 8225,
"s": 7844,
"text": "Edges (E) are connections that represent some kind of relationship between nodes. In the case of analysing hashtags, it might make sense to represent this relationship as some kind of occurrence i.e. if the hashtag #A was mentioned in the same post as #B, we would assume that there is a relationship between #A and #B and therefore we would create an edge between these two nodes"
},
{
"code": null,
"e": 8360,
"s": 8225,
"text": "As we add hashtags from other posts to the graph and model their relationships with all previous posts we begin to see structure form."
},
{
"code": null,
"e": 8591,
"s": 8360,
"text": "Community Detection. We can use algorithms to identify and label clusters of topics/themes that are associated with #happiness. In this example we have 14 hashtags, all connected in various ways but with distinct clusters forming."
},
{
"code": null,
"e": 8844,
"s": 8591,
"text": "Degree Centrality / Betweenness Centrality. We can calculate what hashtags in the network are particularly important in linking the whole network. Much like Heathrow Airport links up a lot of the world, what hashtags link up the #happiness βlandscapeβ?"
},
{
"code": null,
"e": 9029,
"s": 8844,
"text": "Visualisation. If we plot the network using scatterplots, itβs a very compelling way to visualise a huge amount of information about #happiness that would be cumbersome to do otherwise"
},
{
"code": null,
"e": 9222,
"s": 9029,
"text": "MaeΜl Fabien has written a whole series which covers the content around graph theory really well. I strongly recommend you have a read of this at some point if you find this topic interesting."
},
{
"code": null,
"e": 9245,
"s": 9222,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9321,
"s": 9245,
"text": "Letβs now look at the practical steps we need to take to build our network."
},
{
"code": null,
"e": 9557,
"s": 9321,
"text": "I have built two Python classes that handle all the processes needed to go from capturing the data all the way through to building, visualising and analysing the #Happiness graph. The key pipelines within each class are outlined below."
},
{
"code": null,
"e": 9582,
"s": 9557,
"text": "class InstagramScraper()"
},
{
"code": null,
"e": 9640,
"s": 9582,
"text": "Search for hashtags on Instagram using Selenium WebDriver"
},
{
"code": null,
"e": 9671,
"s": 9640,
"text": "Capture unique Instagram URLβs"
},
{
"code": null,
"e": 9749,
"s": 9671,
"text": "Parse hashtags and other content from post html using multi-thread processing"
},
{
"code": null,
"e": 9772,
"s": 9749,
"text": "class InstagramGraph()"
},
{
"code": null,
"e": 9814,
"s": 9772,
"text": "Feature generation & exploratory analysis"
},
{
"code": null,
"e": 9829,
"s": 9814,
"text": "Data selection"
},
{
"code": null,
"e": 9844,
"s": 9829,
"text": "Graph building"
},
{
"code": null,
"e": 9858,
"s": 9844,
"text": "Visualisation"
},
{
"code": null,
"e": 9951,
"s": 9858,
"text": "You can access the full code for these classes and their relevant readme documentation here:"
},
{
"code": null,
"e": 10003,
"s": 9951,
"text": "https://github.com/kitsamho/Instagram_Scraper_Graph"
},
{
"code": null,
"e": 10028,
"s": 10003,
"text": "class InstagramScraper()"
},
{
"code": null,
"e": 10086,
"s": 10028,
"text": "Search for hashtags on Instagram using Selenium WebDriver"
},
{
"code": null,
"e": 10117,
"s": 10086,
"text": "Capture unique Instagram URLβs"
},
{
"code": null,
"e": 10190,
"s": 10117,
"text": "Parse hashtags and other content from html using multi-thread processing"
},
{
"code": null,
"e": 10479,
"s": 10190,
"text": "This stage uses a combination of automated web browsing and html parsing to scrape content from Instagram posts. I have built a custom Python class InstagramScraper that contains a pipeline of scraping and data extraction methods that returns a Pandas DataFrame of scraped Instagram data."
},
{
"code": null,
"e": 10597,
"s": 10479,
"text": "I will walk you through the main processes below with a few example code blocks to highlight the main steps involved."
},
{
"code": null,
"e": 10856,
"s": 10597,
"text": "There is functionality on Instagram where a user can search for specific hashtags and Instagram returns all the posts that contain that hashtag. This is our first step in getting the data we need; get Instagram to do the work for us using Selenium webdriver."
},
{
"code": null,
"e": 11068,
"s": 10856,
"text": "Every post on Instagram has its own unique URL. After we have searched for all the posts containing a specific hashtag, the first step is to capture all of these unique URLβs for posts that contain that hashtag."
},
{
"code": null,
"e": 11282,
"s": 11068,
"text": "I found the best way to do this is through using a combination of Selenium WebDriver and parsing the html on the fly, extracting each posts href attributes to a data structure as we scroll through all the content."
},
{
"code": null,
"e": 11565,
"s": 11282,
"text": "As this part of the Instagram site is highly dynamic requiring consistent scrolling to load new images, using some kind of browser based automation such as Selenium WebDriver is the only feasible way of capturing the data. This means it can take a little while to get all the links."
},
{
"code": null,
"e": 11727,
"s": 11565,
"text": "Once you have a list of all the links, you can then use a combination of urlopen and html parsing (I use Beautiful Soup) to get the data for each Instagram post."
},
{
"code": null,
"e": 11902,
"s": 11727,
"text": "Once you have the html for each post and parse its content, you will find that data for Instagram posts has a consistent structure resembling a dictionary / JSON style format"
},
{
"code": null,
"e": 12010,
"s": 11902,
"text": "The main output of the InstagramScraper class is a Pandas DataFrame containing a host of variables by post."
},
{
"code": null,
"e": 12128,
"s": 12010,
"text": "Most of these variables are self explanatory and offer all kinds of options for exploratory analysis beyond hashtags."
},
{
"code": null,
"e": 12357,
"s": 12128,
"text": "Now that we have our scraped data and have a nice and tidy Pandas DataFrame we can begin to think about processing our data in preparation for building our network and visualising our graph, which is where things get really fun."
},
{
"code": null,
"e": 12612,
"s": 12357,
"text": "I have built a second python class called InstagramGraph which also contains a pipeline of methods that allow you to analyse an Instagram dataset and ultimately model the hashtag data as an instance of a NetworkX graph object using Plotly visualisations."
},
{
"code": null,
"e": 12635,
"s": 12612,
"text": "class InstagramGraph()"
},
{
"code": null,
"e": 12676,
"s": 12635,
"text": "The key processes within this class are:"
},
{
"code": null,
"e": 12718,
"s": 12676,
"text": "Feature Generation & Exploratory Analysis"
},
{
"code": null,
"e": 12733,
"s": 12718,
"text": "Data Selection"
},
{
"code": null,
"e": 12748,
"s": 12733,
"text": "Graph Building"
},
{
"code": null,
"e": 12790,
"s": 12748,
"text": "Visualisation / Analysis & Interpretation"
},
{
"code": null,
"e": 12933,
"s": 12790,
"text": "The code block below outlines a pipeline from the InstagramGraph class which contains a suite of methods that create new features in our data."
},
{
"code": null,
"e": 13207,
"s": 12933,
"text": "There are several methods here, some are linguistic (e.g. determining the language of a post) although most of the processes within this method generate extra descriptive metrics such as median post count by user, total hashtag count by post and median hashtag use by user."
},
{
"code": null,
"e": 13585,
"s": 13207,
"text": "Whilst some of these new features/metrics arenβt directly related to graph building itβs alway worth generating more data points where you can as it offers a chance to do some exploratory analysis of the subject matter which might provide more context about what our graph model reveals. It also might inspire some other ideas for analysis that you hadnβt initially considered."
},
{
"code": null,
"e": 13614,
"s": 13585,
"text": "Letβs explore some of these."
},
{
"code": null,
"e": 13769,
"s": 13614,
"text": "The langdetect library in Python allows us to access the Google Translation library over an API and gives us the ability to identify language in our text."
},
{
"code": null,
"e": 14031,
"s": 13769,
"text": "Note β due to a limit on Google Cloud API requests this can run quite slow when processing a large volume of data. For the purposes of example, this is fine; if you want to productionise this you may want to think about a faster alternative and consider paying."
},
{
"code": null,
"e": 14139,
"s": 14031,
"text": "As we can see the majority of the Instagram posts for #happiness are in English β over 80% of our data set."
},
{
"code": null,
"e": 14379,
"s": 14139,
"text": "A look at some distributions show that the data on user post frequency is extremely positively skewed; there are handful of outlier accounts that post very frequently (up to 140 times) whereas the majority of posters are posting only once."
},
{
"code": null,
"e": 14667,
"s": 14379,
"text": "To extract our hashtags I have created two methods that do the job for us. One method takes a string input and returns a list of hashtags. If people have failed to include a space between their string of hashtags, the code can account for this and βunpackβ them into individual hashtags."
},
{
"code": null,
"e": 15112,
"s": 14667,
"text": "Analysis of hashtag frequency by post indicates that whilst frequency by post tends to follow a uniform distribution , there are some outlier posts that contain an unusually high number of hashtags. Further exploration shows that this partially seems to be driven by people who have posted multiple times across the dataset (high frequency posters). So broadly speaking, those that post more often also tend to use more hashtags in their posts."
},
{
"code": null,
"e": 15572,
"s": 15112,
"text": "A second method then takes this list of hashtags and looks to lemmatise the input, where appropriate. For those unfamiliar with lemmatisation, this is the process where we can reduce a word to its root lexical form. For instance if we have the hashtags #happiest and #happier β these are both inflections of the verb #happy. Therefore lemmatisation reduces these inflections back to #happy. Iβve used an instance of a spaCy model to perform the lemmatisation."
},
{
"code": null,
"e": 15768,
"s": 15572,
"text": "Ok, so the next step is to select the data we want to model. The code outlines a pipeline from the InstagramGraph class which contains a suite of methods that allow us to select the data we want."
},
{
"code": null,
"e": 16016,
"s": 15768,
"text": "Whilst Instagram is an international platform, for simplicity we might want to consider filtering out non-English posts. As we saw previously, over 80% of the data for #happiness is in English so it makes sense to focus on this subset of the data."
},
{
"code": null,
"e": 16269,
"s": 16016,
"text": "Verified users tend to be either brands, celebrities or online shops i.e. βpeopleβ who likely donβt represent the average Instagram user. Depending on your objectives for this analysis, you might want to consider removing verified users from your data."
},
{
"code": null,
"e": 16603,
"s": 16269,
"text": "A cursory inspection of high frequency posters reveals that these are sometimes unverified accounts that are using Instagram to sell stuff under a non-verified status. Do we feel this represents that audience we are interested in understanding? If so we can leave them in, if not β we can filter them out prior to building our graph."
},
{
"code": null,
"e": 16803,
"s": 16603,
"text": "I thought it made sense to have the option to lemmatise the scraped hashtags where possible as it reduces the amount of data needed to build the graph β we donβt necessarily need all that extra data."
},
{
"code": null,
"e": 16922,
"s": 16803,
"text": "Now that we we have selected the data we want to model, we can build the graph. The pipeline we use for this is below:"
},
{
"code": null,
"e": 16987,
"s": 16922,
"text": "There are three main processes that take place in this pipeline:"
},
{
"code": null,
"e": 17341,
"s": 16987,
"text": "This simply extracts hashtags from our DataFrame into a list of lists β each sub-list representing a post from our #Happiness data set. By having the input as a simple list of lists, we can easily re-purpose this graph building approach to other sources of data in future where we can wrangle the raw data in a similarly structured / list of list format"
},
{
"code": null,
"e": 17610,
"s": 17341,
"text": "The next step is to take our list of lists and use this to generate the nodes and edges that exist across the entire data set. Remember the nodes are the unique hashtags in the dataset and an edge is created if any two hashtags are mentioned together in the same post."
},
{
"code": null,
"e": 17747,
"s": 17610,
"text": "The method saves two generated DataFrames as attributes β a DataFrame containing all the nodes and a DataFrame containing all the edges."
},
{
"code": null,
"e": 17843,
"s": 17747,
"text": "The next stage is to add these nodes and edges into an instance of a NetworkX graph object (G)."
},
{
"code": null,
"e": 17983,
"s": 17843,
"text": "Once we have created our NetworkX graph object β we can then use various calculated graph attributes to enhance our node data even further."
},
{
"code": null,
"e": 18005,
"s": 17983,
"text": "Betweeness Centrality"
},
{
"code": null,
"e": 18025,
"s": 18005,
"text": "Adjacency Frequency"
},
{
"code": null,
"e": 18048,
"s": 18025,
"text": "Clustering Coefficient"
},
{
"code": null,
"e": 18058,
"s": 18048,
"text": "Community"
},
{
"code": null,
"e": 18204,
"s": 18058,
"text": "Now we have an instance of a NetworkX graph object that has been built with our node and edge data that we extracted from our #Happiness dataset."
},
{
"code": null,
"e": 18286,
"s": 18204,
"text": "We can now use Plotly to visualise the hashtag graph as a connected scatter plot."
},
{
"code": null,
"e": 18394,
"s": 18286,
"text": "There are a few arguments that I have set up that allow for a degree of customisation to the visualisation."
},
{
"code": null,
"e": 18462,
"s": 18394,
"text": "def plotGraph(node_size=βadjacency_frequencyβ,colorscale=βViridisβ)"
},
{
"code": null,
"e": 18864,
"s": 18462,
"text": "I think it makes sense to use node size to convey some other variable β the default is βadjacency_frequencyβ i.e. how many other nodes a node has edge connections with. In this instance a smaller node would represent a hashtag with fewer edges and contrastingly a larger node would have more edges. We can emphasise this point even further by applying a colour scale that is correlated with node size."
},
{
"code": null,
"e": 18909,
"s": 18864,
"text": "def plotGraph(layout=nx.kamada_kawai_layout)"
},
{
"code": null,
"e": 19340,
"s": 18909,
"text": "NetworkX has a few different graph layouts. The kamada kawai layout arranges nodes in a way so that there are as few overlapping edges as possible. Therefore this has a tendency for the nodes to be arranged in a way that conveys clusters ...but most importantly tends to be the easiest layout to interpret. There are alternatives such as the circular layout or random layout but these are harder to make sense of in my experience."
},
{
"code": null,
"e": 19372,
"s": 19340,
"text": "def plotGraph(light_theme=True)"
},
{
"code": null,
"e": 19417,
"s": 19372,
"text": "There are two colour themes, light and dark."
},
{
"code": null,
"e": 19668,
"s": 19417,
"text": "We can see quite easily how there are several well connected hashtags in the #happiness graph(hashtags that have more node connections). Smile, life, family, motivation, party...these are all hashtags that are frequently mentioned across the network."
},
{
"code": null,
"e": 19908,
"s": 19668,
"text": "As we can see, the force directed layout has a tendency to push groups of hashtags together that are well connected . If we plot the graph again but colour nodes using their community label we can better visualise how communities fall out."
},
{
"code": null,
"e": 19943,
"s": 19908,
"text": "def plotGraph(community_plot=True)"
},
{
"code": null,
"e": 20184,
"s": 19943,
"text": "There seems to be three easily identifiable communities in the #happiness network. We can explore which specific hashtags contribute to each of the communities using sunburst visualisations. Click on the wheel to interact with the clusters."
},
{
"code": null,
"e": 20246,
"s": 20184,
"text": "Community detection identified three clusters interpreted as:"
},
{
"code": null,
"e": 20379,
"s": 20246,
"text": "Aspects of happiness that seem to be about what people do and experience (e.g. β#photography, #summer, #travel,#family ) (Segment 0)"
},
{
"code": null,
"e": 20516,
"s": 20379,
"text": "Aspects of happiness that broadly seem to be about how people think and feel (e.g #life, #motivation, #inspiration, #quotes) (Segment 1)"
},
{
"code": null,
"e": 20615,
"s": 20516,
"text": "A third very distinct cluster was entirely about #weddings, #celebrations and #parties (Segment 3)"
},
{
"code": null,
"e": 20771,
"s": 20615,
"text": "I hope you enjoyed this practical walk through on how to extract hashtag data from Instagram and analyse it using principles borrowed from Network Science."
},
{
"code": null,
"e": 20808,
"s": 20771,
"text": "My main aims with this project were:"
},
{
"code": null,
"e": 21035,
"s": 20808,
"text": "To try and demonstrate that there is an abundance of accessible and potentially insightful content buried in social media data.To show you that there are almost always interesting patterns in places you might not have expected"
},
{
"code": null,
"e": 21163,
"s": 21035,
"text": "To try and demonstrate that there is an abundance of accessible and potentially insightful content buried in social media data."
},
{
"code": null,
"e": 21263,
"s": 21163,
"text": "To show you that there are almost always interesting patterns in places you might not have expected"
},
{
"code": null,
"e": 21573,
"s": 21263,
"text": "I chose #happiness as a case study because hopefully this is something that we can all relate to. However the code works for any hashtag. As long as you can gather sufficient volumes of data to model β there are observable relationships for anything. You could consider brands, places, events and even people."
},
{
"code": null,
"e": 21749,
"s": 21573,
"text": "You donβt even need to use Instagram; the code can easily be repurposed to use all kinds of meta data beyond Instagram....Twitter, LinkedIn even TikTok could be a possibility."
},
{
"code": null,
"e": 21903,
"s": 21749,
"text": "As I mentioned before, the code is available on my GitHub so please feel free to take, use, evolve and improve. Iβd love to see what people do with this."
},
{
"code": null,
"e": 21922,
"s": 21903,
"text": "Until next time! π"
},
{
"code": null,
"e": 21933,
"s": 21922,
"text": "Cheers Sam"
},
{
"code": null,
"e": 21996,
"s": 21933,
"text": "My GitHub: https://github.com/kitsamho/Instagram_Scraper_Graph"
},
{
"code": null,
"e": 22091,
"s": 21996,
"text": "Introduction to Graphs by MaeΜl Fabien: https://maelfabien.github.io/machinelearning/graph_1/#"
},
{
"code": null,
"e": 22128,
"s": 22091,
"text": "Instagram: https://www.instagram.com"
},
{
"code": null,
"e": 22192,
"s": 22128,
"text": "Selenium WebDriver: https://chromedriver.chromium.org/downloads"
},
{
"code": null,
"e": 22264,
"s": 22192,
"text": "Beautiful Soup : https://www.crummy.com/software/BeautifulSoup/bs4/doc/"
}
] |
D3.js node.sort() Function - GeeksforGeeks
|
31 Aug, 2020
The node.sort() function in D3.js is used to sort the children at each level of the given hierarchical data. The comparator function can be used to define the basis on which the sorting would be done.
Syntax:
node.sort( compare )
Parameters: This function accepts a single parameter as mentioned above and described below:
compare: It is a function that specifies the basis on which sorting should be done.
Return Value: This function returns an object.
Below example illustrates the node.sort() function in D3.js:
Example 1:
HTML
<!DOCTYPE html><html> <head> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> // Construct a tree var tree = { // Specify the root node name: "rootNode", children: [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 }, { value: 6 }, ] }; var obj = d3.hierarchy(tree); // Use the sort() function to sort // the nodes in descending order var sorted = obj.sum(d => d.value) .sort((a, b) => d3.descending(a.value, b.value)); // Show the sorted output console.log( sorted.children.map( d => ["value", d.value]) ); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <head> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> // Construct a tree var tree = { // Specify the root node name: "rootNode", children: [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 }, { value: 6 }, ] }; var obj = d3.hierarchy(tree); // Use the sort() function to sort // the nodes in ascending order var sorted = obj.sum(d => d.value) .sort((a, b) => d3.ascending(a.value, b.value)); // Show the sorted output console.log( sorted.children.map(d => ["value", d.value]) ) </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 25501,
"s": 25300,
"text": "The node.sort() function in D3.js is used to sort the children at each level of the given hierarchical data. The comparator function can be used to define the basis on which the sorting would be done."
},
{
"code": null,
"e": 25509,
"s": 25501,
"text": "Syntax:"
},
{
"code": null,
"e": 25530,
"s": 25509,
"text": "node.sort( compare )"
},
{
"code": null,
"e": 25623,
"s": 25530,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25707,
"s": 25623,
"text": "compare: It is a function that specifies the basis on which sorting should be done."
},
{
"code": null,
"e": 25754,
"s": 25707,
"text": "Return Value: This function returns an object."
},
{
"code": null,
"e": 25815,
"s": 25754,
"text": "Below example illustrates the node.sort() function in D3.js:"
},
{
"code": null,
"e": 25826,
"s": 25815,
"text": "Example 1:"
},
{
"code": null,
"e": 25831,
"s": 25826,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> // Construct a tree var tree = { // Specify the root node name: \"rootNode\", children: [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 }, { value: 6 }, ] }; var obj = d3.hierarchy(tree); // Use the sort() function to sort // the nodes in descending order var sorted = obj.sum(d => d.value) .sort((a, b) => d3.descending(a.value, b.value)); // Show the sorted output console.log( sorted.children.map( d => [\"value\", d.value]) ); </script></body> </html>",
"e": 26692,
"s": 25831,
"text": null
},
{
"code": null,
"e": 26700,
"s": 26692,
"text": "Output:"
},
{
"code": null,
"e": 26711,
"s": 26700,
"text": "Example 2:"
},
{
"code": null,
"e": 26716,
"s": 26711,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> // Construct a tree var tree = { // Specify the root node name: \"rootNode\", children: [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 }, { value: 6 }, ] }; var obj = d3.hierarchy(tree); // Use the sort() function to sort // the nodes in ascending order var sorted = obj.sum(d => d.value) .sort((a, b) => d3.ascending(a.value, b.value)); // Show the sorted output console.log( sorted.children.map(d => [\"value\", d.value]) ) </script></body> </html>",
"e": 27556,
"s": 26716,
"text": null
},
{
"code": null,
"e": 27564,
"s": 27556,
"text": "Output:"
},
{
"code": null,
"e": 27570,
"s": 27564,
"text": "D3.js"
},
{
"code": null,
"e": 27581,
"s": 27570,
"text": "JavaScript"
},
{
"code": null,
"e": 27598,
"s": 27581,
"text": "Web Technologies"
},
{
"code": null,
"e": 27696,
"s": 27598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27757,
"s": 27696,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27798,
"s": 27757,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27838,
"s": 27798,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27892,
"s": 27838,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27940,
"s": 27892,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27982,
"s": 27940,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28015,
"s": 27982,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28058,
"s": 28015,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28120,
"s": 28058,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to create an unordered_map of pairs in C++?
|
In this tutorial, we will be discussing a program to understand how to create an unordered map of pairs in C++.
Unordered maps are the ones that don't contain hash function for the pairs by default. If we want a hash value for a particular pair, it needs to be passed on explicitly.
Live Demo
#include <bits/stdc++.h>
using namespace std;
//to hash any given pair
struct hash_pair {
template <class T1, class T2>
size_t operator()(const pair<T1, T2>& p) const{
auto hash1 = hash<T1>{}(p.first);
auto hash2 = hash<T2>{}(p.second);
return hash1 ^ hash2;
}
};
int main(){
//explicitly sending hash function
unordered_map<pair<int, int>, bool, hash_pair> um;
//creating some pairs to be used as keys
pair<int, int> p1(1000, 2000);
pair<int, int> p2(2000, 3000);
pair<int, int> p3(2005, 3005);
um[p1] = true;
um[p2] = false;
um[p3] = true;
cout << "Contents of the unordered_map : \n";
for (auto p : um)
cout << "[" << (p.first).first << ", "<< (p.first).second << "] ==> " << p.second << "\n";
return 0;
}
Contents of the unordered_map :
[1000, 2000] ==> 1
[2005, 3005] ==> 1
[2000, 3000] ==> 0
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to understand how to create an unordered map of pairs in C++."
},
{
"code": null,
"e": 1345,
"s": 1174,
"text": "Unordered maps are the ones that don't contain hash function for the pairs by default. If we want a hash value for a particular pair, it needs to be passed on explicitly."
},
{
"code": null,
"e": 1356,
"s": 1345,
"text": " Live Demo"
},
{
"code": null,
"e": 2134,
"s": 1356,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n//to hash any given pair\nstruct hash_pair {\n template <class T1, class T2>\n size_t operator()(const pair<T1, T2>& p) const{\n auto hash1 = hash<T1>{}(p.first);\n auto hash2 = hash<T2>{}(p.second);\n return hash1 ^ hash2;\n }\n};\nint main(){\n //explicitly sending hash function\n unordered_map<pair<int, int>, bool, hash_pair> um;\n //creating some pairs to be used as keys\n pair<int, int> p1(1000, 2000);\n pair<int, int> p2(2000, 3000);\n pair<int, int> p3(2005, 3005);\n um[p1] = true;\n um[p2] = false;\n um[p3] = true;\n cout << \"Contents of the unordered_map : \\n\";\n for (auto p : um)\n cout << \"[\" << (p.first).first << \", \"<< (p.first).second << \"] ==> \" << p.second << \"\\n\";\n return 0;\n}"
},
{
"code": null,
"e": 2223,
"s": 2134,
"text": "Contents of the unordered_map :\n[1000, 2000] ==> 1\n[2005, 3005] ==> 1\n[2000, 3000] ==> 0"
}
] |
Python Pandas - Create a Horizontal Bar Chart
|
To plot a Horizontal Bar Plot, use the pandas.DataFrame.plot.barh. A bar plot shows comparisons among discrete categories.
At first, import the required libraries β
import pandas as pd
import matplotlib.pyplot as plt
Create a Pandas DataFrame with 4 columns β
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})
Plot Horizontal Bar Chart using the plot.barh() β
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')
Following is the complete code β
import pandas as pd
import matplotlib.pyplot as plt
# creating dataframe
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})
# plotting Horizontal Bar Chart
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')
# set the label
plt.xlabel("CC (Cubic Capacity)" )
# display the plotted Horizontal Bar Chart
plt.show()
This will produce the following output β
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "To plot a Horizontal Bar Plot, use the pandas.DataFrame.plot.barh. A bar plot shows comparisons among discrete categories."
},
{
"code": null,
"e": 1227,
"s": 1185,
"text": "At first, import the required libraries β"
},
{
"code": null,
"e": 1279,
"s": 1227,
"text": "import pandas as pd\nimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1322,
"s": 1279,
"text": "Create a Pandas DataFrame with 4 columns β"
},
{
"code": null,
"e": 1568,
"s": 1322,
"text": "dataFrame = pd.DataFrame({\"Car\": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units_Sold\": [ 100, 110, 150, 80, 200, 90]\n})"
},
{
"code": null,
"e": 1618,
"s": 1568,
"text": "Plot Horizontal Bar Chart using the plot.barh() β"
},
{
"code": null,
"e": 1710,
"s": 1618,
"text": "dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')\n"
},
{
"code": null,
"e": 1743,
"s": 1710,
"text": "Following is the complete code β"
},
{
"code": null,
"e": 2294,
"s": 1743,
"text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\n# creating dataframe\ndataFrame = pd.DataFrame({\"Car\": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units_Sold\": [ 100, 110, 150, 80, 200, 90]\n})\n\n# plotting Horizontal Bar Chart\ndataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')\n\n# set the label\nplt.xlabel(\"CC (Cubic Capacity)\" )\n\n# display the plotted Horizontal Bar Chart\nplt.show()"
},
{
"code": null,
"e": 2335,
"s": 2294,
"text": "This will produce the following output β"
}
] |
How to call a parent window function from an iframe using JavaScript?
|
To call a parent window function, use βwindow.topβ.
You can try to run the following code to call a parent window function from an iframe
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
function display(){
alert("Hello World!");
}
</script>
<iframe id="myFrame">
<a onclick="window.top.display();" href="#">Click</a>
</iframe>
</body>
</html>
|
[
{
"code": null,
"e": 1114,
"s": 1062,
"text": "To call a parent window function, use βwindow.topβ."
},
{
"code": null,
"e": 1200,
"s": 1114,
"text": "You can try to run the following code to call a parent window function from an iframe"
},
{
"code": null,
"e": 1210,
"s": 1200,
"text": "Live Demo"
},
{
"code": null,
"e": 1475,
"s": 1210,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n function display(){\n alert(\"Hello World!\");\n }\n </script>\n <iframe id=\"myFrame\">\n <a onclick=\"window.top.display();\" href=\"#\">Click</a>\n </iframe>\n </body>\n</html>"
}
] |
\odot - Tex Command
|
\odot - Used to create odot symbol.
{ \odot}
\odot command draws odot symbol.
\odot
β
\odot
β
\odot
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8022,
"s": 7986,
"text": "\\odot - Used to create odot symbol."
},
{
"code": null,
"e": 8031,
"s": 8022,
"text": "{ \\odot}"
},
{
"code": null,
"e": 8064,
"s": 8031,
"text": "\\odot command draws odot symbol."
},
{
"code": null,
"e": 8077,
"s": 8064,
"text": "\n\\odot\n\nβ\n\n\n"
},
{
"code": null,
"e": 8088,
"s": 8077,
"text": "\\odot\n\nβ\n\n"
},
{
"code": null,
"e": 8094,
"s": 8088,
"text": "\\odot"
},
{
"code": null,
"e": 8126,
"s": 8094,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8139,
"s": 8126,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8172,
"s": 8139,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8185,
"s": 8172,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8217,
"s": 8185,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8253,
"s": 8217,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8288,
"s": 8253,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8305,
"s": 8288,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8338,
"s": 8305,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8352,
"s": 8338,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8384,
"s": 8352,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8399,
"s": 8384,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8406,
"s": 8399,
"text": " Print"
},
{
"code": null,
"e": 8417,
"s": 8406,
"text": " Add Notes"
}
] |
3-D Reconstruction with Vision. Exactly an year back, before I started... | by Venkatesh Tata | Towards Data Science
|
Exactly a year back, before I started writing this article, I watched Andrej Karapathy, the director of AI at Tesla delivering a talk where he showed the world a glimpse of how a Tesla car perceives depth using the cameras hooked to the car in-order to reconstruct its surroundings in 3D and take decisions in real-time, everything(except the front radar for safety) was being computed just with vision. And that presentation blew my mind!
Of course, I knew 3-D reconstruction of an environment is possible through cameras, but I was in a mindset that why would anyone risk using a normal camera when weβve got such highly accurate sensors like LiDAR, Radar, etc. that could give us an accurate presentation of the environment in 3-D with far less computation? And I started studying(trying to understand) papers related to this topic of Depth Perception and 3-D Reconstruction from Vision and came to the conclusion that we humans have never had rays coming out of our heads to perceive depth and environment around us, we are intelligent and aware of our surroundings just with the two eyes weβve got, from driving our car or bike from office to work, or driving a formula 1 at 230 mph in the worldβs most dangerous tracks, we never required lasers to make decisions in microseconds. The world around us was constructed by us for us, beings with vision and so as Elon said, βthese costly sensors would become pointless once we solve visionβ.
Thereβs huge research going on in this field of depth perception with vision, especially with the advancements in Machine Learning and Deep Learning we are now able to compute depth just from vision at high accuracy. So before we start learning the concepts and implementing these techniques, let us look at what stage this technology is currently in and what are the applications of it.
Robot Vision:
Creating HD Maps for autonomous driving:
SfM(Structure from Motion) and SLAM(Simultaneous Localisation and Mapping) are one of the major techniques that make use of the concepts that I am going to introduce you to in this tutorial.
Now that weβve got enough inspiration to learn, Iβll start the tutorial. So first Iβm going to teach you the basic concepts required to understand whatβs happening behind the hood, and then apply them using the OpenCV library in C++. The question you might ask is why am I implementing these concepts in C++ while doing it in python would be far easier, and thereβs reason behind it. The first reason is that python is not fast enough for these concepts to implement in real-time, and the second reason is that unlike python, using C++ would mandate our understanding of the concept without which one canβt implement.
In this tutorial we are going to write two programs, one is to get a depth map of a scene and another is to obtain a point cloud of the scene, both using stereo vision.
Before we dive right into the coding part, it is important for us to understand the concepts of camera geometry, which I am going to teach you now.
The process used to produce images has not changed since the beginning of photography. The light coming from an observed scene is captured by a camera through a frontal aperture(a lens) that shoots the light onto an image plane located at the back of the camera lens. The process is illustrated in the figure below:
From the above figure, do is the distance from the lens to the observed object, di is the distance between the lens and image plane. And f will hence become the focal length of the lens. These described quantities have a relation between them from the so-called βThin Lens Equationβ shown below:
Now let us look into the process of how an object from the real-world that is 3-Dimensional, is projected onto a 2-Dimensional plane(a photograph). The best way for us to understand this is by taking a look into how a camera works.
A camera can be seen as the function that maps 3-D world to a 2-D image. Let us take the simplest model of a camera, that is the Pinhole Camera Model, the older photography mechanisms in human history. Below is a working diagram of a pinhole camera :
From this diagram we can derive :
Here itβs natural that the size hi of the image formed from the object will be inversely proportional to the distance do of the object from camera. And also that a 3-D scene point located at position (X, Y, Z) will be projected onto the image plane at (x,y) where (x,y) = (fX/Z, fY/Z). Where the Z coordinate refers to the depth of the point, which was done in the previous image. This entire camera configuration and notation can be described with a simple matrix using the homogeneous coordinate system.
When cameras generate a projected image of the world, projective geometry is used as an algebraic representation of the geometry of objects, rotations and transformations in the real world.
Homogeneous coordinates are a system of coordinates used in projective geometry. Even though we can represent the positions of objects(or any point in 3-D space) in real-world in Euclidean Space, any transformation or rotation that has to be performed must be performed in homogeneous coordinate space and then brought back. Let us look at the advantages of using Homogeneous coordinates:
Formulas involving Homogeneous Coordinates are often simpler than in the Cartesian world.
Points at infinity can be represented using finite coordinates.
A single matrix can represent all the possible protective transformations that can occur between a camera and the world.
In homogeneous coordinate space, 2-D points are represented by 3 vectors, and 3-D points are represented by 4 vectors.
In the above equations, the first matrix with the f notation is called the intrinsic parameter matrix(or commonly known as the intrinsic matrix). Here the intrinsic matrix contains just the focal length(f) right now, weβll look into more parameters of this matrix ahead of this tutorial.
The second matrix with the r and t notations is called the extrinsic parameter matrix(or commonly known as the Extrinsic Matrix). The elements within this matrix represent the rotation and translation parameters of the camera(that is where and how the camera is placed in real world).
Thus these intrinsic and extrinsic matrices together can give us a relation between the (x,y) point in image and (X, Y, Z) point in real world. This is how a 3-D scene point is projected onto a 2-D plane depending on the given cameraβs intrinsic and extrinsic parameters.
Now that we have acquired enough knowledge about projective geometry and camera model, itβs time to introduce you to one of the most important element in computer vision geometry, the Fundamental Matrix.
Now that we know how a point in the 3-D world is projected onto an image plane of a camera. We will look into the projective relationship that exists between two images displaying the same scene. These two cameras when separated by a rigid baseline, we use the term stereo-vision. Consider two pinhole cameras observing a given scene point sharing the same baseline as shown in the figure below :
From the above figure, the world point X has its image at position x on the image plane, now this x can be located anywhere on this line in 3-D space. Which implies that if we want to find the same point x in another image, we need to search along the projection of this line on the second image.
This imaginary line drawn from x is known as the epipolar line of x. This epipolar line brings a fundamental constraint with it, that is, the match of a given point must lie on this line in another view. It means that if you want to find x from the first image in the second image, you have to look for it along the epipolar line of x on the second image. These epipolar lines can characterise the geometry between the two views. An important thing to note here is that all the epipolar lines always pass through one single point. This point corresponds to the projection of one cameraβs centre onto the other cameraβs centre and this point is called the epipole.
We can consider fundamental matrix F as the one that maps a 2-D image point in one view to an epipolar line in the other image view. The fundamental matrix between an image pair can be estimated by solving a set of equations that involve a certain number of known matched points between the two images. The minimum number of such matches is seven and an optimal number is eight. Then for a point in one image, the fundamental matrix gives the equation of the line on which its corresponding point in another view should be found.
If the corresponding point of a point of a point (x, y) is (xβ, yβ), and the fundamental matrix between the two images planes is F, then we must have the following equation in homogeneous coordinates.
This equation expresses the relationship between two corresponding points and known as the epipolar constraint.
When two cameras observe the same scene, they see the same objects but under different viewpoints. There are libraries like OpenCV in both C++ and Python that provide us with feature detectors that find us certain points with descriptors in images that they think are unique to image and can be found if given another image of the same scene. However, practically it is not possible to guarantee that a matching set obtained between two images by comparing the descriptors of the detected feature points(like SIFT, ORB, etc.) will be exact and true. This is why a fundamental matrix estimation method based on RANSAC (Random Sampling Consensus) strategy has been introduced.
The idea behind RANSAC is to randomly select some data points from a given set of data points and perform an estimation with only those. The number of selected points should be the minimum number of points required to estimate the mathematical entity, which in our case of the fundamental matrix is eight matches. Once the fundamental matrix is estimated from these eight random matches, all the other matches in the match set are tested against the epipolar constraint we discussed. These matches form the support set of the computed fundamental matrix.
The larger the support set, the higher the probability that the computed matrix is the right one. And if one of the randomly selected matches is an incorrect match, then the computed fundamental matrix will also be incorrect, and its support set will be expected to be small. This process is repeated a number of times and in the end, the matrix with the largest support set will be retained as the most probable one.
The reason humans have evolved to be species with two eyes is so that we can perceive depth. And when we organise cameras in a similar way in a machine, itβs called Stereo-Vision. A stereo-vision system is generally made of two side-by-side cameras looking at the same scene, the following figure shows the setup of a stereo rig with an ideal configuration, aligned perfectly.
Under such an ideal configuration of cameras as shown in the above figure, cameras are only separated by an horizontal translation and therefore all the epipolar lines are horizontal. It means that the corresponding points have the same y coordinates and search is reduced to 1 Dimensional line. When cameras are separated by such a pure horizontal translation, the projective equation of the second camera would become:
The equation would make more sense by looking at the diagram below, which is the general case with digital cameras :
where the point (uo, vo) is the pixel position where the line passing through the principle point of the lens pierces the image plane. Here we obtain a relation :
Here, the term (x-xβ) is called the disparity and Z is, of course, the depth. In order to compute a depth map from a stereo pair, the disparity of each pixel must be computed.
But in a practical world, obtaining such an ideal configuration is very difficult. Even if we place the cameras accurately, they would unavoidably include some extra transitional and rotational components.
Fortunately, it is possible to rectify these images to produce horizontal epilines required by using a robust matching algorithm which makes use of a fundamental matrix to perform the rectification.
Now let us start by obtaining a fundamental matrix for the below stereo images :
You can download the above images from my GitHub repository by clicking here. Before you start writing the code in this tutorial, make sure you have opencv and opencv-contrib libraries built on your computer. If they are not built, I would suggest you visit this link to install them if you are on Ubuntu.
#include <opencv2/opencv.hpp>#include "opencv2/xfeatures2d.hpp"using namespace std;using namespace cv;int main(){cv::Mat img1, img2;img1 = cv::imread("imR.png",cv::IMREAD_GRAYSCALE);img2 = cv::imread("imL.png",cv::IMREAD_GRAYSCALE);
The first thing we did is included the required libraries from opencv and opencv-contrib which I asked you to build before starting this section. In main() function we have initialised two variables of the cv:Mat datatype which is a member function of the opencv library, the Mat datatype can hold vectors of any size by dynamically allocating memory, especially images. Then using the cv::imread() we have imported both the images into img1 and img2 of the mat datatype. The cv::IMREAD_GRAYSCALE parameter imports images as gray-scale.
// Define keypoints vectorstd::vector<cv::KeyPoint> keypoints1, keypoints2;// Define feature detectorcv::Ptr<cv::Feature2D> ptrFeature2D = cv::xfeatures2d::SIFT::create(74);// Keypoint detectionptrFeature2D->detect(img1,keypoints1);ptrFeature2D->detect(img2,keypoints2);// Extract the descriptorcv::Mat descriptors1;cv::Mat descriptors2;ptrFeature2D->compute(img1,keypoints1,descriptors1);ptrFeature2D->compute(img2,keypoints2,descriptors2);
Here we are making use of opencvβs SIFT feature detector in order to extract the required feature points from the images. If you want to understand more about how these feature detectors work visit this link. The descriptors we obtained above describe each point extracted, this description is used in order to find it in another image.
// Construction of the matchercv::BFMatcher matcher(cv::NORM_L2);// Match the two image descriptorsstd::vector<cv::DMatch> outputMatches;matcher.match(descriptors1,descriptors2, outputMatches);
BFMatcher takes the descriptor of one feature in the first set and is matched with all the other features in the second set using some threshold distance calculation, and the closest one is returned. We are storing all the matches returned by BFMatches in output matches variable of type vector<cv::DMatch>.
// Convert keypoints into Point2fstd::vector<cv::Point2f> points1, points2;for (std::vector<cv::DMatch>::const_iterator it= outputMatches.begin(); it!= outputMatches.end(); ++it) { // Get the position of left keypoints points1.push_back(keypoints1[it->queryIdx].pt); // Get the position of right keypoints points2.push_back(keypoints2[it->trainIdx].pt); }
The acquired keypoints first need to be converted into cv::Point2f type in-order to be used with cv::findFundamentalMat, a function we will make use of for computing the fundamental matrix using these feature points we abstracted. The two resulting vectors Points1 and Points2 contain the corresponding point coordinates in two images.
std::vector<uchar> inliers(points1.size(),0);cv::Mat fundamental= cv::findFundamentalMat( points1,points2, // matching points inliers, // match status (inlier or outlier) cv::FM_RANSAC, // RANSAC method 1.0, // distance to epipolar line 0.98); // confidence probabilitycout<<fundamental; //include this for seeing fundamental matrix
And finally, we have called the cv::findFundamentalMat.
// Compute homographic rectificationcv::Mat h1, h2;cv::stereoRectifyUncalibrated(points1, points2, fundamental, img1.size(), h1, h2);// Rectify the images through warpingcv::Mat rectified1;cv::warpPerspective(img1, rectified1, h1, img1.size());cv::Mat rectified2;cv::warpPerspective(img2, rectified2, h2, img1.size());
As i explained you previously in the tutorial that obtaining an ideal configuration of cameras without any error is very difficult in a practical world, hence opencv offers a rectifying function that applies homographic transformation to project the image plane of each camera onto a perfectly aligned virtual plane. This transformation is computed from a set of matched points and fundamental matrix.
// Compute disparitycv::Mat disparity;cv::Ptr<cv::StereoMatcher> pStereo = cv::StereoSGBM::create(0, 32,5);pStereo->compute(rectified1, rectified2, disparity);cv::imwrite("disparity.jpg", disparity);
And finally, weβve computed the disparity map. From the image below, the darker pixels are representing objects nearer to the camera, and the lighter pixels are representing the objects far from the camera. The white pixel noise you are seeing in the output disparity map can be removed with some filters which I wonβt be covering in this tutorial.
Now that we have successfully obtained a depth map from a given stereo pair. Let us now try to re-project the obtained 2-D image points onto 3-D space by making use of a tool called 3D-Viz from opencv that will help us render a 3-D point cloud.
But this time, rather than estimating a fundamental matrix from the given image points, we will project the points using an essential matrix.
The essential matrix can be seen as a fundamental matrix, but for calibrated cameras. We can also call it a specialisation over fundamental matrix where the matrix is computed using calibrated cameras, means that we must first acquire knowledge about our camera in the world.
Hence in-order for us to estimate the essential matrix, we first need the intrinsic matrix of the camera( a matrix that represents the optical centre and focal length of the given camera). Let us take a look at the equation below :
Here, from the first matrix, the fx and fy represent the focal length of the camera, (uo, vo) is the principle point. This is the intrinsic matrix and our goal is to estimate it.
This process of finding different camera parameters is known as camera calibration. We can obviously use specifications provided by the camera manufacturer, but for the tasks like 3-D reconstruction, which we will be doing, these specifications are not accurate enough. Hence we are going to perform our own camera calibration.
The idea is to show a set of scene points to the camera, the points for which we know their actual 3-D positions in the real world, and then observing where these points are projected on the obtained image plane. With a sufficient number of 3-D points and associated 2-D image points, we can abstract the exact camera parameters from a projective equation.
One way to do this is to take several images of a set of 3-D points of the world with their known 3-D positions from different viewpoints. We are going to make use of the opencvβs calibration methods, one of which takes images of chessboards as input and returns us all the corners present. We can freely assume that board is located at Z=0, with X and Y axes well aligned with the grid. We are going to look at how these calibration functions of OpenCV work, in the section below.
Let us first create three functions, that we will use in the main function. These three functions will be
addChessBoardPoints() //returns corners from given chessboard images
calibrate() // returns the intrinsic matrix from the extracted points
triangulate() //returns the 3-D coordinate of re-constructed point
#include "CameraCalibrator.h"#include <opencv2/opencv.hpp>#include "opencv2/xfeatures2d.hpp"using namespace std;using namespace cv;std::vector<cv::Mat> rvecs, tvecs;// Open chessboard images and extract corner pointsint CameraCalibrator::addChessboardPoints( const std::vector<std::string>& filelist, cv::Size & boardSize) {// the points on the chessboardstd::vector<cv::Point2f> imageCorners;std::vector<cv::Point3f> objectCorners;// 3D Scene Points:// Initialize the chessboard corners // in the chessboard reference frame// The corners are at 3D location (X,Y,Z)= (i,j,0)for (int i=0; i<boardSize.height; i++) { for (int j=0; j<boardSize.width; j++) {objectCorners.push_back(cv::Point3f(i, j, 0.0f)); } }// 2D Image points:cv::Mat image; // to contain chessboard imageint successes = 0;// for all viewpointsfor (int i=0; i<filelist.size(); i++) {// Open the image image = cv::imread(filelist[i],0);// Get the chessboard corners bool found = cv::findChessboardCorners( image, boardSize, imageCorners);// Get subpixel accuracy on the corners cv::cornerSubPix(image, imageCorners, cv::Size(5,5), cv::Size(-1,-1), cv::TermCriteria(cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS, 30, // max number of iterations 0.1)); // min accuracy// If we have a good board, add it to our data if (imageCorners.size() == boardSize.area()) {// Add image and scene points from one view addPoints(imageCorners, objectCorners); successes++; }//Draw the corners cv::drawChessboardCorners(image, boardSize, imageCorners, found); cv::imshow("Corners on Chessboard", image); cv::waitKey(100); }return successes;}
In the above code, you can observe that we have included a head file βCameraCalibrator.hβ, which is going to contain all the function declarations and variable initialisation for this file. You can download the header along with all the other files in this tutorial at my Github by visiting this link.
Our function makes use of the findChessBoardCorners() function of opencv which takes image locations array(the array must contain locations of each chessboard image) and the board size(you should enter the number of corners present in your board horizontally and vertically) as input parameters and returns us a vector containing the corner locations.
double CameraCalibrator::calibrate(cv::Size &imageSize){ // undistorter must be reinitialized mustInitUndistort= true;// start calibration return calibrateCamera(objectPoints, // the 3D points imagePoints, // the image points imageSize, // image size cameraMatrix, // output camera matrix distCoeffs, // output distortion matrix rvecs, tvecs, // Rs, Ts flag); // set options}
In this function, we used calibrateCamera() function that takes the 3-D points and image points weβve obtained above and returns to us the intrinsic matrix, rotation vector(which describes rotation of the camera relative to scene points) and translation matrix(describes the position of camera relative to scene points).
cv::Vec3d CameraCalibrator::triangulate(const cv::Mat &p1, const cv::Mat &p2, const cv::Vec2d &u1, const cv::Vec2d &u2) {// system of equations assuming image=[u,v] and X=[x,y,z,1] // from u(p3.X)= p1.X and v(p3.X)=p2.X cv::Matx43d A(u1(0)*p1.at<double>(2, 0) - p1.at<double>(0, 0), u1(0)*p1.at<double>(2, 1) - p1.at<double>(0, 1), u1(0)*p1.at<double>(2, 2) - p1.at<double>(0, 2), u1(1)*p1.at<double>(2, 0) - p1.at<double>(1, 0), u1(1)*p1.at<double>(2, 1) - p1.at<double>(1, 1), u1(1)*p1.at<double>(2, 2) - p1.at<double>(1, 2), u2(0)*p2.at<double>(2, 0) - p2.at<double>(0, 0), u2(0)*p2.at<double>(2, 1) - p2.at<double>(0, 1), u2(0)*p2.at<double>(2, 2) - p2.at<double>(0, 2), u2(1)*p2.at<double>(2, 0) - p2.at<double>(1, 0), u2(1)*p2.at<double>(2, 1) - p2.at<double>(1, 1), u2(1)*p2.at<double>(2, 2) - p2.at<double>(1, 2));cv::Matx41d B(p1.at<double>(0, 3) - u1(0)*p1.at<double>(2,3), p1.at<double>(1, 3) - u1(1)*p1.at<double>(2,3), p2.at<double>(0, 3) - u2(0)*p2.at<double>(2,3), p2.at<double>(1, 3) - u2(1)*p2.at<double>(2,3));// X contains the 3D coordinate of the reconstructed point cv::Vec3d X; // solve AX=B cv::solve(A, B, X, cv::DECOMP_SVD); return X;}
This above function takes the projection matrices and normalised image points that can be obtained using the intrinsic matrix from previous function and returns the 3-D coordinate of above points.
Below is the complete code for 3-D reconstruction from stereo pair. This code requires a minimum of 25 to 30 chessboard images taken from the same camera you have shot your stereo pair images with. In-order to first run this code in your PC, clone my GitHub repo, replace the stereo pair with the stereo pair of your own, and replace the chessboard images locations array with as array of your own, then build and compile. I am uploading an example chessboard image to my GitHub for your reference, you have to shoot around 30 such images and mention in the code.
int main(){cout<<"compiled"<<endl;const std::vector<std::string> files = {"boards/1.jpg"......}; cv::Size board_size(7,7);CameraCalibrator cal; cal.addChessboardPoints(files, board_size);cv::Mat img = cv::imread("boards/1.jpg");cv::Size img_size = img.size(); cal.calibrate(img_size); cout<<cameraMatrix<<endl;cv::Mat image1 = cv::imread("imR.png"); cv::Mat image2 = cv::imread("imL.png");// vector of keypoints and descriptors std::vector<cv::KeyPoint> keypoints1; std::vector<cv::KeyPoint> keypoints2; cv::Mat descriptors1, descriptors2;// Construction of the SIFT feature detector cv::Ptr<cv::Feature2D> ptrFeature2D = cv::xfeatures2d::SIFT::create(10000);// Detection of the SIFT features and associated descriptors ptrFeature2D->detectAndCompute(image1, cv::noArray(), keypoints1, descriptors1); ptrFeature2D->detectAndCompute(image2, cv::noArray(), keypoints2, descriptors2);// Match the two image descriptors // Construction of the matcher with crosscheck cv::BFMatcher matcher(cv::NORM_L2, true); std::vector<cv::DMatch> matches; matcher.match(descriptors1, descriptors2, matches);cv::Mat matchImage;cv::namedWindow("img1"); cv::drawMatches(image1, keypoints1, image2, keypoints2, matches, matchImage, Scalar::all(-1), Scalar::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); cv::imwrite("matches.jpg", matchImage);// Convert keypoints into Point2f std::vector<cv::Point2f> points1, points2;for (std::vector<cv::DMatch>::const_iterator it = matches.begin(); it != matches.end(); ++it) { // Get the position of left keypoints float x = keypoints1[it->queryIdx].pt.x; float y = keypoints1[it->queryIdx].pt.y; points1.push_back(cv::Point2f(x, y)); // Get the position of right keypoints x = keypoints2[it->trainIdx].pt.x; y = keypoints2[it->trainIdx].pt.y; points2.push_back(cv::Point2f(x, y)); }// Find the essential between image 1 and image 2 cv::Mat inliers; cv::Mat essential = cv::findEssentialMat(points1, points2, cameraMatrix, cv::RANSAC, 0.9, 1.0, inliers);cout<<essential<<endl;// recover relative camera pose from essential matrix cv::Mat rotation, translation; cv::recoverPose(essential, points1, points2, cameraMatrix, rotation, translation, inliers); cout<<rotation<<endl; cout<<translation<<endl;// compose projection matrix from R,T cv::Mat projection2(3, 4, CV_64F); // the 3x4 projection matrix rotation.copyTo(projection2(cv::Rect(0, 0, 3, 3))); translation.copyTo(projection2.colRange(3, 4)); // compose generic projection matrix cv::Mat projection1(3, 4, CV_64F, 0.); // the 3x4 projection matrix cv::Mat diag(cv::Mat::eye(3, 3, CV_64F)); diag.copyTo(projection1(cv::Rect(0, 0, 3, 3))); // to contain the inliers std::vector<cv::Vec2d> inlierPts1; std::vector<cv::Vec2d> inlierPts2; // create inliers input point vector for triangulation int j(0); for (int i = 0; i < inliers.rows; i++) { if (inliers.at<uchar>(i)) { inlierPts1.push_back(cv::Vec2d(points1[i].x, points1[i].y)); inlierPts2.push_back(cv::Vec2d(points2[i].x, points2[i].y)); } } // undistort and normalize the image points std::vector<cv::Vec2d> points1u; cv::undistortPoints(inlierPts1, points1u, cameraMatrix, distCoeffs); std::vector<cv::Vec2d> points2u; cv::undistortPoints(inlierPts2, points2u, cameraMatrix, distCoeffs);// Triangulation std::vector<cv::Vec3d> points3D; cal.triangulate(projection1, projection2, points1u, points2u, points3D);cout<<"3D points :"<<points3D.size()<<endl;viz::Viz3d window; //creating a Viz window//Displaying the Coordinate Origin (0,0,0) window.showWidget("coordinate", viz::WCoordinateSystem());window.setBackgroundColor(cv::viz::Color::black());//Displaying the 3D points in green window.showWidget("points", viz::WCloud(points3D, viz::Color::green())); window.spin();}
I know that mediumβs code display is a mess especially for C++, and hence even code is looking like a mess, so I would suggest you go to my GitHub and understand the above code.
The Output for a given pair for me would look like below, can be improved by tuning the feature detector and its types.
Anyone out there who is interested in learning these concepts in-depth, I would suggest this book below, which I think is the bible for Computer Vision Geometry. Which is also the reference book for this tutorial.
Multiple View Geometry in Computer Vision 2nd Edition - by Richard Hartley and Andrew Zisserman.
If you have any questions, please let me know in the comments section.
|
[
{
"code": null,
"e": 611,
"s": 171,
"text": "Exactly a year back, before I started writing this article, I watched Andrej Karapathy, the director of AI at Tesla delivering a talk where he showed the world a glimpse of how a Tesla car perceives depth using the cameras hooked to the car in-order to reconstruct its surroundings in 3D and take decisions in real-time, everything(except the front radar for safety) was being computed just with vision. And that presentation blew my mind!"
},
{
"code": null,
"e": 1615,
"s": 611,
"text": "Of course, I knew 3-D reconstruction of an environment is possible through cameras, but I was in a mindset that why would anyone risk using a normal camera when weβve got such highly accurate sensors like LiDAR, Radar, etc. that could give us an accurate presentation of the environment in 3-D with far less computation? And I started studying(trying to understand) papers related to this topic of Depth Perception and 3-D Reconstruction from Vision and came to the conclusion that we humans have never had rays coming out of our heads to perceive depth and environment around us, we are intelligent and aware of our surroundings just with the two eyes weβve got, from driving our car or bike from office to work, or driving a formula 1 at 230 mph in the worldβs most dangerous tracks, we never required lasers to make decisions in microseconds. The world around us was constructed by us for us, beings with vision and so as Elon said, βthese costly sensors would become pointless once we solve visionβ."
},
{
"code": null,
"e": 2003,
"s": 1615,
"text": "Thereβs huge research going on in this field of depth perception with vision, especially with the advancements in Machine Learning and Deep Learning we are now able to compute depth just from vision at high accuracy. So before we start learning the concepts and implementing these techniques, let us look at what stage this technology is currently in and what are the applications of it."
},
{
"code": null,
"e": 2017,
"s": 2003,
"text": "Robot Vision:"
},
{
"code": null,
"e": 2058,
"s": 2017,
"text": "Creating HD Maps for autonomous driving:"
},
{
"code": null,
"e": 2249,
"s": 2058,
"text": "SfM(Structure from Motion) and SLAM(Simultaneous Localisation and Mapping) are one of the major techniques that make use of the concepts that I am going to introduce you to in this tutorial."
},
{
"code": null,
"e": 2867,
"s": 2249,
"text": "Now that weβve got enough inspiration to learn, Iβll start the tutorial. So first Iβm going to teach you the basic concepts required to understand whatβs happening behind the hood, and then apply them using the OpenCV library in C++. The question you might ask is why am I implementing these concepts in C++ while doing it in python would be far easier, and thereβs reason behind it. The first reason is that python is not fast enough for these concepts to implement in real-time, and the second reason is that unlike python, using C++ would mandate our understanding of the concept without which one canβt implement."
},
{
"code": null,
"e": 3036,
"s": 2867,
"text": "In this tutorial we are going to write two programs, one is to get a depth map of a scene and another is to obtain a point cloud of the scene, both using stereo vision."
},
{
"code": null,
"e": 3184,
"s": 3036,
"text": "Before we dive right into the coding part, it is important for us to understand the concepts of camera geometry, which I am going to teach you now."
},
{
"code": null,
"e": 3500,
"s": 3184,
"text": "The process used to produce images has not changed since the beginning of photography. The light coming from an observed scene is captured by a camera through a frontal aperture(a lens) that shoots the light onto an image plane located at the back of the camera lens. The process is illustrated in the figure below:"
},
{
"code": null,
"e": 3796,
"s": 3500,
"text": "From the above figure, do is the distance from the lens to the observed object, di is the distance between the lens and image plane. And f will hence become the focal length of the lens. These described quantities have a relation between them from the so-called βThin Lens Equationβ shown below:"
},
{
"code": null,
"e": 4028,
"s": 3796,
"text": "Now let us look into the process of how an object from the real-world that is 3-Dimensional, is projected onto a 2-Dimensional plane(a photograph). The best way for us to understand this is by taking a look into how a camera works."
},
{
"code": null,
"e": 4279,
"s": 4028,
"text": "A camera can be seen as the function that maps 3-D world to a 2-D image. Let us take the simplest model of a camera, that is the Pinhole Camera Model, the older photography mechanisms in human history. Below is a working diagram of a pinhole camera :"
},
{
"code": null,
"e": 4313,
"s": 4279,
"text": "From this diagram we can derive :"
},
{
"code": null,
"e": 4819,
"s": 4313,
"text": "Here itβs natural that the size hi of the image formed from the object will be inversely proportional to the distance do of the object from camera. And also that a 3-D scene point located at position (X, Y, Z) will be projected onto the image plane at (x,y) where (x,y) = (fX/Z, fY/Z). Where the Z coordinate refers to the depth of the point, which was done in the previous image. This entire camera configuration and notation can be described with a simple matrix using the homogeneous coordinate system."
},
{
"code": null,
"e": 5009,
"s": 4819,
"text": "When cameras generate a projected image of the world, projective geometry is used as an algebraic representation of the geometry of objects, rotations and transformations in the real world."
},
{
"code": null,
"e": 5398,
"s": 5009,
"text": "Homogeneous coordinates are a system of coordinates used in projective geometry. Even though we can represent the positions of objects(or any point in 3-D space) in real-world in Euclidean Space, any transformation or rotation that has to be performed must be performed in homogeneous coordinate space and then brought back. Let us look at the advantages of using Homogeneous coordinates:"
},
{
"code": null,
"e": 5488,
"s": 5398,
"text": "Formulas involving Homogeneous Coordinates are often simpler than in the Cartesian world."
},
{
"code": null,
"e": 5552,
"s": 5488,
"text": "Points at infinity can be represented using finite coordinates."
},
{
"code": null,
"e": 5673,
"s": 5552,
"text": "A single matrix can represent all the possible protective transformations that can occur between a camera and the world."
},
{
"code": null,
"e": 5792,
"s": 5673,
"text": "In homogeneous coordinate space, 2-D points are represented by 3 vectors, and 3-D points are represented by 4 vectors."
},
{
"code": null,
"e": 6080,
"s": 5792,
"text": "In the above equations, the first matrix with the f notation is called the intrinsic parameter matrix(or commonly known as the intrinsic matrix). Here the intrinsic matrix contains just the focal length(f) right now, weβll look into more parameters of this matrix ahead of this tutorial."
},
{
"code": null,
"e": 6365,
"s": 6080,
"text": "The second matrix with the r and t notations is called the extrinsic parameter matrix(or commonly known as the Extrinsic Matrix). The elements within this matrix represent the rotation and translation parameters of the camera(that is where and how the camera is placed in real world)."
},
{
"code": null,
"e": 6637,
"s": 6365,
"text": "Thus these intrinsic and extrinsic matrices together can give us a relation between the (x,y) point in image and (X, Y, Z) point in real world. This is how a 3-D scene point is projected onto a 2-D plane depending on the given cameraβs intrinsic and extrinsic parameters."
},
{
"code": null,
"e": 6841,
"s": 6637,
"text": "Now that we have acquired enough knowledge about projective geometry and camera model, itβs time to introduce you to one of the most important element in computer vision geometry, the Fundamental Matrix."
},
{
"code": null,
"e": 7238,
"s": 6841,
"text": "Now that we know how a point in the 3-D world is projected onto an image plane of a camera. We will look into the projective relationship that exists between two images displaying the same scene. These two cameras when separated by a rigid baseline, we use the term stereo-vision. Consider two pinhole cameras observing a given scene point sharing the same baseline as shown in the figure below :"
},
{
"code": null,
"e": 7535,
"s": 7238,
"text": "From the above figure, the world point X has its image at position x on the image plane, now this x can be located anywhere on this line in 3-D space. Which implies that if we want to find the same point x in another image, we need to search along the projection of this line on the second image."
},
{
"code": null,
"e": 8199,
"s": 7535,
"text": "This imaginary line drawn from x is known as the epipolar line of x. This epipolar line brings a fundamental constraint with it, that is, the match of a given point must lie on this line in another view. It means that if you want to find x from the first image in the second image, you have to look for it along the epipolar line of x on the second image. These epipolar lines can characterise the geometry between the two views. An important thing to note here is that all the epipolar lines always pass through one single point. This point corresponds to the projection of one cameraβs centre onto the other cameraβs centre and this point is called the epipole."
},
{
"code": null,
"e": 8729,
"s": 8199,
"text": "We can consider fundamental matrix F as the one that maps a 2-D image point in one view to an epipolar line in the other image view. The fundamental matrix between an image pair can be estimated by solving a set of equations that involve a certain number of known matched points between the two images. The minimum number of such matches is seven and an optimal number is eight. Then for a point in one image, the fundamental matrix gives the equation of the line on which its corresponding point in another view should be found."
},
{
"code": null,
"e": 8930,
"s": 8729,
"text": "If the corresponding point of a point of a point (x, y) is (xβ, yβ), and the fundamental matrix between the two images planes is F, then we must have the following equation in homogeneous coordinates."
},
{
"code": null,
"e": 9042,
"s": 8930,
"text": "This equation expresses the relationship between two corresponding points and known as the epipolar constraint."
},
{
"code": null,
"e": 9717,
"s": 9042,
"text": "When two cameras observe the same scene, they see the same objects but under different viewpoints. There are libraries like OpenCV in both C++ and Python that provide us with feature detectors that find us certain points with descriptors in images that they think are unique to image and can be found if given another image of the same scene. However, practically it is not possible to guarantee that a matching set obtained between two images by comparing the descriptors of the detected feature points(like SIFT, ORB, etc.) will be exact and true. This is why a fundamental matrix estimation method based on RANSAC (Random Sampling Consensus) strategy has been introduced."
},
{
"code": null,
"e": 10272,
"s": 9717,
"text": "The idea behind RANSAC is to randomly select some data points from a given set of data points and perform an estimation with only those. The number of selected points should be the minimum number of points required to estimate the mathematical entity, which in our case of the fundamental matrix is eight matches. Once the fundamental matrix is estimated from these eight random matches, all the other matches in the match set are tested against the epipolar constraint we discussed. These matches form the support set of the computed fundamental matrix."
},
{
"code": null,
"e": 10690,
"s": 10272,
"text": "The larger the support set, the higher the probability that the computed matrix is the right one. And if one of the randomly selected matches is an incorrect match, then the computed fundamental matrix will also be incorrect, and its support set will be expected to be small. This process is repeated a number of times and in the end, the matrix with the largest support set will be retained as the most probable one."
},
{
"code": null,
"e": 11067,
"s": 10690,
"text": "The reason humans have evolved to be species with two eyes is so that we can perceive depth. And when we organise cameras in a similar way in a machine, itβs called Stereo-Vision. A stereo-vision system is generally made of two side-by-side cameras looking at the same scene, the following figure shows the setup of a stereo rig with an ideal configuration, aligned perfectly."
},
{
"code": null,
"e": 11488,
"s": 11067,
"text": "Under such an ideal configuration of cameras as shown in the above figure, cameras are only separated by an horizontal translation and therefore all the epipolar lines are horizontal. It means that the corresponding points have the same y coordinates and search is reduced to 1 Dimensional line. When cameras are separated by such a pure horizontal translation, the projective equation of the second camera would become:"
},
{
"code": null,
"e": 11605,
"s": 11488,
"text": "The equation would make more sense by looking at the diagram below, which is the general case with digital cameras :"
},
{
"code": null,
"e": 11768,
"s": 11605,
"text": "where the point (uo, vo) is the pixel position where the line passing through the principle point of the lens pierces the image plane. Here we obtain a relation :"
},
{
"code": null,
"e": 11944,
"s": 11768,
"text": "Here, the term (x-xβ) is called the disparity and Z is, of course, the depth. In order to compute a depth map from a stereo pair, the disparity of each pixel must be computed."
},
{
"code": null,
"e": 12150,
"s": 11944,
"text": "But in a practical world, obtaining such an ideal configuration is very difficult. Even if we place the cameras accurately, they would unavoidably include some extra transitional and rotational components."
},
{
"code": null,
"e": 12349,
"s": 12150,
"text": "Fortunately, it is possible to rectify these images to produce horizontal epilines required by using a robust matching algorithm which makes use of a fundamental matrix to perform the rectification."
},
{
"code": null,
"e": 12430,
"s": 12349,
"text": "Now let us start by obtaining a fundamental matrix for the below stereo images :"
},
{
"code": null,
"e": 12736,
"s": 12430,
"text": "You can download the above images from my GitHub repository by clicking here. Before you start writing the code in this tutorial, make sure you have opencv and opencv-contrib libraries built on your computer. If they are not built, I would suggest you visit this link to install them if you are on Ubuntu."
},
{
"code": null,
"e": 12969,
"s": 12736,
"text": "#include <opencv2/opencv.hpp>#include \"opencv2/xfeatures2d.hpp\"using namespace std;using namespace cv;int main(){cv::Mat img1, img2;img1 = cv::imread(\"imR.png\",cv::IMREAD_GRAYSCALE);img2 = cv::imread(\"imL.png\",cv::IMREAD_GRAYSCALE);"
},
{
"code": null,
"e": 13506,
"s": 12969,
"text": "The first thing we did is included the required libraries from opencv and opencv-contrib which I asked you to build before starting this section. In main() function we have initialised two variables of the cv:Mat datatype which is a member function of the opencv library, the Mat datatype can hold vectors of any size by dynamically allocating memory, especially images. Then using the cv::imread() we have imported both the images into img1 and img2 of the mat datatype. The cv::IMREAD_GRAYSCALE parameter imports images as gray-scale."
},
{
"code": null,
"e": 13948,
"s": 13506,
"text": "// Define keypoints vectorstd::vector<cv::KeyPoint> keypoints1, keypoints2;// Define feature detectorcv::Ptr<cv::Feature2D> ptrFeature2D = cv::xfeatures2d::SIFT::create(74);// Keypoint detectionptrFeature2D->detect(img1,keypoints1);ptrFeature2D->detect(img2,keypoints2);// Extract the descriptorcv::Mat descriptors1;cv::Mat descriptors2;ptrFeature2D->compute(img1,keypoints1,descriptors1);ptrFeature2D->compute(img2,keypoints2,descriptors2);"
},
{
"code": null,
"e": 14285,
"s": 13948,
"text": "Here we are making use of opencvβs SIFT feature detector in order to extract the required feature points from the images. If you want to understand more about how these feature detectors work visit this link. The descriptors we obtained above describe each point extracted, this description is used in order to find it in another image."
},
{
"code": null,
"e": 14479,
"s": 14285,
"text": "// Construction of the matchercv::BFMatcher matcher(cv::NORM_L2);// Match the two image descriptorsstd::vector<cv::DMatch> outputMatches;matcher.match(descriptors1,descriptors2, outputMatches);"
},
{
"code": null,
"e": 14787,
"s": 14479,
"text": "BFMatcher takes the descriptor of one feature in the first set and is matched with all the other features in the second set using some threshold distance calculation, and the closest one is returned. We are storing all the matches returned by BFMatches in output matches variable of type vector<cv::DMatch>."
},
{
"code": null,
"e": 15161,
"s": 14787,
"text": "// Convert keypoints into Point2fstd::vector<cv::Point2f> points1, points2;for (std::vector<cv::DMatch>::const_iterator it= outputMatches.begin(); it!= outputMatches.end(); ++it) { // Get the position of left keypoints points1.push_back(keypoints1[it->queryIdx].pt); // Get the position of right keypoints points2.push_back(keypoints2[it->trainIdx].pt); }"
},
{
"code": null,
"e": 15497,
"s": 15161,
"text": "The acquired keypoints first need to be converted into cv::Point2f type in-order to be used with cv::findFundamentalMat, a function we will make use of for computing the fundamental matrix using these feature points we abstracted. The two resulting vectors Points1 and Points2 contain the corresponding point coordinates in two images."
},
{
"code": null,
"e": 15870,
"s": 15497,
"text": "std::vector<uchar> inliers(points1.size(),0);cv::Mat fundamental= cv::findFundamentalMat( points1,points2, // matching points inliers, // match status (inlier or outlier) cv::FM_RANSAC, // RANSAC method 1.0, // distance to epipolar line 0.98); // confidence probabilitycout<<fundamental; //include this for seeing fundamental matrix"
},
{
"code": null,
"e": 15926,
"s": 15870,
"text": "And finally, we have called the cv::findFundamentalMat."
},
{
"code": null,
"e": 16245,
"s": 15926,
"text": "// Compute homographic rectificationcv::Mat h1, h2;cv::stereoRectifyUncalibrated(points1, points2, fundamental, img1.size(), h1, h2);// Rectify the images through warpingcv::Mat rectified1;cv::warpPerspective(img1, rectified1, h1, img1.size());cv::Mat rectified2;cv::warpPerspective(img2, rectified2, h2, img1.size());"
},
{
"code": null,
"e": 16647,
"s": 16245,
"text": "As i explained you previously in the tutorial that obtaining an ideal configuration of cameras without any error is very difficult in a practical world, hence opencv offers a rectifying function that applies homographic transformation to project the image plane of each camera onto a perfectly aligned virtual plane. This transformation is computed from a set of matched points and fundamental matrix."
},
{
"code": null,
"e": 16861,
"s": 16647,
"text": "// Compute disparitycv::Mat disparity;cv::Ptr<cv::StereoMatcher> pStereo = cv::StereoSGBM::create(0, 32,5);pStereo->compute(rectified1, rectified2, disparity);cv::imwrite(\"disparity.jpg\", disparity);"
},
{
"code": null,
"e": 17210,
"s": 16861,
"text": "And finally, weβve computed the disparity map. From the image below, the darker pixels are representing objects nearer to the camera, and the lighter pixels are representing the objects far from the camera. The white pixel noise you are seeing in the output disparity map can be removed with some filters which I wonβt be covering in this tutorial."
},
{
"code": null,
"e": 17455,
"s": 17210,
"text": "Now that we have successfully obtained a depth map from a given stereo pair. Let us now try to re-project the obtained 2-D image points onto 3-D space by making use of a tool called 3D-Viz from opencv that will help us render a 3-D point cloud."
},
{
"code": null,
"e": 17597,
"s": 17455,
"text": "But this time, rather than estimating a fundamental matrix from the given image points, we will project the points using an essential matrix."
},
{
"code": null,
"e": 17873,
"s": 17597,
"text": "The essential matrix can be seen as a fundamental matrix, but for calibrated cameras. We can also call it a specialisation over fundamental matrix where the matrix is computed using calibrated cameras, means that we must first acquire knowledge about our camera in the world."
},
{
"code": null,
"e": 18105,
"s": 17873,
"text": "Hence in-order for us to estimate the essential matrix, we first need the intrinsic matrix of the camera( a matrix that represents the optical centre and focal length of the given camera). Let us take a look at the equation below :"
},
{
"code": null,
"e": 18284,
"s": 18105,
"text": "Here, from the first matrix, the fx and fy represent the focal length of the camera, (uo, vo) is the principle point. This is the intrinsic matrix and our goal is to estimate it."
},
{
"code": null,
"e": 18612,
"s": 18284,
"text": "This process of finding different camera parameters is known as camera calibration. We can obviously use specifications provided by the camera manufacturer, but for the tasks like 3-D reconstruction, which we will be doing, these specifications are not accurate enough. Hence we are going to perform our own camera calibration."
},
{
"code": null,
"e": 18969,
"s": 18612,
"text": "The idea is to show a set of scene points to the camera, the points for which we know their actual 3-D positions in the real world, and then observing where these points are projected on the obtained image plane. With a sufficient number of 3-D points and associated 2-D image points, we can abstract the exact camera parameters from a projective equation."
},
{
"code": null,
"e": 19451,
"s": 18969,
"text": "One way to do this is to take several images of a set of 3-D points of the world with their known 3-D positions from different viewpoints. We are going to make use of the opencvβs calibration methods, one of which takes images of chessboards as input and returns us all the corners present. We can freely assume that board is located at Z=0, with X and Y axes well aligned with the grid. We are going to look at how these calibration functions of OpenCV work, in the section below."
},
{
"code": null,
"e": 19557,
"s": 19451,
"text": "Let us first create three functions, that we will use in the main function. These three functions will be"
},
{
"code": null,
"e": 19626,
"s": 19557,
"text": "addChessBoardPoints() //returns corners from given chessboard images"
},
{
"code": null,
"e": 19696,
"s": 19626,
"text": "calibrate() // returns the intrinsic matrix from the extracted points"
},
{
"code": null,
"e": 19763,
"s": 19696,
"text": "triangulate() //returns the 3-D coordinate of re-constructed point"
},
{
"code": null,
"e": 21581,
"s": 19763,
"text": "#include \"CameraCalibrator.h\"#include <opencv2/opencv.hpp>#include \"opencv2/xfeatures2d.hpp\"using namespace std;using namespace cv;std::vector<cv::Mat> rvecs, tvecs;// Open chessboard images and extract corner pointsint CameraCalibrator::addChessboardPoints( const std::vector<std::string>& filelist, cv::Size & boardSize) {// the points on the chessboardstd::vector<cv::Point2f> imageCorners;std::vector<cv::Point3f> objectCorners;// 3D Scene Points:// Initialize the chessboard corners // in the chessboard reference frame// The corners are at 3D location (X,Y,Z)= (i,j,0)for (int i=0; i<boardSize.height; i++) { for (int j=0; j<boardSize.width; j++) {objectCorners.push_back(cv::Point3f(i, j, 0.0f)); } }// 2D Image points:cv::Mat image; // to contain chessboard imageint successes = 0;// for all viewpointsfor (int i=0; i<filelist.size(); i++) {// Open the image image = cv::imread(filelist[i],0);// Get the chessboard corners bool found = cv::findChessboardCorners( image, boardSize, imageCorners);// Get subpixel accuracy on the corners cv::cornerSubPix(image, imageCorners, cv::Size(5,5), cv::Size(-1,-1), cv::TermCriteria(cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS, 30, // max number of iterations 0.1)); // min accuracy// If we have a good board, add it to our data if (imageCorners.size() == boardSize.area()) {// Add image and scene points from one view addPoints(imageCorners, objectCorners); successes++; }//Draw the corners cv::drawChessboardCorners(image, boardSize, imageCorners, found); cv::imshow(\"Corners on Chessboard\", image); cv::waitKey(100); }return successes;}"
},
{
"code": null,
"e": 21883,
"s": 21581,
"text": "In the above code, you can observe that we have included a head file βCameraCalibrator.hβ, which is going to contain all the function declarations and variable initialisation for this file. You can download the header along with all the other files in this tutorial at my Github by visiting this link."
},
{
"code": null,
"e": 22235,
"s": 21883,
"text": "Our function makes use of the findChessBoardCorners() function of opencv which takes image locations array(the array must contain locations of each chessboard image) and the board size(you should enter the number of corners present in your board horizontally and vertically) as input parameters and returns us a vector containing the corner locations."
},
{
"code": null,
"e": 22687,
"s": 22235,
"text": "double CameraCalibrator::calibrate(cv::Size &imageSize){ // undistorter must be reinitialized mustInitUndistort= true;// start calibration return calibrateCamera(objectPoints, // the 3D points imagePoints, // the image points imageSize, // image size cameraMatrix, // output camera matrix distCoeffs, // output distortion matrix rvecs, tvecs, // Rs, Ts flag); // set options}"
},
{
"code": null,
"e": 23008,
"s": 22687,
"text": "In this function, we used calibrateCamera() function that takes the 3-D points and image points weβve obtained above and returns to us the intrinsic matrix, rotation vector(which describes rotation of the camera relative to scene points) and translation matrix(describes the position of camera relative to scene points)."
},
{
"code": null,
"e": 24231,
"s": 23008,
"text": "cv::Vec3d CameraCalibrator::triangulate(const cv::Mat &p1, const cv::Mat &p2, const cv::Vec2d &u1, const cv::Vec2d &u2) {// system of equations assuming image=[u,v] and X=[x,y,z,1] // from u(p3.X)= p1.X and v(p3.X)=p2.X cv::Matx43d A(u1(0)*p1.at<double>(2, 0) - p1.at<double>(0, 0), u1(0)*p1.at<double>(2, 1) - p1.at<double>(0, 1), u1(0)*p1.at<double>(2, 2) - p1.at<double>(0, 2), u1(1)*p1.at<double>(2, 0) - p1.at<double>(1, 0), u1(1)*p1.at<double>(2, 1) - p1.at<double>(1, 1), u1(1)*p1.at<double>(2, 2) - p1.at<double>(1, 2), u2(0)*p2.at<double>(2, 0) - p2.at<double>(0, 0), u2(0)*p2.at<double>(2, 1) - p2.at<double>(0, 1), u2(0)*p2.at<double>(2, 2) - p2.at<double>(0, 2), u2(1)*p2.at<double>(2, 0) - p2.at<double>(1, 0), u2(1)*p2.at<double>(2, 1) - p2.at<double>(1, 1), u2(1)*p2.at<double>(2, 2) - p2.at<double>(1, 2));cv::Matx41d B(p1.at<double>(0, 3) - u1(0)*p1.at<double>(2,3), p1.at<double>(1, 3) - u1(1)*p1.at<double>(2,3), p2.at<double>(0, 3) - u2(0)*p2.at<double>(2,3), p2.at<double>(1, 3) - u2(1)*p2.at<double>(2,3));// X contains the 3D coordinate of the reconstructed point cv::Vec3d X; // solve AX=B cv::solve(A, B, X, cv::DECOMP_SVD); return X;}"
},
{
"code": null,
"e": 24428,
"s": 24231,
"text": "This above function takes the projection matrices and normalised image points that can be obtained using the intrinsic matrix from previous function and returns the 3-D coordinate of above points."
},
{
"code": null,
"e": 24992,
"s": 24428,
"text": "Below is the complete code for 3-D reconstruction from stereo pair. This code requires a minimum of 25 to 30 chessboard images taken from the same camera you have shot your stereo pair images with. In-order to first run this code in your PC, clone my GitHub repo, replace the stereo pair with the stereo pair of your own, and replace the chessboard images locations array with as array of your own, then build and compile. I am uploading an example chessboard image to my GitHub for your reference, you have to shoot around 30 such images and mention in the code."
},
{
"code": null,
"e": 28801,
"s": 24992,
"text": "int main(){cout<<\"compiled\"<<endl;const std::vector<std::string> files = {\"boards/1.jpg\"......}; cv::Size board_size(7,7);CameraCalibrator cal; cal.addChessboardPoints(files, board_size);cv::Mat img = cv::imread(\"boards/1.jpg\");cv::Size img_size = img.size(); cal.calibrate(img_size); cout<<cameraMatrix<<endl;cv::Mat image1 = cv::imread(\"imR.png\"); cv::Mat image2 = cv::imread(\"imL.png\");// vector of keypoints and descriptors std::vector<cv::KeyPoint> keypoints1; std::vector<cv::KeyPoint> keypoints2; cv::Mat descriptors1, descriptors2;// Construction of the SIFT feature detector cv::Ptr<cv::Feature2D> ptrFeature2D = cv::xfeatures2d::SIFT::create(10000);// Detection of the SIFT features and associated descriptors ptrFeature2D->detectAndCompute(image1, cv::noArray(), keypoints1, descriptors1); ptrFeature2D->detectAndCompute(image2, cv::noArray(), keypoints2, descriptors2);// Match the two image descriptors // Construction of the matcher with crosscheck cv::BFMatcher matcher(cv::NORM_L2, true); std::vector<cv::DMatch> matches; matcher.match(descriptors1, descriptors2, matches);cv::Mat matchImage;cv::namedWindow(\"img1\"); cv::drawMatches(image1, keypoints1, image2, keypoints2, matches, matchImage, Scalar::all(-1), Scalar::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); cv::imwrite(\"matches.jpg\", matchImage);// Convert keypoints into Point2f std::vector<cv::Point2f> points1, points2;for (std::vector<cv::DMatch>::const_iterator it = matches.begin(); it != matches.end(); ++it) { // Get the position of left keypoints float x = keypoints1[it->queryIdx].pt.x; float y = keypoints1[it->queryIdx].pt.y; points1.push_back(cv::Point2f(x, y)); // Get the position of right keypoints x = keypoints2[it->trainIdx].pt.x; y = keypoints2[it->trainIdx].pt.y; points2.push_back(cv::Point2f(x, y)); }// Find the essential between image 1 and image 2 cv::Mat inliers; cv::Mat essential = cv::findEssentialMat(points1, points2, cameraMatrix, cv::RANSAC, 0.9, 1.0, inliers);cout<<essential<<endl;// recover relative camera pose from essential matrix cv::Mat rotation, translation; cv::recoverPose(essential, points1, points2, cameraMatrix, rotation, translation, inliers); cout<<rotation<<endl; cout<<translation<<endl;// compose projection matrix from R,T cv::Mat projection2(3, 4, CV_64F); // the 3x4 projection matrix rotation.copyTo(projection2(cv::Rect(0, 0, 3, 3))); translation.copyTo(projection2.colRange(3, 4)); // compose generic projection matrix cv::Mat projection1(3, 4, CV_64F, 0.); // the 3x4 projection matrix cv::Mat diag(cv::Mat::eye(3, 3, CV_64F)); diag.copyTo(projection1(cv::Rect(0, 0, 3, 3))); // to contain the inliers std::vector<cv::Vec2d> inlierPts1; std::vector<cv::Vec2d> inlierPts2; // create inliers input point vector for triangulation int j(0); for (int i = 0; i < inliers.rows; i++) { if (inliers.at<uchar>(i)) { inlierPts1.push_back(cv::Vec2d(points1[i].x, points1[i].y)); inlierPts2.push_back(cv::Vec2d(points2[i].x, points2[i].y)); } } // undistort and normalize the image points std::vector<cv::Vec2d> points1u; cv::undistortPoints(inlierPts1, points1u, cameraMatrix, distCoeffs); std::vector<cv::Vec2d> points2u; cv::undistortPoints(inlierPts2, points2u, cameraMatrix, distCoeffs);// Triangulation std::vector<cv::Vec3d> points3D; cal.triangulate(projection1, projection2, points1u, points2u, points3D);cout<<\"3D points :\"<<points3D.size()<<endl;viz::Viz3d window; //creating a Viz window//Displaying the Coordinate Origin (0,0,0) window.showWidget(\"coordinate\", viz::WCoordinateSystem());window.setBackgroundColor(cv::viz::Color::black());//Displaying the 3D points in green window.showWidget(\"points\", viz::WCloud(points3D, viz::Color::green())); window.spin();}"
},
{
"code": null,
"e": 28979,
"s": 28801,
"text": "I know that mediumβs code display is a mess especially for C++, and hence even code is looking like a mess, so I would suggest you go to my GitHub and understand the above code."
},
{
"code": null,
"e": 29099,
"s": 28979,
"text": "The Output for a given pair for me would look like below, can be improved by tuning the feature detector and its types."
},
{
"code": null,
"e": 29313,
"s": 29099,
"text": "Anyone out there who is interested in learning these concepts in-depth, I would suggest this book below, which I think is the bible for Computer Vision Geometry. Which is also the reference book for this tutorial."
},
{
"code": null,
"e": 29410,
"s": 29313,
"text": "Multiple View Geometry in Computer Vision 2nd Edition - by Richard Hartley and Andrew Zisserman."
}
] |
C Quiz - 101 | Question 2 - GeeksforGeeks
|
28 Jun, 2021
Assume int is 4 bytes, char is 1 byte and float is 4 bytes. Also, assume that pointer size is 4 bytes (i.e. typical case)
char *pChar;int *pInt;float *pFloat; sizeof(pChar);sizeof(pInt);sizeof(pFloat);
Whatβs the size returned for each of sizeof() operator?(A) 4 4 4(B) 1 4 4(C) 1 4 8(D) None of the aboveAnswer: (A)Explanation: Irrespective of the type of pointer, the size for a pointer is always same. So whether itβs pointer to char or pointer to float, the size of any pointer would be same. Even size of a pointer to user defined data type (e.g. struct) is also would be same.Quiz of this Question
C Quiz - 101
C-C Quiz - 101
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1
C | Misc | Question 7
|
[
{
"code": null,
"e": 24378,
"s": 24350,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24500,
"s": 24378,
"text": "Assume int is 4 bytes, char is 1 byte and float is 4 bytes. Also, assume that pointer size is 4 bytes (i.e. typical case)"
},
{
"code": "char *pChar;int *pInt;float *pFloat; sizeof(pChar);sizeof(pInt);sizeof(pFloat);",
"e": 24581,
"s": 24500,
"text": null
},
{
"code": null,
"e": 24983,
"s": 24581,
"text": "Whatβs the size returned for each of sizeof() operator?(A) 4 4 4(B) 1 4 4(C) 1 4 8(D) None of the aboveAnswer: (A)Explanation: Irrespective of the type of pointer, the size for a pointer is always same. So whether itβs pointer to char or pointer to float, the size of any pointer would be same. Even size of a pointer to user defined data type (e.g. struct) is also would be same.Quiz of this Question"
},
{
"code": null,
"e": 24996,
"s": 24983,
"text": "C Quiz - 101"
},
{
"code": null,
"e": 25011,
"s": 24996,
"text": "C-C Quiz - 101"
},
{
"code": null,
"e": 25022,
"s": 25011,
"text": "C Language"
},
{
"code": null,
"e": 25029,
"s": 25022,
"text": "C Quiz"
},
{
"code": null,
"e": 25127,
"s": 25029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25162,
"s": 25127,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25190,
"s": 25162,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25236,
"s": 25190,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25276,
"s": 25236,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25288,
"s": 25276,
"text": "fork() in C"
},
{
"code": null,
"e": 25331,
"s": 25288,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25372,
"s": 25331,
"text": "Output of C programs | Set 64 (Pointers)"
},
{
"code": null,
"e": 25408,
"s": 25372,
"text": "C | Structure & Union | Question 10"
},
{
"code": null,
"e": 25439,
"s": 25408,
"text": "C | File Handling | Question 1"
}
] |
All combinations of strings that can be used to dial a number - GeeksforGeeks
|
06 Nov, 2020
Given a number, print all possible combinations of strings that can be used to dial the given number in a phone with following specifications.
In the given phone, we can dial,2 using A or B or C,3 using D or E or F,...................8 using T or U or V,9 using W or X or Y or Z,1 using only 10 using 0.
For example if 23, is the given phone number, the program should print AD, AE, AF, BD, BE, BF, CD, CE, CF
The idea is to store digit to characters mapping in hash map. The map stores all characters that can be used dial a digit. We place every possible character for current digit and recur for remaining digits. Below is Java implementation of this idea.
// Java program to print all possible key strings// that can be used to dial a phone number.import java.util.HashMap; class ConvertToString{ // A Recursive function to print all combinations // that can be used to dial a given number. // phNo ==> Given Phone Number // i ==> Current digit of phNo to be processed // hm ==> Stores characters that can be used to // to dial a digit. // str ==> Current output string static void printStrings(String phNo, int i, HashMap<Character, String> hm, StringBuilder str) { // If all digits are processed, print output // string if (i == phNo.length()) { System.out.print(str + " "); return; } // Get current digit of phNo, and recur for all // characters that can be used to dial it. String s = hm.get(phNo.charAt(i)); for (int j = 0; j < s.length(); j++) { str.append(s.charAt(j)); printStrings(phNo, i+1, hm, str); str.deleteCharAt(str.length()-1); } } // Prints all possible combinations of strings that // can be used to dial c[]. static void printStringForNumber(String phNo) { // Create a HashMap HashMap<Character, String> hm = new HashMap<Character, String>(); // For every digit, store characters that can // be used to dial it. hm.put('2', "ABC"); hm.put('3', "DEF"); hm.put('4', "GHI"); hm.put('5', "JKL"); hm.put('6', "MNO"); hm.put('7', "PQRS"); hm.put('8', "TUV"); hm.put('9', "WXYZ"); hm.put('1', "1"); hm.put('0', "0"); // Create a string to store a particular output // string StringBuilder str = new StringBuilder(); // Call recursive function printStrings(phNo, 0, hm, str); } // Driver code to test above methods public static void main(String args[]) { // Prints printStringForNumber("23"); }}
Output :
AD AE AF BD BE BF CD CE CF
YouTubeGeeksforGeeks507K subscribersAll combinations of strings that can be used to dial a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:45β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=tE9EF-2Jw8U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Phalgun. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
VigeneΜre Cipher
sprintf() in C
Convert character array to string in C++
String class in Java | Set 1
How to Append a Character to a String in C
Program to count occurrence of a given character in a string
Naive algorithm for Pattern Searching
Boyer Moore Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 26099,
"s": 26071,
"text": "\n06 Nov, 2020"
},
{
"code": null,
"e": 26242,
"s": 26099,
"text": "Given a number, print all possible combinations of strings that can be used to dial the given number in a phone with following specifications."
},
{
"code": null,
"e": 26403,
"s": 26242,
"text": "In the given phone, we can dial,2 using A or B or C,3 using D or E or F,...................8 using T or U or V,9 using W or X or Y or Z,1 using only 10 using 0."
},
{
"code": null,
"e": 26509,
"s": 26403,
"text": "For example if 23, is the given phone number, the program should print AD, AE, AF, BD, BE, BF, CD, CE, CF"
},
{
"code": null,
"e": 26759,
"s": 26509,
"text": "The idea is to store digit to characters mapping in hash map. The map stores all characters that can be used dial a digit. We place every possible character for current digit and recur for remaining digits. Below is Java implementation of this idea."
},
{
"code": "// Java program to print all possible key strings// that can be used to dial a phone number.import java.util.HashMap; class ConvertToString{ // A Recursive function to print all combinations // that can be used to dial a given number. // phNo ==> Given Phone Number // i ==> Current digit of phNo to be processed // hm ==> Stores characters that can be used to // to dial a digit. // str ==> Current output string static void printStrings(String phNo, int i, HashMap<Character, String> hm, StringBuilder str) { // If all digits are processed, print output // string if (i == phNo.length()) { System.out.print(str + \" \"); return; } // Get current digit of phNo, and recur for all // characters that can be used to dial it. String s = hm.get(phNo.charAt(i)); for (int j = 0; j < s.length(); j++) { str.append(s.charAt(j)); printStrings(phNo, i+1, hm, str); str.deleteCharAt(str.length()-1); } } // Prints all possible combinations of strings that // can be used to dial c[]. static void printStringForNumber(String phNo) { // Create a HashMap HashMap<Character, String> hm = new HashMap<Character, String>(); // For every digit, store characters that can // be used to dial it. hm.put('2', \"ABC\"); hm.put('3', \"DEF\"); hm.put('4', \"GHI\"); hm.put('5', \"JKL\"); hm.put('6', \"MNO\"); hm.put('7', \"PQRS\"); hm.put('8', \"TUV\"); hm.put('9', \"WXYZ\"); hm.put('1', \"1\"); hm.put('0', \"0\"); // Create a string to store a particular output // string StringBuilder str = new StringBuilder(); // Call recursive function printStrings(phNo, 0, hm, str); } // Driver code to test above methods public static void main(String args[]) { // Prints printStringForNumber(\"23\"); }}",
"e": 28833,
"s": 26759,
"text": null
},
{
"code": null,
"e": 28842,
"s": 28833,
"text": "Output :"
},
{
"code": null,
"e": 28870,
"s": 28842,
"text": "AD AE AF BD BE BF CD CE CF "
},
{
"code": null,
"e": 29990,
"s": 28870,
"text": "YouTubeGeeksforGeeks507K subscribersAll combinations of strings that can be used to dial a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:45β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=tE9EF-2Jw8U\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Phalgun. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30114,
"s": 29990,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 30122,
"s": 30114,
"text": "Strings"
},
{
"code": null,
"e": 30130,
"s": 30122,
"text": "Strings"
},
{
"code": null,
"e": 30228,
"s": 30130,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30273,
"s": 30228,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 30318,
"s": 30273,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 30335,
"s": 30318,
"text": "VigeneΜre Cipher"
},
{
"code": null,
"e": 30350,
"s": 30335,
"text": "sprintf() in C"
},
{
"code": null,
"e": 30391,
"s": 30350,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 30420,
"s": 30391,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 30463,
"s": 30420,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 30524,
"s": 30463,
"text": "Program to count occurrence of a given character in a string"
},
{
"code": null,
"e": 30562,
"s": 30524,
"text": "Naive algorithm for Pattern Searching"
}
] |
GWT - TextBox Widget
|
The TextBox widget represents a standard single-line text box.
Following is the declaration for com.google.gwt.user.client.ui.TextBox class β
public class TextBox
extends TextBoxBase
implements HasDirection
Following default CSS Style rules will be applied to all the TextBox widget. You can override it as per your requirements.
.gwt-TextBox {}
.gwt-TextBox-readonly {}
TextBox()
Creates an empty text box.
TextBox(Element element)
This constructor may be used by subclasses to explicitly use an existing element.
HasDirection.Direction getDirection()
Gets the directionality of the widget.
int getMaxLength()
Gets the maximum allowable length of the text box.
int getVisibleLength()
Gets the number of visible characters in the text box.
void setDirection(HasDirection.Direction direction)
Sets the directionality for a widget.
void setMaxLength(int length)
Sets the maximum allowable length of the text box.
void setVisibleLength(int length)
Sets the number of visible characters in the text box.
static TextBox wrap(Element element)
Creates a TextBox widget that wraps an existing <input type='text'> element.
This class inherits methods from the following classes β
com.google.gwt.user.client.ui.UIObject
com.google.gwt.user.client.ui.UIObject
com.google.gwt.user.client.ui.Widget
com.google.gwt.user.client.ui.Widget
com.google.gwt.user.client.ui.FocusWidget
com.google.gwt.user.client.ui.FocusWidget
com.google.gwt.user.client.ui.TextBoxBase
com.google.gwt.user.client.ui.TextBoxBase
java.lang.Object
java.lang.Object
This example will take you through simple steps to show usage of a TextBox Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter β
Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name = 'com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class = 'com.tutorialspoint.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path = 'client'/>
<source path = 'shared'/>
</module>
Following is the content of the modified Style Sheet file war/HelloWorld.css.
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.gwt-TextBox {
color: green;
}
.gwt-TextBox-readonly {
background-color: yellow;
}
Following is the content of the modified HTML host file war/HelloWorld.html.
<html>
<head>
<title>Hello World</title>
<link rel = "stylesheet" href = "HelloWorld.css"/>
<script language = "javascript" src = "helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>TextBox Widget Demonstration</h1>
<div id = "gwtContainer"></div>
</body>
</html>
Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of TextBox widget.
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
//create textboxes
TextBox textBox1 = new TextBox();
TextBox textBox2 = new TextBox();
//add text to text box
textBox2.setText("Hello World!");
//set textbox as readonly
textBox2.setReadOnly(true);
// Add text boxes to the root panel.
VerticalPanel panel = new VerticalPanel();
panel.setSpacing(10);
panel.add(textBox1);
panel.add(textBox2);
RootPanel.get("gwtContainer").add(panel);
}
}
Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result β
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2086,
"s": 2023,
"text": "The TextBox widget represents a standard single-line text box."
},
{
"code": null,
"e": 2165,
"s": 2086,
"text": "Following is the declaration for com.google.gwt.user.client.ui.TextBox class β"
},
{
"code": null,
"e": 2239,
"s": 2165,
"text": "public class TextBox\n extends TextBoxBase\n implements HasDirection"
},
{
"code": null,
"e": 2362,
"s": 2239,
"text": "Following default CSS Style rules will be applied to all the TextBox widget. You can override it as per your requirements."
},
{
"code": null,
"e": 2405,
"s": 2362,
"text": ".gwt-TextBox {}\n\n.gwt-TextBox-readonly {} "
},
{
"code": null,
"e": 2415,
"s": 2405,
"text": "TextBox()"
},
{
"code": null,
"e": 2442,
"s": 2415,
"text": "Creates an empty text box."
},
{
"code": null,
"e": 2467,
"s": 2442,
"text": "TextBox(Element element)"
},
{
"code": null,
"e": 2549,
"s": 2467,
"text": "This constructor may be used by subclasses to explicitly use an existing element."
},
{
"code": null,
"e": 2587,
"s": 2549,
"text": "HasDirection.Direction getDirection()"
},
{
"code": null,
"e": 2626,
"s": 2587,
"text": "Gets the directionality of the widget."
},
{
"code": null,
"e": 2645,
"s": 2626,
"text": "int getMaxLength()"
},
{
"code": null,
"e": 2696,
"s": 2645,
"text": "Gets the maximum allowable length of the text box."
},
{
"code": null,
"e": 2719,
"s": 2696,
"text": "int getVisibleLength()"
},
{
"code": null,
"e": 2774,
"s": 2719,
"text": "Gets the number of visible characters in the text box."
},
{
"code": null,
"e": 2826,
"s": 2774,
"text": "void setDirection(HasDirection.Direction direction)"
},
{
"code": null,
"e": 2864,
"s": 2826,
"text": "Sets the directionality for a widget."
},
{
"code": null,
"e": 2894,
"s": 2864,
"text": "void setMaxLength(int length)"
},
{
"code": null,
"e": 2945,
"s": 2894,
"text": "Sets the maximum allowable length of the text box."
},
{
"code": null,
"e": 2979,
"s": 2945,
"text": "void setVisibleLength(int length)"
},
{
"code": null,
"e": 3034,
"s": 2979,
"text": "Sets the number of visible characters in the text box."
},
{
"code": null,
"e": 3071,
"s": 3034,
"text": "static TextBox wrap(Element element)"
},
{
"code": null,
"e": 3148,
"s": 3071,
"text": "Creates a TextBox widget that wraps an existing <input type='text'> element."
},
{
"code": null,
"e": 3205,
"s": 3148,
"text": "This class inherits methods from the following classes β"
},
{
"code": null,
"e": 3244,
"s": 3205,
"text": "com.google.gwt.user.client.ui.UIObject"
},
{
"code": null,
"e": 3283,
"s": 3244,
"text": "com.google.gwt.user.client.ui.UIObject"
},
{
"code": null,
"e": 3320,
"s": 3283,
"text": "com.google.gwt.user.client.ui.Widget"
},
{
"code": null,
"e": 3357,
"s": 3320,
"text": "com.google.gwt.user.client.ui.Widget"
},
{
"code": null,
"e": 3399,
"s": 3357,
"text": "com.google.gwt.user.client.ui.FocusWidget"
},
{
"code": null,
"e": 3441,
"s": 3399,
"text": "com.google.gwt.user.client.ui.FocusWidget"
},
{
"code": null,
"e": 3483,
"s": 3441,
"text": "com.google.gwt.user.client.ui.TextBoxBase"
},
{
"code": null,
"e": 3525,
"s": 3483,
"text": "com.google.gwt.user.client.ui.TextBoxBase"
},
{
"code": null,
"e": 3542,
"s": 3525,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3559,
"s": 3542,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3756,
"s": 3559,
"text": "This example will take you through simple steps to show usage of a TextBox Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter β"
},
{
"code": null,
"e": 3858,
"s": 3756,
"text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml."
},
{
"code": null,
"e": 4467,
"s": 3858,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>"
},
{
"code": null,
"e": 4545,
"s": 4467,
"text": "Following is the content of the modified Style Sheet file war/HelloWorld.css."
},
{
"code": null,
"e": 4824,
"s": 4545,
"text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-TextBox {\n color: green; \n}\n\n.gwt-TextBox-readonly {\n background-color: yellow;\t\n}"
},
{
"code": null,
"e": 4901,
"s": 4824,
"text": "Following is the content of the modified HTML host file war/HelloWorld.html."
},
{
"code": null,
"e": 5227,
"s": 4901,
"text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>TextBox Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 5355,
"s": 5227,
"text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of TextBox widget."
},
{
"code": null,
"e": 6139,
"s": 5355,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.TextBox;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n //create textboxes\n TextBox textBox1 = new TextBox(); \n TextBox textBox2 = new TextBox();\n\n //add text to text box\n textBox2.setText(\"Hello World!\");\n\n //set textbox as readonly\n textBox2.setReadOnly(true);\n\n // Add text boxes to the root panel.\n VerticalPanel panel = new VerticalPanel();\n panel.setSpacing(10);\n panel.add(textBox1);\n panel.add(textBox2);\n\n RootPanel.get(\"gwtContainer\").add(panel);\n }\t\n}"
},
{
"code": null,
"e": 6373,
"s": 6139,
"text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result β"
},
{
"code": null,
"e": 6380,
"s": 6373,
"text": " Print"
},
{
"code": null,
"e": 6391,
"s": 6380,
"text": " Add Notes"
}
] |
How to display Material Chip View in React Native?
|
To display chips in the UI, we are going to make use of React Native Paper Material
Design.
Install react native paper as shown below β
npm install --save-dev react-native-paper
The chip component looks as follows on the UI β
The basic chip component is as follows β
<Chip icon="icontodisplay" onPress={onPressfunc}>Chip Name</Chip>
The basic properties of chip are as follows β
The code that displays chip is as follows β
<SafeAreaView style={styles.container}>
<Chip icon="camera" disabled onPress={() => console.log('camera')}>Click
Here</Chip>
<Chip icon="apple" mode="outlined"selectedColor='green' selected
onPress={() => console.log('apple')}>Apple Icon</Chip>
</SafeAreaView>
import * as React from 'react';
import { StyleSheet, Text, SafeAreaView } from 'react-native';
import { Chip } from 'react-native-paper';
const MyComponent = () => (
<SafeAreaView style={styles.container}>
<Chip icon="camera" style={styles.chip} disabled onPress={() =>
console.log('camera')}>Click Here</Chip>
<Chip icon="apple" style={styles.chip}
mode="outlined"selectedColor='green' selected onPress={() =>
console.log('apple')}>Apple Icon</Chip>
<Chip icon="calendar-month" style={styles.chip} mode="outlined" selected
onPress={() => console.log('calendar')}>Select Date</Chip>
</SafeAreaView>
);
export default MyComponent;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
chip: {
marginTop:10
}
});
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To display chips in the UI, we are going to make use of React Native Paper Material\nDesign."
},
{
"code": null,
"e": 1198,
"s": 1154,
"text": "Install react native paper as shown below β"
},
{
"code": null,
"e": 1240,
"s": 1198,
"text": "npm install --save-dev react-native-paper"
},
{
"code": null,
"e": 1288,
"s": 1240,
"text": "The chip component looks as follows on the UI β"
},
{
"code": null,
"e": 1329,
"s": 1288,
"text": "The basic chip component is as follows β"
},
{
"code": null,
"e": 1395,
"s": 1329,
"text": "<Chip icon=\"icontodisplay\" onPress={onPressfunc}>Chip Name</Chip>"
},
{
"code": null,
"e": 1441,
"s": 1395,
"text": "The basic properties of chip are as follows β"
},
{
"code": null,
"e": 1485,
"s": 1441,
"text": "The code that displays chip is as follows β"
},
{
"code": null,
"e": 1770,
"s": 1485,
"text": "<SafeAreaView style={styles.container}>\n <Chip icon=\"camera\" disabled onPress={() => console.log('camera')}>Click\n Here</Chip>\n <Chip icon=\"apple\" mode=\"outlined\"selectedColor='green' selected\n onPress={() => console.log('apple')}>Apple Icon</Chip>\n</SafeAreaView>"
},
{
"code": null,
"e": 2657,
"s": 1770,
"text": "import * as React from 'react';\nimport { StyleSheet, Text, SafeAreaView } from 'react-native';\nimport { Chip } from 'react-native-paper';\nconst MyComponent = () => (\n <SafeAreaView style={styles.container}>\n <Chip icon=\"camera\" style={styles.chip} disabled onPress={() =>\n console.log('camera')}>Click Here</Chip>\n <Chip icon=\"apple\" style={styles.chip}\n mode=\"outlined\"selectedColor='green' selected onPress={() =>\n console.log('apple')}>Apple Icon</Chip>\n <Chip icon=\"calendar-month\" style={styles.chip} mode=\"outlined\" selected\n onPress={() => console.log('calendar')}>Select Date</Chip>\n </SafeAreaView>\n );\n export default MyComponent;\n const styles = StyleSheet.create({\n container: {\n flex: 1,\n alignItems: \"center\",\n justifyContent: \"center\"\n },\n chip: {\n marginTop:10\n }\n});"
}
] |
Check multiple conditions in if statement - Python - GeeksforGeeks
|
26 Mar, 2020
If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true.
Syntax:
if (condition):
code1
else:
code2
[on_true] if [expression] else [on_false]
Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-elif)
Here weβll study how can we check multiple conditions in a single if statement. This can be done by using βandβ or βorβ or BOTH in a single statement.
Syntax:
if (cond1 AND/OR COND2) AND/OR (cond3 AND/OR cond4):
code1
else:
code2
and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesnβt check the second one. If the first condition is true and the compiler moves to the second and if the second comes out to be false, false is returned to the if statement.
or Comparison = for this to work normally either condition needs to be true. The compiler checks the first condition first and if that turns out to be true, the compiler runs the assigned code and the second condition is not evaluated. If the first condition turns out to be false, the compiler checks the second, if that is true the assigned code runs but if that fails too, false is returned to the if statement.
The following examples will help understand this better:PROGRAM 1: program that grants access only to kids aged between 8-12
age = 18 if ((age>= 8) and (age<= 12)): print("YOU ARE ALLOWED. WELCOME !")else: print("SORRY ! YOU ARE NOT ALLOWED. BYE !")
Output:
SORRY ! YOU ARE NOT ALLOWED. BYE !
PROGRAM 2:
program that checks the agreement of the user to the terms
var = 'N' if (var =='Y' or var =='y'): print("YOU SAID YES")elif(var =='N' or var =='n'): print("YOU SAID NO")else: print("INVALID INPUT")
Output:
YOU SAID NO
PROGRAM 3: program to compare the entered three numbers
a = 7b = 9c = 3 if((a>b and a>c) and (a != b and a != c)): print(a, " is the largest")elif((b>a and b>c) and (b != a and b != c)): print(b, " is the largest")elif((c>a and c>b) and (c != a and c != b)): print(c, " is the largest")else: print("entered numbers are equal")
Output:
9 is the largest
Not just two conditions we can check more than that by using βandβ and βorβ.PROGRAM 4:
a = 1b = 1c = 1if(a == 1 and b == 1 and c == 1): print("working")else: print("stopped")
Output:
working
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
*args and **kwargs in Python
sum() function in Python
|
[
{
"code": null,
"e": 24243,
"s": 24215,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24366,
"s": 24243,
"text": "If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true."
},
{
"code": null,
"e": 24374,
"s": 24366,
"text": "Syntax:"
},
{
"code": null,
"e": 24417,
"s": 24374,
"text": "if (condition):\n code1\nelse:\n code2\n"
},
{
"code": null,
"e": 24459,
"s": 24417,
"text": "[on_true] if [expression] else [on_false]"
},
{
"code": null,
"e": 24558,
"s": 24459,
"text": "Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-elif)"
},
{
"code": null,
"e": 24709,
"s": 24558,
"text": "Here weβll study how can we check multiple conditions in a single if statement. This can be done by using βandβ or βorβ or BOTH in a single statement."
},
{
"code": null,
"e": 24717,
"s": 24709,
"text": "Syntax:"
},
{
"code": null,
"e": 24797,
"s": 24717,
"text": "if (cond1 AND/OR COND2) AND/OR (cond3 AND/OR cond4):\n code1\nelse:\n code2\n"
},
{
"code": null,
"e": 25113,
"s": 24797,
"text": "and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesnβt check the second one. If the first condition is true and the compiler moves to the second and if the second comes out to be false, false is returned to the if statement."
},
{
"code": null,
"e": 25528,
"s": 25113,
"text": "or Comparison = for this to work normally either condition needs to be true. The compiler checks the first condition first and if that turns out to be true, the compiler runs the assigned code and the second condition is not evaluated. If the first condition turns out to be false, the compiler checks the second, if that is true the assigned code runs but if that fails too, false is returned to the if statement."
},
{
"code": null,
"e": 25653,
"s": 25528,
"text": "The following examples will help understand this better:PROGRAM 1: program that grants access only to kids aged between 8-12"
},
{
"code": "age = 18 if ((age>= 8) and (age<= 12)): print(\"YOU ARE ALLOWED. WELCOME !\")else: print(\"SORRY ! YOU ARE NOT ALLOWED. BYE !\")",
"e": 25785,
"s": 25653,
"text": null
},
{
"code": null,
"e": 25793,
"s": 25785,
"text": "Output:"
},
{
"code": null,
"e": 25829,
"s": 25793,
"text": "SORRY ! YOU ARE NOT ALLOWED. BYE !\n"
},
{
"code": null,
"e": 25840,
"s": 25829,
"text": "PROGRAM 2:"
},
{
"code": null,
"e": 25899,
"s": 25840,
"text": "program that checks the agreement of the user to the terms"
},
{
"code": "var = 'N' if (var =='Y' or var =='y'): print(\"YOU SAID YES\")elif(var =='N' or var =='n'): print(\"YOU SAID NO\")else: print(\"INVALID INPUT\")",
"e": 26048,
"s": 25899,
"text": null
},
{
"code": null,
"e": 26056,
"s": 26048,
"text": "Output:"
},
{
"code": null,
"e": 26069,
"s": 26056,
"text": "YOU SAID NO\n"
},
{
"code": null,
"e": 26125,
"s": 26069,
"text": "PROGRAM 3: program to compare the entered three numbers"
},
{
"code": "a = 7b = 9c = 3 if((a>b and a>c) and (a != b and a != c)): print(a, \" is the largest\")elif((b>a and b>c) and (b != a and b != c)): print(b, \" is the largest\")elif((c>a and c>b) and (c != a and c != b)): print(c, \" is the largest\")else: print(\"entered numbers are equal\")",
"e": 26411,
"s": 26125,
"text": null
},
{
"code": null,
"e": 26419,
"s": 26411,
"text": "Output:"
},
{
"code": null,
"e": 26437,
"s": 26419,
"text": "9 is the largest"
},
{
"code": null,
"e": 26524,
"s": 26437,
"text": "Not just two conditions we can check more than that by using βandβ and βorβ.PROGRAM 4:"
},
{
"code": "a = 1b = 1c = 1if(a == 1 and b == 1 and c == 1): print(\"working\")else: print(\"stopped\")",
"e": 26618,
"s": 26524,
"text": null
},
{
"code": null,
"e": 26626,
"s": 26618,
"text": "Output:"
},
{
"code": null,
"e": 26634,
"s": 26626,
"text": "working"
},
{
"code": null,
"e": 26648,
"s": 26634,
"text": "python-basics"
},
{
"code": null,
"e": 26655,
"s": 26648,
"text": "Python"
},
{
"code": null,
"e": 26753,
"s": 26655,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26762,
"s": 26753,
"text": "Comments"
},
{
"code": null,
"e": 26775,
"s": 26762,
"text": "Old Comments"
},
{
"code": null,
"e": 26793,
"s": 26775,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26828,
"s": 26793,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26860,
"s": 26828,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26902,
"s": 26860,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26928,
"s": 26902,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26965,
"s": 26928,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27009,
"s": 26965,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27064,
"s": 27009,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27093,
"s": 27064,
"text": "*args and **kwargs in Python"
}
] |
How to use AlarmManager in Android?
|
This example demonstrates how do I use AlarmManager in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_gravity="center"
android:id="@+id/buttonAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Alarm" />
</LinearLayout>
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.java
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
lateinit var btnSetAlarm: Button
lateinit var timePicker: TimePicker
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
timePicker = findViewById(R.id.timePicker)
btnSetAlarm = findViewById(R.id.buttonAlarm)
btnSetAlarm.setOnClickListener {
val calendar: Calendar = Calendar.getInstance()
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), timePicker.hour, timePicker.minute, 0)
}
else {
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.currentHour,
timePicker.currentMinute, 0)
}
setAlarm(calendar.timeInMillis)
}
}
private fun setAlarm(timeInMillis: Long) {
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, MyAlarm::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmManager.setRepeating(AlarmManager.RTC, timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent)
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show()
}
private class MyAlarm : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("Alarm Bell", "Alarm just fired")
}
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code.
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "This example demonstrates how do I use AlarmManager in android."
},
{
"code": null,
"e": 1255,
"s": 1126,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1320,
"s": 1255,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2222,
"s": 1320,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <LinearLayout\n android:id=\"@+id/linearLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerVertical=\"true\"\n android:orientation=\"vertical\">\n <TimePicker\n android:id=\"@+id/timePicker\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:layout_gravity=\"center\"\n android:id=\"@+id/buttonAlarm\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Set Alarm\" />\n </LinearLayout>\n</RelativeLayout>\n"
},
{
"code": null,
"e": 2279,
"s": 2222,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4290,
"s": 2279,
"text": "import android.app.AlarmManager\nimport android.app.PendingIntent\nimport android.content.BroadcastReceiver\nimport android.content.Context\nimport android.content.Intent\nimport android.os.Build\nimport android.os.Bundle\nimport android.util.Log\nimport android.widget.Button\nimport android.widget.TimePicker\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport java.util.*\nclass MainActivity : AppCompatActivity() {\n lateinit var btnSetAlarm: Button\n lateinit var timePicker: TimePicker\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) \n title = \"KotlinApp\"\n timePicker = findViewById(R.id.timePicker)\n btnSetAlarm = findViewById(R.id.buttonAlarm)\n btnSetAlarm.setOnClickListener {\n val calendar: Calendar = Calendar.getInstance()\n if (Build.VERSION.SDK_INT >= 23) {\n calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), timePicker.hour, timePicker.minute, 0)\n }\n else {\n calendar.set(calendar.get(Calendar.YEAR),\n calendar.get(Calendar.MONTH),\n calendar.get(Calendar.DAY_OF_MONTH),\n timePicker.currentHour,\n timePicker.currentMinute, 0)\n }\n setAlarm(calendar.timeInMillis)\n }\n }\n private fun setAlarm(timeInMillis: Long) {\n val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager\n val intent = Intent(this, MyAlarm::class.java)\n val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)\n alarmManager.setRepeating(AlarmManager.RTC, timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent)\n Toast.makeText(this, \"Alarm is set\", Toast.LENGTH_SHORT).show()\n }\n private class MyAlarm : BroadcastReceiver() {\n override fun onReceive(context: Context, intent: Intent) {\n Log.d(\"Alarm Bell\", \"Alarm just fired\")\n }\n }\n}"
},
{
"code": null,
"e": 4345,
"s": 4290,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5016,
"s": 4345,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5364,
"s": 5016,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 5405,
"s": 5364,
"text": "Click here to download the project code."
}
] |
Spring - BeanFactory - GeeksforGeeks
|
02 Aug, 2021
The first foremost thing when we talk about spring is dependency injection which is possible because spring is actually a container and behaves as a factory of Beans. Just like the BeanFactory interface is the simplest container providing an advanced configuration mechanism to instantiate, configure and manage the life cycle of beans. Beans are java objects that are configured at run-time by Spring IoC Container. BeanFactory represents a basic IoC container which is a parent interface of ApplicationContext. BeanFactory uses Beans and their dependencies metadata to create and configure them at run-time. BeanFactory loads the bean definitions and dependency amongst the beans based on a configuration file(XML) or the beans can be directly returned when required using Java Configuration. There are other types of configuration files like LDAP, RDMS, properties file, etc. BeanFactory does not support Annotation-based configuration whereas ApplicationContext does.
Let us do first go through some of the methods of Bean factory before landing up on implementation which are shown below in tabular format below as follows:
Method
Description
Procedure:
Creating a Spring project using start.spring.io.Creating a POJO class.Configure the Student bean in the bean-factory-demo.xml file.Writing it to application class.
Creating a Spring project using start.spring.io.
Creating a POJO class.
Configure the Student bean in the bean-factory-demo.xml file.
Writing it to application class.
Implementation:
Step 1: Bean Definition: Create a Student POJO class.
// Java Program where we are creating a POJO class
// POJO class
public class Student {
// Member variables
private String name;
private String age;
// Constructor 1
public Student() {
}
// Constructor 2
public Student(String name, String age) {
this.name = name;
this.age = age;
}
// Method inside POJO class
@Override
public String toString() {
// Print student clas attributes
return "Student{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}';
}
}
Step 2: XML Bean Configuration: Configure the Student bean in the bean-factory-demo.xml file.
<?xml version = "1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class = "com.gfg.demo.domain.Student">
<constructor-arg name="name" value="Tina"/>
<constructor-arg name="age" value="21"/>
</bean>
</beans>
Step 3: Main Class
// Application class
@SpringBootApplication
// Main class
public class DemoApplication {
// Main driver method
public static void main(String[] args) {
// Creating object in a spring container (Beans)
BeanFactory factory = new ClassPathXmlApplicationContext("bean-factory-demo.xml");
Student student = (Student) factory.getBean("student");
System.out.println(student);
}
}
Output:
Student{name='Tina', age='21'}
Note: XmlBeanFactory class is deprecated.
surindertarika1234
Java-Spring
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
PriorityQueue in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n02 Aug, 2021"
},
{
"code": null,
"e": 26320,
"s": 25347,
"text": "The first foremost thing when we talk about spring is dependency injection which is possible because spring is actually a container and behaves as a factory of Beans. Just like the BeanFactory interface is the simplest container providing an advanced configuration mechanism to instantiate, configure and manage the life cycle of beans. Beans are java objects that are configured at run-time by Spring IoC Container. BeanFactory represents a basic IoC container which is a parent interface of ApplicationContext. BeanFactory uses Beans and their dependencies metadata to create and configure them at run-time. BeanFactory loads the bean definitions and dependency amongst the beans based on a configuration file(XML) or the beans can be directly returned when required using Java Configuration. There are other types of configuration files like LDAP, RDMS, properties file, etc. BeanFactory does not support Annotation-based configuration whereas ApplicationContext does."
},
{
"code": null,
"e": 26477,
"s": 26320,
"text": "Let us do first go through some of the methods of Bean factory before landing up on implementation which are shown below in tabular format below as follows:"
},
{
"code": null,
"e": 26484,
"s": 26477,
"text": "Method"
},
{
"code": null,
"e": 26496,
"s": 26484,
"text": "Description"
},
{
"code": null,
"e": 26508,
"s": 26496,
"text": "Procedure: "
},
{
"code": null,
"e": 26672,
"s": 26508,
"text": "Creating a Spring project using start.spring.io.Creating a POJO class.Configure the Student bean in the bean-factory-demo.xml file.Writing it to application class."
},
{
"code": null,
"e": 26721,
"s": 26672,
"text": "Creating a Spring project using start.spring.io."
},
{
"code": null,
"e": 26744,
"s": 26721,
"text": "Creating a POJO class."
},
{
"code": null,
"e": 26806,
"s": 26744,
"text": "Configure the Student bean in the bean-factory-demo.xml file."
},
{
"code": null,
"e": 26839,
"s": 26806,
"text": "Writing it to application class."
},
{
"code": null,
"e": 26855,
"s": 26839,
"text": "Implementation:"
},
{
"code": null,
"e": 26909,
"s": 26855,
"text": "Step 1: Bean Definition: Create a Student POJO class."
},
{
"code": null,
"e": 27416,
"s": 26909,
"text": "// Java Program where we are creating a POJO class\n\n// POJO class\npublic class Student {\n\n // Member variables\n private String name;\n private String age;\n\n // Constructor 1\n public Student() {\n }\n\n // Constructor 2\n public Student(String name, String age) {\n this.name = name;\n this.age = age;\n }\n\n // Method inside POJO class\n @Override\n public String toString() {\n\n // Print student clas attributes\n return \"Student{\" + \"name='\" + name + '\\'' + \", age='\" + age + '\\'' + '}';\n }\n}"
},
{
"code": null,
"e": 27510,
"s": 27416,
"text": "Step 2: XML Bean Configuration: Configure the Student bean in the bean-factory-demo.xml file."
},
{
"code": null,
"e": 28049,
"s": 27510,
"text": "<?xml version = \"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n https://www.springframework.org/schema/beans/spring-beans.xsd\">\n \n <bean id=\"student\" class = \"com.gfg.demo.domain.Student\">\n <constructor-arg name=\"name\" value=\"Tina\"/>\n <constructor-arg name=\"age\" value=\"21\"/>\n </bean>\n</beans>"
},
{
"code": null,
"e": 28068,
"s": 28049,
"text": "Step 3: Main Class"
},
{
"code": null,
"e": 28468,
"s": 28068,
"text": "// Application class \n@SpringBootApplication\n\n// Main class\npublic class DemoApplication {\n\n // Main driver method\n public static void main(String[] args) {\n\n // Creating object in a spring container (Beans)\n BeanFactory factory = new ClassPathXmlApplicationContext(\"bean-factory-demo.xml\");\n Student student = (Student) factory.getBean(\"student\");\n\n System.out.println(student);\n }\n}"
},
{
"code": null,
"e": 28476,
"s": 28468,
"text": "Output:"
},
{
"code": null,
"e": 28507,
"s": 28476,
"text": "Student{name='Tina', age='21'}"
},
{
"code": null,
"e": 28550,
"s": 28507,
"text": "Note: XmlBeanFactory class is deprecated. "
},
{
"code": null,
"e": 28569,
"s": 28550,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28581,
"s": 28569,
"text": "Java-Spring"
},
{
"code": null,
"e": 28586,
"s": 28581,
"text": "Java"
},
{
"code": null,
"e": 28591,
"s": 28586,
"text": "Java"
},
{
"code": null,
"e": 28689,
"s": 28591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28704,
"s": 28689,
"text": "Stream In Java"
},
{
"code": null,
"e": 28723,
"s": 28704,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28744,
"s": 28723,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28790,
"s": 28744,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28820,
"s": 28790,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28837,
"s": 28820,
"text": "Generics in Java"
},
{
"code": null,
"e": 28880,
"s": 28837,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28901,
"s": 28880,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28923,
"s": 28901,
"text": "PriorityQueue in Java"
}
] |
TensorFlow vs PyTorch for Deep Learning | Towards Data Science
|
You may be wondering whether to learn PyTorch or TensorFlow (2.0). If so hopefully this blog post can help. The idea is not to give an absolute answer here but just to show what developing and training neural networks look like in both.
Before looking into the code, some things that are good to know: Both TensorFlow and PyTorch are machine learning frameworks specifically designed for developing deep learning algorithms with access to the computational power needed to process lots of data (e.g. parallel computing, training on GPUs, etc).
TensorFlow, which comes out of Google, was released in 2015 under the Apache 2.0 license. In Oktober 2019, TensorFlow 2.0 was released, which is said to be a huge improvement. Itβs typically used in Python. PyTorch, on the other hand, comes out of Facebook and was released in 2016 under a similarly permissive open source license. As its name suggests, itβs also a Python library.
Back to the main reason for this blog post. The plan is to implement a simple neural network architecture in both TensorFlow and PyTorch to see some of the similarities and differences.
The neural network model consists of three layers: Embedding Layer β Global Average Pooling Layer β Dense Layer. Itβs based on this example.
The dataset used here consists of 40,000 tweets and their sentiment (0=negative, 1=positive). First, loading the data from a CSV file and displaying some rows of the data frame to get an idea of the data.
import numpy as npimport pandas as pddata = pd.read_csv("./data/tweets.csv", encoding=βutf-8')data[:10]
To vectorize the tweets, I used Kerasβ tokenizer here but thereβre countless others that can do the same or even more.
Hereβs what happens in the code snippet above. We assign an integer to each of the 20,000 most common words of the tweets and then turn the tweets into sequences of integers. We pad shorter ones with zeros and cut off longer ones, forcing a sequence length of 42. Finally, we should have a matrix of dimension 40,000 x 42 (tweets x sequence length).
import tensorflow as tf
Creating TensorFlow models is typically done using Keras. Keras is built on top of TensorFlow and allows for easy and fast prototyping because it has many layers built-in β it would be tedious or even prohibitive to code them from scratch each time.
There are three ways to build a neural network model in Keras.
You can create your own fully-customizable models by subclassing the tf.keras.Model class and implementing the forward pass in the call method. Put differently, layers are defined in the __init__() method and the logic of the forward pass in the call method.
The benefit of using such an object-oriented approach is that you can reuse layers multiple times within the call method or define a more complex forward pass. But nothing like that is happening in this example here, itβs just a linear stack of layers.
In the functional API, given some input tensor(s) and output tensor(s), you can also instantiate a Model. Itβs a user-friendly way to build a neural network and Keras even recommends it over model subclassing. With this approach, you essentially define a layer and immediately pass it the input of the previous layer. So it requires slightly less coding with the same result.
The sequential API is the most compact way to define a model and sufficient for certain (simple) neural networks, typically consisting of just a few common layers β kind of a shortcut to a trainable model. Itβs definitely convenient and works well but is too inflexible if you wish to implement more sophisticated ideas.
Regardless of how you build a Keras model, there are two functions Iβd like to show you. First, calling model.summary() prints a compact summary of the model and the number of parameters, which is super useful.
Second, by calling tf.keras.utils.plot_model() you get a graphical summary of the model. It didnβt work in my Jupyter Notebook, however. So I canβt show it to you here, unfortunately.
Before you can train a Keras model, it must be compiled by running the model.compile() function, which is also where you specify the loss function and optimizer.
model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])
Keras models have a convenient fit function for training a model (just like Scikit-Learn), which also takes care of batch processing and even evaluates the model on the run (if you tell it to do so).
model.fit(x=X, y, batch_size=32, epochs=5, verbose=2, validation_split=0.2)
Note: Itβs okay to pass Numpy arrays as inputs to the fit function even though TensorFlow (PyTorch too for that matter) operates on tensors only, which is a similar data structure but optimized for matrix computations. Keras takes care of transforming the arrays under the hood.
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optim
There are two ways to build a neural network model in PyTorch.
Similar to TensorFlow, in PyTorch you subclass the nn.Model module and define your layers in the __init__() method. The only difference is that you create the forward pass in a method named forward instead of call.
Note: Difference to the Keras model: Thereβs only an average-pooling layer in PyTorch so it needs to have the right kernel size in order the make it global average-pooling.
PyTorch also offers a Sequential module that looks almost equivalent to TensorFlowβs.
Note: I found that many layers do not work with PyTorchβs nn.Sequential such as many recurrent layers (RNNs, LSTMS, etc.). In fact, PyTorch didnβt really want to implement the sequential module at all because it wants developers to use subclassing.
Thereβs no pre-made fit function for PyTorch models, so the training loop needs to be implemented from scratch. Hereβs what a typical training loop in PyTorch looks like.
Note: In oder to process the data in batches, a dataloader must be created (left out here, see GitHub code). The dataloader returns one batch at a time in a dictionary format.
Short description of the training loop: For each batch, we calculate the loss and then call loss.backward() to backpropagate the gradient through the layers. In addition, we call optimizer.step() to tell the optimizer to update the parameters. For a more detailed description of how to train a PyTorch model see here.
Hereβre the best resources I know about getting started with TensorFlow and/or PyTorch.
PyTorchβs official tutorial on their website is awesome and in my view better than TensorFlowβs. Thereβs also a really good free PyTorch course on Udacity.
Tutorials on the PyTorch Website
Intro to Deep Learning with PyTorch on Udacity
Deep Learning with PyTorch (Book)
TensorFlow has some really good courses on Coursera, and thereβs a great book written by FrancΜ§ois Chollet, the creator of Keras. TensorFlowβs and especially Kerasβ official websites are important sources too.
TensorFlow Website
Keras Dokumentation
Intro to TensorFlow for Deep Learning on Udacity
TensorFlow in Practice from deeplearning.ai on Coursera
Deep Learning with Python by FrancΜ§ois Chollet (Book)
I donβt really feel able to answer that because I have only scratched the surface so far. But here are some of the things Iβve noticed.
TensorFlow is a lot like Scikit-Learn thanks to its fit function, which makes training a model super easy and quick. But even though you need to build every training loop in PyTorch yourself, I kind of like it because it makes you think more carefully about what youβre doing. So itβs less of a black box and thatβs always good. I fist learned PyTorch and I think that was a very good idea.
Note: Of course, TensorFlow allows you to build customized training loops as well, but itβs not as neat. Plus, there are third-party libraries for PyTorch that automate the training loop so that the difference here may not be so big after all.
All in all, itβs certainly easier to go from a blank script to a trained neural network in TensorFlow than in PyTorch β mostly due to TensorFlowβs fit method. But another difference plays a role here too. Iβve noticed that Keras layers often do not require you to specify the input dimension whereas in PyTorch you need to be more explicit. Itβs easy to confuse the dimensions, especially if you want to try out different ones. Apart from that, Kerasβ model.summary() and tf.keras.utils.plot_model()are super useful functions, as mentioned before. There are no standard PyTorch functions (Iβm aware of) that can do the same.
These are definitely some plus points for TensorFlow. But in general, the two libraries feel VERY similar. It seems that they have converged a lot already by learning from each other and adopted each otherβs best features. Thatβs not at all a bad thing but simply a sign that they have matured a lot. Therefore itβs also really easy to switch β so donβt worry about choosing the βwrongβ library. For sure, there are a lot more aspects that I did not consider here, especially any advanced features such as parallel computing, training on GPUs, etc.
Anyway, it will be interesting to see how TensorFlow and PyTorch will do in 2020. While PyTorch has been more popular among researchers lately, TensorFlow is the frontrunner in the industry. Thanks to TensorFlow and PyTorch, deep learning is more accessible than ever and more people will use it. Itβs never been easier.
The code can also be found as a Jupyter Notebook here.
|
[
{
"code": null,
"e": 408,
"s": 171,
"text": "You may be wondering whether to learn PyTorch or TensorFlow (2.0). If so hopefully this blog post can help. The idea is not to give an absolute answer here but just to show what developing and training neural networks look like in both."
},
{
"code": null,
"e": 715,
"s": 408,
"text": "Before looking into the code, some things that are good to know: Both TensorFlow and PyTorch are machine learning frameworks specifically designed for developing deep learning algorithms with access to the computational power needed to process lots of data (e.g. parallel computing, training on GPUs, etc)."
},
{
"code": null,
"e": 1097,
"s": 715,
"text": "TensorFlow, which comes out of Google, was released in 2015 under the Apache 2.0 license. In Oktober 2019, TensorFlow 2.0 was released, which is said to be a huge improvement. Itβs typically used in Python. PyTorch, on the other hand, comes out of Facebook and was released in 2016 under a similarly permissive open source license. As its name suggests, itβs also a Python library."
},
{
"code": null,
"e": 1283,
"s": 1097,
"text": "Back to the main reason for this blog post. The plan is to implement a simple neural network architecture in both TensorFlow and PyTorch to see some of the similarities and differences."
},
{
"code": null,
"e": 1424,
"s": 1283,
"text": "The neural network model consists of three layers: Embedding Layer β Global Average Pooling Layer β Dense Layer. Itβs based on this example."
},
{
"code": null,
"e": 1629,
"s": 1424,
"text": "The dataset used here consists of 40,000 tweets and their sentiment (0=negative, 1=positive). First, loading the data from a CSV file and displaying some rows of the data frame to get an idea of the data."
},
{
"code": null,
"e": 1733,
"s": 1629,
"text": "import numpy as npimport pandas as pddata = pd.read_csv(\"./data/tweets.csv\", encoding=βutf-8')data[:10]"
},
{
"code": null,
"e": 1852,
"s": 1733,
"text": "To vectorize the tweets, I used Kerasβ tokenizer here but thereβre countless others that can do the same or even more."
},
{
"code": null,
"e": 2202,
"s": 1852,
"text": "Hereβs what happens in the code snippet above. We assign an integer to each of the 20,000 most common words of the tweets and then turn the tweets into sequences of integers. We pad shorter ones with zeros and cut off longer ones, forcing a sequence length of 42. Finally, we should have a matrix of dimension 40,000 x 42 (tweets x sequence length)."
},
{
"code": null,
"e": 2226,
"s": 2202,
"text": "import tensorflow as tf"
},
{
"code": null,
"e": 2476,
"s": 2226,
"text": "Creating TensorFlow models is typically done using Keras. Keras is built on top of TensorFlow and allows for easy and fast prototyping because it has many layers built-in β it would be tedious or even prohibitive to code them from scratch each time."
},
{
"code": null,
"e": 2539,
"s": 2476,
"text": "There are three ways to build a neural network model in Keras."
},
{
"code": null,
"e": 2798,
"s": 2539,
"text": "You can create your own fully-customizable models by subclassing the tf.keras.Model class and implementing the forward pass in the call method. Put differently, layers are defined in the __init__() method and the logic of the forward pass in the call method."
},
{
"code": null,
"e": 3051,
"s": 2798,
"text": "The benefit of using such an object-oriented approach is that you can reuse layers multiple times within the call method or define a more complex forward pass. But nothing like that is happening in this example here, itβs just a linear stack of layers."
},
{
"code": null,
"e": 3427,
"s": 3051,
"text": "In the functional API, given some input tensor(s) and output tensor(s), you can also instantiate a Model. Itβs a user-friendly way to build a neural network and Keras even recommends it over model subclassing. With this approach, you essentially define a layer and immediately pass it the input of the previous layer. So it requires slightly less coding with the same result."
},
{
"code": null,
"e": 3748,
"s": 3427,
"text": "The sequential API is the most compact way to define a model and sufficient for certain (simple) neural networks, typically consisting of just a few common layers β kind of a shortcut to a trainable model. Itβs definitely convenient and works well but is too inflexible if you wish to implement more sophisticated ideas."
},
{
"code": null,
"e": 3959,
"s": 3748,
"text": "Regardless of how you build a Keras model, there are two functions Iβd like to show you. First, calling model.summary() prints a compact summary of the model and the number of parameters, which is super useful."
},
{
"code": null,
"e": 4143,
"s": 3959,
"text": "Second, by calling tf.keras.utils.plot_model() you get a graphical summary of the model. It didnβt work in my Jupyter Notebook, however. So I canβt show it to you here, unfortunately."
},
{
"code": null,
"e": 4305,
"s": 4143,
"text": "Before you can train a Keras model, it must be compiled by running the model.compile() function, which is also where you specify the loss function and optimizer."
},
{
"code": null,
"e": 4387,
"s": 4305,
"text": "model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])"
},
{
"code": null,
"e": 4587,
"s": 4387,
"text": "Keras models have a convenient fit function for training a model (just like Scikit-Learn), which also takes care of batch processing and even evaluates the model on the run (if you tell it to do so)."
},
{
"code": null,
"e": 4663,
"s": 4587,
"text": "model.fit(x=X, y, batch_size=32, epochs=5, verbose=2, validation_split=0.2)"
},
{
"code": null,
"e": 4942,
"s": 4663,
"text": "Note: Itβs okay to pass Numpy arrays as inputs to the fit function even though TensorFlow (PyTorch too for that matter) operates on tensors only, which is a similar data structure but optimized for matrix computations. Keras takes care of transforming the arrays under the hood."
},
{
"code": null,
"e": 5034,
"s": 4942,
"text": "import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optim"
},
{
"code": null,
"e": 5097,
"s": 5034,
"text": "There are two ways to build a neural network model in PyTorch."
},
{
"code": null,
"e": 5312,
"s": 5097,
"text": "Similar to TensorFlow, in PyTorch you subclass the nn.Model module and define your layers in the __init__() method. The only difference is that you create the forward pass in a method named forward instead of call."
},
{
"code": null,
"e": 5485,
"s": 5312,
"text": "Note: Difference to the Keras model: Thereβs only an average-pooling layer in PyTorch so it needs to have the right kernel size in order the make it global average-pooling."
},
{
"code": null,
"e": 5571,
"s": 5485,
"text": "PyTorch also offers a Sequential module that looks almost equivalent to TensorFlowβs."
},
{
"code": null,
"e": 5820,
"s": 5571,
"text": "Note: I found that many layers do not work with PyTorchβs nn.Sequential such as many recurrent layers (RNNs, LSTMS, etc.). In fact, PyTorch didnβt really want to implement the sequential module at all because it wants developers to use subclassing."
},
{
"code": null,
"e": 5991,
"s": 5820,
"text": "Thereβs no pre-made fit function for PyTorch models, so the training loop needs to be implemented from scratch. Hereβs what a typical training loop in PyTorch looks like."
},
{
"code": null,
"e": 6167,
"s": 5991,
"text": "Note: In oder to process the data in batches, a dataloader must be created (left out here, see GitHub code). The dataloader returns one batch at a time in a dictionary format."
},
{
"code": null,
"e": 6485,
"s": 6167,
"text": "Short description of the training loop: For each batch, we calculate the loss and then call loss.backward() to backpropagate the gradient through the layers. In addition, we call optimizer.step() to tell the optimizer to update the parameters. For a more detailed description of how to train a PyTorch model see here."
},
{
"code": null,
"e": 6573,
"s": 6485,
"text": "Hereβre the best resources I know about getting started with TensorFlow and/or PyTorch."
},
{
"code": null,
"e": 6729,
"s": 6573,
"text": "PyTorchβs official tutorial on their website is awesome and in my view better than TensorFlowβs. Thereβs also a really good free PyTorch course on Udacity."
},
{
"code": null,
"e": 6762,
"s": 6729,
"text": "Tutorials on the PyTorch Website"
},
{
"code": null,
"e": 6809,
"s": 6762,
"text": "Intro to Deep Learning with PyTorch on Udacity"
},
{
"code": null,
"e": 6843,
"s": 6809,
"text": "Deep Learning with PyTorch (Book)"
},
{
"code": null,
"e": 7053,
"s": 6843,
"text": "TensorFlow has some really good courses on Coursera, and thereβs a great book written by FrancΜ§ois Chollet, the creator of Keras. TensorFlowβs and especially Kerasβ official websites are important sources too."
},
{
"code": null,
"e": 7072,
"s": 7053,
"text": "TensorFlow Website"
},
{
"code": null,
"e": 7092,
"s": 7072,
"text": "Keras Dokumentation"
},
{
"code": null,
"e": 7141,
"s": 7092,
"text": "Intro to TensorFlow for Deep Learning on Udacity"
},
{
"code": null,
"e": 7197,
"s": 7141,
"text": "TensorFlow in Practice from deeplearning.ai on Coursera"
},
{
"code": null,
"e": 7251,
"s": 7197,
"text": "Deep Learning with Python by FrancΜ§ois Chollet (Book)"
},
{
"code": null,
"e": 7387,
"s": 7251,
"text": "I donβt really feel able to answer that because I have only scratched the surface so far. But here are some of the things Iβve noticed."
},
{
"code": null,
"e": 7778,
"s": 7387,
"text": "TensorFlow is a lot like Scikit-Learn thanks to its fit function, which makes training a model super easy and quick. But even though you need to build every training loop in PyTorch yourself, I kind of like it because it makes you think more carefully about what youβre doing. So itβs less of a black box and thatβs always good. I fist learned PyTorch and I think that was a very good idea."
},
{
"code": null,
"e": 8022,
"s": 7778,
"text": "Note: Of course, TensorFlow allows you to build customized training loops as well, but itβs not as neat. Plus, there are third-party libraries for PyTorch that automate the training loop so that the difference here may not be so big after all."
},
{
"code": null,
"e": 8647,
"s": 8022,
"text": "All in all, itβs certainly easier to go from a blank script to a trained neural network in TensorFlow than in PyTorch β mostly due to TensorFlowβs fit method. But another difference plays a role here too. Iβve noticed that Keras layers often do not require you to specify the input dimension whereas in PyTorch you need to be more explicit. Itβs easy to confuse the dimensions, especially if you want to try out different ones. Apart from that, Kerasβ model.summary() and tf.keras.utils.plot_model()are super useful functions, as mentioned before. There are no standard PyTorch functions (Iβm aware of) that can do the same."
},
{
"code": null,
"e": 9196,
"s": 8647,
"text": "These are definitely some plus points for TensorFlow. But in general, the two libraries feel VERY similar. It seems that they have converged a lot already by learning from each other and adopted each otherβs best features. Thatβs not at all a bad thing but simply a sign that they have matured a lot. Therefore itβs also really easy to switch β so donβt worry about choosing the βwrongβ library. For sure, there are a lot more aspects that I did not consider here, especially any advanced features such as parallel computing, training on GPUs, etc."
},
{
"code": null,
"e": 9517,
"s": 9196,
"text": "Anyway, it will be interesting to see how TensorFlow and PyTorch will do in 2020. While PyTorch has been more popular among researchers lately, TensorFlow is the frontrunner in the industry. Thanks to TensorFlow and PyTorch, deep learning is more accessible than ever and more people will use it. Itβs never been easier."
}
] |
CBSE Class 11 | Concepts of Programming Methodology - GeeksforGeeks
|
22 Aug, 2018
Programming is all about solving a particular problem through computerized codes. Whether it be a problem of inventory management at any shopping complex, marks evaluation of OMR sheets, running of a remote car, or even running of a missile. Thus the scope of programming ranges from very simpleton tasks to extremely complicated ones. But behind all the codes, one parameter is common, that is, to handle and solve the problem efficiently. As one canβt learn to fly an aeroplane simply by watching it flying, one has to actually learn it. Similarly to become a proficient coder, one has to actually do the codes. And, the task of coding is extremely easy once one learns how to apply the logic for problem solving.
Computer Programming comprises of the fundamental entities which are writing, testing, troubleshooting, debugging, and maintaining of a computer program.
Writing involves writing down on a paper what is the desired output of the code. This can easily be done by drawing a flowchart which depicts all the steps involved from starting to end. Then writing also involves writing the first copy of the course actually onto the corresponding software. Then the written code has to be tested.Once tested, if there are some errors, then those errors has to be removed. This process is called troubleshooting.To determine the exact location of the error in the code is executed through a process called debugging.After successful completion of all these steps, the program is being executed to obtain the desired result. This is called running the program.
Writing involves writing down on a paper what is the desired output of the code. This can easily be done by drawing a flowchart which depicts all the steps involved from starting to end. Then writing also involves writing the first copy of the course actually onto the corresponding software. Then the written code has to be tested.
Once tested, if there are some errors, then those errors has to be removed. This process is called troubleshooting.
To determine the exact location of the error in the code is executed through a process called debugging.
After successful completion of all these steps, the program is being executed to obtain the desired result. This is called running the program.
A program is called an efficient program only if it gives correct output corresponding to every input, including the wrong input. The systematic approach to write such an efficient article involves two steps:a) Program Structure and b) Program Representation. While the former is implemented by using bottom-up or top-down approach and is termed as βpopular approachβ ; the latter is used to make the code more readable and comprehensible.
A good program is one which produces faster and accurate results and should occupy less space in the computer memory. This constraint on the memory space is often termed as memory constraints. The eminent programmers of the world have agreed upon a list of habits which are considered good for programming.
This list contains:
Clarity and Simplicity of Expression: Operators, Operands and Constants constitute to form an expression. To ensure the clarity and simplicity of an expression, following points should be kept in mind :Use library functions to make programs more powerfulFor Example:Find Output = x4
Output = x*x*x*x
We can use output = power (x, 6)
Follow simplicity to maintain the clarity of expressionFor Example:X = (A + B) / (A - B) - (U + VY) / (X + Y)We can simplify it and write as:X1 = (A + B) / (A - B)
X2 = (U + VY) / (X + Y)
X = X1 - X2
Avoid program tricks usage, the meaning of whose is difficult to comprehend by the user.Use of proper names for identifiers: User defined names which are used to name things are called Identifiers. A name associated with any function, constant or variable is used to refer to that particular object. Only letters (A-Z, a-z), underscore character ( _ ) and digits (0-9) can make up a valid identifier. However, digits can not be used to start the name of any identifier.A meaningful name for a data object (variable) and function should be used.To find area of a rectangle
Use the variable names as length and breadth
Area = length * breadth
Meaningful names of constants should be chosen.E = 2.71
Use instead euler_constant = 2.71
Similar names like book, bookkeeper or library, librarian should be avoided.One letter identifiers like a, b, c should be avoided. Instead use more relevant names like age, name, first_name etcComments: To enhance the readability of a program, comments are used. These are used to embed programmer-readable annotations in the original or source code of a program. These comments are profoundly important for the programmer but are simply overlooked by the compilers and interpreters. Comments should be added in the program in simple English language where they denote why a particular function has been used in the program or to specify the reason to use any particular data object or function in the code. Comments are generally categorized into two categories, viz, βBlock Commentsβ and βLine Commentsβ. Line comments are single line comments while block comments are usually multi line comments. The symbols to denote block comments and line comments are different in different languages. However, the symbol for block comments can also be used for line comments. In python for example, Block comments are implemented by βββ and βββ while line comments are implemented by #. Lets take an example:βWrite a program using while loop in python to print a sequence of numbers from 1 to 50.while (n < 50); # While loopprint nn = n + 1Indentation: Indentation is defined as the process of leading white space (tabs and spaces) at the beginning of each statement. It is used to determine the group of a statement. Lets take an example:# Let Anshul and Vivek denote age of two brothersIf Anshul > Vivekprint β Anshul is elder β # Block 1else:print βVivek is elderβ # Block 2In this example, the βifβ block being used is a type of code block. If the βifβ condition evaluates to true, the Block 1 is executed, else (otherwise) Block 2 is executed. Though, the individual blocks can have multiple lines, but itβs conspicuous that a proper indentation makes the visibility of a particular block easier and simpler.
Clarity and Simplicity of Expression: Operators, Operands and Constants constitute to form an expression. To ensure the clarity and simplicity of an expression, following points should be kept in mind :Use library functions to make programs more powerfulFor Example:Find Output = x4
Output = x*x*x*x
We can use output = power (x, 6)
Follow simplicity to maintain the clarity of expressionFor Example:X = (A + B) / (A - B) - (U + VY) / (X + Y)We can simplify it and write as:X1 = (A + B) / (A - B)
X2 = (U + VY) / (X + Y)
X = X1 - X2
Avoid program tricks usage, the meaning of whose is difficult to comprehend by the user.
Use library functions to make programs more powerfulFor Example:Find Output = x4
Output = x*x*x*x
We can use output = power (x, 6)
For Example:
Find Output = x4
Output = x*x*x*x
We can use output = power (x, 6)
Follow simplicity to maintain the clarity of expressionFor Example:X = (A + B) / (A - B) - (U + VY) / (X + Y)We can simplify it and write as:X1 = (A + B) / (A - B)
X2 = (U + VY) / (X + Y)
X = X1 - X2
For Example:
X = (A + B) / (A - B) - (U + VY) / (X + Y)
We can simplify it and write as:
X1 = (A + B) / (A - B)
X2 = (U + VY) / (X + Y)
X = X1 - X2
Avoid program tricks usage, the meaning of whose is difficult to comprehend by the user.
Use of proper names for identifiers: User defined names which are used to name things are called Identifiers. A name associated with any function, constant or variable is used to refer to that particular object. Only letters (A-Z, a-z), underscore character ( _ ) and digits (0-9) can make up a valid identifier. However, digits can not be used to start the name of any identifier.A meaningful name for a data object (variable) and function should be used.To find area of a rectangle
Use the variable names as length and breadth
Area = length * breadth
Meaningful names of constants should be chosen.E = 2.71
Use instead euler_constant = 2.71
Similar names like book, bookkeeper or library, librarian should be avoided.One letter identifiers like a, b, c should be avoided. Instead use more relevant names like age, name, first_name etc
A meaningful name for a data object (variable) and function should be used.To find area of a rectangle
Use the variable names as length and breadth
Area = length * breadth
To find area of a rectangle
Use the variable names as length and breadth
Area = length * breadth
Meaningful names of constants should be chosen.E = 2.71
Use instead euler_constant = 2.71
E = 2.71
Use instead euler_constant = 2.71
Similar names like book, bookkeeper or library, librarian should be avoided.
One letter identifiers like a, b, c should be avoided. Instead use more relevant names like age, name, first_name etc
Comments: To enhance the readability of a program, comments are used. These are used to embed programmer-readable annotations in the original or source code of a program. These comments are profoundly important for the programmer but are simply overlooked by the compilers and interpreters. Comments should be added in the program in simple English language where they denote why a particular function has been used in the program or to specify the reason to use any particular data object or function in the code. Comments are generally categorized into two categories, viz, βBlock Commentsβ and βLine Commentsβ. Line comments are single line comments while block comments are usually multi line comments. The symbols to denote block comments and line comments are different in different languages. However, the symbol for block comments can also be used for line comments. In python for example, Block comments are implemented by βββ and βββ while line comments are implemented by #. Lets take an example:βWrite a program using while loop in python to print a sequence of numbers from 1 to 50.while (n < 50); # While loopprint nn = n + 1
βWrite a program using while loop in python to print a sequence of numbers from 1 to 50.
while (n < 50); # While loop
print n
n = n + 1
Indentation: Indentation is defined as the process of leading white space (tabs and spaces) at the beginning of each statement. It is used to determine the group of a statement. Lets take an example:# Let Anshul and Vivek denote age of two brothersIf Anshul > Vivekprint β Anshul is elder β # Block 1else:print βVivek is elderβ # Block 2In this example, the βifβ block being used is a type of code block. If the βifβ condition evaluates to true, the Block 1 is executed, else (otherwise) Block 2 is executed. Though, the individual blocks can have multiple lines, but itβs conspicuous that a proper indentation makes the visibility of a particular block easier and simpler.
# Let Anshul and Vivek denote age of two brothers
If Anshul > Vivek
print β Anshul is elder β # Block 1
else:
print βVivek is elderβ # Block 2
In this example, the βifβ block being used is a type of code block. If the βifβ condition evaluates to true, the Block 1 is executed, else (otherwise) Block 2 is executed. Though, the individual blocks can have multiple lines, but itβs conspicuous that a proper indentation makes the visibility of a particular block easier and simpler.
Characteristics of Good Programming
What happens, if we bury a seed of mango under the earth. After many years a mango tree will be grown at that place. Well, itβs is a very fundamental thing. The concept of the idea is that βinput determines the outputβ. And this concept applies even in programming. To yield/provide correct and desired output, we need to feed/provide the computer with proper and correct instruction set. The characteristics of a good program are as follows :
Flexibility: It should be possible to accommodate modifications in the program without having the requirement to write the entire code again. The program should be able to serve multiple purposes. For instance, CAD (Computer Aided Design) software can efficiently be used to serve diverse fields like engineering drafting, industrial art, fabric designing, printing circuit layout and designing, architectural drawing etc. Most softwares are developed for a particular period and updations are required to make the software adaptable for serving new purposes as well.
User Friendly: User friendly programs are those programs which can easily be understood by a beginner. The interaction between user and program should be easy to understand. The commands in the program like to input data, to print result, etc. must easily be comprehensible by the naive user.
Portability: The ability of a program to run on different operating systems without having any or minimum changes is termed as the portability of the program or application. With the rise of numerous platforms having different operating systems embedded within them, and with the availability of various hardware and softwares, portability is something which is being taken care of by every application developer these days.Without portability, a program highly usable for one one platform becomes obsolete for another. Program developed in high level languages are generally more portable than programs developed in assembly level languages.
Reliability: Reliability of a program refers to its ability to perform its intended function accurately along with certain modifications. The ability of a program to handle exceptions of wrong input or no input is one of the fundamental behaviors which define reliability. Although, the program is not expected to produce correct result in these exceptions but it should be able enough to provide an error message. A program equipped with such a characteristic is called a reliable program.
Self-Documenting Code: A self-documenting code is the source code, in which suitable names for the identifiers are being used. Proper names for the identifiers makes it easier for the user to understand the functionality of a particular variable or consonant (identifier). Hence, it is advisable that every good program must have a self-documenting code.
Modular Approach to Programming
Often there are very long codes in the practical world. These codes are written to perform various functions or tasks. Now, an efficient program or code is one where the lengthy code is being divided into different sections/modules. This process of dividing a long code into different sub codes is called modular approach to programming. These different modules are often termed as functions in a program.
Take for an Example:
Let the code below represents a program to evaluate percentage of a student in 10th class exam.
Input marks of first subject
Input marks of second subject
Input marks of third subject
Input marks of fourth subject
Input marks of fifth subject
Add marks of all subject
Multiply the total marks by 100
Divide the above result by 5
Output the result as percentage of the student.
Now, the above program is a brief illustration of how a lengthy program can be even more difficult to operate with. Now, as per the modular approach, the above program looks like:
Input marks
Get total marks
Evaluate percentage
Output result
Input Marks # Module 1{ Input marks of first subject Input marks of second subject Input marks of third subject Input marks of fourth subject Input marks of fifth subject } Get total marks # Module 2{ Add marks of all subject} Evaluate Percentage # Module 3{ Multiply the total marks by 100 Divide the above result by 5} Output result # Module 4{ Output the result as percentage of the student.}
This is called a modular approach to programming and should be followed with long programs.
Documentation and Program Maintenance
In the modular approach of programming we saw that different modules help to deal with the program in an efficient way. In the pragmatic world, where the codes are longer than usual, different modules of a same program are developed by different departments of the organization. These modules are thus required to be properly documented and maintained so that each department can use them efficiently. This procedure is called documentation and maintenance of a program.
Guidelines for a good document are as follows:
Documentation should be done from the readerβs perspective.It should not be ambiguous.Repetition of documents should be avoided.While preparing the document, industrial standards should be followed.Regular updation of documents should be done.Outdated documents should either be removed or updated.Merits of DocumentationHelps to track the complete program in a modular way.Easier maintenanceEnhances quality of the softwareCode becomes comprehensible to developer and others as well.Makes user β training easierIf the first developer leaves the job in between then the new developer can easily get acquainted with the ongoing work.Types of DocumentsUser manual: It is like a βHow to useβ guide for the end users.Operational Manual: It contains all the operations and their inter dependencies which are being used in the program.Design Document: It enlists all the design aspects of the program and contains diagrams like data flow, entity relationships etc.Requirement Document: It enlists the requirements to run the software efficiently.Technical Document: Components like program codes, algorithms, functional modules etc. are listed in this document.List of Known Bugs Document: In this document those bugs or errors are listed which were discovered later and thus couldnβt be removed from the software.
Documentation should be done from the readerβs perspective.It should not be ambiguous.Repetition of documents should be avoided.While preparing the document, industrial standards should be followed.Regular updation of documents should be done.Outdated documents should either be removed or updated.
It should not be ambiguous.
Repetition of documents should be avoided.
While preparing the document, industrial standards should be followed.
Regular updation of documents should be done.
Outdated documents should either be removed or updated.
Merits of DocumentationHelps to track the complete program in a modular way.Easier maintenanceEnhances quality of the softwareCode becomes comprehensible to developer and others as well.Makes user β training easierIf the first developer leaves the job in between then the new developer can easily get acquainted with the ongoing work.
Helps to track the complete program in a modular way.
Easier maintenance
Enhances quality of the software
Code becomes comprehensible to developer and others as well.
Makes user β training easier
If the first developer leaves the job in between then the new developer can easily get acquainted with the ongoing work.
Types of DocumentsUser manual: It is like a βHow to useβ guide for the end users.Operational Manual: It contains all the operations and their inter dependencies which are being used in the program.Design Document: It enlists all the design aspects of the program and contains diagrams like data flow, entity relationships etc.Requirement Document: It enlists the requirements to run the software efficiently.Technical Document: Components like program codes, algorithms, functional modules etc. are listed in this document.List of Known Bugs Document: In this document those bugs or errors are listed which were discovered later and thus couldnβt be removed from the software.
User manual: It is like a βHow to useβ guide for the end users.
Operational Manual: It contains all the operations and their inter dependencies which are being used in the program.
Design Document: It enlists all the design aspects of the program and contains diagrams like data flow, entity relationships etc.
Requirement Document: It enlists the requirements to run the software efficiently.
Technical Document: Components like program codes, algorithms, functional modules etc. are listed in this document.
List of Known Bugs Document: In this document those bugs or errors are listed which were discovered later and thus couldnβt be removed from the software.
Errors and their types
Errors are unwanted aberration that occur in a program because of illegal operation performed by the developer or user of the program. Errors are also termed as βbugβ in programming language. They are not detected until the program is compiled or executed. The common types or errors are as follows:
Syntax Errors: Syntax errors or compile time errors are errors which occur when the proper writing rules of a particular language are not followed. Each language has a set of instructions which has to be followed while writing a code in that particular language. These errors are called syntax errors. Since these errors are detected by compiler at the time of compilation, thus these are also called compile time errors.Example:a = int(input('Enter a number: '))
whille a%3 == 0:
print('The number is divisible by 3.')
else:
print ('The number is not divisible by 3.')
Notice that the βwhileβ keyword in above code is not spelled correctly. These type of errors are called Syntax errors.
Example:
a = int(input('Enter a number: '))
whille a%3 == 0:
print('The number is divisible by 3.')
else:
print ('The number is not divisible by 3.')
Notice that the βwhileβ keyword in above code is not spelled correctly. These type of errors are called Syntax errors.
Run Time Errors: These are errors which occur while the program is being executed, hence also called execution time errors. These errors result in abrupt completion of the program or the program may also enter an endless loop.Example:a = int(input('Enter a number: '))
b = 0
whille a%b == 0:
print('The first number is a multiple of second number.')
else:
print ('The first number is not a multiple of second number.')
Notice that the second number is by default set to zero. Now a number divided by zero results in infinity which is not known. Such errors are called runtime errors.
Example:
a = int(input('Enter a number: '))
b = 0
whille a%b == 0:
print('The first number is a multiple of second number.')
else:
print ('The first number is not a multiple of second number.')
Notice that the second number is by default set to zero. Now a number divided by zero results in infinity which is not known. Such errors are called runtime errors.
Logical Errors: These errors as self explanatory by its name, occur due to the implementation of incorrect logic by the developer of the program. These errors are not detected while compiling or executing the program.Example:x = float(input('Enter a number: '))
y = float(input('Enter a number: '))
z = x + y / 2
print ('The average of the two numbers you have entered is:', z)
Now, as per the desired goal, the above program is expected to give the average of two numbers x and y. But it doesnβt produces the desired result. Because firstly, y is being divided by 2 and the result is then added to x. Thus incorrect logic is there. As per the correct logic, the developer should have written :z = ( x + y ) / 2These types of errors are called logical errors or semantic errors.
Example:
x = float(input('Enter a number: '))
y = float(input('Enter a number: '))
z = x + y / 2
print ('The average of the two numbers you have entered is:', z)
Now, as per the desired goal, the above program is expected to give the average of two numbers x and y. But it doesnβt produces the desired result. Because firstly, y is being divided by 2 and the result is then added to x. Thus incorrect logic is there. As per the correct logic, the developer should have written :
z = ( x + y ) / 2
These types of errors are called logical errors or semantic errors.
CBSE - Class 11
Programming Basics
school-programming
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Constructors in C++
Operator Overloading in C++
Copy Constructor in C++
C++ Data Types
Types of Operating Systems
Introduction To PYTHON
Exceptions in Java
Overriding in Java
Constructors in Java
|
[
{
"code": null,
"e": 25451,
"s": 25423,
"text": "\n22 Aug, 2018"
},
{
"code": null,
"e": 26167,
"s": 25451,
"text": "Programming is all about solving a particular problem through computerized codes. Whether it be a problem of inventory management at any shopping complex, marks evaluation of OMR sheets, running of a remote car, or even running of a missile. Thus the scope of programming ranges from very simpleton tasks to extremely complicated ones. But behind all the codes, one parameter is common, that is, to handle and solve the problem efficiently. As one canβt learn to fly an aeroplane simply by watching it flying, one has to actually learn it. Similarly to become a proficient coder, one has to actually do the codes. And, the task of coding is extremely easy once one learns how to apply the logic for problem solving."
},
{
"code": null,
"e": 26321,
"s": 26167,
"text": "Computer Programming comprises of the fundamental entities which are writing, testing, troubleshooting, debugging, and maintaining of a computer program."
},
{
"code": null,
"e": 27016,
"s": 26321,
"text": "Writing involves writing down on a paper what is the desired output of the code. This can easily be done by drawing a flowchart which depicts all the steps involved from starting to end. Then writing also involves writing the first copy of the course actually onto the corresponding software. Then the written code has to be tested.Once tested, if there are some errors, then those errors has to be removed. This process is called troubleshooting.To determine the exact location of the error in the code is executed through a process called debugging.After successful completion of all these steps, the program is being executed to obtain the desired result. This is called running the program."
},
{
"code": null,
"e": 27349,
"s": 27016,
"text": "Writing involves writing down on a paper what is the desired output of the code. This can easily be done by drawing a flowchart which depicts all the steps involved from starting to end. Then writing also involves writing the first copy of the course actually onto the corresponding software. Then the written code has to be tested."
},
{
"code": null,
"e": 27465,
"s": 27349,
"text": "Once tested, if there are some errors, then those errors has to be removed. This process is called troubleshooting."
},
{
"code": null,
"e": 27570,
"s": 27465,
"text": "To determine the exact location of the error in the code is executed through a process called debugging."
},
{
"code": null,
"e": 27714,
"s": 27570,
"text": "After successful completion of all these steps, the program is being executed to obtain the desired result. This is called running the program."
},
{
"code": null,
"e": 28154,
"s": 27714,
"text": "A program is called an efficient program only if it gives correct output corresponding to every input, including the wrong input. The systematic approach to write such an efficient article involves two steps:a) Program Structure and b) Program Representation. While the former is implemented by using bottom-up or top-down approach and is termed as βpopular approachβ ; the latter is used to make the code more readable and comprehensible."
},
{
"code": null,
"e": 28461,
"s": 28154,
"text": "A good program is one which produces faster and accurate results and should occupy less space in the computer memory. This constraint on the memory space is often termed as memory constraints. The eminent programmers of the world have agreed upon a list of habits which are considered good for programming."
},
{
"code": null,
"e": 28481,
"s": 28461,
"text": "This list contains:"
},
{
"code": null,
"e": 31758,
"s": 28481,
"text": "Clarity and Simplicity of Expression: Operators, Operands and Constants constitute to form an expression. To ensure the clarity and simplicity of an expression, following points should be kept in mind :Use library functions to make programs more powerfulFor Example:Find Output = x4\n\nOutput = x*x*x*x\n\nWe can use output = power (x, 6)\nFollow simplicity to maintain the clarity of expressionFor Example:X = (A + B) / (A - B) - (U + VY) / (X + Y)We can simplify it and write as:X1 = (A + B) / (A - B)\n\nX2 = (U + VY) / (X + Y)\n\nX = X1 - X2\nAvoid program tricks usage, the meaning of whose is difficult to comprehend by the user.Use of proper names for identifiers: User defined names which are used to name things are called Identifiers. A name associated with any function, constant or variable is used to refer to that particular object. Only letters (A-Z, a-z), underscore character ( _ ) and digits (0-9) can make up a valid identifier. However, digits can not be used to start the name of any identifier.A meaningful name for a data object (variable) and function should be used.To find area of a rectangle\n\nUse the variable names as length and breadth\n\nArea = length * breadth\nMeaningful names of constants should be chosen.E = 2.71\n\nUse instead euler_constant = 2.71\nSimilar names like book, bookkeeper or library, librarian should be avoided.One letter identifiers like a, b, c should be avoided. Instead use more relevant names like age, name, first_name etcComments: To enhance the readability of a program, comments are used. These are used to embed programmer-readable annotations in the original or source code of a program. These comments are profoundly important for the programmer but are simply overlooked by the compilers and interpreters. Comments should be added in the program in simple English language where they denote why a particular function has been used in the program or to specify the reason to use any particular data object or function in the code. Comments are generally categorized into two categories, viz, βBlock Commentsβ and βLine Commentsβ. Line comments are single line comments while block comments are usually multi line comments. The symbols to denote block comments and line comments are different in different languages. However, the symbol for block comments can also be used for line comments. In python for example, Block comments are implemented by βββ and βββ while line comments are implemented by #. Lets take an example:βWrite a program using while loop in python to print a sequence of numbers from 1 to 50.while (n < 50); # While loopprint nn = n + 1Indentation: Indentation is defined as the process of leading white space (tabs and spaces) at the beginning of each statement. It is used to determine the group of a statement. Lets take an example:# Let Anshul and Vivek denote age of two brothersIf Anshul > Vivekprint β Anshul is elder β # Block 1else:print βVivek is elderβ # Block 2In this example, the βifβ block being used is a type of code block. If the βifβ condition evaluates to true, the Block 1 is executed, else (otherwise) Block 2 is executed. Though, the individual blocks can have multiple lines, but itβs conspicuous that a proper indentation makes the visibility of a particular block easier and simpler."
},
{
"code": null,
"e": 32384,
"s": 31758,
"text": "Clarity and Simplicity of Expression: Operators, Operands and Constants constitute to form an expression. To ensure the clarity and simplicity of an expression, following points should be kept in mind :Use library functions to make programs more powerfulFor Example:Find Output = x4\n\nOutput = x*x*x*x\n\nWe can use output = power (x, 6)\nFollow simplicity to maintain the clarity of expressionFor Example:X = (A + B) / (A - B) - (U + VY) / (X + Y)We can simplify it and write as:X1 = (A + B) / (A - B)\n\nX2 = (U + VY) / (X + Y)\n\nX = X1 - X2\nAvoid program tricks usage, the meaning of whose is difficult to comprehend by the user."
},
{
"code": null,
"e": 32518,
"s": 32384,
"text": "Use library functions to make programs more powerfulFor Example:Find Output = x4\n\nOutput = x*x*x*x\n\nWe can use output = power (x, 6)\n"
},
{
"code": null,
"e": 32531,
"s": 32518,
"text": "For Example:"
},
{
"code": null,
"e": 32601,
"s": 32531,
"text": "Find Output = x4\n\nOutput = x*x*x*x\n\nWe can use output = power (x, 6)\n"
},
{
"code": null,
"e": 32804,
"s": 32601,
"text": "Follow simplicity to maintain the clarity of expressionFor Example:X = (A + B) / (A - B) - (U + VY) / (X + Y)We can simplify it and write as:X1 = (A + B) / (A - B)\n\nX2 = (U + VY) / (X + Y)\n\nX = X1 - X2\n"
},
{
"code": null,
"e": 32817,
"s": 32804,
"text": "For Example:"
},
{
"code": null,
"e": 32860,
"s": 32817,
"text": "X = (A + B) / (A - B) - (U + VY) / (X + Y)"
},
{
"code": null,
"e": 32893,
"s": 32860,
"text": "We can simplify it and write as:"
},
{
"code": null,
"e": 32955,
"s": 32893,
"text": "X1 = (A + B) / (A - B)\n\nX2 = (U + VY) / (X + Y)\n\nX = X1 - X2\n"
},
{
"code": null,
"e": 33044,
"s": 32955,
"text": "Avoid program tricks usage, the meaning of whose is difficult to comprehend by the user."
},
{
"code": null,
"e": 33884,
"s": 33044,
"text": "Use of proper names for identifiers: User defined names which are used to name things are called Identifiers. A name associated with any function, constant or variable is used to refer to that particular object. Only letters (A-Z, a-z), underscore character ( _ ) and digits (0-9) can make up a valid identifier. However, digits can not be used to start the name of any identifier.A meaningful name for a data object (variable) and function should be used.To find area of a rectangle\n\nUse the variable names as length and breadth\n\nArea = length * breadth\nMeaningful names of constants should be chosen.E = 2.71\n\nUse instead euler_constant = 2.71\nSimilar names like book, bookkeeper or library, librarian should be avoided.One letter identifiers like a, b, c should be avoided. Instead use more relevant names like age, name, first_name etc"
},
{
"code": null,
"e": 34059,
"s": 33884,
"text": "A meaningful name for a data object (variable) and function should be used.To find area of a rectangle\n\nUse the variable names as length and breadth\n\nArea = length * breadth\n"
},
{
"code": null,
"e": 34159,
"s": 34059,
"text": "To find area of a rectangle\n\nUse the variable names as length and breadth\n\nArea = length * breadth\n"
},
{
"code": null,
"e": 34251,
"s": 34159,
"text": "Meaningful names of constants should be chosen.E = 2.71\n\nUse instead euler_constant = 2.71\n"
},
{
"code": null,
"e": 34296,
"s": 34251,
"text": "E = 2.71\n\nUse instead euler_constant = 2.71\n"
},
{
"code": null,
"e": 34373,
"s": 34296,
"text": "Similar names like book, bookkeeper or library, librarian should be avoided."
},
{
"code": null,
"e": 34491,
"s": 34373,
"text": "One letter identifiers like a, b, c should be avoided. Instead use more relevant names like age, name, first_name etc"
},
{
"code": null,
"e": 35631,
"s": 34491,
"text": "Comments: To enhance the readability of a program, comments are used. These are used to embed programmer-readable annotations in the original or source code of a program. These comments are profoundly important for the programmer but are simply overlooked by the compilers and interpreters. Comments should be added in the program in simple English language where they denote why a particular function has been used in the program or to specify the reason to use any particular data object or function in the code. Comments are generally categorized into two categories, viz, βBlock Commentsβ and βLine Commentsβ. Line comments are single line comments while block comments are usually multi line comments. The symbols to denote block comments and line comments are different in different languages. However, the symbol for block comments can also be used for line comments. In python for example, Block comments are implemented by βββ and βββ while line comments are implemented by #. Lets take an example:βWrite a program using while loop in python to print a sequence of numbers from 1 to 50.while (n < 50); # While loopprint nn = n + 1"
},
{
"code": null,
"e": 35720,
"s": 35631,
"text": "βWrite a program using while loop in python to print a sequence of numbers from 1 to 50."
},
{
"code": null,
"e": 35749,
"s": 35720,
"text": "while (n < 50); # While loop"
},
{
"code": null,
"e": 35757,
"s": 35749,
"text": "print n"
},
{
"code": null,
"e": 35767,
"s": 35757,
"text": "n = n + 1"
},
{
"code": null,
"e": 36441,
"s": 35767,
"text": "Indentation: Indentation is defined as the process of leading white space (tabs and spaces) at the beginning of each statement. It is used to determine the group of a statement. Lets take an example:# Let Anshul and Vivek denote age of two brothersIf Anshul > Vivekprint β Anshul is elder β # Block 1else:print βVivek is elderβ # Block 2In this example, the βifβ block being used is a type of code block. If the βifβ condition evaluates to true, the Block 1 is executed, else (otherwise) Block 2 is executed. Though, the individual blocks can have multiple lines, but itβs conspicuous that a proper indentation makes the visibility of a particular block easier and simpler."
},
{
"code": null,
"e": 36491,
"s": 36441,
"text": "# Let Anshul and Vivek denote age of two brothers"
},
{
"code": null,
"e": 36509,
"s": 36491,
"text": "If Anshul > Vivek"
},
{
"code": null,
"e": 36545,
"s": 36509,
"text": "print β Anshul is elder β # Block 1"
},
{
"code": null,
"e": 36551,
"s": 36545,
"text": "else:"
},
{
"code": null,
"e": 36584,
"s": 36551,
"text": "print βVivek is elderβ # Block 2"
},
{
"code": null,
"e": 36921,
"s": 36584,
"text": "In this example, the βifβ block being used is a type of code block. If the βifβ condition evaluates to true, the Block 1 is executed, else (otherwise) Block 2 is executed. Though, the individual blocks can have multiple lines, but itβs conspicuous that a proper indentation makes the visibility of a particular block easier and simpler."
},
{
"code": null,
"e": 36957,
"s": 36921,
"text": "Characteristics of Good Programming"
},
{
"code": null,
"e": 37401,
"s": 36957,
"text": "What happens, if we bury a seed of mango under the earth. After many years a mango tree will be grown at that place. Well, itβs is a very fundamental thing. The concept of the idea is that βinput determines the outputβ. And this concept applies even in programming. To yield/provide correct and desired output, we need to feed/provide the computer with proper and correct instruction set. The characteristics of a good program are as follows :"
},
{
"code": null,
"e": 37969,
"s": 37401,
"text": "Flexibility: It should be possible to accommodate modifications in the program without having the requirement to write the entire code again. The program should be able to serve multiple purposes. For instance, CAD (Computer Aided Design) software can efficiently be used to serve diverse fields like engineering drafting, industrial art, fabric designing, printing circuit layout and designing, architectural drawing etc. Most softwares are developed for a particular period and updations are required to make the software adaptable for serving new purposes as well."
},
{
"code": null,
"e": 38262,
"s": 37969,
"text": "User Friendly: User friendly programs are those programs which can easily be understood by a beginner. The interaction between user and program should be easy to understand. The commands in the program like to input data, to print result, etc. must easily be comprehensible by the naive user."
},
{
"code": null,
"e": 38905,
"s": 38262,
"text": "Portability: The ability of a program to run on different operating systems without having any or minimum changes is termed as the portability of the program or application. With the rise of numerous platforms having different operating systems embedded within them, and with the availability of various hardware and softwares, portability is something which is being taken care of by every application developer these days.Without portability, a program highly usable for one one platform becomes obsolete for another. Program developed in high level languages are generally more portable than programs developed in assembly level languages."
},
{
"code": null,
"e": 39396,
"s": 38905,
"text": "Reliability: Reliability of a program refers to its ability to perform its intended function accurately along with certain modifications. The ability of a program to handle exceptions of wrong input or no input is one of the fundamental behaviors which define reliability. Although, the program is not expected to produce correct result in these exceptions but it should be able enough to provide an error message. A program equipped with such a characteristic is called a reliable program."
},
{
"code": null,
"e": 39751,
"s": 39396,
"text": "Self-Documenting Code: A self-documenting code is the source code, in which suitable names for the identifiers are being used. Proper names for the identifiers makes it easier for the user to understand the functionality of a particular variable or consonant (identifier). Hence, it is advisable that every good program must have a self-documenting code."
},
{
"code": null,
"e": 39783,
"s": 39751,
"text": "Modular Approach to Programming"
},
{
"code": null,
"e": 40189,
"s": 39783,
"text": "Often there are very long codes in the practical world. These codes are written to perform various functions or tasks. Now, an efficient program or code is one where the lengthy code is being divided into different sections/modules. This process of dividing a long code into different sub codes is called modular approach to programming. These different modules are often termed as functions in a program."
},
{
"code": null,
"e": 40210,
"s": 40189,
"text": "Take for an Example:"
},
{
"code": null,
"e": 40306,
"s": 40210,
"text": "Let the code below represents a program to evaluate percentage of a student in 10th class exam."
},
{
"code": null,
"e": 40596,
"s": 40306,
"text": "Input marks of first subject\n\nInput marks of second subject\n\nInput marks of third subject\n\nInput marks of fourth subject\n\nInput marks of fifth subject\n\nAdd marks of all subject\n\nMultiply the total marks by 100\n\nDivide the above result by 5\n\nOutput the result as percentage of the student.\n"
},
{
"code": null,
"e": 40776,
"s": 40596,
"text": "Now, the above program is a brief illustration of how a lengthy program can be even more difficult to operate with. Now, as per the modular approach, the above program looks like:"
},
{
"code": null,
"e": 40842,
"s": 40776,
"text": "Input marks\n\nGet total marks\n\nEvaluate percentage\n\nOutput result\n"
},
{
"code": "Input Marks # Module 1{ Input marks of first subject Input marks of second subject Input marks of third subject Input marks of fourth subject Input marks of fifth subject } Get total marks # Module 2{ Add marks of all subject} Evaluate Percentage # Module 3{ Multiply the total marks by 100 Divide the above result by 5} Output result # Module 4{ Output the result as percentage of the student.}",
"e": 41323,
"s": 40842,
"text": null
},
{
"code": null,
"e": 41415,
"s": 41323,
"text": "This is called a modular approach to programming and should be followed with long programs."
},
{
"code": null,
"e": 41453,
"s": 41415,
"text": "Documentation and Program Maintenance"
},
{
"code": null,
"e": 41924,
"s": 41453,
"text": "In the modular approach of programming we saw that different modules help to deal with the program in an efficient way. In the pragmatic world, where the codes are longer than usual, different modules of a same program are developed by different departments of the organization. These modules are thus required to be properly documented and maintained so that each department can use them efficiently. This procedure is called documentation and maintenance of a program."
},
{
"code": null,
"e": 41971,
"s": 41924,
"text": "Guidelines for a good document are as follows:"
},
{
"code": null,
"e": 43280,
"s": 41971,
"text": "Documentation should be done from the readerβs perspective.It should not be ambiguous.Repetition of documents should be avoided.While preparing the document, industrial standards should be followed.Regular updation of documents should be done.Outdated documents should either be removed or updated.Merits of DocumentationHelps to track the complete program in a modular way.Easier maintenanceEnhances quality of the softwareCode becomes comprehensible to developer and others as well.Makes user β training easierIf the first developer leaves the job in between then the new developer can easily get acquainted with the ongoing work.Types of DocumentsUser manual: It is like a βHow to useβ guide for the end users.Operational Manual: It contains all the operations and their inter dependencies which are being used in the program.Design Document: It enlists all the design aspects of the program and contains diagrams like data flow, entity relationships etc.Requirement Document: It enlists the requirements to run the software efficiently.Technical Document: Components like program codes, algorithms, functional modules etc. are listed in this document.List of Known Bugs Document: In this document those bugs or errors are listed which were discovered later and thus couldnβt be removed from the software."
},
{
"code": null,
"e": 43579,
"s": 43280,
"text": "Documentation should be done from the readerβs perspective.It should not be ambiguous.Repetition of documents should be avoided.While preparing the document, industrial standards should be followed.Regular updation of documents should be done.Outdated documents should either be removed or updated."
},
{
"code": null,
"e": 43607,
"s": 43579,
"text": "It should not be ambiguous."
},
{
"code": null,
"e": 43650,
"s": 43607,
"text": "Repetition of documents should be avoided."
},
{
"code": null,
"e": 43721,
"s": 43650,
"text": "While preparing the document, industrial standards should be followed."
},
{
"code": null,
"e": 43767,
"s": 43721,
"text": "Regular updation of documents should be done."
},
{
"code": null,
"e": 43823,
"s": 43767,
"text": "Outdated documents should either be removed or updated."
},
{
"code": null,
"e": 44158,
"s": 43823,
"text": "Merits of DocumentationHelps to track the complete program in a modular way.Easier maintenanceEnhances quality of the softwareCode becomes comprehensible to developer and others as well.Makes user β training easierIf the first developer leaves the job in between then the new developer can easily get acquainted with the ongoing work."
},
{
"code": null,
"e": 44212,
"s": 44158,
"text": "Helps to track the complete program in a modular way."
},
{
"code": null,
"e": 44231,
"s": 44212,
"text": "Easier maintenance"
},
{
"code": null,
"e": 44264,
"s": 44231,
"text": "Enhances quality of the software"
},
{
"code": null,
"e": 44325,
"s": 44264,
"text": "Code becomes comprehensible to developer and others as well."
},
{
"code": null,
"e": 44354,
"s": 44325,
"text": "Makes user β training easier"
},
{
"code": null,
"e": 44475,
"s": 44354,
"text": "If the first developer leaves the job in between then the new developer can easily get acquainted with the ongoing work."
},
{
"code": null,
"e": 45152,
"s": 44475,
"text": "Types of DocumentsUser manual: It is like a βHow to useβ guide for the end users.Operational Manual: It contains all the operations and their inter dependencies which are being used in the program.Design Document: It enlists all the design aspects of the program and contains diagrams like data flow, entity relationships etc.Requirement Document: It enlists the requirements to run the software efficiently.Technical Document: Components like program codes, algorithms, functional modules etc. are listed in this document.List of Known Bugs Document: In this document those bugs or errors are listed which were discovered later and thus couldnβt be removed from the software."
},
{
"code": null,
"e": 45216,
"s": 45152,
"text": "User manual: It is like a βHow to useβ guide for the end users."
},
{
"code": null,
"e": 45333,
"s": 45216,
"text": "Operational Manual: It contains all the operations and their inter dependencies which are being used in the program."
},
{
"code": null,
"e": 45463,
"s": 45333,
"text": "Design Document: It enlists all the design aspects of the program and contains diagrams like data flow, entity relationships etc."
},
{
"code": null,
"e": 45546,
"s": 45463,
"text": "Requirement Document: It enlists the requirements to run the software efficiently."
},
{
"code": null,
"e": 45662,
"s": 45546,
"text": "Technical Document: Components like program codes, algorithms, functional modules etc. are listed in this document."
},
{
"code": null,
"e": 45816,
"s": 45662,
"text": "List of Known Bugs Document: In this document those bugs or errors are listed which were discovered later and thus couldnβt be removed from the software."
},
{
"code": null,
"e": 45839,
"s": 45816,
"text": "Errors and their types"
},
{
"code": null,
"e": 46139,
"s": 45839,
"text": "Errors are unwanted aberration that occur in a program because of illegal operation performed by the developer or user of the program. Errors are also termed as βbugβ in programming language. They are not detected until the program is compiled or executed. The common types or errors are as follows:"
},
{
"code": null,
"e": 46837,
"s": 46139,
"text": "Syntax Errors: Syntax errors or compile time errors are errors which occur when the proper writing rules of a particular language are not followed. Each language has a set of instructions which has to be followed while writing a code in that particular language. These errors are called syntax errors. Since these errors are detected by compiler at the time of compilation, thus these are also called compile time errors.Example:a = int(input('Enter a number: '))\n\nwhille a%3 == 0:\n print('The number is divisible by 3.')\nelse:\n print ('The number is not divisible by 3.')\nNotice that the βwhileβ keyword in above code is not spelled correctly. These type of errors are called Syntax errors."
},
{
"code": null,
"e": 46846,
"s": 46837,
"text": "Example:"
},
{
"code": null,
"e": 46997,
"s": 46846,
"text": "a = int(input('Enter a number: '))\n\nwhille a%3 == 0:\n print('The number is divisible by 3.')\nelse:\n print ('The number is not divisible by 3.')\n"
},
{
"code": null,
"e": 47116,
"s": 46997,
"text": "Notice that the βwhileβ keyword in above code is not spelled correctly. These type of errors are called Syntax errors."
},
{
"code": null,
"e": 47709,
"s": 47116,
"text": "Run Time Errors: These are errors which occur while the program is being executed, hence also called execution time errors. These errors result in abrupt completion of the program or the program may also enter an endless loop.Example:a = int(input('Enter a number: '))\nb = 0\nwhille a%b == 0:\n print('The first number is a multiple of second number.')\nelse:\n print ('The first number is not a multiple of second number.')\nNotice that the second number is by default set to zero. Now a number divided by zero results in infinity which is not known. Such errors are called runtime errors."
},
{
"code": null,
"e": 47718,
"s": 47709,
"text": "Example:"
},
{
"code": null,
"e": 47913,
"s": 47718,
"text": "a = int(input('Enter a number: '))\nb = 0\nwhille a%b == 0:\n print('The first number is a multiple of second number.')\nelse:\n print ('The first number is not a multiple of second number.')\n"
},
{
"code": null,
"e": 48078,
"s": 47913,
"text": "Notice that the second number is by default set to zero. Now a number divided by zero results in infinity which is not known. Such errors are called runtime errors."
},
{
"code": null,
"e": 48858,
"s": 48078,
"text": "Logical Errors: These errors as self explanatory by its name, occur due to the implementation of incorrect logic by the developer of the program. These errors are not detected while compiling or executing the program.Example:x = float(input('Enter a number: '))\ny = float(input('Enter a number: '))\n\nz = x + y / 2\nprint ('The average of the two numbers you have entered is:', z)\nNow, as per the desired goal, the above program is expected to give the average of two numbers x and y. But it doesnβt produces the desired result. Because firstly, y is being divided by 2 and the result is then added to x. Thus incorrect logic is there. As per the correct logic, the developer should have written :z = ( x + y ) / 2These types of errors are called logical errors or semantic errors."
},
{
"code": null,
"e": 48867,
"s": 48858,
"text": "Example:"
},
{
"code": null,
"e": 49022,
"s": 48867,
"text": "x = float(input('Enter a number: '))\ny = float(input('Enter a number: '))\n\nz = x + y / 2\nprint ('The average of the two numbers you have entered is:', z)\n"
},
{
"code": null,
"e": 49339,
"s": 49022,
"text": "Now, as per the desired goal, the above program is expected to give the average of two numbers x and y. But it doesnβt produces the desired result. Because firstly, y is being divided by 2 and the result is then added to x. Thus incorrect logic is there. As per the correct logic, the developer should have written :"
},
{
"code": null,
"e": 49357,
"s": 49339,
"text": "z = ( x + y ) / 2"
},
{
"code": null,
"e": 49425,
"s": 49357,
"text": "These types of errors are called logical errors or semantic errors."
},
{
"code": null,
"e": 49441,
"s": 49425,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 49460,
"s": 49441,
"text": "Programming Basics"
},
{
"code": null,
"e": 49479,
"s": 49460,
"text": "school-programming"
},
{
"code": null,
"e": 49498,
"s": 49479,
"text": "School Programming"
},
{
"code": null,
"e": 49596,
"s": 49498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49615,
"s": 49596,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 49635,
"s": 49615,
"text": "Constructors in C++"
},
{
"code": null,
"e": 49663,
"s": 49635,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 49687,
"s": 49663,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 49702,
"s": 49687,
"text": "C++ Data Types"
},
{
"code": null,
"e": 49729,
"s": 49702,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 49752,
"s": 49729,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 49771,
"s": 49752,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 49790,
"s": 49771,
"text": "Overriding in Java"
}
] |
How to create a SnackBar service?
|
14 May, 2020
MatSnackBar is an angular directive thatβs used for showing a notification bar specifically on the mobile devices.These types of UI components are generally used several times.So to avoid the repetition of code, a service can simply be created to use SnackBar in different components.
Approach:
To create a service you have to use the following command:ng g s snackBar
ng g s snackBar
Now import MatSnackBar from @angular/core and define the function openSnackBar (you can always use a different name).import { Injectable } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root'})export class SnackBarService { //create an instance of MatSnackBar constructor(private snackBar:MatSnackBar) { } /* It takes three parameters 1.the message string 2.the action 3.the duration, alignment, etc. */ openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); }}
import { Injectable } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root'})export class SnackBarService { //create an instance of MatSnackBar constructor(private snackBar:MatSnackBar) { } /* It takes three parameters 1.the message string 2.the action 3.the duration, alignment, etc. */ openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); }}
Import the snackBarService and inject it inside the constructor of the component, in which you want to use the Snackbar. This will create an instance of the service say snackBService.Now call the openSnackBar function wherever it is required, with the help of snackBService.import { Component, OnInit } from '@angular/core';import {SnackBarService} from '../snack.service'; @Component({ selector: 'app-profile', templateUrl: './snackBar.html', styleUrls: ['./snackBar.css']})export class SnackBar { // create an instance of SnackBarService constructor(private snackBService:SnackBarService) { } //defining method for display of SnackBar trigger(message:string, action:string) { this.snackBService.openSnackBar(message, action); } }
import { Component, OnInit } from '@angular/core';import {SnackBarService} from '../snack.service'; @Component({ selector: 'app-profile', templateUrl: './snackBar.html', styleUrls: ['./snackBar.css']})export class SnackBar { // create an instance of SnackBarService constructor(private snackBService:SnackBarService) { } //defining method for display of SnackBar trigger(message:string, action:string) { this.snackBService.openSnackBar(message, action); } }
By repeating these steps we can use the snackBar inside any component.Example:<button (click)="trigger('This is a ', 'SnackBar')"> SnackBarButton</button>
<button (click)="trigger('This is a ', 'SnackBar')"> SnackBarButton</button>
Output:
AngularJS-Misc
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 337,
"s": 52,
"text": "MatSnackBar is an angular directive thatβs used for showing a notification bar specifically on the mobile devices.These types of UI components are generally used several times.So to avoid the repetition of code, a service can simply be created to use SnackBar in different components."
},
{
"code": null,
"e": 347,
"s": 337,
"text": "Approach:"
},
{
"code": null,
"e": 421,
"s": 347,
"text": "To create a service you have to use the following command:ng g s snackBar"
},
{
"code": null,
"e": 437,
"s": 421,
"text": "ng g s snackBar"
},
{
"code": null,
"e": 1043,
"s": 437,
"text": "Now import MatSnackBar from @angular/core and define the function openSnackBar (you can always use a different name).import { Injectable } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root'})export class SnackBarService { //create an instance of MatSnackBar constructor(private snackBar:MatSnackBar) { } /* It takes three parameters 1.the message string 2.the action 3.the duration, alignment, etc. */ openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); }}"
},
{
"code": "import { Injectable } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root'})export class SnackBarService { //create an instance of MatSnackBar constructor(private snackBar:MatSnackBar) { } /* It takes three parameters 1.the message string 2.the action 3.the duration, alignment, etc. */ openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); }}",
"e": 1532,
"s": 1043,
"text": null
},
{
"code": null,
"e": 2288,
"s": 1532,
"text": "Import the snackBarService and inject it inside the constructor of the component, in which you want to use the Snackbar. This will create an instance of the service say snackBService.Now call the openSnackBar function wherever it is required, with the help of snackBService.import { Component, OnInit } from '@angular/core';import {SnackBarService} from '../snack.service'; @Component({ selector: 'app-profile', templateUrl: './snackBar.html', styleUrls: ['./snackBar.css']})export class SnackBar { // create an instance of SnackBarService constructor(private snackBService:SnackBarService) { } //defining method for display of SnackBar trigger(message:string, action:string) { this.snackBService.openSnackBar(message, action); } }"
},
{
"code": "import { Component, OnInit } from '@angular/core';import {SnackBarService} from '../snack.service'; @Component({ selector: 'app-profile', templateUrl: './snackBar.html', styleUrls: ['./snackBar.css']})export class SnackBar { // create an instance of SnackBarService constructor(private snackBService:SnackBarService) { } //defining method for display of SnackBar trigger(message:string, action:string) { this.snackBService.openSnackBar(message, action); } }",
"e": 2770,
"s": 2288,
"text": null
},
{
"code": null,
"e": 2929,
"s": 2770,
"text": "By repeating these steps we can use the snackBar inside any component.Example:<button (click)=\"trigger('This is a ', 'SnackBar')\"> SnackBarButton</button>"
},
{
"code": "<button (click)=\"trigger('This is a ', 'SnackBar')\"> SnackBarButton</button>",
"e": 3010,
"s": 2929,
"text": null
},
{
"code": null,
"e": 3018,
"s": 3010,
"text": "Output:"
},
{
"code": null,
"e": 3033,
"s": 3018,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3043,
"s": 3033,
"text": "AngularJS"
},
{
"code": null,
"e": 3060,
"s": 3043,
"text": "Web Technologies"
}
] |
React-Bootstrap Jumbotron Component
|
21 Jan, 2022
React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap.
NOTE: AS OF BOOTSTRAP 5.X, JUMBOTRONS ARE NO LONGER SUPPORTED
Jumbotron is mainly used to display the core and main content of the website.
Jumbotron props:
as: It can be used as a custom element type for this component.
fluid: This property is used to make the jumbotron full width and without rounded corners.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap css.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command:npm install react-bootstrap bootstrap
Step 3: After creating the ReactJS application, Install the required modules using the following command:
npm install react-bootstrap bootstrap
Step 4: Add the below line in index.js file:import 'bootstrap/dist/css/bootstrap.css';
Step 4: Add the below line in index.js file:
import 'bootstrap/dist/css/bootstrap.css';
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import Jumbotron from 'react-bootstrap/Jumbotron';import Button from 'react-bootstrap/Button';import Container from 'react-bootstrap/Container' import React from 'react'; export default function JumbotronExample() { return ( <> <Jumbotron> <h1>Regular, Jumbotron!</h1> <p> This is a simple Jumbotron example. </p> <p> <Button variant="primary"> Primary Button </Button> </p> </Jumbotron> <br/> <Jumbotron fluid> <Container> <h1>Fluid jumbotron !</h1> <p> This is a modified fluid jumbotron which stretches the whole horizontal space. </p> <Button variant="primary"> Primary Button </Button> </Container> </Jumbotron> </> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference link: https://react-bootstrap.netlify.app/components/jumbotron/
saiansh2525
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to do crud operations in ReactJS ?
How to Use Bootstrap with React?
How to install bootstrap in React.js ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap. "
},
{
"code": null,
"e": 258,
"s": 196,
"text": "NOTE: AS OF BOOTSTRAP 5.X, JUMBOTRONS ARE NO LONGER SUPPORTED"
},
{
"code": null,
"e": 336,
"s": 258,
"text": "Jumbotron is mainly used to display the core and main content of the website."
},
{
"code": null,
"e": 353,
"s": 336,
"text": "Jumbotron props:"
},
{
"code": null,
"e": 417,
"s": 353,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 508,
"s": 417,
"text": "fluid: This property is used to make the jumbotron full width and without rounded corners."
},
{
"code": null,
"e": 592,
"s": 508,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap css."
},
{
"code": null,
"e": 642,
"s": 592,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 737,
"s": 642,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 801,
"s": 737,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 833,
"s": 801,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 946,
"s": 833,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 1046,
"s": 946,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1060,
"s": 1046,
"text": "cd foldername"
},
{
"code": null,
"e": 1203,
"s": 1060,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command:npm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 1309,
"s": 1203,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command:"
},
{
"code": null,
"e": 1347,
"s": 1309,
"text": "npm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 1434,
"s": 1347,
"text": "Step 4: Add the below line in index.js file:import 'bootstrap/dist/css/bootstrap.css';"
},
{
"code": null,
"e": 1479,
"s": 1434,
"text": "Step 4: Add the below line in index.js file:"
},
{
"code": null,
"e": 1522,
"s": 1479,
"text": "import 'bootstrap/dist/css/bootstrap.css';"
},
{
"code": null,
"e": 1574,
"s": 1522,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1704,
"s": 1574,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1711,
"s": 1704,
"text": "App.js"
},
{
"code": "import Jumbotron from 'react-bootstrap/Jumbotron';import Button from 'react-bootstrap/Button';import Container from 'react-bootstrap/Container' import React from 'react'; export default function JumbotronExample() { return ( <> <Jumbotron> <h1>Regular, Jumbotron!</h1> <p> This is a simple Jumbotron example. </p> <p> <Button variant=\"primary\"> Primary Button </Button> </p> </Jumbotron> <br/> <Jumbotron fluid> <Container> <h1>Fluid jumbotron !</h1> <p> This is a modified fluid jumbotron which stretches the whole horizontal space. </p> <Button variant=\"primary\"> Primary Button </Button> </Container> </Jumbotron> </> );}",
"e": 2497,
"s": 1711,
"text": null
},
{
"code": null,
"e": 2610,
"s": 2497,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2620,
"s": 2610,
"text": "npm start"
},
{
"code": null,
"e": 2719,
"s": 2620,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 2793,
"s": 2719,
"text": "Reference link: https://react-bootstrap.netlify.app/components/jumbotron/"
},
{
"code": null,
"e": 2805,
"s": 2793,
"text": "saiansh2525"
},
{
"code": null,
"e": 2821,
"s": 2805,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 2829,
"s": 2821,
"text": "ReactJS"
},
{
"code": null,
"e": 2846,
"s": 2829,
"text": "Web Technologies"
},
{
"code": null,
"e": 2944,
"s": 2846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2982,
"s": 2944,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 3009,
"s": 2982,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 3048,
"s": 3009,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 3081,
"s": 3048,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 3120,
"s": 3081,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 3153,
"s": 3120,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3215,
"s": 3153,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3276,
"s": 3215,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3326,
"s": 3276,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
List of vectors in C++ STL with examples
|
10 Nov, 2021
Lists
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list.
Functions used with List:
push_front(x): Adds a new element βxβ at the beginning of the list.
push_back(x): Adds a new element βxβ at the end of the list.
Forward Lists
Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. Forward List is preferred over the list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc.
Functions used with Forward List:
push_front(x):β Adds a new element βxβ at the beginning of the list.
Vectors
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.
Functions used with Vectors:
size(): Returns the number of elements in the vector.
push_back(): This function is used to push elements into a vector from the back.
A list of vectors can be quite useful while designing complex data structures. Each node can hold a vector.
Below is the implementation of the list of vectors:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print list// contentsvoid print(list<vector<int> >& listOfVectors){ for (auto vect : listOfVectors) { // Each element of the list is // a vector itself vector<int> currentVector = vect; cout << "[ "; // Printing vector contents for (auto element : currentVector) cout << element << ' '; cout << ']'; cout << '\n'; }} // Driver codeint main(){ // Declaring a list of vectors list<vector<int> > listOfVectors; // Declaring a vector vector<int> vector1; // Adding elements into the // vector vector1.push_back(10); vector1.push_back(14); vector1.push_back(17); // Push the vector at the back // in the list listOfVectors.push_back(vector1); // Declaring another vector vector<int> vector2; // Adding elements in the vector vector2.push_back(2); vector2.push_back(6); vector2.push_back(11); // Push the vector at the back // in the list listOfVectors.push_back(vector2); // Declaring another vector vector<int> vector3; // Adding elements in the // vector vector3.push_back(11); vector3.push_back(16); vector3.push_back(29); // Push the vector at the front // in the list listOfVectors.push_front(vector3); // Calling print function print(listOfVectors); return 0;}
[ 10 14 17 ]
[ 2 6 11 ]
[ 11 16 29 ]
Below is the implementation of forward list of vectors:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print forward// list contentsvoid print(forward_list<vector<int> >& forwardListOfVectors){ for (auto vect : forwardListOfVectors) { // Each element of the forward list // is a vector itself vector<int> currentVector = vect; cout << "[ "; // Printing vector contents for (auto element : currentVector) cout << element << ' '; cout << ']'; cout << '\n'; }} // Driver codeint main(){ // Declaring a list of vectors forward_list<vector<int> > forwardListOfVectors; // Declaring a vector vector<int> vector1; // Adding elements into the vector vector1.push_back(10); vector1.push_back(14); vector1.push_back(17); // Push the vector in the forward // list forwardListOfVectors.push_front(vector1); // Declaring another vector vector<int> vector2; // Adding elements in the vector vector2.push_back(2); vector2.push_back(6); vector2.push_back(11); // Push the vector in the forward // list forwardListOfVectors.push_front(vector2); // Declaring another vector vector<int> vector3; // Adding elements in the vector vector3.push_back(11); vector3.push_back(16); vector3.push_back(29); // Push the vector in the forward // list forwardListOfVectors.push_front(vector3); // Calling print function print(forwardListOfVectors); return 0;}
[ 11 16 29 ]
[ 2 6 11 ]
[ 10 14 17 ]
CPP-forward-list
cpp-list
cpp-vector
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 58,
"s": 52,
"text": "Lists"
},
{
"code": null,
"e": 383,
"s": 58,
"text": "Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list."
},
{
"code": null,
"e": 409,
"s": 383,
"text": "Functions used with List:"
},
{
"code": null,
"e": 477,
"s": 409,
"text": "push_front(x): Adds a new element βxβ at the beginning of the list."
},
{
"code": null,
"e": 538,
"s": 477,
"text": "push_back(x): Adds a new element βxβ at the end of the list."
},
{
"code": null,
"e": 552,
"s": 538,
"text": "Forward Lists"
},
{
"code": null,
"e": 1428,
"s": 552,
"text": "Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. Forward List is preferred over the list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc."
},
{
"code": null,
"e": 1462,
"s": 1428,
"text": "Functions used with Forward List:"
},
{
"code": null,
"e": 1531,
"s": 1462,
"text": "push_front(x):β Adds a new element βxβ at the beginning of the list."
},
{
"code": null,
"e": 1539,
"s": 1531,
"text": "Vectors"
},
{
"code": null,
"e": 1735,
"s": 1539,
"text": "Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container."
},
{
"code": null,
"e": 1764,
"s": 1735,
"text": "Functions used with Vectors:"
},
{
"code": null,
"e": 1818,
"s": 1764,
"text": "size(): Returns the number of elements in the vector."
},
{
"code": null,
"e": 1899,
"s": 1818,
"text": "push_back(): This function is used to push elements into a vector from the back."
},
{
"code": null,
"e": 2007,
"s": 1899,
"text": "A list of vectors can be quite useful while designing complex data structures. Each node can hold a vector."
},
{
"code": null,
"e": 2059,
"s": 2007,
"text": "Below is the implementation of the list of vectors:"
},
{
"code": null,
"e": 2063,
"s": 2059,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print list// contentsvoid print(list<vector<int> >& listOfVectors){ for (auto vect : listOfVectors) { // Each element of the list is // a vector itself vector<int> currentVector = vect; cout << \"[ \"; // Printing vector contents for (auto element : currentVector) cout << element << ' '; cout << ']'; cout << '\\n'; }} // Driver codeint main(){ // Declaring a list of vectors list<vector<int> > listOfVectors; // Declaring a vector vector<int> vector1; // Adding elements into the // vector vector1.push_back(10); vector1.push_back(14); vector1.push_back(17); // Push the vector at the back // in the list listOfVectors.push_back(vector1); // Declaring another vector vector<int> vector2; // Adding elements in the vector vector2.push_back(2); vector2.push_back(6); vector2.push_back(11); // Push the vector at the back // in the list listOfVectors.push_back(vector2); // Declaring another vector vector<int> vector3; // Adding elements in the // vector vector3.push_back(11); vector3.push_back(16); vector3.push_back(29); // Push the vector at the front // in the list listOfVectors.push_front(vector3); // Calling print function print(listOfVectors); return 0;}",
"e": 3536,
"s": 2063,
"text": null
},
{
"code": null,
"e": 3573,
"s": 3536,
"text": "[ 10 14 17 ]\n[ 2 6 11 ]\n[ 11 16 29 ]"
},
{
"code": null,
"e": 3630,
"s": 3573,
"text": "Below is the implementation of forward list of vectors:"
},
{
"code": null,
"e": 3634,
"s": 3630,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print forward// list contentsvoid print(forward_list<vector<int> >& forwardListOfVectors){ for (auto vect : forwardListOfVectors) { // Each element of the forward list // is a vector itself vector<int> currentVector = vect; cout << \"[ \"; // Printing vector contents for (auto element : currentVector) cout << element << ' '; cout << ']'; cout << '\\n'; }} // Driver codeint main(){ // Declaring a list of vectors forward_list<vector<int> > forwardListOfVectors; // Declaring a vector vector<int> vector1; // Adding elements into the vector vector1.push_back(10); vector1.push_back(14); vector1.push_back(17); // Push the vector in the forward // list forwardListOfVectors.push_front(vector1); // Declaring another vector vector<int> vector2; // Adding elements in the vector vector2.push_back(2); vector2.push_back(6); vector2.push_back(11); // Push the vector in the forward // list forwardListOfVectors.push_front(vector2); // Declaring another vector vector<int> vector3; // Adding elements in the vector vector3.push_back(11); vector3.push_back(16); vector3.push_back(29); // Push the vector in the forward // list forwardListOfVectors.push_front(vector3); // Calling print function print(forwardListOfVectors); return 0;}",
"e": 5167,
"s": 3634,
"text": null
},
{
"code": null,
"e": 5204,
"s": 5167,
"text": "[ 11 16 29 ]\n[ 2 6 11 ]\n[ 10 14 17 ]"
},
{
"code": null,
"e": 5221,
"s": 5204,
"text": "CPP-forward-list"
},
{
"code": null,
"e": 5230,
"s": 5221,
"text": "cpp-list"
},
{
"code": null,
"e": 5241,
"s": 5230,
"text": "cpp-vector"
},
{
"code": null,
"e": 5245,
"s": 5241,
"text": "C++"
},
{
"code": null,
"e": 5249,
"s": 5245,
"text": "CPP"
}
] |
Implement Token Authentication using Django REST Framework
|
19 Nov, 2021
Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API. The token authentication works by providing token in exchange for exchanging usernames and passwords.
django :
pip install django
crispy_forms :
pip install --upgrade django-crispy-forms
django rest_framework :
pip install djangorestframework
HTTPie :
pip install httpie
and a project to add API, here we are using Sign Up and log in
Go to user folder in given project and make a api folder to keep all api related files
cd user && mkdir api
Now, make user/api/serializers.py and user/api/viewsets.py in api folder
cd user/api && touch serializers.py viewsets.py
now edit user/api/serializers.py
Python3
from rest_framework import serializersfrom django.contrib.auth.models import User class userSerializers(serializers.ModelSerializer): class Meta: model = User fields = '__all__'
also edit user/api/viewsets.py
Python3
from rest_framework import viewsetsfrom .serializers import userSerializersfrom django.contrib.auth.models import User class userviewsets(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = userSerializers
Edit settings.pyadd rest_framework and rest_framework.authtoken in INSTALLED_APPS in setting.py
Edit rest_framework settings as below
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
),
}
Creating router goto project/ and create router.py
cd project/ && touch router.py
edit project/router.py,
Python3
from user.api.viewsets import userviewsetsfrom rest_framework import routers router = routers.DefaultRouter()router.register('user', userviewsets, base_name ='user_api')
Editing url.pygoto to project/urls.pyand edit it Import router and rest_framework.authtoken for token authentication
Python3
from .router import routerfrom rest_framework.authtoken import views
add API related paths
Python3
path('api/', include(router.urls)),path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),
Testing API first, migrate models
python manage.py migrate
start server using below command
python manage.py runserver
open another terminal and let us check our API using HTTP POST request for a token and paste username and password.
http POST http://localhost:8081/api-token-auth/ username='your_username' password="your_password"
now use this token to get data from API, place your API token
http http://localhost:8081/api/user/ "Authorization: Token API_KEY_HERE"
varshagumber28
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 425,
"s": 52,
"text": "Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API. The token authentication works by providing token in exchange for exchanging usernames and passwords. "
},
{
"code": null,
"e": 435,
"s": 425,
"text": "django : "
},
{
"code": null,
"e": 454,
"s": 435,
"text": "pip install django"
},
{
"code": null,
"e": 470,
"s": 454,
"text": "crispy_forms : "
},
{
"code": null,
"e": 514,
"s": 470,
"text": " pip install --upgrade django-crispy-forms "
},
{
"code": null,
"e": 539,
"s": 514,
"text": "django rest_framework : "
},
{
"code": null,
"e": 571,
"s": 539,
"text": "pip install djangorestframework"
},
{
"code": null,
"e": 581,
"s": 571,
"text": "HTTPie : "
},
{
"code": null,
"e": 600,
"s": 581,
"text": "pip install httpie"
},
{
"code": null,
"e": 664,
"s": 600,
"text": "and a project to add API, here we are using Sign Up and log in "
},
{
"code": null,
"e": 753,
"s": 664,
"text": "Go to user folder in given project and make a api folder to keep all api related files "
},
{
"code": null,
"e": 776,
"s": 753,
"text": " cd user && mkdir api "
},
{
"code": null,
"e": 849,
"s": 776,
"text": "Now, make user/api/serializers.py and user/api/viewsets.py in api folder"
},
{
"code": null,
"e": 899,
"s": 849,
"text": " cd user/api && touch serializers.py viewsets.py "
},
{
"code": null,
"e": 933,
"s": 899,
"text": "now edit user/api/serializers.py "
},
{
"code": null,
"e": 941,
"s": 933,
"text": "Python3"
},
{
"code": "from rest_framework import serializersfrom django.contrib.auth.models import User class userSerializers(serializers.ModelSerializer): class Meta: model = User fields = '__all__'",
"e": 1139,
"s": 941,
"text": null
},
{
"code": null,
"e": 1171,
"s": 1139,
"text": "also edit user/api/viewsets.py "
},
{
"code": null,
"e": 1179,
"s": 1171,
"text": "Python3"
},
{
"code": "from rest_framework import viewsetsfrom .serializers import userSerializersfrom django.contrib.auth.models import User class userviewsets(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = userSerializers",
"e": 1413,
"s": 1179,
"text": null
},
{
"code": null,
"e": 1509,
"s": 1413,
"text": "Edit settings.pyadd rest_framework and rest_framework.authtoken in INSTALLED_APPS in setting.py"
},
{
"code": null,
"e": 1548,
"s": 1509,
"text": "Edit rest_framework settings as below "
},
{
"code": null,
"e": 1789,
"s": 1548,
"text": "REST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n ),\n 'DEFAULT_PERMISSION_CLASSES':(\n 'rest_framework.permissions.IsAuthenticated',\n ),\n\n}"
},
{
"code": null,
"e": 1841,
"s": 1789,
"text": "Creating router goto project/ and create router.py "
},
{
"code": null,
"e": 1874,
"s": 1841,
"text": " cd project/ && touch router.py "
},
{
"code": null,
"e": 1899,
"s": 1874,
"text": "edit project/router.py, "
},
{
"code": null,
"e": 1907,
"s": 1899,
"text": "Python3"
},
{
"code": "from user.api.viewsets import userviewsetsfrom rest_framework import routers router = routers.DefaultRouter()router.register('user', userviewsets, base_name ='user_api')",
"e": 2077,
"s": 1907,
"text": null
},
{
"code": null,
"e": 2195,
"s": 2077,
"text": "Editing url.pygoto to project/urls.pyand edit it Import router and rest_framework.authtoken for token authentication "
},
{
"code": null,
"e": 2203,
"s": 2195,
"text": "Python3"
},
{
"code": "from .router import routerfrom rest_framework.authtoken import views",
"e": 2272,
"s": 2203,
"text": null
},
{
"code": null,
"e": 2295,
"s": 2272,
"text": "add API related paths "
},
{
"code": null,
"e": 2303,
"s": 2295,
"text": "Python3"
},
{
"code": "path('api/', include(router.urls)),path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),",
"e": 2411,
"s": 2303,
"text": null
},
{
"code": null,
"e": 2447,
"s": 2411,
"text": "Testing API first, migrate models "
},
{
"code": null,
"e": 2473,
"s": 2447,
"text": "python manage.py migrate "
},
{
"code": null,
"e": 2508,
"s": 2473,
"text": "start server using below command "
},
{
"code": null,
"e": 2535,
"s": 2508,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 2652,
"s": 2535,
"text": "open another terminal and let us check our API using HTTP POST request for a token and paste username and password. "
},
{
"code": null,
"e": 2750,
"s": 2652,
"text": "http POST http://localhost:8081/api-token-auth/ username='your_username' password=\"your_password\""
},
{
"code": null,
"e": 2813,
"s": 2750,
"text": "now use this token to get data from API, place your API token "
},
{
"code": null,
"e": 2886,
"s": 2813,
"text": "http http://localhost:8081/api/user/ \"Authorization: Token API_KEY_HERE\""
},
{
"code": null,
"e": 2901,
"s": 2886,
"text": "varshagumber28"
},
{
"code": null,
"e": 2908,
"s": 2901,
"text": "Python"
},
{
"code": null,
"e": 2927,
"s": 2908,
"text": "Technical Scripter"
}
] |
Ways to apply an if condition in Pandas DataFrame
|
07 Oct, 2021
Letβs discuss the different ways of applying If condition to a data frame in pandas.
1) Applying IF condition on Numbers Let us create a Pandas DataFrame that has 5 numbers (say from 51 to 55). Let us apply IF conditions for the following situation. If the particular number is equal or lower than 53, then assign the value of βTrueβ. Otherwise, if the number is greater than 53, then assign the value of βFalseβ.
Syntax:
df.loc[df[βcolumn nameβ] condition, βnew column nameβ] = βvalue if condition is metβ
Example:
Python3
from pandas import DataFrame numbers = {'mynumbers': [51, 52, 53, 54, 55]}df = DataFrame(numbers, columns =['mynumbers']) df.loc[df['mynumbers'] <= 53, '<= 53'] = 'True'df.loc[df['mynumbers'] > 53, '<= 53'] = 'False' df
Output:
2) Applying IF condition with lambda Let us create a Pandas DataFrame that has 5 numbers (say from 51 to 55). Let us apply IF conditions for the following situation. If the particular number is equal or lower than 53, then assign the value of βTrueβ. Otherwise, if the number is greater than 53, then assign the value of βFalseβ.
Syntax:
df[βnew column nameβ] = df[βcolumn nameβ].apply(lambda x: βvalue if condition is metβ if x condition else βvalue if condition is not metβ)
Example:
Python3
from pandas import DataFrame numbers = {'mynumbers': [51, 52, 53, 54, 55]}df = DataFrame(numbers, columns =['mynumbers']) df['<= 53'] = df['mynumbers'].apply(lambda x: 'True' if x <= 53 else 'False') print (df)
Output:
3) Applying IF condition on strings We will deal with the DataFrame that contains only strings with 5 names: Hanah, Ria, Jay, Bholu, Sachin. The conditions are: If the name is equal to βRia, β then assign the value of βFoundβ. Otherwise, if the name is not βRia, β then assign the value of βNot Foundβ.
Example:
Python3
from pandas import DataFrame names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}df = DataFrame(names, columns =['First_name']) df.loc[df['First_name'] == 'Ria', 'Status'] = 'Found' df.loc[df['First_name'] != 'Ria', 'Status'] = 'Not Found' print (df)
Output:
4) Applying IF condition on strings using lambda We will deal with the DataFrame that contains only strings with 5 names: Hanah, Ria, Jay, Bholu, Sachin. The conditions are: If the name is equal to βRia, β then assign the value of βFoundβ. Otherwise, if the name is not βRia, β then assign the value of βNot Foundβ. But this time we will deal with it using lambdas.
Example
Python3
from pandas import DataFrame names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}df = DataFrame(names, columns =['First_name']) df['Status'] = df['First_name'].apply(lambda x: 'Found' if x == 'Ria' else 'Not Found') print (df)
Output:
5) Applying IF condition with OR We will deal with the DataFrame that contains only strings with 5 names: Hanah, Ria, Jay, Bholu, Sachin. The conditions are: If the name is equal to βRiaβ, or βJayβ then assign the value of βFoundβ. Otherwise, if the name is not βRiaβ or βJayβ then assign the value of βNot Foundβ.
Example
Python3
from pandas import DataFrame names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}df = DataFrame(names, columns =['First_name']) df.loc[(df['First_name'] == 'Ria') | (df['First_name'] == 'Jay'), 'Status'] = 'Found' df.loc[(df['First_name'] != 'Ria') & (df['First_name'] != 'Jay'), 'Status'] = 'Not Found' print (df)
Output:
abhishek0719kadiyan
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 137,
"s": 52,
"text": "Letβs discuss the different ways of applying If condition to a data frame in pandas."
},
{
"code": null,
"e": 466,
"s": 137,
"text": "1) Applying IF condition on Numbers Let us create a Pandas DataFrame that has 5 numbers (say from 51 to 55). Let us apply IF conditions for the following situation. If the particular number is equal or lower than 53, then assign the value of βTrueβ. Otherwise, if the number is greater than 53, then assign the value of βFalseβ."
},
{
"code": null,
"e": 474,
"s": 466,
"text": "Syntax:"
},
{
"code": null,
"e": 561,
"s": 474,
"text": "df.loc[df[βcolumn nameβ] condition, βnew column nameβ] = βvalue if condition is metβ "
},
{
"code": null,
"e": 572,
"s": 561,
"text": "Example: "
},
{
"code": null,
"e": 580,
"s": 572,
"text": "Python3"
},
{
"code": "from pandas import DataFrame numbers = {'mynumbers': [51, 52, 53, 54, 55]}df = DataFrame(numbers, columns =['mynumbers']) df.loc[df['mynumbers'] <= 53, '<= 53'] = 'True'df.loc[df['mynumbers'] > 53, '<= 53'] = 'False' df",
"e": 800,
"s": 580,
"text": null
},
{
"code": null,
"e": 809,
"s": 800,
"text": "Output: "
},
{
"code": null,
"e": 1139,
"s": 809,
"text": "2) Applying IF condition with lambda Let us create a Pandas DataFrame that has 5 numbers (say from 51 to 55). Let us apply IF conditions for the following situation. If the particular number is equal or lower than 53, then assign the value of βTrueβ. Otherwise, if the number is greater than 53, then assign the value of βFalseβ."
},
{
"code": null,
"e": 1148,
"s": 1139,
"text": "Syntax: "
},
{
"code": null,
"e": 1289,
"s": 1148,
"text": "df[βnew column nameβ] = df[βcolumn nameβ].apply(lambda x: βvalue if condition is metβ if x condition else βvalue if condition is not metβ) "
},
{
"code": null,
"e": 1300,
"s": 1289,
"text": "Example: "
},
{
"code": null,
"e": 1308,
"s": 1300,
"text": "Python3"
},
{
"code": "from pandas import DataFrame numbers = {'mynumbers': [51, 52, 53, 54, 55]}df = DataFrame(numbers, columns =['mynumbers']) df['<= 53'] = df['mynumbers'].apply(lambda x: 'True' if x <= 53 else 'False') print (df)",
"e": 1519,
"s": 1308,
"text": null
},
{
"code": null,
"e": 1528,
"s": 1519,
"text": "Output: "
},
{
"code": null,
"e": 1831,
"s": 1528,
"text": "3) Applying IF condition on strings We will deal with the DataFrame that contains only strings with 5 names: Hanah, Ria, Jay, Bholu, Sachin. The conditions are: If the name is equal to βRia, β then assign the value of βFoundβ. Otherwise, if the name is not βRia, β then assign the value of βNot Foundβ."
},
{
"code": null,
"e": 1842,
"s": 1831,
"text": "Example: "
},
{
"code": null,
"e": 1850,
"s": 1842,
"text": "Python3"
},
{
"code": "from pandas import DataFrame names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}df = DataFrame(names, columns =['First_name']) df.loc[df['First_name'] == 'Ria', 'Status'] = 'Found' df.loc[df['First_name'] != 'Ria', 'Status'] = 'Not Found' print (df)",
"e": 2115,
"s": 1850,
"text": null
},
{
"code": null,
"e": 2124,
"s": 2115,
"text": "Output: "
},
{
"code": null,
"e": 2490,
"s": 2124,
"text": "4) Applying IF condition on strings using lambda We will deal with the DataFrame that contains only strings with 5 names: Hanah, Ria, Jay, Bholu, Sachin. The conditions are: If the name is equal to βRia, β then assign the value of βFoundβ. Otherwise, if the name is not βRia, β then assign the value of βNot Foundβ. But this time we will deal with it using lambdas."
},
{
"code": null,
"e": 2500,
"s": 2490,
"text": "Example "
},
{
"code": null,
"e": 2508,
"s": 2500,
"text": "Python3"
},
{
"code": "from pandas import DataFrame names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}df = DataFrame(names, columns =['First_name']) df['Status'] = df['First_name'].apply(lambda x: 'Found' if x == 'Ria' else 'Not Found') print (df)",
"e": 2749,
"s": 2508,
"text": null
},
{
"code": null,
"e": 2758,
"s": 2749,
"text": "Output: "
},
{
"code": null,
"e": 3074,
"s": 2758,
"text": "5) Applying IF condition with OR We will deal with the DataFrame that contains only strings with 5 names: Hanah, Ria, Jay, Bholu, Sachin. The conditions are: If the name is equal to βRiaβ, or βJayβ then assign the value of βFoundβ. Otherwise, if the name is not βRiaβ or βJayβ then assign the value of βNot Foundβ. "
},
{
"code": null,
"e": 3084,
"s": 3074,
"text": "Example "
},
{
"code": null,
"e": 3092,
"s": 3084,
"text": "Python3"
},
{
"code": "from pandas import DataFrame names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}df = DataFrame(names, columns =['First_name']) df.loc[(df['First_name'] == 'Ria') | (df['First_name'] == 'Jay'), 'Status'] = 'Found' df.loc[(df['First_name'] != 'Ria') & (df['First_name'] != 'Jay'), 'Status'] = 'Not Found' print (df)",
"e": 3422,
"s": 3092,
"text": null
},
{
"code": null,
"e": 3431,
"s": 3422,
"text": "Output: "
},
{
"code": null,
"e": 3453,
"s": 3433,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 3477,
"s": 3453,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3491,
"s": 3477,
"text": "Python-pandas"
},
{
"code": null,
"e": 3498,
"s": 3491,
"text": "Python"
}
] |
How to add color picker in a form using HTML ?
|
05 Oct, 2021
In this article. we will learn how to add a color picker in a form using HTML. As we know, a color picker is also known as a color-chooser. It is an interface in which a user can select a single color from multiple collections of background colors.
Approach:
First, we create an HTML document that contains an <input> tag.
Use the type attribute with the <input> element.
Set the type attribute to value βcolorβ.
Syntax
<input type="color">
Example:
HTML
<!DOCTYPE html><html> <head> <title> How to add a color picker in form using HTML? </title></head> <body style="text-align: center;"> <h1> GeeksForGeeks </h1> <h2> How to add a color picker in Form using HTML? </h2> <form> <label>First Name</label> <input type="text" name="fname"><br /><br> <label>Last name</label> <input type="text" name="lname"><br /> <p> Select your favorite color: <input type="color" value="red" id="color" /> </p> <input type="submit" value="submit"> </form></body> </html>
Output:
HTML-Attributes
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "In this article. we will learn how to add a color picker in a form using HTML. As we know, a color picker is also known as a color-chooser. It is an interface in which a user can select a single color from multiple collections of background colors. "
},
{
"code": null,
"e": 290,
"s": 280,
"text": "Approach:"
},
{
"code": null,
"e": 354,
"s": 290,
"text": "First, we create an HTML document that contains an <input> tag."
},
{
"code": null,
"e": 403,
"s": 354,
"text": "Use the type attribute with the <input> element."
},
{
"code": null,
"e": 444,
"s": 403,
"text": "Set the type attribute to value βcolorβ."
},
{
"code": null,
"e": 451,
"s": 444,
"text": "Syntax"
},
{
"code": null,
"e": 472,
"s": 451,
"text": "<input type=\"color\">"
},
{
"code": null,
"e": 482,
"s": 472,
"text": "Example: "
},
{
"code": null,
"e": 487,
"s": 482,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to add a color picker in form using HTML? </title></head> <body style=\"text-align: center;\"> <h1> GeeksForGeeks </h1> <h2> How to add a color picker in Form using HTML? </h2> <form> <label>First Name</label> <input type=\"text\" name=\"fname\"><br /><br> <label>Last name</label> <input type=\"text\" name=\"lname\"><br /> <p> Select your favorite color: <input type=\"color\" value=\"red\" id=\"color\" /> </p> <input type=\"submit\" value=\"submit\"> </form></body> </html>",
"e": 1129,
"s": 487,
"text": null
},
{
"code": null,
"e": 1139,
"s": 1131,
"text": "Output:"
},
{
"code": null,
"e": 1155,
"s": 1139,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1170,
"s": 1155,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1180,
"s": 1170,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1185,
"s": 1180,
"text": "HTML"
},
{
"code": null,
"e": 1202,
"s": 1185,
"text": "Web Technologies"
},
{
"code": null,
"e": 1207,
"s": 1202,
"text": "HTML"
}
] |
Relative and Absolute Cell References in MS Excel
|
06 Jun, 2021
Cell reference is the address or name of a cell or a range of cells. It is the combination of column name and row number. It helps the software to identify the cell from where the data/value is to be used in the formula. We can reference the cell of other worksheets and also of other programs.
Referencing the cell of other worksheets is known as External referencing.
Referencing the cell of other programs is known as Remote referencing.
There are two types of cell references in Excel:
Relative reference
Absolute reference
Relative reference is the default cell reference in Excel. It is simply the combination of column name and row number without any dollar ($) sign. When you copy the formula from one cell to another the relative cell address changes depending on the relative position of column and row. C1, D2, E4, etc are examples of relative cell references. Relative references are used when we want to perform a similar operation on multiple cells and the formula must change according to the relative address of column and row.
For example, We want to add the marks of two subjects entered in column A and column B and display the result in column C. Here, we will use relative reference so that the same rows of columnβs A and B are added.
Steps to Use Relative Reference:
Step 1: We write the formula in any cell and press enter so that it is calculated. In this example, we write the formula(= B2 + A2) in cell C2 and press enter to calculate the formula.
Step 2: Now click on the Fill handle at the corner of cell which contains the formula(C2).
Step 3: Drag the Fill handle up to the cells you want to fill. In our example, we will drag it till cell C10.
Step 4: Now we can see that the addition operation is performed between the cell A2 and B2, A3 and B3 and so on.
Step 5: You can double-click on any cell to check that the operation is performed in between which cells.
Thus, in the above example, we see that the relative address of cell A2 changes to A3, A4, and so on, similarly the relative address changes for column B, depending on the relative position of the row.
Absolute reference is the cell reference in which the row and column are made constant by adding the dollar ($) sign before the column name and row number. The absolute reference does not change as you copy the formula from one cell to other. If either the row or the column is made constant then it is known as a mixed reference. You can also press the F4 key to make any cell reference constant. $A$1, $B$3 are examples of absolute cell reference.
For example, We want to multiply the sum of marks of two subjects, entered in column A and column B, with the percentage entered in cell C2 and display the result in column D. Here, we will use absolute reference so that the address of cell C2 remains constant and does not change with the relative position of column and rows.
Steps to Use Absolute Reference:
Step 1: We write the formula in any cell and press enter so that it is calculated. In this example, we write the formula(=(A2+B2)*$C$2) in cell D2 and press enter to calculate the formula.
Step 2: Now click on the Fill handle at the corner of cell which contains the formula(D2).
Step 3: Drag the Fill handle up to the cells you want to fill. In our example, we will drag it till cell D10.
Step 4: Now we can see that the percentage is calculated in column D.
Step 5: You can double-click on any cell to check that the operation is performed in between which cells, and we see that the address of cell C2 does not change.
Thus, in the above example we see that the address of cell C2 is not changed whereas the address of column A and B changes with the relative position of the row and column, this happened because we used the absolute address of the cell C2.
Picked
class 6
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 323,
"s": 28,
"text": "Cell reference is the address or name of a cell or a range of cells. It is the combination of column name and row number. It helps the software to identify the cell from where the data/value is to be used in the formula. We can reference the cell of other worksheets and also of other programs."
},
{
"code": null,
"e": 398,
"s": 323,
"text": "Referencing the cell of other worksheets is known as External referencing."
},
{
"code": null,
"e": 469,
"s": 398,
"text": "Referencing the cell of other programs is known as Remote referencing."
},
{
"code": null,
"e": 520,
"s": 469,
"text": "There are two types of cell references in Excel: "
},
{
"code": null,
"e": 539,
"s": 520,
"text": "Relative reference"
},
{
"code": null,
"e": 558,
"s": 539,
"text": "Absolute reference"
},
{
"code": null,
"e": 1074,
"s": 558,
"text": "Relative reference is the default cell reference in Excel. It is simply the combination of column name and row number without any dollar ($) sign. When you copy the formula from one cell to another the relative cell address changes depending on the relative position of column and row. C1, D2, E4, etc are examples of relative cell references. Relative references are used when we want to perform a similar operation on multiple cells and the formula must change according to the relative address of column and row."
},
{
"code": null,
"e": 1287,
"s": 1074,
"text": "For example, We want to add the marks of two subjects entered in column A and column B and display the result in column C. Here, we will use relative reference so that the same rows of columnβs A and B are added."
},
{
"code": null,
"e": 1320,
"s": 1287,
"text": "Steps to Use Relative Reference:"
},
{
"code": null,
"e": 1505,
"s": 1320,
"text": "Step 1: We write the formula in any cell and press enter so that it is calculated. In this example, we write the formula(= B2 + A2) in cell C2 and press enter to calculate the formula."
},
{
"code": null,
"e": 1596,
"s": 1505,
"text": "Step 2: Now click on the Fill handle at the corner of cell which contains the formula(C2)."
},
{
"code": null,
"e": 1706,
"s": 1596,
"text": "Step 3: Drag the Fill handle up to the cells you want to fill. In our example, we will drag it till cell C10."
},
{
"code": null,
"e": 1819,
"s": 1706,
"text": "Step 4: Now we can see that the addition operation is performed between the cell A2 and B2, A3 and B3 and so on."
},
{
"code": null,
"e": 1925,
"s": 1819,
"text": "Step 5: You can double-click on any cell to check that the operation is performed in between which cells."
},
{
"code": null,
"e": 2127,
"s": 1925,
"text": "Thus, in the above example, we see that the relative address of cell A2 changes to A3, A4, and so on, similarly the relative address changes for column B, depending on the relative position of the row."
},
{
"code": null,
"e": 2577,
"s": 2127,
"text": "Absolute reference is the cell reference in which the row and column are made constant by adding the dollar ($) sign before the column name and row number. The absolute reference does not change as you copy the formula from one cell to other. If either the row or the column is made constant then it is known as a mixed reference. You can also press the F4 key to make any cell reference constant. $A$1, $B$3 are examples of absolute cell reference."
},
{
"code": null,
"e": 2905,
"s": 2577,
"text": "For example, We want to multiply the sum of marks of two subjects, entered in column A and column B, with the percentage entered in cell C2 and display the result in column D. Here, we will use absolute reference so that the address of cell C2 remains constant and does not change with the relative position of column and rows."
},
{
"code": null,
"e": 2938,
"s": 2905,
"text": "Steps to Use Absolute Reference:"
},
{
"code": null,
"e": 3127,
"s": 2938,
"text": "Step 1: We write the formula in any cell and press enter so that it is calculated. In this example, we write the formula(=(A2+B2)*$C$2) in cell D2 and press enter to calculate the formula."
},
{
"code": null,
"e": 3218,
"s": 3127,
"text": "Step 2: Now click on the Fill handle at the corner of cell which contains the formula(D2)."
},
{
"code": null,
"e": 3328,
"s": 3218,
"text": "Step 3: Drag the Fill handle up to the cells you want to fill. In our example, we will drag it till cell D10."
},
{
"code": null,
"e": 3398,
"s": 3328,
"text": "Step 4: Now we can see that the percentage is calculated in column D."
},
{
"code": null,
"e": 3560,
"s": 3398,
"text": "Step 5: You can double-click on any cell to check that the operation is performed in between which cells, and we see that the address of cell C2 does not change."
},
{
"code": null,
"e": 3800,
"s": 3560,
"text": "Thus, in the above example we see that the address of cell C2 is not changed whereas the address of column A and B changes with the relative position of the row and column, this happened because we used the absolute address of the cell C2."
},
{
"code": null,
"e": 3807,
"s": 3800,
"text": "Picked"
},
{
"code": null,
"e": 3815,
"s": 3807,
"text": "class 6"
},
{
"code": null,
"e": 3831,
"s": 3815,
"text": "School Learning"
},
{
"code": null,
"e": 3850,
"s": 3831,
"text": "School Programming"
}
] |
Select statement in MS SQL Server
|
04 Jun, 2020
In this article, the most basic statement used in SQL is being discussed.
Basic statement: select
There are large amounts of data available everywhere.The data is stored in a sequential order in form of a table.Each table consists of a row which represents a unique record and column represents a field.Schemas are used to arrange the tables in a logical order.In order to extract particular data from the tables, queries are being used which is written in Structured Query Language(SQL).To query data, select statement is used.
There are large amounts of data available everywhere.
The data is stored in a sequential order in form of a table.
Each table consists of a row which represents a unique record and column represents a field.
Schemas are used to arrange the tables in a logical order.
In order to extract particular data from the tables, queries are being used which is written in Structured Query Language(SQL).
To query data, select statement is used.
Syntax:
select
select_list;
from
schema_name.table.name;
In order to retrieve all the columns from a table, select* is being used.
Syntax -
select*
from
table_name;
Points to remember:
In the real time databases, select* isnβt recommended for use because it retrieves the data more than your requirements.It results in slow functioning of the application.In case, the user adds more columns to the table, the select* statement retrieves all the columns including the new ones resulting in crashing of the application.
In the real time databases, select* isnβt recommended for use because it retrieves the data more than your requirements.
It results in slow functioning of the application.
In case, the user adds more columns to the table, the select* statement retrieves all the columns including the new ones resulting in crashing of the application.
Example:
If the user wants to retrieve the name of the student pursuing Computer Science, the query is as follows:
select
name
from
course.student
where course='cse'
Note that course is the name of the schema and student is the name of the table.
The output will be retrieved as follows:
Note βTo retrieve the query, another statement where is being used which will be discussed in further articles.
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jun, 2020"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "In this article, the most basic statement used in SQL is being discussed."
},
{
"code": null,
"e": 126,
"s": 102,
"text": "Basic statement: select"
},
{
"code": null,
"e": 557,
"s": 126,
"text": "There are large amounts of data available everywhere.The data is stored in a sequential order in form of a table.Each table consists of a row which represents a unique record and column represents a field.Schemas are used to arrange the tables in a logical order.In order to extract particular data from the tables, queries are being used which is written in Structured Query Language(SQL).To query data, select statement is used."
},
{
"code": null,
"e": 611,
"s": 557,
"text": "There are large amounts of data available everywhere."
},
{
"code": null,
"e": 672,
"s": 611,
"text": "The data is stored in a sequential order in form of a table."
},
{
"code": null,
"e": 765,
"s": 672,
"text": "Each table consists of a row which represents a unique record and column represents a field."
},
{
"code": null,
"e": 824,
"s": 765,
"text": "Schemas are used to arrange the tables in a logical order."
},
{
"code": null,
"e": 952,
"s": 824,
"text": "In order to extract particular data from the tables, queries are being used which is written in Structured Query Language(SQL)."
},
{
"code": null,
"e": 993,
"s": 952,
"text": "To query data, select statement is used."
},
{
"code": null,
"e": 1001,
"s": 993,
"text": "Syntax:"
},
{
"code": null,
"e": 1052,
"s": 1001,
"text": "select \nselect_list;\nfrom\nschema_name.table.name; "
},
{
"code": null,
"e": 1126,
"s": 1052,
"text": "In order to retrieve all the columns from a table, select* is being used."
},
{
"code": null,
"e": 1161,
"s": 1126,
"text": "Syntax -\nselect*\nfrom\ntable_name; "
},
{
"code": null,
"e": 1181,
"s": 1161,
"text": "Points to remember:"
},
{
"code": null,
"e": 1514,
"s": 1181,
"text": "In the real time databases, select* isnβt recommended for use because it retrieves the data more than your requirements.It results in slow functioning of the application.In case, the user adds more columns to the table, the select* statement retrieves all the columns including the new ones resulting in crashing of the application."
},
{
"code": null,
"e": 1635,
"s": 1514,
"text": "In the real time databases, select* isnβt recommended for use because it retrieves the data more than your requirements."
},
{
"code": null,
"e": 1686,
"s": 1635,
"text": "It results in slow functioning of the application."
},
{
"code": null,
"e": 1849,
"s": 1686,
"text": "In case, the user adds more columns to the table, the select* statement retrieves all the columns including the new ones resulting in crashing of the application."
},
{
"code": null,
"e": 1858,
"s": 1849,
"text": "Example:"
},
{
"code": null,
"e": 1964,
"s": 1858,
"text": "If the user wants to retrieve the name of the student pursuing Computer Science, the query is as follows:"
},
{
"code": null,
"e": 2018,
"s": 1964,
"text": "select \nname \nfrom\ncourse.student\nwhere course='cse' "
},
{
"code": null,
"e": 2099,
"s": 2018,
"text": "Note that course is the name of the schema and student is the name of the table."
},
{
"code": null,
"e": 2140,
"s": 2099,
"text": "The output will be retrieved as follows:"
},
{
"code": null,
"e": 2252,
"s": 2140,
"text": "Note βTo retrieve the query, another statement where is being used which will be discussed in further articles."
},
{
"code": null,
"e": 2263,
"s": 2252,
"text": "SQL-Server"
},
{
"code": null,
"e": 2268,
"s": 2263,
"text": "DBMS"
},
{
"code": null,
"e": 2272,
"s": 2268,
"text": "SQL"
},
{
"code": null,
"e": 2277,
"s": 2272,
"text": "DBMS"
},
{
"code": null,
"e": 2281,
"s": 2277,
"text": "SQL"
}
] |
What is Type Coercion in JavaScript ?
|
01 Jul, 2020
Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values.
In case the behavior of the implicit conversion is not sure, the constructors of a data type can be used to convert any value to that datatype, like the Number(), String() or Boolean() constructor.
1. String to Number Conversion: When any string or non-string value is added to a string, it always converts the non-string value to a string implicitly. When the string βRahulβ is added to the number 10 then JavaScript does not give an error. It converts the number 10 to string β10β using coercion and then concatenates both the strings. Some more examples are shown below.
Example:
<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // The Number 10 is converted to // string '10' and then '+' // concatenates both strings var x = 10 + '20'; var y = '20' + 10; // The Boolean value true is converted // to string 'true' and then '+' // concatenates both the strings var z = true + '10'; document.write(x); document.write("<br>"); document.write(y); document.write("<br>"); document.write(z); </script></body> </html>
Output:
2. String to Number Conversion: When an operation like subtraction (-), multiplication (*), division (/) or modulus (%) is performed, all the values that are not number are converted into the number data type, as these operations can be performed between numbers only. Some examples of this are shown below.
Example:
<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // The string '5' is converted // to number 5 in all cases // implicitly var w = 10 - '5'; var x = 10 * '5'; var y = 10 / '5'; var z = 10 % '5'; document.write(w); document.write("<br>") document.write(x); document.write("<br>") document.write(y); document.write("<br>") document.write(z); </script></body> </html>
Output:
3. Boolean to Number: When a Boolean is added to a Number, the Boolean value is converted to a number as it is safer and easier to convert Boolean values to Number values. A Boolean value can be represented as 0 for βfalseβ or 1 for βtrueβ. Some examples of this are shown below.
Example:
<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // The Boolean value true is // converted to number 1 and // then operation is performed var x = true + 2; // The Boolean value false is // converted to number 0 and // then operation is performed var y = false + 2; document.write(x); document.write("<br>") document.write(y); </script></body> </html>
Output:
4. The Equality Operator: The equality operator (==) can be used to compare values irrespective of their type. This is done by coercing a non-number data type to a number. Some examples of this are shown below:
Example:
<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // Should output 'true' as string '10' // is coerced to number 10 var x = (10 == '10'); // Should output 'true', as boolean true // is coerced to number 1 var y = (true == 1); // Should output 'false' as string 'true' // is coerced to NaN which is not equal to // 1 of Boolean true var z = (true == 'true'); document.write(x); document.write("<br>"); document.write(y); document.write("<br>"); document.write(z); </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 315,
"s": 52,
"text": "Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values."
},
{
"code": null,
"e": 513,
"s": 315,
"text": "In case the behavior of the implicit conversion is not sure, the constructors of a data type can be used to convert any value to that datatype, like the Number(), String() or Boolean() constructor."
},
{
"code": null,
"e": 889,
"s": 513,
"text": "1. String to Number Conversion: When any string or non-string value is added to a string, it always converts the non-string value to a string implicitly. When the string βRahulβ is added to the number 10 then JavaScript does not give an error. It converts the number 10 to string β10β using coercion and then concatenates both the strings. Some more examples are shown below."
},
{
"code": null,
"e": 898,
"s": 889,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // The Number 10 is converted to // string '10' and then '+' // concatenates both strings var x = 10 + '20'; var y = '20' + 10; // The Boolean value true is converted // to string 'true' and then '+' // concatenates both the strings var z = true + '10'; document.write(x); document.write(\"<br>\"); document.write(y); document.write(\"<br>\"); document.write(z); </script></body> </html>",
"e": 1656,
"s": 898,
"text": null
},
{
"code": null,
"e": 1664,
"s": 1656,
"text": "Output:"
},
{
"code": null,
"e": 1972,
"s": 1664,
"text": "2. String to Number Conversion: When an operation like subtraction (-), multiplication (*), division (/) or modulus (%) is performed, all the values that are not number are converted into the number data type, as these operations can be performed between numbers only. Some examples of this are shown below."
},
{
"code": null,
"e": 1981,
"s": 1972,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // The string '5' is converted // to number 5 in all cases // implicitly var w = 10 - '5'; var x = 10 * '5'; var y = 10 / '5'; var z = 10 % '5'; document.write(w); document.write(\"<br>\") document.write(x); document.write(\"<br>\") document.write(y); document.write(\"<br>\") document.write(z); </script></body> </html>",
"e": 2662,
"s": 1981,
"text": null
},
{
"code": null,
"e": 2670,
"s": 2662,
"text": "Output:"
},
{
"code": null,
"e": 2950,
"s": 2670,
"text": "3. Boolean to Number: When a Boolean is added to a Number, the Boolean value is converted to a number as it is safer and easier to convert Boolean values to Number values. A Boolean value can be represented as 0 for βfalseβ or 1 for βtrueβ. Some examples of this are shown below."
},
{
"code": null,
"e": 2959,
"s": 2950,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // The Boolean value true is // converted to number 1 and // then operation is performed var x = true + 2; // The Boolean value false is // converted to number 0 and // then operation is performed var y = false + 2; document.write(x); document.write(\"<br>\") document.write(y); </script></body> </html>",
"e": 3597,
"s": 2959,
"text": null
},
{
"code": null,
"e": 3605,
"s": 3597,
"text": "Output:"
},
{
"code": null,
"e": 3816,
"s": 3605,
"text": "4. The Equality Operator: The equality operator (==) can be used to compare values irrespective of their type. This is done by coercing a non-number data type to a number. Some examples of this are shown below:"
},
{
"code": null,
"e": 3825,
"s": 3816,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is Type Coercion in JavaScript? </title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2>Type Coercion</h2> <h3>Output</h3> <script> // Should output 'true' as string '10' // is coerced to number 10 var x = (10 == '10'); // Should output 'true', as boolean true // is coerced to number 1 var y = (true == 1); // Should output 'false' as string 'true' // is coerced to NaN which is not equal to // 1 of Boolean true var z = (true == 'true'); document.write(x); document.write(\"<br>\"); document.write(y); document.write(\"<br>\"); document.write(z); </script></body> </html>",
"e": 4623,
"s": 3825,
"text": null
},
{
"code": null,
"e": 4632,
"s": 4623,
"text": "Output: "
},
{
"code": null,
"e": 4641,
"s": 4632,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4651,
"s": 4641,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4667,
"s": 4651,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4674,
"s": 4667,
"text": "Picked"
},
{
"code": null,
"e": 4678,
"s": 4674,
"text": "CSS"
},
{
"code": null,
"e": 4683,
"s": 4678,
"text": "HTML"
},
{
"code": null,
"e": 4694,
"s": 4683,
"text": "JavaScript"
},
{
"code": null,
"e": 4711,
"s": 4694,
"text": "Web Technologies"
},
{
"code": null,
"e": 4738,
"s": 4711,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4743,
"s": 4738,
"text": "HTML"
}
] |
Check if a number is a Mystery Number
|
25 May, 2021
Given a number, check whether it is a mystery number or not. A mystery number is a number that can be expressed as the sum of two numbers and those two numbers should be the reverse of each other.
Examples:
Input : n = 121 Output : 29 92
Input : n = 22 Output : 11 11
Source: Paytm Interview Set 23The idea is to try every possible pair smaller than or equal to n.
Below is the implementation of the above approach.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Finds reverse of given num x.
int reverseNum(int x)
{
string s = to_string(x);
reverse(s.begin(), s.end());
stringstream ss(s);
int rev = 0;
ss >> rev;
return rev;
}
bool isMysteryNumber(int n)
{
for (int i=1; i <= n/2; i++)
{
// if found print the pair, return
int j = reverseNum(i);
if (i + j == n)
{
cout << i << " " << j;
return true;
}
}
cout << "Not a Mystery Number";
return false;
}
int main()
{
int n = 121;
isMysteryNumber(n);
return 0;
}
// Java implementation of above approach
class GFG
{
// Finds reverse of given num x.
static int reverseNum(int x)
{
String s = Integer.toString(x);
String str="";
for(int i=s.length()-1;i>=0;i--)
{
str=str+s.charAt(i);
}
int rev=Integer.parseInt(str);
return rev;
}
static boolean isMysteryNumber(int n)
{
for (int i=1; i <= n/2; i++)
{
// if found print the pair, return
int j = reverseNum(i);
if (i + j == n)
{
System.out.println( i + " " + j);
return true;
}
}
System.out.println("Not a Mystery Number");
return false;
}
public static void main(String []args)
{
int n = 121;
isMysteryNumber(n);
}
}
// This code is contributed by ihritik
# Python3 implementation of above approach
# Finds reverse of given num x.
def reverseNum(x):
s = str(x)
s = s[::-1]
return int(s)
def isMysteryNumber(n):
for i in range(1, n // 2 + 1):
# if found print the pair, return
j = reverseNum(i)
if i + j == n:
print(i, j)
return True
print("Not a Mystery Number")
return False
# Driver Code
n = 121
isMysteryNumber(n)
# This code is contributed by
# Mohit Kumar 29 (IIIT gwalior)
// C# implementation of above approach
using System;
class GFG
{
// Finds reverse of given num x.
static int reverseNum(int x)
{
string s = x.ToString();
string str="";
for(int i=s.Length-1;i>=0;i--)
{
str=str+s[i];
}
int rev=Int32.Parse(str);
return rev;
}
static bool isMysteryNumber(int n)
{
for (int i=1; i <= n/2; i++)
{
// if found print the pair, return
int j = reverseNum(i);
if (i + j == n)
{
Console.WriteLine( i + " " + j);
return true;
}
}
Console.WriteLine("Not a Mystery Number");
return false;
}
public static void Main()
{
int n = 121;
isMysteryNumber(n);
}
}
// This code is contributed by ihritik
<?php
// PHP implementation of above approach
// Finds reverse of given num x.
function reverseNum($x)
{
$s = (string)$x;
$s = strrev($s);
$rev = (int)$s;
return $rev;
}
function isMysteryNumber($n)
{
for ($i=1; $i <= $n/2; $i++)
{
// if found print the pair, return
$j = reverseNum($i);
if ($i + $j == $n)
{
echo $i . " ".$j;
return true;
}
}
echo "Not a Mystery Number";
return false;
}
$n = 121;
isMysteryNumber($n);
return 0;
// This code is contribute by Ita_c.
?>
<script>
// Javascript implementation of above approach
// Finds reverse of given num x.
function reverseNum(x)
{
let s = x.toString();
let str="";
for(let i=s.length-1;i>=0;i--)
{
str=str+s[i];
}
let rev=parseInt(str);
return rev;
}
function isMysteryNumber(n)
{
for (let i=1; i <= Math.floor(n/2); i++)
{
// if found print the pair, return
let j = reverseNum(i);
if (i + j == n)
{
document.write( i + " " + j+"<br>");
return true;
}
}
document.write("Not a Mystery Number<br>");
return false;
}
let n = 121;
isMysteryNumber(n);
// This code is contributed by avanitrachhadiya2155
</script>
29 92
Mystery Numbers | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersMystery Numbers | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:14β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=JEc8AH_8th8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
mohit kumar 29
ihritik
ukasp
avanitrachhadiya2155
number-digits
Paytm
Technical Scripter 2018
Mathematical
Paytm
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 57,
"s": 26,
"text": " \n25 May, 2021\n"
},
{
"code": null,
"e": 254,
"s": 57,
"text": "Given a number, check whether it is a mystery number or not. A mystery number is a number that can be expressed as the sum of two numbers and those two numbers should be the reverse of each other."
},
{
"code": null,
"e": 264,
"s": 254,
"text": "Examples:"
},
{
"code": null,
"e": 295,
"s": 264,
"text": "Input : n = 121 Output : 29 92"
},
{
"code": null,
"e": 327,
"s": 295,
"text": "Input : n = 22 Output : 11 11 "
},
{
"code": null,
"e": 424,
"s": 327,
"text": "Source: Paytm Interview Set 23The idea is to try every possible pair smaller than or equal to n."
},
{
"code": null,
"e": 476,
"s": 424,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 480,
"s": 476,
"text": "C++"
},
{
"code": null,
"e": 485,
"s": 480,
"text": "Java"
},
{
"code": null,
"e": 493,
"s": 485,
"text": "Python3"
},
{
"code": null,
"e": 496,
"s": 493,
"text": "C#"
},
{
"code": null,
"e": 500,
"s": 496,
"text": "PHP"
},
{
"code": null,
"e": 511,
"s": 500,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ implementation of above approach\n#include <bits/stdc++.h>\nusing namespace std;\n \n// Finds reverse of given num x.\nint reverseNum(int x) \n{\n string s = to_string(x);\n reverse(s.begin(), s.end());\n stringstream ss(s); \n int rev = 0; \n ss >> rev;\n return rev; \n}\n \nbool isMysteryNumber(int n)\n{\n for (int i=1; i <= n/2; i++) \n {\n // if found print the pair, return \n int j = reverseNum(i);\n if (i + j == n) \n {\n cout << i << \" \" << j; \n return true;\n }\n }\n \n cout << \"Not a Mystery Number\";\n return false;\n}\n \nint main()\n{\n int n = 121;\n isMysteryNumber(n);\n return 0;\n}\n\n\n\n\n\n",
"e": 1209,
"s": 521,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java implementation of above approach\n \nclass GFG\n{\n // Finds reverse of given num x.\n static int reverseNum(int x) \n {\n String s = Integer.toString(x);\n String str=\"\";\n for(int i=s.length()-1;i>=0;i--)\n {\n \n str=str+s.charAt(i);\n }\n \n int rev=Integer.parseInt(str);\n return rev; \n }\n \n static boolean isMysteryNumber(int n)\n {\n for (int i=1; i <= n/2; i++) \n {\n // if found print the pair, return \n int j = reverseNum(i);\n if (i + j == n) \n {\n System.out.println( i + \" \" + j); \n return true;\n }\n }\n \n System.out.println(\"Not a Mystery Number\");\n return false;\n }\n \n public static void main(String []args)\n {\n int n = 121;\n isMysteryNumber(n);\n \n }\n \n}\n \n// This code is contributed by ihritik\n\n\n\n\n\n",
"e": 2191,
"s": 1219,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 implementation of above approach\n \n# Finds reverse of given num x.\ndef reverseNum(x):\n s = str(x)\n s = s[::-1]\n return int(s)\n \ndef isMysteryNumber(n):\n \n for i in range(1, n // 2 + 1):\n \n # if found print the pair, return\n j = reverseNum(i)\n \n if i + j == n:\n print(i, j)\n return True\n \n print(\"Not a Mystery Number\")\n return False\n \n# Driver Code\nn = 121\nisMysteryNumber(n)\n \n# This code is contributed by \n# Mohit Kumar 29 (IIIT gwalior)\n\n\n\n\n\n",
"e": 2754,
"s": 2201,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# implementation of above approach\n \nusing System;\nclass GFG\n{\n // Finds reverse of given num x.\n static int reverseNum(int x) \n {\n string s = x.ToString();\n string str=\"\";\n for(int i=s.Length-1;i>=0;i--)\n {\n \n str=str+s[i];\n }\n \n int rev=Int32.Parse(str);\n return rev; \n }\n \n static bool isMysteryNumber(int n)\n {\n for (int i=1; i <= n/2; i++) \n {\n // if found print the pair, return \n int j = reverseNum(i);\n if (i + j == n) \n {\n Console.WriteLine( i + \" \" + j); \n return true;\n }\n }\n \n Console.WriteLine(\"Not a Mystery Number\");\n return false;\n }\n \n public static void Main()\n {\n int n = 121;\n isMysteryNumber(n);\n \n }\n \n}\n \n// This code is contributed by ihritik\n\n\n\n\n\n",
"e": 3708,
"s": 2764,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<?php \n// PHP implementation of above approach\n \n// Finds reverse of given num x.\nfunction reverseNum($x) \n{\n $s = (string)$x;\n $s = strrev($s);\n $rev = (int)$s;\n return $rev;\n}\n \nfunction isMysteryNumber($n)\n{\n for ($i=1; $i <= $n/2; $i++) \n {\n // if found print the pair, return \n $j = reverseNum($i);\n if ($i + $j == $n) \n {\n echo $i . \" \".$j; \n return true;\n }\n }\n \n echo \"Not a Mystery Number\";\n return false;\n}\n \n \n$n = 121;\nisMysteryNumber($n);\nreturn 0;\n// This code is contribute by Ita_c.\n?>\n\n\n\n\n\n",
"e": 4322,
"s": 3718,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n// Javascript implementation of above approach\n \n // Finds reverse of given num x.\n function reverseNum(x)\n {\n let s = x.toString();\n let str=\"\";\n for(let i=s.length-1;i>=0;i--)\n {\n \n str=str+s[i];\n }\n \n let rev=parseInt(str);\n return rev; \n }\n \n function isMysteryNumber(n)\n {\n for (let i=1; i <= Math.floor(n/2); i++) \n {\n // if found print the pair, return \n let j = reverseNum(i);\n if (i + j == n) \n {\n document.write( i + \" \" + j+\"<br>\"); \n return true;\n }\n }\n \n document.write(\"Not a Mystery Number<br>\");\n return false;\n }\n \n let n = 121;\n isMysteryNumber(n);\n \n \n \n \n// This code is contributed by avanitrachhadiya2155\n</script>\n\n\n\n\n\n",
"e": 5251,
"s": 4332,
"text": null
},
{
"code": null,
"e": 5257,
"s": 5251,
"text": "29 92"
},
{
"code": null,
"e": 6107,
"s": 5259,
"text": "Mystery Numbers | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersMystery Numbers | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:14β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=JEc8AH_8th8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 6122,
"s": 6107,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 6130,
"s": 6122,
"text": "ihritik"
},
{
"code": null,
"e": 6136,
"s": 6130,
"text": "ukasp"
},
{
"code": null,
"e": 6157,
"s": 6136,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 6173,
"s": 6157,
"text": "\nnumber-digits\n"
},
{
"code": null,
"e": 6181,
"s": 6173,
"text": "\nPaytm\n"
},
{
"code": null,
"e": 6207,
"s": 6181,
"text": "\nTechnical Scripter 2018\n"
},
{
"code": null,
"e": 6222,
"s": 6207,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 6228,
"s": 6222,
"text": "Paytm"
},
{
"code": null,
"e": 6241,
"s": 6228,
"text": "Mathematical"
}
] |
Morse Code Translator In Python
|
26 Apr, 2022
Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.
The algorithm is very simple. Every character in the English language is substituted by a series of βdotsβ and βdashesβ or sometimes just singular βdotβ or βdashβ and vice versa. Please refer to this Wikipedia image for details.
In the case of encryption, we extract each character (if not space) from a word one at a time and match it with its corresponding morse code stored in whichever data structure we have chosen(if you are coding in python, dictionaries can turn out to be very useful in this case)Store the morse code in a variable that will contain our encoded string and then we add a space to our string that will contain the result.While encoding in morse code we need to add 1 space between every character and 2 consecutive spaces between every word.If the character is a space then add another space to the variable containing the result. We repeat this process till we traverse the whole string
In the case of encryption, we extract each character (if not space) from a word one at a time and match it with its corresponding morse code stored in whichever data structure we have chosen(if you are coding in python, dictionaries can turn out to be very useful in this case)
Store the morse code in a variable that will contain our encoded string and then we add a space to our string that will contain the result.
While encoding in morse code we need to add 1 space between every character and 2 consecutive spaces between every word.
If the character is a space then add another space to the variable containing the result. We repeat this process till we traverse the whole string
In the case of decryption, we start by adding a space at the end of the string to be decoded (this will be explained later).Now we keep extracting characters from the string till we are not getting any space.As soon as we get a space we look up the corresponding English language character to the extracted sequence of characters (or our morse code) and add it to a variable that will store the result.Remember keeping track of the space is the most important part of this decryption process. As soon as we get 2 consecutive spaces we will add another space to our variable containing the decoded string.The last space at the end of the string will help us identify the last sequence of morse code characters (since space acts as a check for extracting characters and start decoding them).
In the case of decryption, we start by adding a space at the end of the string to be decoded (this will be explained later).
Now we keep extracting characters from the string till we are not getting any space.
As soon as we get a space we look up the corresponding English language character to the extracted sequence of characters (or our morse code) and add it to a variable that will store the result.
Remember keeping track of the space is the most important part of this decryption process. As soon as we get 2 consecutive spaces we will add another space to our variable containing the decoded string.
The last space at the end of the string will help us identify the last sequence of morse code characters (since space acts as a check for extracting characters and start decoding them).
Python provides a data structure called a dictionary which stores information in the form of key-value pairs which is very convenient for implementing a cipher such as a morse code. We can save the morse code chart in a dictionary where (key-value pairs) => (English Characters-Morse Code). The plaintext (English characters) takes the place of keys and the ciphertext (Morse code) forms the values of the corresponding keys. The values of keys can be accessed from the dictionary in the same way we access the values of an array through their index and vice versa.
Python3
# Python program to implement Morse Code Translator '''VARIABLE KEY'cipher' -> 'stores the morse translated form of the english string''decipher' -> 'stores the english translated form of the morse string''citext' -> 'stores morse code of a single character''i' -> 'keeps count of the spaces between morse characters''message' -> 'stores the string to be encoded or decoded'''' # Dictionary representing the morse code chartMORSE_CODE_DICT = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} # Function to encrypt the string# according to the morse code chartdef encrypt(message): cipher = '' for letter in message: if letter != ' ': # Looks up the dictionary and adds the # corresponding morse code # along with a space to separate # morse codes for different characters cipher += MORSE_CODE_DICT[letter] + ' ' else: # 1 space indicates different characters # and 2 indicates different words cipher += ' ' return cipher # Function to decrypt the string# from morse to englishdef decrypt(message): # extra space added at the end to access the # last morse code message += ' ' decipher = '' citext = '' for letter in message: # checks for space if (letter != ' '): # counter to keep track of space i = 0 # storing morse code of a single character citext += letter # in case of space else: # if i = 1 that indicates a new character i += 1 # if i = 2 that indicates a new word if i == 2 : # adding space to separate words decipher += ' ' else: # accessing the keys using their values (reverse of encryption) decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT .values()).index(citext)] citext = '' return decipher # Hard-coded driver function to run the programdef main(): message = "GEEKS-FOR-GEEKS" result = encrypt(message.upper()) print (result) message = "--. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ... " result = decrypt(message) print (result) # Executes the main functionif __name__ == '__main__': main()
Output:
--. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ...
GEEKS-FOR-GEEKS
This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vicky978654
faruk007rastavi
amartyaghoshgfg
simmytarika5
Python-projects
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 314,
"s": 52,
"text": "Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph."
},
{
"code": null,
"e": 543,
"s": 314,
"text": "The algorithm is very simple. Every character in the English language is substituted by a series of βdotsβ and βdashesβ or sometimes just singular βdotβ or βdashβ and vice versa. Please refer to this Wikipedia image for details."
},
{
"code": null,
"e": 1226,
"s": 543,
"text": "In the case of encryption, we extract each character (if not space) from a word one at a time and match it with its corresponding morse code stored in whichever data structure we have chosen(if you are coding in python, dictionaries can turn out to be very useful in this case)Store the morse code in a variable that will contain our encoded string and then we add a space to our string that will contain the result.While encoding in morse code we need to add 1 space between every character and 2 consecutive spaces between every word.If the character is a space then add another space to the variable containing the result. We repeat this process till we traverse the whole string"
},
{
"code": null,
"e": 1504,
"s": 1226,
"text": "In the case of encryption, we extract each character (if not space) from a word one at a time and match it with its corresponding morse code stored in whichever data structure we have chosen(if you are coding in python, dictionaries can turn out to be very useful in this case)"
},
{
"code": null,
"e": 1644,
"s": 1504,
"text": "Store the morse code in a variable that will contain our encoded string and then we add a space to our string that will contain the result."
},
{
"code": null,
"e": 1765,
"s": 1644,
"text": "While encoding in morse code we need to add 1 space between every character and 2 consecutive spaces between every word."
},
{
"code": null,
"e": 1912,
"s": 1765,
"text": "If the character is a space then add another space to the variable containing the result. We repeat this process till we traverse the whole string"
},
{
"code": null,
"e": 2702,
"s": 1912,
"text": "In the case of decryption, we start by adding a space at the end of the string to be decoded (this will be explained later).Now we keep extracting characters from the string till we are not getting any space.As soon as we get a space we look up the corresponding English language character to the extracted sequence of characters (or our morse code) and add it to a variable that will store the result.Remember keeping track of the space is the most important part of this decryption process. As soon as we get 2 consecutive spaces we will add another space to our variable containing the decoded string.The last space at the end of the string will help us identify the last sequence of morse code characters (since space acts as a check for extracting characters and start decoding them)."
},
{
"code": null,
"e": 2827,
"s": 2702,
"text": "In the case of decryption, we start by adding a space at the end of the string to be decoded (this will be explained later)."
},
{
"code": null,
"e": 2912,
"s": 2827,
"text": "Now we keep extracting characters from the string till we are not getting any space."
},
{
"code": null,
"e": 3107,
"s": 2912,
"text": "As soon as we get a space we look up the corresponding English language character to the extracted sequence of characters (or our morse code) and add it to a variable that will store the result."
},
{
"code": null,
"e": 3310,
"s": 3107,
"text": "Remember keeping track of the space is the most important part of this decryption process. As soon as we get 2 consecutive spaces we will add another space to our variable containing the decoded string."
},
{
"code": null,
"e": 3496,
"s": 3310,
"text": "The last space at the end of the string will help us identify the last sequence of morse code characters (since space acts as a check for extracting characters and start decoding them)."
},
{
"code": null,
"e": 4063,
"s": 3496,
"text": "Python provides a data structure called a dictionary which stores information in the form of key-value pairs which is very convenient for implementing a cipher such as a morse code. We can save the morse code chart in a dictionary where (key-value pairs) => (English Characters-Morse Code). The plaintext (English characters) takes the place of keys and the ciphertext (Morse code) forms the values of the corresponding keys. The values of keys can be accessed from the dictionary in the same way we access the values of an array through their index and vice versa. "
},
{
"code": null,
"e": 4071,
"s": 4063,
"text": "Python3"
},
{
"code": "# Python program to implement Morse Code Translator '''VARIABLE KEY'cipher' -> 'stores the morse translated form of the english string''decipher' -> 'stores the english translated form of the morse string''citext' -> 'stores morse code of a single character''i' -> 'keeps count of the spaces between morse characters''message' -> 'stores the string to be encoded or decoded'''' # Dictionary representing the morse code chartMORSE_CODE_DICT = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} # Function to encrypt the string# according to the morse code chartdef encrypt(message): cipher = '' for letter in message: if letter != ' ': # Looks up the dictionary and adds the # corresponding morse code # along with a space to separate # morse codes for different characters cipher += MORSE_CODE_DICT[letter] + ' ' else: # 1 space indicates different characters # and 2 indicates different words cipher += ' ' return cipher # Function to decrypt the string# from morse to englishdef decrypt(message): # extra space added at the end to access the # last morse code message += ' ' decipher = '' citext = '' for letter in message: # checks for space if (letter != ' '): # counter to keep track of space i = 0 # storing morse code of a single character citext += letter # in case of space else: # if i = 1 that indicates a new character i += 1 # if i = 2 that indicates a new word if i == 2 : # adding space to separate words decipher += ' ' else: # accessing the keys using their values (reverse of encryption) decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT .values()).index(citext)] citext = '' return decipher # Hard-coded driver function to run the programdef main(): message = \"GEEKS-FOR-GEEKS\" result = encrypt(message.upper()) print (result) message = \"--. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ... \" result = decrypt(message) print (result) # Executes the main functionif __name__ == '__main__': main()",
"e": 7122,
"s": 4071,
"text": null
},
{
"code": null,
"e": 7130,
"s": 7122,
"text": "Output:"
},
{
"code": null,
"e": 7206,
"s": 7130,
"text": "--. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ... \nGEEKS-FOR-GEEKS"
},
{
"code": null,
"e": 7631,
"s": 7206,
"text": "This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7643,
"s": 7631,
"text": "vicky978654"
},
{
"code": null,
"e": 7659,
"s": 7643,
"text": "faruk007rastavi"
},
{
"code": null,
"e": 7675,
"s": 7659,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 7688,
"s": 7675,
"text": "simmytarika5"
},
{
"code": null,
"e": 7704,
"s": 7688,
"text": "Python-projects"
},
{
"code": null,
"e": 7712,
"s": 7704,
"text": "Project"
},
{
"code": null,
"e": 7719,
"s": 7712,
"text": "Python"
}
] |
How to define a rectangular array in C#?
|
Multi-dimensional arrays are also called rectangular array. You can define a 3-dimensional array of integer as β
int [ , , ] a;
Let us see how to define a two-dimensional array β
Int[,] a = new[3,3]
The following is an example showing how to work with a multi-dimensional i.e. rectangular array in C# β
Live Demo
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int[,] a = new int[3, 3];
a[0,1]= 1;
a[0,2]= 2;
a[1,0]= 3;
a[1,1]= 4;
a[1,2]= 5;
a[2,0]= 6;
a[2,1]= 7;
a[2,2]= 8;
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console.ReadKey();
}
}
}
a[0,0] = 0
a[0,1] = 1
a[0,2] = 2
a[1,0] = 3
a[1,1] = 4
a[1,2] = 5
a[2,0] = 6
a[2,1] = 7
a[2,2] = 8
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Multi-dimensional arrays are also called rectangular array. You can define a 3-dimensional array of integer as β"
},
{
"code": null,
"e": 1190,
"s": 1175,
"text": "int [ , , ] a;"
},
{
"code": null,
"e": 1241,
"s": 1190,
"text": "Let us see how to define a two-dimensional array β"
},
{
"code": null,
"e": 1261,
"s": 1241,
"text": "Int[,] a = new[3,3]"
},
{
"code": null,
"e": 1365,
"s": 1261,
"text": "The following is an example showing how to work with a multi-dimensional i.e. rectangular array in C# β"
},
{
"code": null,
"e": 1376,
"s": 1365,
"text": " Live Demo"
},
{
"code": null,
"e": 1894,
"s": 1376,
"text": "using System;\n\nnamespace Demo {\n\n class Program {\n static void Main(string[] args) {\n\n int[,] a = new int[3, 3];\n a[0,1]= 1;\n a[0,2]= 2;\n a[1,0]= 3;\n a[1,1]= 4;\n a[1,2]= 5;\n a[2,0]= 6;\n a[2,1]= 7;\n a[2,2]= 8;\n\n int i, j;\n\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 3; j++) {\n Console.WriteLine(\"a[{0},{1}] = {2}\", i, j, a[i,j]);\n }\n }\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 1993,
"s": 1894,
"text": "a[0,0] = 0\na[0,1] = 1\na[0,2] = 2\na[1,0] = 3\na[1,1] = 4\na[1,2] = 5\na[2,0] = 6\na[2,1] = 7\na[2,2] = 8"
}
] |
AudioManager in Android with Example - GeeksforGeeks
|
06 Sep, 2021
AudioManager is a class provided by Android which can be used to control the ringer volume of your Android device. With the help of this Audio Manager class, you can easily control the ringer volume of your device. Audio Manager Class can be used by calling the getSystemService() method in Android. When you create Audio Manager Class then you can use setRingerMode() method to change the ringer volume of your device. The setRingerMode() method takes an integer parameter to set the ringer profile of your device. There are three different integer parameters that need to be passed in setRingerMode() method are as follows:
This is the Simple Example where we are creating Ringtone Manager App. This app will help you to change the current state of your device from General to Vibrate and then to Silent Mode. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add permissions in the AndroidManifest.xml file
Add below line in AndroidManifest.xml file.
<uses-permission android:name=βandroid.permission.ACCESS_NOTIFICATION_POLICYβ />
Step 3: Add google repository in the build.gradle file of the application project if by default it is not there
buildscript {
repositories {
google()
mavenCentral()
}
All Jetpack components are available in the Google Maven repository, include them in the build.gradle file
allprojects {
repositories {
google()
mavenCentral()
}
}
Step 4: Modify the strings.xml file
Below is the code for the strings.xml file.
XML
<resources> <string name="app_name">GFG Ringtone Manager</string> <string name="vibrate_mode">vibrate_mode</string> <string name="silent_mode">silent_mode</string> <string name="ring_mode">ringtone_mode</string> <string name="welcome_to_ringtone_manager_app">Welcome to Ringtone Manager App</string> <string name="current_mode">Current Mode</string></resources>
Step 5: Working with the activity_main.xml file
Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><!--XML Code for your activity_main.xml--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Textview to display the heading of the app--> <TextView android:id="@+id/idTVHeading" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginTop="50dp" android:layout_marginRight="20dp" android:text="@string/welcome_to_ringtone_manager_app" android:textAlignment="center" android:textColor="@color/green" android:textSize="20sp" /> <!-- Textview to display the current mode of the Ringer mode--> <TextView android:id="@+id/idTVCurrentMode" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeading" android:layout_marginTop="60dp" android:text="@string/current_mode" android:textAlignment="center" android:textAllCaps="true" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVCurrentMode" android:layout_marginTop="80dp" android:orientation="horizontal" android:weightSum="3"> <!-- width of image button is 0dp because we have mentioned weight=1--> <!-- tint represents the color of icons of image button--> <!-- all icons of image button are placed in drawable folder--> <ImageButton android:id="@+id/idIBVibrateMode" android:layout_width="0dp" android:layout_height="100dp" android:layout_margin="10dp" android:layout_weight="1" android:background="@color/green" android:contentDescription="@string/vibrate_mode" android:src="@drawable/ic_vibrate" android:tint="@color/white" /> <ImageButton android:id="@+id/idIBSilentMode" android:layout_width="0dp" android:layout_height="100dp" android:layout_margin="10dp" android:layout_weight="1" android:background="@color/green" android:contentDescription="@string/silent_mode" android:src="@drawable/ic_silent_mode" android:tint="@color/white" /> <ImageButton android:id="@+id/idIBRingtoneMode" android:layout_width="0dp" android:layout_height="100dp" android:layout_margin="10dp" android:layout_weight="1" android:background="@color/green" android:contentDescription="@string/ring_mode" android:src="@drawable/ic_ringtone_mode" android:tint="@color/white" /> </LinearLayout></RelativeLayout>
Step 6: Working with the MainActivity.java file
Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.app.NotificationManager;import android.content.Context;import android.content.Intent;import android.media.AudioManager;import android.os.Build;import android.os.Bundle;import android.view.View;import android.widget.ImageButton;import android.widget.TextView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // TextView to display the current ringer mode TextView currentStateTV; // Image buttons to switch ringer mode. ImageButton silentIB, vibrateIB, ringtoneIB; // object class variable for audio manager class. private AudioManager audioManager; // current mode to store integer value of ringer mode. int currentmode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); currentStateTV = findViewById(R.id.idTVCurrentMode); silentIB = findViewById(R.id.idIBSilentMode); vibrateIB = findViewById(R.id.idIBVibrateMode); ringtoneIB = findViewById(R.id.idIBRingtoneMode); audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // current mode will store current mode // of ringer of users device.. currentmode = audioManager.getRingerMode(); switch (currentmode) { case AudioManager.RINGER_MODE_NORMAL: currentStateTV.setText("Ringer Mode"); break; case AudioManager.RINGER_MODE_SILENT: currentStateTV.setText("Silent Mode"); break; case AudioManager.RINGER_MODE_VIBRATE: currentStateTV.setText("Vibrate Mode"); default: currentStateTV.setText("Fail to get mode"); } silentIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // the below code is to check the permission that the access // notification policy settings from users device.. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !notificationManager.isNotificationPolicyAccessGranted()) { Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS); startActivity(intent); } // set ringer mode here will sets your ringer mode to silent mode audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); Toast.makeText(MainActivity.this, "Silent Mode Activated..", Toast.LENGTH_SHORT).show(); currentStateTV.setText("Silent Mode Activated.."); } }); vibrateIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // set ringer mode here will sets your ringer mode to vibrate mode audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); Toast.makeText(MainActivity.this, "Vibrate Mode Activated..", Toast.LENGTH_SHORT).show(); currentStateTV.setText("Vibrate Mode Activated.."); } }); ringtoneIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // set ringer mode here will sets your ringer mode to normal mode audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); Toast.makeText(MainActivity.this, "Ringtone Mode Activated..", Toast.LENGTH_SHORT).show(); currentStateTV.setText("Ringtone Mode Activated.."); } }); }}
Output: Run the app on your device
Project Link: Click Here
hemantjain99
android
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
How to Change the Background Color After Clicking the Button in Android?
Android Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 25743,
"s": 25116,
"text": "AudioManager is a class provided by Android which can be used to control the ringer volume of your Android device. With the help of this Audio Manager class, you can easily control the ringer volume of your device. Audio Manager Class can be used by calling the getSystemService() method in Android. When you create Audio Manager Class then you can use setRingerMode() method to change the ringer volume of your device. The setRingerMode() method takes an integer parameter to set the ringer profile of your device. There are three different integer parameters that need to be passed in setRingerMode() method are as follows: "
},
{
"code": null,
"e": 26094,
"s": 25743,
"text": "This is the Simple Example where we are creating Ringtone Manager App. This app will help you to change the current state of your device from General to Vibrate and then to Silent Mode. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26123,
"s": 26094,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26285,
"s": 26123,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26341,
"s": 26285,
"text": "Step 2: Add permissions in the AndroidManifest.xml file"
},
{
"code": null,
"e": 26386,
"s": 26341,
"text": "Add below line in AndroidManifest.xml file. "
},
{
"code": null,
"e": 26467,
"s": 26386,
"text": "<uses-permission android:name=βandroid.permission.ACCESS_NOTIFICATION_POLICYβ />"
},
{
"code": null,
"e": 26579,
"s": 26467,
"text": "Step 3: Add google repository in the build.gradle file of the application project if by default it is not there"
},
{
"code": null,
"e": 26593,
"s": 26579,
"text": "buildscript {"
},
{
"code": null,
"e": 26609,
"s": 26593,
"text": " repositories {"
},
{
"code": null,
"e": 26622,
"s": 26609,
"text": " google()"
},
{
"code": null,
"e": 26641,
"s": 26622,
"text": " mavenCentral()"
},
{
"code": null,
"e": 26643,
"s": 26641,
"text": "}"
},
{
"code": null,
"e": 26750,
"s": 26643,
"text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file"
},
{
"code": null,
"e": 26764,
"s": 26750,
"text": "allprojects {"
},
{
"code": null,
"e": 26780,
"s": 26764,
"text": " repositories {"
},
{
"code": null,
"e": 26793,
"s": 26780,
"text": " google()"
},
{
"code": null,
"e": 26811,
"s": 26793,
"text": " mavenCentral()"
},
{
"code": null,
"e": 26814,
"s": 26811,
"text": " }"
},
{
"code": null,
"e": 26816,
"s": 26814,
"text": "}"
},
{
"code": null,
"e": 26852,
"s": 26816,
"text": "Step 4: Modify the strings.xml file"
},
{
"code": null,
"e": 26896,
"s": 26852,
"text": "Below is the code for the strings.xml file."
},
{
"code": null,
"e": 26900,
"s": 26896,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GFG Ringtone Manager</string> <string name=\"vibrate_mode\">vibrate_mode</string> <string name=\"silent_mode\">silent_mode</string> <string name=\"ring_mode\">ringtone_mode</string> <string name=\"welcome_to_ringtone_manager_app\">Welcome to Ringtone Manager App</string> <string name=\"current_mode\">Current Mode</string></resources>",
"e": 27280,
"s": 26900,
"text": null
},
{
"code": null,
"e": 27328,
"s": 27280,
"text": "Step 5: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27452,
"s": 27328,
"text": "Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 27456,
"s": 27452,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--XML Code for your activity_main.xml--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Textview to display the heading of the app--> <TextView android:id=\"@+id/idTVHeading\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"20dp\" android:layout_marginTop=\"50dp\" android:layout_marginRight=\"20dp\" android:text=\"@string/welcome_to_ringtone_manager_app\" android:textAlignment=\"center\" android:textColor=\"@color/green\" android:textSize=\"20sp\" /> <!-- Textview to display the current mode of the Ringer mode--> <TextView android:id=\"@+id/idTVCurrentMode\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeading\" android:layout_marginTop=\"60dp\" android:text=\"@string/current_mode\" android:textAlignment=\"center\" android:textAllCaps=\"true\" android:textColor=\"@color/black\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVCurrentMode\" android:layout_marginTop=\"80dp\" android:orientation=\"horizontal\" android:weightSum=\"3\"> <!-- width of image button is 0dp because we have mentioned weight=1--> <!-- tint represents the color of icons of image button--> <!-- all icons of image button are placed in drawable folder--> <ImageButton android:id=\"@+id/idIBVibrateMode\" android:layout_width=\"0dp\" android:layout_height=\"100dp\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:background=\"@color/green\" android:contentDescription=\"@string/vibrate_mode\" android:src=\"@drawable/ic_vibrate\" android:tint=\"@color/white\" /> <ImageButton android:id=\"@+id/idIBSilentMode\" android:layout_width=\"0dp\" android:layout_height=\"100dp\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:background=\"@color/green\" android:contentDescription=\"@string/silent_mode\" android:src=\"@drawable/ic_silent_mode\" android:tint=\"@color/white\" /> <ImageButton android:id=\"@+id/idIBRingtoneMode\" android:layout_width=\"0dp\" android:layout_height=\"100dp\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:background=\"@color/green\" android:contentDescription=\"@string/ring_mode\" android:src=\"@drawable/ic_ringtone_mode\" android:tint=\"@color/white\" /> </LinearLayout></RelativeLayout>",
"e": 30608,
"s": 27456,
"text": null
},
{
"code": null,
"e": 30657,
"s": 30608,
"text": "Step 6: Working with the MainActivity.java file "
},
{
"code": null,
"e": 30781,
"s": 30657,
"text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30786,
"s": 30781,
"text": "Java"
},
{
"code": "import android.app.NotificationManager;import android.content.Context;import android.content.Intent;import android.media.AudioManager;import android.os.Build;import android.os.Bundle;import android.view.View;import android.widget.ImageButton;import android.widget.TextView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // TextView to display the current ringer mode TextView currentStateTV; // Image buttons to switch ringer mode. ImageButton silentIB, vibrateIB, ringtoneIB; // object class variable for audio manager class. private AudioManager audioManager; // current mode to store integer value of ringer mode. int currentmode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); currentStateTV = findViewById(R.id.idTVCurrentMode); silentIB = findViewById(R.id.idIBSilentMode); vibrateIB = findViewById(R.id.idIBVibrateMode); ringtoneIB = findViewById(R.id.idIBRingtoneMode); audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // current mode will store current mode // of ringer of users device.. currentmode = audioManager.getRingerMode(); switch (currentmode) { case AudioManager.RINGER_MODE_NORMAL: currentStateTV.setText(\"Ringer Mode\"); break; case AudioManager.RINGER_MODE_SILENT: currentStateTV.setText(\"Silent Mode\"); break; case AudioManager.RINGER_MODE_VIBRATE: currentStateTV.setText(\"Vibrate Mode\"); default: currentStateTV.setText(\"Fail to get mode\"); } silentIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // the below code is to check the permission that the access // notification policy settings from users device.. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !notificationManager.isNotificationPolicyAccessGranted()) { Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS); startActivity(intent); } // set ringer mode here will sets your ringer mode to silent mode audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); Toast.makeText(MainActivity.this, \"Silent Mode Activated..\", Toast.LENGTH_SHORT).show(); currentStateTV.setText(\"Silent Mode Activated..\"); } }); vibrateIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // set ringer mode here will sets your ringer mode to vibrate mode audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); Toast.makeText(MainActivity.this, \"Vibrate Mode Activated..\", Toast.LENGTH_SHORT).show(); currentStateTV.setText(\"Vibrate Mode Activated..\"); } }); ringtoneIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // set ringer mode here will sets your ringer mode to normal mode audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); Toast.makeText(MainActivity.this, \"Ringtone Mode Activated..\", Toast.LENGTH_SHORT).show(); currentStateTV.setText(\"Ringtone Mode Activated..\"); } }); }}",
"e": 34634,
"s": 30786,
"text": null
},
{
"code": null,
"e": 34669,
"s": 34634,
"text": "Output: Run the app on your device"
},
{
"code": null,
"e": 34694,
"s": 34669,
"text": "Project Link: Click Here"
},
{
"code": null,
"e": 34707,
"s": 34694,
"text": "hemantjain99"
},
{
"code": null,
"e": 34715,
"s": 34707,
"text": "android"
},
{
"code": null,
"e": 34722,
"s": 34715,
"text": "Picked"
},
{
"code": null,
"e": 34746,
"s": 34722,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34754,
"s": 34746,
"text": "Android"
},
{
"code": null,
"e": 34759,
"s": 34754,
"text": "Java"
},
{
"code": null,
"e": 34778,
"s": 34759,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34783,
"s": 34778,
"text": "Java"
},
{
"code": null,
"e": 34791,
"s": 34783,
"text": "Android"
},
{
"code": null,
"e": 34889,
"s": 34791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34898,
"s": 34889,
"text": "Comments"
},
{
"code": null,
"e": 34911,
"s": 34898,
"text": "Old Comments"
},
{
"code": null,
"e": 34950,
"s": 34911,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 34992,
"s": 34950,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 35025,
"s": 34992,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 35098,
"s": 35025,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 35136,
"s": 35098,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 35151,
"s": 35136,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35195,
"s": 35151,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35217,
"s": 35195,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35253,
"s": 35217,
"text": "Arrays.sort() in Java with examples"
}
] |
Java Program to Get Year From Date - GeeksforGeeks
|
09 Jul, 2021
Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, which is how to get a year from date using Java.
Methods:
There are many ways to get a year from date of which frequently used two methods are listed below.
Using get() method LocalDate classUsing get() method of Calendar classUsing split() method of String class
Using get() method LocalDate class
Using get() method of Calendar class
Using split() method of String class
Let us discuss each of them in detail alongside implementing the methods
Method 1: Using get() method of LocalDate class
The get() method of LocalDate class in Java method gets the value of the specified field from this Date as an int.
Syntax:
public int get(TemporalField field)
Parameter: This method accepts a parameter field which is the field to get and not necessarily null.
Return Value: It returns the value for the field.
Exceptions: It throws three exceptions namely as follows:
DateTimeException: This exception is thrown if a value for the field cannot be obtained or the value is outside the range of valid values for the field.
UnsupportedTemporalTypeException: This exception is thrown if the field is not supported or the range of values exceeds an int
ArithmeticException: This exception is thrown if numeric overflow occurs
Example
Java
// Java Program to Get Year From Date// Using LocalDate class // Importing Classes/Filesimport java.time.LocalDate;import java.time.Month;import java.util.Date; // Main classclass GFG { // Method 1 // To get the year public static void getYear(String date) { // Getting an instance of LocalTime from date LocalDate currentDate = LocalDate.parse(date); // Getting year from date int year = currentDate.getYear(); // Printing the year System.out.println("Year: " + year); } // Method 2 // Main driver method public static void main(String args[]) { // Specifying a date String date = "2021-05-21"; // Function Call getYear(date); }}
Output:
Year: 2021
Method 2: Using get() method of Calendar class
The get(int field_value) method of Calendar class is used to return the value of the given calendar field in the parameter.
Syntax:
public int get(int field)
Parameters: The method takes one parameter field_value of integer type and refers to the calendar whose value is needed to be returned.
Return Value: The method returns the value of the passed field.
Note: In above program, get() method is used to get the year from the specified date.
Example
Java
// Java Program to Get Year From Date// using Calendar class // Importing Classes/Filesimport java.util.*; // main classclass GFG { // Main Driver Code public static void main(String args[]) { // Creating a calendar object Calendar Cal = new GregorianCalendar( 2021, 05, 21); // Getting the values of year from calendar // object int year = Cal.get(Calendar.YEAR); // Printing the year value System.out.println("Year: " + year); }}
Output:
Year: 2021
Method 3: Using split() method of String class
This method does break a given string around matches of the given regular expression.
Parameters: It takes two parameters namely:
Regex: A delimiting regular expression
Limit: The resulting threshold
Return type: An array of strings computed by splitting the given string.
Exceptions: PatternSyntaxException β if the provided regular expressionβs syntax is invalid.
Here split() function of String class is used to split a specified date string according to the given pattern, and it returns an array of string.
Example
Java
// Java Program to Get Year From Date// Using String.split() method // Main classclass GFG { // Method 1 // To get year from date public static void findYear(String date) { // Splitting the given date by '-' String dateParts[] = date.split("-"); // Getting year from date String year = dateParts[2]; // Printing the year System.out.println("Year: " + year); } // Method 2 // Main Driver Code public static void main(String args[]) { // Given date String date = "21-05-2021"; // Function calling findYear(date); }}
Output:
Year: 2021
anikakapoor
akshaysingh98088
arorakashish0911
Java-Date-Time
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 24236,
"s": 23948,
"text": "Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, which is how to get a year from date using Java."
},
{
"code": null,
"e": 24245,
"s": 24236,
"text": "Methods:"
},
{
"code": null,
"e": 24344,
"s": 24245,
"text": "There are many ways to get a year from date of which frequently used two methods are listed below."
},
{
"code": null,
"e": 24451,
"s": 24344,
"text": "Using get() method LocalDate classUsing get() method of Calendar classUsing split() method of String class"
},
{
"code": null,
"e": 24486,
"s": 24451,
"text": "Using get() method LocalDate class"
},
{
"code": null,
"e": 24523,
"s": 24486,
"text": "Using get() method of Calendar class"
},
{
"code": null,
"e": 24560,
"s": 24523,
"text": "Using split() method of String class"
},
{
"code": null,
"e": 24634,
"s": 24560,
"text": "Let us discuss each of them in detail alongside implementing the methods "
},
{
"code": null,
"e": 24682,
"s": 24634,
"text": "Method 1: Using get() method of LocalDate class"
},
{
"code": null,
"e": 24797,
"s": 24682,
"text": "The get() method of LocalDate class in Java method gets the value of the specified field from this Date as an int."
},
{
"code": null,
"e": 24805,
"s": 24797,
"text": "Syntax:"
},
{
"code": null,
"e": 24841,
"s": 24805,
"text": "public int get(TemporalField field)"
},
{
"code": null,
"e": 24942,
"s": 24841,
"text": "Parameter: This method accepts a parameter field which is the field to get and not necessarily null."
},
{
"code": null,
"e": 24992,
"s": 24942,
"text": "Return Value: It returns the value for the field."
},
{
"code": null,
"e": 25050,
"s": 24992,
"text": "Exceptions: It throws three exceptions namely as follows:"
},
{
"code": null,
"e": 25203,
"s": 25050,
"text": "DateTimeException: This exception is thrown if a value for the field cannot be obtained or the value is outside the range of valid values for the field."
},
{
"code": null,
"e": 25330,
"s": 25203,
"text": "UnsupportedTemporalTypeException: This exception is thrown if the field is not supported or the range of values exceeds an int"
},
{
"code": null,
"e": 25403,
"s": 25330,
"text": "ArithmeticException: This exception is thrown if numeric overflow occurs"
},
{
"code": null,
"e": 25412,
"s": 25403,
"text": "Example "
},
{
"code": null,
"e": 25417,
"s": 25412,
"text": "Java"
},
{
"code": "// Java Program to Get Year From Date// Using LocalDate class // Importing Classes/Filesimport java.time.LocalDate;import java.time.Month;import java.util.Date; // Main classclass GFG { // Method 1 // To get the year public static void getYear(String date) { // Getting an instance of LocalTime from date LocalDate currentDate = LocalDate.parse(date); // Getting year from date int year = currentDate.getYear(); // Printing the year System.out.println(\"Year: \" + year); } // Method 2 // Main driver method public static void main(String args[]) { // Specifying a date String date = \"2021-05-21\"; // Function Call getYear(date); }}",
"e": 26154,
"s": 25417,
"text": null
},
{
"code": null,
"e": 26162,
"s": 26154,
"text": "Output:"
},
{
"code": null,
"e": 26173,
"s": 26162,
"text": "Year: 2021"
},
{
"code": null,
"e": 26220,
"s": 26173,
"text": "Method 2: Using get() method of Calendar class"
},
{
"code": null,
"e": 26344,
"s": 26220,
"text": "The get(int field_value) method of Calendar class is used to return the value of the given calendar field in the parameter."
},
{
"code": null,
"e": 26352,
"s": 26344,
"text": "Syntax:"
},
{
"code": null,
"e": 26378,
"s": 26352,
"text": "public int get(int field)"
},
{
"code": null,
"e": 26514,
"s": 26378,
"text": "Parameters: The method takes one parameter field_value of integer type and refers to the calendar whose value is needed to be returned."
},
{
"code": null,
"e": 26578,
"s": 26514,
"text": "Return Value: The method returns the value of the passed field."
},
{
"code": null,
"e": 26665,
"s": 26578,
"text": "Note: In above program, get() method is used to get the year from the specified date. "
},
{
"code": null,
"e": 26674,
"s": 26665,
"text": "Example "
},
{
"code": null,
"e": 26679,
"s": 26674,
"text": "Java"
},
{
"code": "// Java Program to Get Year From Date// using Calendar class // Importing Classes/Filesimport java.util.*; // main classclass GFG { // Main Driver Code public static void main(String args[]) { // Creating a calendar object Calendar Cal = new GregorianCalendar( 2021, 05, 21); // Getting the values of year from calendar // object int year = Cal.get(Calendar.YEAR); // Printing the year value System.out.println(\"Year: \" + year); }}",
"e": 27201,
"s": 26679,
"text": null
},
{
"code": null,
"e": 27209,
"s": 27201,
"text": "Output:"
},
{
"code": null,
"e": 27220,
"s": 27209,
"text": "Year: 2021"
},
{
"code": null,
"e": 27267,
"s": 27220,
"text": "Method 3: Using split() method of String class"
},
{
"code": null,
"e": 27353,
"s": 27267,
"text": "This method does break a given string around matches of the given regular expression."
},
{
"code": null,
"e": 27397,
"s": 27353,
"text": "Parameters: It takes two parameters namely:"
},
{
"code": null,
"e": 27436,
"s": 27397,
"text": "Regex: A delimiting regular expression"
},
{
"code": null,
"e": 27467,
"s": 27436,
"text": "Limit: The resulting threshold"
},
{
"code": null,
"e": 27540,
"s": 27467,
"text": "Return type: An array of strings computed by splitting the given string."
},
{
"code": null,
"e": 27635,
"s": 27540,
"text": "Exceptions: PatternSyntaxException β if the provided regular expressionβs syntax is invalid. "
},
{
"code": null,
"e": 27781,
"s": 27635,
"text": "Here split() function of String class is used to split a specified date string according to the given pattern, and it returns an array of string."
},
{
"code": null,
"e": 27790,
"s": 27781,
"text": "Example "
},
{
"code": null,
"e": 27795,
"s": 27790,
"text": "Java"
},
{
"code": "// Java Program to Get Year From Date// Using String.split() method // Main classclass GFG { // Method 1 // To get year from date public static void findYear(String date) { // Splitting the given date by '-' String dateParts[] = date.split(\"-\"); // Getting year from date String year = dateParts[2]; // Printing the year System.out.println(\"Year: \" + year); } // Method 2 // Main Driver Code public static void main(String args[]) { // Given date String date = \"21-05-2021\"; // Function calling findYear(date); }}",
"e": 28420,
"s": 27795,
"text": null
},
{
"code": null,
"e": 28428,
"s": 28420,
"text": "Output:"
},
{
"code": null,
"e": 28439,
"s": 28428,
"text": "Year: 2021"
},
{
"code": null,
"e": 28451,
"s": 28439,
"text": "anikakapoor"
},
{
"code": null,
"e": 28468,
"s": 28451,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 28485,
"s": 28468,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28500,
"s": 28485,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 28507,
"s": 28500,
"text": "Picked"
},
{
"code": null,
"e": 28512,
"s": 28507,
"text": "Java"
},
{
"code": null,
"e": 28526,
"s": 28512,
"text": "Java Programs"
},
{
"code": null,
"e": 28531,
"s": 28526,
"text": "Java"
},
{
"code": null,
"e": 28629,
"s": 28531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28638,
"s": 28629,
"text": "Comments"
},
{
"code": null,
"e": 28651,
"s": 28638,
"text": "Old Comments"
},
{
"code": null,
"e": 28697,
"s": 28651,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28718,
"s": 28697,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28733,
"s": 28718,
"text": "Stream In Java"
},
{
"code": null,
"e": 28750,
"s": 28733,
"text": "Generics in Java"
},
{
"code": null,
"e": 28769,
"s": 28750,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28813,
"s": 28769,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28839,
"s": 28813,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28873,
"s": 28839,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28920,
"s": 28873,
"text": "Implementing a Linked List in Java using Class"
}
] |
Python String istitle() Method
|
Python string method istitle() checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase.
Following is the syntax for istitle() method β
str.istitle()
NA
NA
This method returns true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones.It returns false otherwise.
The following example shows the usage of istitle() method.
#!/usr/bin/python
str = "This Is String Example...Wow!!!";
print str.istitle()
str = "This is string example....wow!!!";
print str.istitle()
When we run above program, it produces following result β
True
False
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2432,
"s": 2244,
"text": "Python string method istitle() checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase."
},
{
"code": null,
"e": 2479,
"s": 2432,
"text": "Following is the syntax for istitle() method β"
},
{
"code": null,
"e": 2494,
"s": 2479,
"text": "str.istitle()\n"
},
{
"code": null,
"e": 2497,
"s": 2494,
"text": "NA"
},
{
"code": null,
"e": 2500,
"s": 2497,
"text": "NA"
},
{
"code": null,
"e": 2736,
"s": 2500,
"text": "This method returns true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones.It returns false otherwise."
},
{
"code": null,
"e": 2795,
"s": 2736,
"text": "The following example shows the usage of istitle() method."
},
{
"code": null,
"e": 2938,
"s": 2795,
"text": "#!/usr/bin/python\n\nstr = \"This Is String Example...Wow!!!\";\nprint str.istitle()\n\nstr = \"This is string example....wow!!!\";\nprint str.istitle()"
},
{
"code": null,
"e": 2996,
"s": 2938,
"text": "When we run above program, it produces following result β"
},
{
"code": null,
"e": 3008,
"s": 2996,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 3045,
"s": 3008,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3061,
"s": 3045,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3094,
"s": 3061,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3113,
"s": 3094,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3148,
"s": 3113,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3170,
"s": 3148,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3204,
"s": 3170,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3232,
"s": 3204,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3267,
"s": 3232,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3281,
"s": 3267,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3314,
"s": 3281,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3331,
"s": 3314,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3338,
"s": 3331,
"text": " Print"
},
{
"code": null,
"e": 3349,
"s": 3338,
"text": " Add Notes"
}
] |
Automating Pac-man with Deep Q-learning: An Implementation in Tensorflow. | by Adrian Yijie Xu | Towards Data Science
|
Over the course of our articles covering the fundamentals of reinforcement learning at GradientCrescent, weβve studied both model-based and sample-based approaches to reinforcement learning. Briefly, the former class is characterized by requiring knowledge of the complete probability distributions of all possible state transitions, and can be exemplified by Markovian Decision Processes. In contrast, sample-based learning methods allow for the determination of state values simply through repeated observations, without the need for transition dynamics. Within this domain, weβve covered both Monte Carlo and Temporal Difference learning. Briefly, the two can be separated by the frequency of state-value updates: while a Monte Carlo approach requires that an episode be finished for a round of updates to take place, Temporal Difference approaches update intra-episode incrementally, using old estimations of state-values together with discounted rewards to generate new updates.
The rapid reactivity of TD or βonlineβ learning approaches makes them suitable for highly dynamic environments, as the values of states and actions is continuously updated throughout time through sets of estimates. Perhaps most notably, TD is the foundation of Q-learning, a more advanced algorithm used to train agents tackling game environments such as those observed in the OpenAI Atari gyms, and the focus of this article.
Recall that in Temporal Difference learning, we observed that an agent behaves cyclically in an environment, through sequence of States (S), Actions (A), and (Rewards).
Due to this cyclic behavior, we can update the value of the previous state as soon as we reach the next state. However, we can expand the scope of our training to include state-action values, just as we did with Markov Decision Processes prior. This is generally known as SARSA. Letβs compare the state-action and state-value TD update equations:
Q-learning takes this a step further by forcing a selection of the action with the highest action value during an update, in a similar way to whatβs observed with Bellman Optimality Equations. We can inspect SARSA and Q-learning next to the Bellman and Bellman Optimality Equations, below:
You may be wondering about how ensure complete exploration of our state-action space, given the need to constantly select actions for a state with the highest existing action-value. In theory, we could be avoiding the optimal action simply by failing to evaluate it in the first place. To encourage exploration, we can use a decaying e-greedy policy, essentially forcing the agent to select an apparent sub-optimal action in order to learn more about its value, at a certain percentage of the time. By introducing a decaying process, we can limit exploration once all of the states have been evaluated, after which weβll permanently select the optimal actions for each state.
As weβve tackled Pong before with a MDP-based model, letβs take what weβve learned about Q-learning and apply it to a game of Atariβs Ms. Pac-man.
Our Google Colaboratory implementation is written in Python utilizing Tensorflow Core, and can be found on the GradientCrescent Github. Itβs based on that by Ravichandiran et. al, but upgraded to be compatible with Tensorflow 2.0, and significantly expanded to facilitate improved visualization and explanations. As the implementation for this approach is quite convoluted, letβs summarize the order of actions required:
We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilitieses, we do not include any activation function in our final layer.As Q-learning require us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal.With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function, and use it to build an epsilon greedy policy.Using our policy, weβll then select the action a, and evaluate our decision in the gym environment to receive information on the new state sβ, the reward r, and whether the episode has been finished.We store this combination of information in a buffer in the list form <s,a,r,sβ,d>, and repeat steps 2β4 for a preset number of times to build up a large enough buffer dataset.Once step 5 has finished,we move to generate our target y-values, Rβ and Aβ, that are required for the loss calculation. While the former is simply discounted from R, we obtain the Aβ by feeding Sβ into our network.With all of our components in place, we can then calculate the loss to train our network.Once training has finished, weβll evaluate the performance of our agent graphically and through a demonstration.
We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilitieses, we do not include any activation function in our final layer.
As Q-learning require us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal.
With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function, and use it to build an epsilon greedy policy.
Using our policy, weβll then select the action a, and evaluate our decision in the gym environment to receive information on the new state sβ, the reward r, and whether the episode has been finished.
We store this combination of information in a buffer in the list form <s,a,r,sβ,d>, and repeat steps 2β4 for a preset number of times to build up a large enough buffer dataset.
Once step 5 has finished,we move to generate our target y-values, Rβ and Aβ, that are required for the loss calculation. While the former is simply discounted from R, we obtain the Aβ by feeding Sβ into our network.
With all of our components in place, we can then calculate the loss to train our network.
Once training has finished, weβll evaluate the performance of our agent graphically and through a demonstration.
Letβs get started. With Tensorflow 2 on the horizon for Colaboratory environments, weβve converted our code to be TF2 compliant, using the new compat package. Note that this code is not TF2 native.
Letβs by importing all of the necessary packages, including the OpenAI gym environments and Tensorflow core.
import numpy as npimport gymimport tensorflow as tffrom tensorflow.contrib.layers import flatten, conv2d, fully_connectedfrom collections import deque, Counterimport randomfrom datetime import datetime
Next, we define a preprocessing function to crop the images from our gym environment and convert them into one-dimensional tensors. Weβve seen this before in our Pong automation implementation.
def preprocess_observation(obs): # Crop and resize the image img = obs[1:176:2, ::2] # Convert the image to greyscale img = img.mean(axis=2) # Improve image contrast img[img==color] = 0 # Next we normalize the image from -1 to +1 img = (img β 128) / 128β1 return img.reshape(88,80,1)
Next, letβs initialize the gym environment, and inspect a few screens of gameplay, and also understand the 9 actions available within the gamespace. Naturally, this information is not available to our agent.
env = gym.make(βMsPacman-v0β)n_outputs = env.action_space.nprint(n_outputs)print(env.env.get_action_meanings())observation = env.reset()import tensorflow as tfimport matplotlib.pyplot as pltfor i in range(22): if i > 20: plt.imshow(observation) plt.show()observation, _, _, _ = env.step(1)
You should observe the following:
We can take this chance to compare our original and preprocessed input images:
Next, letβs define our model, a deep Q-network. This is essentially a three layer convolutional network that takes preprocessed input images, flattens and feeds them to a fully-connected layer, and outputs the probabilities of taking each action in the game space. As previously mentioned, thereβs no activation layer here, as the presence of one would result in a binary output distribution.
def q_network(X, name_scope):# Initialize layers initializer = tf.compat.v1.keras.initializers.VarianceScaling(scale=2.0) with tf.compat.v1.variable_scope(name_scope) as scope: # initialize the convolutional layers layer_1 = conv2d(X, num_outputs=32, kernel_size=(8,8), stride=4, padding=βSAMEβ, weights_initializer=initializer) tf.compat.v1.summary.histogram(βlayer_1β,layer_1) layer_2 = conv2d(layer_1, num_outputs=64, kernel_size=(4,4), stride=2, padding=βSAMEβ, weights_initializer=initializer) tf.compat.v1.summary.histogram(βlayer_2β,layer_2) layer_3 = conv2d(layer_2, num_outputs=64, kernel_size=(3,3), stride=1, padding=βSAMEβ, weights_initializer=initializer) tf.compat.v1.summary.histogram(βlayer_3β,layer_3) flat = flatten(layer_3) fc = fully_connected(flat, num_outputs=128, weights_initializer=initializer) tf.compat.v1.summary.histogram(βfcβ,fc) #Add final output layer output = fully_connected(fc, num_outputs=n_outputs, activation_fn=None, weights_initializer=initializer) tf.compat.v1.summary.histogram(βoutputβ,output) vars = {v.name[len(scope.name):]: v for v in tf.compat.v1.get_collection(key=tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope=scope.name)} #Return both variables and outputs togetherreturn vars, output
Letβs also take this chance to define our hyperparameters for our model and training process
num_episodes = 800batch_size = 48input_shape = (None, 88, 80, 1)#Recall shape is img.reshape(88,80,1)learning_rate = 0.001X_shape = (None, 88, 80, 1)discount_factor = 0.97global_step = 0copy_steps = 100steps_train = 4start_steps = 2000
Recall, that Q-learning requires us to select actions with the highest action values. To ensure that we still visit every single possible state-action combination, weβll have our agent follow an epsilon-greedy policy, with an exploration rate of 5%. Weβll set a this exploration rate to decay with time, as we eventually assume all combinations have already been explored β any exploration after that point would simply result in the forced selection of sub-optimal actions.
epsilon = 0.5eps_min = 0.05eps_max = 1.0eps_decay_steps = 500000#def epsilon_greedy(action, step): p = np.random.random(1).squeeze() #1D entries returned using squeeze epsilon = max(eps_min, eps_max β (eps_max-eps_min) * step/eps_decay_steps) #Decaying policy with more steps if np.random.rand() < epsilon: return np.random.randint(n_outputs) else: return action
Recall from the equations above, that the update function for Q-learning requires the following:
The current state s
The current action a
The reward following the current action r
The next state sβ
The next action aβ
To supply these parameters in meaningful quantities, we need to evaluate our current policy following a set of parameters and store all of the variables in a buffer, from which weβll draw data in minibatches during training.. This is unlike in our previous implementation in Pong, where we used an incremental approach. Letβs go ahead and create our buffer and a simple sampling function:
buffer_len = 20000#Buffer is made from a deque β double ended queueexp_buffer = deque(maxlen=buffer_len)def sample_memories(batch_size): perm_batch = np.random.permutation(len(exp_buffer))[:batch_size] mem = np.array(exp_buffer)[perm_batch] return mem[:,0], mem[:,1], mem[:,2], mem[:,3], mem[:,4]
Next, letβs copy the weight parameters of our original network into a target network. This dual-network approach allows us to generate data during the training process using an existing policy while still optimizing our parameters for the next policy iteration.
# we build our Q network, which takes the input X and generates Q values for all the actions in the statemainQ, mainQ_outputs = q_network(X, βmainQβ)# similarly we build our target Q network, for policy evaluationtargetQ, targetQ_outputs = q_network(X, βtargetQβ)copy_op = [tf.compat.v1.assign(main_name, targetQ[var_name]) for var_name, main_name in mainQ.items()]copy_target_to_main = tf.group(*copy_op)
Finally, weβll also define our loss. This is simply the squared difference of our target action (with the highest action value) and our predicted action. Weβll use an ADAM optimizer to minimize our loss during training.
# define a placeholder for our output i.e actiony = tf.compat.v1.placeholder(tf.float32, shape=(None,1))# now we calculate the loss which is the difference between actual value and predicted valueloss = tf.reduce_mean(input_tensor=tf.square(y β Q_action))# we use adam optimizer for minimizing the lossoptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate)training_op = optimizer.minimize(loss)init = tf.compat.v1.global_variables_initializer()loss_summary = tf.compat.v1.summary.scalar(βLOSSβ, loss)merge_summary = tf.compat.v1.summary.merge_all()file_writer = tf.compat.v1.summary.FileWriter(logdir, tf.compat.v1.get_default_graph())
With all of our code defined, letβs run our network and go over the training process. Weβve defined most of this in the initial summary, but letβs recall for posterity.
For each epoch, we feed an input image into our network to generate a probability distribution of the available actions, before using an epsilon-greedy policy to select the next action
We then input this into the gym environment, and obtain information on the next state and accompanying rewards, and store this into our buffer.
After our buffer is large enough, we sample the next states into our network in order to obtain the next action. We also calculate the next reward by discounting the current one
We generate our target y-values through the Q-learning update function, and train our network.
By minimizing the training loss, we update the network weight parameters to output improved state-action values for the next policy.
with tf.compat.v1.Session() as sess: init.run() # for each episode history = [] for i in range(num_episodes): done = False obs = env.reset() epoch = 0 episodic_reward = 0 actions_counter = Counter() episodic_loss = [] # while the state is not the terminal state while not done: # get the preprocessed game screen obs = preprocess_observation(obs) # feed the game screen and get the Q values for each action, actions = mainQ_outputs.eval(feed_dict={X:[obs], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) # now perform the action and move to the next state, next_obs, receive reward next_obs, reward, done, _ = env.step(action) # Store this transition as an experience in the replay buffer! Quite important exp_buffer.append([obs, action, preprocess_observation(next_obs), reward, done]) # After certain steps we move on to generating y-values for Q network with samples from the experience replay buffer if global_step % steps_train == 0 and global_step > start_steps: o_obs, o_act, o_next_obs, o_rew, o_done = sample_memories(batch_size) # states o_obs = [x for x in o_obs] # next states o_next_obs = [x for x in o_next_obs] # next actions next_act = mainQ_outputs.eval(feed_dict={X:o_next_obs, in_training_mode:False}) #discounted reward for action: these are our Y-values y_batch = o_rew + discount_factor * np.max(next_act, axis=-1) * (1-o_done) # merge all summaries and write to the file mrg_summary = merge_summary.eval(feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:False}) file_writer.add_summary(mrg_summary, global_step) # To calculate the loss, we run the previously defined functions mentioned while feeding inputs train_loss, _ = sess.run([loss, training_op], feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:True}) episodic_loss.append(train_loss) # after some interval we copy our main Q network weights to target Q network if (global_step+1) % copy_steps == 0 and global_step > start_steps: copy_target_to_main.run() obs = next_obs epoch += 1 global_step += 1 episodic_reward += reward history.append(episodic_reward)print(βEpochs per episode:β, epoch, βEpisode Reward:β, episodic_reward,βEpisode number:β, len(history))
Once training is complete, we can plot the reward distribution against incremental episodes. The first 550 episodes (roughly 2 hours) looks something like this:
After an additional 800 episodes, this converges into the following:
To evaluate our results within the confinement of the Colaboratory environment, we can record an entire episode and display it within a virtual display using a wrapped based on the IPython library:
βββUtility functions to enable video recording of gym environment and displaying it. To enable video, just do βenv = wrap_env(env)ββββdef show_video(): mp4list = glob.glob(βvideo/*.mp4β) if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, βr+bβ).read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data=βββ<video alt=βtestβ autoplay loop controls style=βheight: 400px;β> <source src=βdata:video/mp4;base64,{0}β type=βvideo/mp4" /> </video>βββ.format(encoded.decode(βasciiβ)))) else: print(βCould not find videoβ) def wrap_env(env): env = Monitor(env, β./videoβ, force=True) return env
We then run a new session of our environment using our model, and record it.
#Evaluate model on openAi GYMobservation = env.reset()new_observation = observationprev_input = Nonedone = Falsewith tf.compat.v1.Session() as sess: init.run() while True: if True: #set input to network to be difference image obs = preprocess_observation(observation) # feed the game screen and get the Q values for each action actions = mainQ_outputs.eval(feed_dict={X:[obs], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) env.render() observation = new_observation # now perform the action and move to the next state, next_obs, receive reward new_observation, reward, done, _ = env.step(action) if done: #observation = env.reset() break env.close() show_video()
You should observe something a few rounds of the game! Hereβs a couple of episodes we recorded.
Not bad for a model trained in a few hours, scoring well above 400. In particular, it seems our agent performs quite well when directly chased by a ghost, but is still poor at anticipating incoming ones, probably as it hasnβt had enough experience observing their movements yet.
That wraps up this introduction to Q-learning. In our next article, weβll move on from the world of Atari to tackling one of the most well known FPS games in the world. Stay tuned!
We hope you enjoyed this article, and hope you check out the many other articles on GradientCrescent, covering applied and theoretical aspects of AI. To stay up to date with the latest updates on GradientCrescent, please consider following the publication and following our Github repository.
References
Sutton et. al, Reinforcement Learning
White et. al, Fundamentals of Reinforcement Learning, University of Alberta
Silva et. al, Reinforcement Learning, UCL
Ravichandiran et. al, Hands-On Reinforcement Learning with Python
|
[
{
"code": null,
"e": 1156,
"s": 172,
"text": "Over the course of our articles covering the fundamentals of reinforcement learning at GradientCrescent, weβve studied both model-based and sample-based approaches to reinforcement learning. Briefly, the former class is characterized by requiring knowledge of the complete probability distributions of all possible state transitions, and can be exemplified by Markovian Decision Processes. In contrast, sample-based learning methods allow for the determination of state values simply through repeated observations, without the need for transition dynamics. Within this domain, weβve covered both Monte Carlo and Temporal Difference learning. Briefly, the two can be separated by the frequency of state-value updates: while a Monte Carlo approach requires that an episode be finished for a round of updates to take place, Temporal Difference approaches update intra-episode incrementally, using old estimations of state-values together with discounted rewards to generate new updates."
},
{
"code": null,
"e": 1583,
"s": 1156,
"text": "The rapid reactivity of TD or βonlineβ learning approaches makes them suitable for highly dynamic environments, as the values of states and actions is continuously updated throughout time through sets of estimates. Perhaps most notably, TD is the foundation of Q-learning, a more advanced algorithm used to train agents tackling game environments such as those observed in the OpenAI Atari gyms, and the focus of this article."
},
{
"code": null,
"e": 1752,
"s": 1583,
"text": "Recall that in Temporal Difference learning, we observed that an agent behaves cyclically in an environment, through sequence of States (S), Actions (A), and (Rewards)."
},
{
"code": null,
"e": 2099,
"s": 1752,
"text": "Due to this cyclic behavior, we can update the value of the previous state as soon as we reach the next state. However, we can expand the scope of our training to include state-action values, just as we did with Markov Decision Processes prior. This is generally known as SARSA. Letβs compare the state-action and state-value TD update equations:"
},
{
"code": null,
"e": 2389,
"s": 2099,
"text": "Q-learning takes this a step further by forcing a selection of the action with the highest action value during an update, in a similar way to whatβs observed with Bellman Optimality Equations. We can inspect SARSA and Q-learning next to the Bellman and Bellman Optimality Equations, below:"
},
{
"code": null,
"e": 3065,
"s": 2389,
"text": "You may be wondering about how ensure complete exploration of our state-action space, given the need to constantly select actions for a state with the highest existing action-value. In theory, we could be avoiding the optimal action simply by failing to evaluate it in the first place. To encourage exploration, we can use a decaying e-greedy policy, essentially forcing the agent to select an apparent sub-optimal action in order to learn more about its value, at a certain percentage of the time. By introducing a decaying process, we can limit exploration once all of the states have been evaluated, after which weβll permanently select the optimal actions for each state."
},
{
"code": null,
"e": 3212,
"s": 3065,
"text": "As weβve tackled Pong before with a MDP-based model, letβs take what weβve learned about Q-learning and apply it to a game of Atariβs Ms. Pac-man."
},
{
"code": null,
"e": 3633,
"s": 3212,
"text": "Our Google Colaboratory implementation is written in Python utilizing Tensorflow Core, and can be found on the GradientCrescent Github. Itβs based on that by Ravichandiran et. al, but upgraded to be compatible with Tensorflow 2.0, and significantly expanded to facilitate improved visualization and explanations. As the implementation for this approach is quite convoluted, letβs summarize the order of actions required:"
},
{
"code": null,
"e": 5245,
"s": 3633,
"text": "We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilitieses, we do not include any activation function in our final layer.As Q-learning require us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal.With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function, and use it to build an epsilon greedy policy.Using our policy, weβll then select the action a, and evaluate our decision in the gym environment to receive information on the new state sβ, the reward r, and whether the episode has been finished.We store this combination of information in a buffer in the list form <s,a,r,sβ,d>, and repeat steps 2β4 for a preset number of times to build up a large enough buffer dataset.Once step 5 has finished,we move to generate our target y-values, Rβ and Aβ, that are required for the loss calculation. While the former is simply discounted from R, we obtain the Aβ by feeding Sβ into our network.With all of our components in place, we can then calculate the loss to train our network.Once training has finished, weβll evaluate the performance of our agent graphically and through a demonstration."
},
{
"code": null,
"e": 5535,
"s": 5245,
"text": "We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilitieses, we do not include any activation function in our final layer."
},
{
"code": null,
"e": 5896,
"s": 5535,
"text": "As Q-learning require us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal."
},
{
"code": null,
"e": 6068,
"s": 5896,
"text": "With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function, and use it to build an epsilon greedy policy."
},
{
"code": null,
"e": 6268,
"s": 6068,
"text": "Using our policy, weβll then select the action a, and evaluate our decision in the gym environment to receive information on the new state sβ, the reward r, and whether the episode has been finished."
},
{
"code": null,
"e": 6445,
"s": 6268,
"text": "We store this combination of information in a buffer in the list form <s,a,r,sβ,d>, and repeat steps 2β4 for a preset number of times to build up a large enough buffer dataset."
},
{
"code": null,
"e": 6661,
"s": 6445,
"text": "Once step 5 has finished,we move to generate our target y-values, Rβ and Aβ, that are required for the loss calculation. While the former is simply discounted from R, we obtain the Aβ by feeding Sβ into our network."
},
{
"code": null,
"e": 6751,
"s": 6661,
"text": "With all of our components in place, we can then calculate the loss to train our network."
},
{
"code": null,
"e": 6864,
"s": 6751,
"text": "Once training has finished, weβll evaluate the performance of our agent graphically and through a demonstration."
},
{
"code": null,
"e": 7062,
"s": 6864,
"text": "Letβs get started. With Tensorflow 2 on the horizon for Colaboratory environments, weβve converted our code to be TF2 compliant, using the new compat package. Note that this code is not TF2 native."
},
{
"code": null,
"e": 7171,
"s": 7062,
"text": "Letβs by importing all of the necessary packages, including the OpenAI gym environments and Tensorflow core."
},
{
"code": null,
"e": 7373,
"s": 7171,
"text": "import numpy as npimport gymimport tensorflow as tffrom tensorflow.contrib.layers import flatten, conv2d, fully_connectedfrom collections import deque, Counterimport randomfrom datetime import datetime"
},
{
"code": null,
"e": 7567,
"s": 7373,
"text": "Next, we define a preprocessing function to crop the images from our gym environment and convert them into one-dimensional tensors. Weβve seen this before in our Pong automation implementation."
},
{
"code": null,
"e": 7860,
"s": 7567,
"text": "def preprocess_observation(obs): # Crop and resize the image img = obs[1:176:2, ::2] # Convert the image to greyscale img = img.mean(axis=2) # Improve image contrast img[img==color] = 0 # Next we normalize the image from -1 to +1 img = (img β 128) / 128β1 return img.reshape(88,80,1)"
},
{
"code": null,
"e": 8068,
"s": 7860,
"text": "Next, letβs initialize the gym environment, and inspect a few screens of gameplay, and also understand the 9 actions available within the gamespace. Naturally, this information is not available to our agent."
},
{
"code": null,
"e": 8365,
"s": 8068,
"text": "env = gym.make(βMsPacman-v0β)n_outputs = env.action_space.nprint(n_outputs)print(env.env.get_action_meanings())observation = env.reset()import tensorflow as tfimport matplotlib.pyplot as pltfor i in range(22): if i > 20: plt.imshow(observation) plt.show()observation, _, _, _ = env.step(1)"
},
{
"code": null,
"e": 8399,
"s": 8365,
"text": "You should observe the following:"
},
{
"code": null,
"e": 8478,
"s": 8399,
"text": "We can take this chance to compare our original and preprocessed input images:"
},
{
"code": null,
"e": 8871,
"s": 8478,
"text": "Next, letβs define our model, a deep Q-network. This is essentially a three layer convolutional network that takes preprocessed input images, flattens and feeds them to a fully-connected layer, and outputs the probabilities of taking each action in the game space. As previously mentioned, thereβs no activation layer here, as the presence of one would result in a binary output distribution."
},
{
"code": null,
"e": 10161,
"s": 8871,
"text": "def q_network(X, name_scope):# Initialize layers initializer = tf.compat.v1.keras.initializers.VarianceScaling(scale=2.0) with tf.compat.v1.variable_scope(name_scope) as scope: # initialize the convolutional layers layer_1 = conv2d(X, num_outputs=32, kernel_size=(8,8), stride=4, padding=βSAMEβ, weights_initializer=initializer) tf.compat.v1.summary.histogram(βlayer_1β,layer_1) layer_2 = conv2d(layer_1, num_outputs=64, kernel_size=(4,4), stride=2, padding=βSAMEβ, weights_initializer=initializer) tf.compat.v1.summary.histogram(βlayer_2β,layer_2) layer_3 = conv2d(layer_2, num_outputs=64, kernel_size=(3,3), stride=1, padding=βSAMEβ, weights_initializer=initializer) tf.compat.v1.summary.histogram(βlayer_3β,layer_3) flat = flatten(layer_3) fc = fully_connected(flat, num_outputs=128, weights_initializer=initializer) tf.compat.v1.summary.histogram(βfcβ,fc) #Add final output layer output = fully_connected(fc, num_outputs=n_outputs, activation_fn=None, weights_initializer=initializer) tf.compat.v1.summary.histogram(βoutputβ,output) vars = {v.name[len(scope.name):]: v for v in tf.compat.v1.get_collection(key=tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope=scope.name)} #Return both variables and outputs togetherreturn vars, output"
},
{
"code": null,
"e": 10254,
"s": 10161,
"text": "Letβs also take this chance to define our hyperparameters for our model and training process"
},
{
"code": null,
"e": 10490,
"s": 10254,
"text": "num_episodes = 800batch_size = 48input_shape = (None, 88, 80, 1)#Recall shape is img.reshape(88,80,1)learning_rate = 0.001X_shape = (None, 88, 80, 1)discount_factor = 0.97global_step = 0copy_steps = 100steps_train = 4start_steps = 2000"
},
{
"code": null,
"e": 10965,
"s": 10490,
"text": "Recall, that Q-learning requires us to select actions with the highest action values. To ensure that we still visit every single possible state-action combination, weβll have our agent follow an epsilon-greedy policy, with an exploration rate of 5%. Weβll set a this exploration rate to decay with time, as we eventually assume all combinations have already been explored β any exploration after that point would simply result in the forced selection of sub-optimal actions."
},
{
"code": null,
"e": 11338,
"s": 10965,
"text": "epsilon = 0.5eps_min = 0.05eps_max = 1.0eps_decay_steps = 500000#def epsilon_greedy(action, step): p = np.random.random(1).squeeze() #1D entries returned using squeeze epsilon = max(eps_min, eps_max β (eps_max-eps_min) * step/eps_decay_steps) #Decaying policy with more steps if np.random.rand() < epsilon: return np.random.randint(n_outputs) else: return action"
},
{
"code": null,
"e": 11435,
"s": 11338,
"text": "Recall from the equations above, that the update function for Q-learning requires the following:"
},
{
"code": null,
"e": 11455,
"s": 11435,
"text": "The current state s"
},
{
"code": null,
"e": 11476,
"s": 11455,
"text": "The current action a"
},
{
"code": null,
"e": 11518,
"s": 11476,
"text": "The reward following the current action r"
},
{
"code": null,
"e": 11536,
"s": 11518,
"text": "The next state sβ"
},
{
"code": null,
"e": 11555,
"s": 11536,
"text": "The next action aβ"
},
{
"code": null,
"e": 11944,
"s": 11555,
"text": "To supply these parameters in meaningful quantities, we need to evaluate our current policy following a set of parameters and store all of the variables in a buffer, from which weβll draw data in minibatches during training.. This is unlike in our previous implementation in Pong, where we used an incremental approach. Letβs go ahead and create our buffer and a simple sampling function:"
},
{
"code": null,
"e": 12244,
"s": 11944,
"text": "buffer_len = 20000#Buffer is made from a deque β double ended queueexp_buffer = deque(maxlen=buffer_len)def sample_memories(batch_size): perm_batch = np.random.permutation(len(exp_buffer))[:batch_size] mem = np.array(exp_buffer)[perm_batch] return mem[:,0], mem[:,1], mem[:,2], mem[:,3], mem[:,4]"
},
{
"code": null,
"e": 12506,
"s": 12244,
"text": "Next, letβs copy the weight parameters of our original network into a target network. This dual-network approach allows us to generate data during the training process using an existing policy while still optimizing our parameters for the next policy iteration."
},
{
"code": null,
"e": 12912,
"s": 12506,
"text": "# we build our Q network, which takes the input X and generates Q values for all the actions in the statemainQ, mainQ_outputs = q_network(X, βmainQβ)# similarly we build our target Q network, for policy evaluationtargetQ, targetQ_outputs = q_network(X, βtargetQβ)copy_op = [tf.compat.v1.assign(main_name, targetQ[var_name]) for var_name, main_name in mainQ.items()]copy_target_to_main = tf.group(*copy_op)"
},
{
"code": null,
"e": 13132,
"s": 12912,
"text": "Finally, weβll also define our loss. This is simply the squared difference of our target action (with the highest action value) and our predicted action. Weβll use an ADAM optimizer to minimize our loss during training."
},
{
"code": null,
"e": 13773,
"s": 13132,
"text": "# define a placeholder for our output i.e actiony = tf.compat.v1.placeholder(tf.float32, shape=(None,1))# now we calculate the loss which is the difference between actual value and predicted valueloss = tf.reduce_mean(input_tensor=tf.square(y β Q_action))# we use adam optimizer for minimizing the lossoptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate)training_op = optimizer.minimize(loss)init = tf.compat.v1.global_variables_initializer()loss_summary = tf.compat.v1.summary.scalar(βLOSSβ, loss)merge_summary = tf.compat.v1.summary.merge_all()file_writer = tf.compat.v1.summary.FileWriter(logdir, tf.compat.v1.get_default_graph())"
},
{
"code": null,
"e": 13942,
"s": 13773,
"text": "With all of our code defined, letβs run our network and go over the training process. Weβve defined most of this in the initial summary, but letβs recall for posterity."
},
{
"code": null,
"e": 14127,
"s": 13942,
"text": "For each epoch, we feed an input image into our network to generate a probability distribution of the available actions, before using an epsilon-greedy policy to select the next action"
},
{
"code": null,
"e": 14271,
"s": 14127,
"text": "We then input this into the gym environment, and obtain information on the next state and accompanying rewards, and store this into our buffer."
},
{
"code": null,
"e": 14449,
"s": 14271,
"text": "After our buffer is large enough, we sample the next states into our network in order to obtain the next action. We also calculate the next reward by discounting the current one"
},
{
"code": null,
"e": 14544,
"s": 14449,
"text": "We generate our target y-values through the Q-learning update function, and train our network."
},
{
"code": null,
"e": 14677,
"s": 14544,
"text": "By minimizing the training loss, we update the network weight parameters to output improved state-action values for the next policy."
},
{
"code": null,
"e": 17248,
"s": 14677,
"text": "with tf.compat.v1.Session() as sess: init.run() # for each episode history = [] for i in range(num_episodes): done = False obs = env.reset() epoch = 0 episodic_reward = 0 actions_counter = Counter() episodic_loss = [] # while the state is not the terminal state while not done: # get the preprocessed game screen obs = preprocess_observation(obs) # feed the game screen and get the Q values for each action, actions = mainQ_outputs.eval(feed_dict={X:[obs], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) # now perform the action and move to the next state, next_obs, receive reward next_obs, reward, done, _ = env.step(action) # Store this transition as an experience in the replay buffer! Quite important exp_buffer.append([obs, action, preprocess_observation(next_obs), reward, done]) # After certain steps we move on to generating y-values for Q network with samples from the experience replay buffer if global_step % steps_train == 0 and global_step > start_steps: o_obs, o_act, o_next_obs, o_rew, o_done = sample_memories(batch_size) # states o_obs = [x for x in o_obs] # next states o_next_obs = [x for x in o_next_obs] # next actions next_act = mainQ_outputs.eval(feed_dict={X:o_next_obs, in_training_mode:False}) #discounted reward for action: these are our Y-values y_batch = o_rew + discount_factor * np.max(next_act, axis=-1) * (1-o_done) # merge all summaries and write to the file mrg_summary = merge_summary.eval(feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:False}) file_writer.add_summary(mrg_summary, global_step) # To calculate the loss, we run the previously defined functions mentioned while feeding inputs train_loss, _ = sess.run([loss, training_op], feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:True}) episodic_loss.append(train_loss) # after some interval we copy our main Q network weights to target Q network if (global_step+1) % copy_steps == 0 and global_step > start_steps: copy_target_to_main.run() obs = next_obs epoch += 1 global_step += 1 episodic_reward += reward history.append(episodic_reward)print(βEpochs per episode:β, epoch, βEpisode Reward:β, episodic_reward,βEpisode number:β, len(history))"
},
{
"code": null,
"e": 17409,
"s": 17248,
"text": "Once training is complete, we can plot the reward distribution against incremental episodes. The first 550 episodes (roughly 2 hours) looks something like this:"
},
{
"code": null,
"e": 17478,
"s": 17409,
"text": "After an additional 800 episodes, this converges into the following:"
},
{
"code": null,
"e": 17676,
"s": 17478,
"text": "To evaluate our results within the confinement of the Colaboratory environment, we can record an entire episode and display it within a virtual display using a wrapped based on the IPython library:"
},
{
"code": null,
"e": 18335,
"s": 17676,
"text": "βββUtility functions to enable video recording of gym environment and displaying it. To enable video, just do βenv = wrap_env(env)ββββdef show_video(): mp4list = glob.glob(βvideo/*.mp4β) if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, βr+bβ).read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data=βββ<video alt=βtestβ autoplay loop controls style=βheight: 400px;β> <source src=βdata:video/mp4;base64,{0}β type=βvideo/mp4\" /> </video>βββ.format(encoded.decode(βasciiβ)))) else: print(βCould not find videoβ) def wrap_env(env): env = Monitor(env, β./videoβ, force=True) return env"
},
{
"code": null,
"e": 18412,
"s": 18335,
"text": "We then run a new session of our environment using our model, and record it."
},
{
"code": null,
"e": 19294,
"s": 18412,
"text": "#Evaluate model on openAi GYMobservation = env.reset()new_observation = observationprev_input = Nonedone = Falsewith tf.compat.v1.Session() as sess: init.run() while True: if True: #set input to network to be difference image obs = preprocess_observation(observation) # feed the game screen and get the Q values for each action actions = mainQ_outputs.eval(feed_dict={X:[obs], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) env.render() observation = new_observation # now perform the action and move to the next state, next_obs, receive reward new_observation, reward, done, _ = env.step(action) if done: #observation = env.reset() break env.close() show_video()"
},
{
"code": null,
"e": 19390,
"s": 19294,
"text": "You should observe something a few rounds of the game! Hereβs a couple of episodes we recorded."
},
{
"code": null,
"e": 19669,
"s": 19390,
"text": "Not bad for a model trained in a few hours, scoring well above 400. In particular, it seems our agent performs quite well when directly chased by a ghost, but is still poor at anticipating incoming ones, probably as it hasnβt had enough experience observing their movements yet."
},
{
"code": null,
"e": 19850,
"s": 19669,
"text": "That wraps up this introduction to Q-learning. In our next article, weβll move on from the world of Atari to tackling one of the most well known FPS games in the world. Stay tuned!"
},
{
"code": null,
"e": 20143,
"s": 19850,
"text": "We hope you enjoyed this article, and hope you check out the many other articles on GradientCrescent, covering applied and theoretical aspects of AI. To stay up to date with the latest updates on GradientCrescent, please consider following the publication and following our Github repository."
},
{
"code": null,
"e": 20154,
"s": 20143,
"text": "References"
},
{
"code": null,
"e": 20192,
"s": 20154,
"text": "Sutton et. al, Reinforcement Learning"
},
{
"code": null,
"e": 20268,
"s": 20192,
"text": "White et. al, Fundamentals of Reinforcement Learning, University of Alberta"
},
{
"code": null,
"e": 20310,
"s": 20268,
"text": "Silva et. al, Reinforcement Learning, UCL"
}
] |
Python | Convert String to Binary - GeeksforGeeks
|
16 Feb, 2021
Data conversion have always been widely used utility and one among them can be conversion of a string to itβs binary equivalent. Letβs discuss certain ways in which this can be done.
Method #1 : Using join() + ord() + format()The combination of above functions can be used to perform this particular task. The ord function converts the character to itβs ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string.
# Python3 code to demonstrate working of# Converting String to binary# Using join() + ord() + format() # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + str(test_str)) # using join() + ord() + format()# Converting String to binaryres = ''.join(format(ord(i), '08b') for i in test_str) # printing result print("The string after binary conversion : " + str(res))
The original string is : GeeksforGeeks
The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011
Method #2 : Using join() + bytearray() + format()This method is almost similar to the above function. The difference here is that rather than converting the character to itβs ASCII using ord function, the conversion at once of string is done by bytearray function.
# Python3 code to demonstrate working of# Converting String to binary# Using join() + bytearray() + format() # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + str(test_str)) # using join() + bytearray() + format()# Converting String to binaryres = ''.join(format(i, '08b') for i in bytearray(test_str, encoding ='utf-8')) # printing result print("The string after binary conversion : " + str(res))
The original string is : GeeksforGeeks
The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 24899,
"s": 24716,
"text": "Data conversion have always been widely used utility and one among them can be conversion of a string to itβs binary equivalent. Letβs discuss certain ways in which this can be done."
},
{
"code": null,
"e": 25194,
"s": 24899,
"text": "Method #1 : Using join() + ord() + format()The combination of above functions can be used to perform this particular task. The ord function converts the character to itβs ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string."
},
{
"code": "# Python3 code to demonstrate working of# Converting String to binary# Using join() + ord() + format() # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + str(test_str)) # using join() + ord() + format()# Converting String to binaryres = ''.join(format(ord(i), '08b') for i in test_str) # printing result print(\"The string after binary conversion : \" + str(res))",
"e": 25621,
"s": 25194,
"text": null
},
{
"code": null,
"e": 25802,
"s": 25621,
"text": "The original string is : GeeksforGeeks\nThe string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011"
},
{
"code": null,
"e": 26069,
"s": 25804,
"text": "Method #2 : Using join() + bytearray() + format()This method is almost similar to the above function. The difference here is that rather than converting the character to itβs ASCII using ord function, the conversion at once of string is done by bytearray function."
},
{
"code": "# Python3 code to demonstrate working of# Converting String to binary# Using join() + bytearray() + format() # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + str(test_str)) # using join() + bytearray() + format()# Converting String to binaryres = ''.join(format(i, '08b') for i in bytearray(test_str, encoding ='utf-8')) # printing result print(\"The string after binary conversion : \" + str(res))",
"e": 26533,
"s": 26069,
"text": null
},
{
"code": null,
"e": 26715,
"s": 26533,
"text": "The original string is : GeeksforGeeks\nThe string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011\n"
},
{
"code": null,
"e": 26738,
"s": 26715,
"text": "Python string-programs"
},
{
"code": null,
"e": 26745,
"s": 26738,
"text": "Python"
},
{
"code": null,
"e": 26761,
"s": 26745,
"text": "Python Programs"
},
{
"code": null,
"e": 26859,
"s": 26761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26877,
"s": 26859,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26912,
"s": 26877,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26934,
"s": 26912,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26966,
"s": 26934,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26996,
"s": 26966,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27039,
"s": 26996,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27061,
"s": 27039,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27107,
"s": 27061,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27146,
"s": 27107,
"text": "Python | Get dictionary keys as a list"
}
] |
Element-wise concatenation of two NumPy arrays of string - GeeksforGeeks
|
04 Jan, 2022
In this article, we will discuss how to concatenate element-wise two arrays of string
Example :
Input :
A = ['Akash', 'Ayush', 'Diksha', 'Radhika']
B = ['Kumar', 'Sharma', 'Tewari', 'Pegowal']
Output :
A + B = [AkashKumar, AyushSharma, 'DikshTewari', 'RadhikaPegowal']
We will be using the numpy.char.add() method.
Syntax : numpy.char.add(x1, x2)Parameters :
x1 : first array to be concatenated (concatenated at the beginning)
x2 : second array to be concatenated (concatenated at the end)
Returns : Array of strings or unicode
Example 1: String array with a single element.
Python3
# importing library numpy as npimport numpy as np # creating array as first_namefirst_name = np.array(['Geeks'], dtype = np.str)print("Printing first name array:")print(first_name) # creating array as last namelast_name = np.array(['forGeeks'], dtype = np.str)print("Printing last name array:")print(last_name) # concat first_name and last_name# into new array named as full_namefull_name = np.char.add(first_name, last_name)print("\nPrinting concatenate array as full name:")print(full_name)
Output :
Printing first name array:
['Geeks']
Printing last name array:
['forGeeks']
Printing concatenate array as full name:
['GeeksforGeeks']
Example 2: String array with multiple elements.
Python3
# importing library numpy as npimport numpy as np # creating array as first_namefirst_name = np.array(['Akash', 'Ayush', 'Diksha', 'Radhika'], dtype = np.str)print("Printing first name array:")print(first_name) # creating array as last namelast_name = np.array(['Kumar', 'Sharma', 'Tewari', 'Pegowal'], dtype = np.str)print("Printing last name array:")print(last_name) # concat first_name and last_name# into new array named as full_namefull_name = np.char.add(first_name, last_name)print("\nPrinting concatenate array as full name:")print(full_name)
Output :
Printing first name array:
['Akash' 'Ayush' 'Diksha' 'Radhika']
Printing last name array:
['Kumar' 'Sharma' 'Tewari' 'Pegowal']
Printing concatenate array as full name:
['AkashKumar' 'AyushSharma' 'DikshaTewari' 'RadhikaPegowal']
varshagumber28
Python numpy-String Operation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24379,
"s": 24292,
"text": "In this article, we will discuss how to concatenate element-wise two arrays of string "
},
{
"code": null,
"e": 24389,
"s": 24379,
"text": "Example :"
},
{
"code": null,
"e": 24563,
"s": 24389,
"text": "Input :\nA = ['Akash', 'Ayush', 'Diksha', 'Radhika']\nB = ['Kumar', 'Sharma', 'Tewari', 'Pegowal']\n\nOutput :\nA + B = [AkashKumar, AyushSharma, 'DikshTewari', 'RadhikaPegowal']"
},
{
"code": null,
"e": 24609,
"s": 24563,
"text": "We will be using the numpy.char.add() method."
},
{
"code": null,
"e": 24653,
"s": 24609,
"text": "Syntax : numpy.char.add(x1, x2)Parameters :"
},
{
"code": null,
"e": 24721,
"s": 24653,
"text": "x1 : first array to be concatenated (concatenated at the beginning)"
},
{
"code": null,
"e": 24784,
"s": 24721,
"text": "x2 : second array to be concatenated (concatenated at the end)"
},
{
"code": null,
"e": 24822,
"s": 24784,
"text": "Returns : Array of strings or unicode"
},
{
"code": null,
"e": 24869,
"s": 24822,
"text": "Example 1: String array with a single element."
},
{
"code": null,
"e": 24877,
"s": 24869,
"text": "Python3"
},
{
"code": "# importing library numpy as npimport numpy as np # creating array as first_namefirst_name = np.array(['Geeks'], dtype = np.str)print(\"Printing first name array:\")print(first_name) # creating array as last namelast_name = np.array(['forGeeks'], dtype = np.str)print(\"Printing last name array:\")print(last_name) # concat first_name and last_name# into new array named as full_namefull_name = np.char.add(first_name, last_name)print(\"\\nPrinting concatenate array as full name:\")print(full_name)",
"e": 25411,
"s": 24877,
"text": null
},
{
"code": null,
"e": 25423,
"s": 25411,
"text": " Output : "
},
{
"code": null,
"e": 25559,
"s": 25423,
"text": "Printing first name array:\n['Geeks']\nPrinting last name array:\n['forGeeks']\n\nPrinting concatenate array as full name:\n['GeeksforGeeks']"
},
{
"code": null,
"e": 25607,
"s": 25559,
"text": "Example 2: String array with multiple elements."
},
{
"code": null,
"e": 25615,
"s": 25607,
"text": "Python3"
},
{
"code": "# importing library numpy as npimport numpy as np # creating array as first_namefirst_name = np.array(['Akash', 'Ayush', 'Diksha', 'Radhika'], dtype = np.str)print(\"Printing first name array:\")print(first_name) # creating array as last namelast_name = np.array(['Kumar', 'Sharma', 'Tewari', 'Pegowal'], dtype = np.str)print(\"Printing last name array:\")print(last_name) # concat first_name and last_name# into new array named as full_namefull_name = np.char.add(first_name, last_name)print(\"\\nPrinting concatenate array as full name:\")print(full_name)",
"e": 26209,
"s": 25615,
"text": null
},
{
"code": null,
"e": 26221,
"s": 26209,
"text": " Output : "
},
{
"code": null,
"e": 26452,
"s": 26221,
"text": "Printing first name array:\n['Akash' 'Ayush' 'Diksha' 'Radhika']\nPrinting last name array:\n['Kumar' 'Sharma' 'Tewari' 'Pegowal']\n\nPrinting concatenate array as full name:\n['AkashKumar' 'AyushSharma' 'DikshaTewari' 'RadhikaPegowal']"
},
{
"code": null,
"e": 26467,
"s": 26452,
"text": "varshagumber28"
},
{
"code": null,
"e": 26497,
"s": 26467,
"text": "Python numpy-String Operation"
},
{
"code": null,
"e": 26510,
"s": 26497,
"text": "Python-numpy"
},
{
"code": null,
"e": 26517,
"s": 26510,
"text": "Python"
},
{
"code": null,
"e": 26615,
"s": 26517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26624,
"s": 26615,
"text": "Comments"
},
{
"code": null,
"e": 26637,
"s": 26624,
"text": "Old Comments"
},
{
"code": null,
"e": 26669,
"s": 26637,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26725,
"s": 26669,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26780,
"s": 26725,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26822,
"s": 26780,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26864,
"s": 26822,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26895,
"s": 26864,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26934,
"s": 26895,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26963,
"s": 26934,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26985,
"s": 26963,
"text": "Defaultdict in Python"
}
] |
Android - Custom Components
|
Implementing own components in pre built-in components with extending subclass with own defined class
Android offers a great list of pre-built widgets like Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc. which you can use directly in your Android application development, but there may be a situation when you are not satisfied with existing functionality of any of the available widgets. Android provides you with means of creating your own custom components which you can customized to suit your needs.
If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods which will give you precise control over the appearance and function of a screen element.
This tutorial explains you how to create custom Views and use them in your application using simple and easy steps.
Create the following attributes file called attrs.xml in your res/values folder.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TimeView">
<declare-styleable name="TimeView">
<attr name="title" format="string" />
<attr name="setColor" format="boolean"/>
</declare-styleable>
</declare-styleable>
</resources>
Change the layout file used by the activity to the following.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.tutorialspoint7.myapplication.TimeView
android:id="@+id/timeView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:title="my time view"
custom:setColor="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/simple"
android:layout_below="@id/timeView"
android:layout_marginTop="10dp" />
</RelativeLayout>
Create the following java file called timeview for your compound view.
package com.example.tutorialspoint7.myapplication;
/**
* Created by TutorialsPoint7 on 9/14/2016.
*/
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;
public class TimeView extends TextView {
private String titleText;
private boolean color;
public TimeView(Context context) {
super(context);
setTimeView();
}
public TimeView(Context context, AttributeSet attrs) {
super(context, attrs);
// retrieved values correspond to the positions of the attributes
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.TimeView);
int count = typedArray.getIndexCount();
try{
for (int i = 0; i < count; ++i) {
int attr = typedArray.getIndex(i);
// the attr corresponds to the title attribute
if(attr == R.styleable.TimeView_title) {
// set the text from the layout
titleText = typedArray.getString(attr);
setTimeView();
} else if(attr == R.styleable.TimeView_setColor) {
// set the color of the attr "setColor"
color = typedArray.getBoolean(attr, false);
decorateText();
}
}
}
// the recycle() will be executed obligatorily
finally {
// for reuse
typedArray.recycle();
}
}
public TimeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTimeView();
}
private void setTimeView() {
// has the format hour.minuits am/pm
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
String time = dateFormat.format(Calendar.getInstance().getTime());
if(this.titleText != null )
setText(this.titleText+" "+time);
else
setText(time);
}
private void decorateText() {
// when we set setColor attribute to true in the XML layout
if(this.color == true){
// set the characteristics and the color of the shadow
setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));
setBackgroundColor(Color.CYAN);
} else {
setBackgroundColor(Color.RED);
}
}
}
Change your Main activity java file to the following code and run your application.
package com.example.tutorialspoint7.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView simpleText = (TextView) findViewById(R.id.simple);
simpleText.setText("That is a simple TextView");
}
}
The running application should look like the following screen shot.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3709,
"s": 3607,
"text": "Implementing own components in pre built-in components with extending subclass with own defined class"
},
{
"code": null,
"e": 4169,
"s": 3709,
"text": "Android offers a great list of pre-built widgets like Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc. which you can use directly in your Android application development, but there may be a situation when you are not satisfied with existing functionality of any of the available widgets. Android provides you with means of creating your own custom components which you can customized to suit your needs."
},
{
"code": null,
"e": 4405,
"s": 4169,
"text": "If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods which will give you precise control over the appearance and function of a screen element."
},
{
"code": null,
"e": 4521,
"s": 4405,
"text": "This tutorial explains you how to create custom Views and use them in your application using simple and easy steps."
},
{
"code": null,
"e": 4602,
"s": 4521,
"text": "Create the following attributes file called attrs.xml in your res/values folder."
},
{
"code": null,
"e": 4895,
"s": 4602,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <declare-styleable name=\"TimeView\">\n <declare-styleable name=\"TimeView\">\n <attr name=\"title\" format=\"string\" />\n <attr name=\"setColor\" format=\"boolean\"/>\n </declare-styleable>\n </declare-styleable>\n</resources>"
},
{
"code": null,
"e": 4957,
"s": 4895,
"text": "Change the layout file used by the activity to the following."
},
{
"code": null,
"e": 5825,
"s": 4957,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n xmlns:custom=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\" >\n\n <com.example.tutorialspoint7.myapplication.TimeView\n android:id=\"@+id/timeView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:textColor=\"#fff\"\n android:textSize=\"40sp\"\n custom:title=\"my time view\"\n custom:setColor=\"true\" />\n\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/simple\"\n android:layout_below=\"@id/timeView\"\n android:layout_marginTop=\"10dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 5896,
"s": 5825,
"text": "Create the following java file called timeview for your compound view."
},
{
"code": null,
"e": 8340,
"s": 5896,
"text": "package com.example.tutorialspoint7.myapplication;\n/**\n * Created by TutorialsPoint7 on 9/14/2016.\n */\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\n\nimport android.content.Context;\nimport android.content.res.TypedArray;\n\nimport android.graphics.Color;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\npublic class TimeView extends TextView {\n private String titleText;\n private boolean color;\n\n public TimeView(Context context) {\n super(context);\n setTimeView();\n }\n\n public TimeView(Context context, AttributeSet attrs) {\n super(context, attrs);\n // retrieved values correspond to the positions of the attributes\n TypedArray typedArray = context.obtainStyledAttributes(attrs, \n R.styleable.TimeView);\n int count = typedArray.getIndexCount();\n try{\n \n for (int i = 0; i < count; ++i) {\n \n int attr = typedArray.getIndex(i);\n // the attr corresponds to the title attribute\n if(attr == R.styleable.TimeView_title) {\n \n // set the text from the layout\n titleText = typedArray.getString(attr);\n setTimeView();\n } else if(attr == R.styleable.TimeView_setColor) {\n // set the color of the attr \"setColor\"\n color = typedArray.getBoolean(attr, false);\n decorateText();\n }\n }\n }\n \n // the recycle() will be executed obligatorily\n finally {\n // for reuse\n typedArray.recycle();\n }\n }\n\n public TimeView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setTimeView();\n }\n\n private void setTimeView() {\n // has the format hour.minuits am/pm\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"hh.mm aa\");\n String time = dateFormat.format(Calendar.getInstance().getTime());\n \n if(this.titleText != null )\n setText(this.titleText+\" \"+time);\n else\n setText(time);\n }\n\n private void decorateText() {\n // when we set setColor attribute to true in the XML layout\n if(this.color == true){\n // set the characteristics and the color of the shadow\n setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));\n setBackgroundColor(Color.CYAN);\n } else {\n setBackgroundColor(Color.RED);\n }\n }\n}\n"
},
{
"code": null,
"e": 8424,
"s": 8340,
"text": "Change your Main activity java file to the following code and run your application."
},
{
"code": null,
"e": 8896,
"s": 8424,
"text": "package com.example.tutorialspoint7.myapplication;\n\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport android.app.Activity;\n\npublic class MainActivity extends Activity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n TextView simpleText = (TextView) findViewById(R.id.simple);\n simpleText.setText(\"That is a simple TextView\");\n }\n}"
},
{
"code": null,
"e": 8964,
"s": 8896,
"text": "The running application should look like the following screen shot."
},
{
"code": null,
"e": 8999,
"s": 8964,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9011,
"s": 8999,
"text": " Aditya Dua"
},
{
"code": null,
"e": 9046,
"s": 9011,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9060,
"s": 9046,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 9092,
"s": 9060,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9109,
"s": 9092,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9144,
"s": 9109,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9161,
"s": 9144,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9196,
"s": 9161,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9213,
"s": 9196,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9246,
"s": 9213,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9263,
"s": 9246,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9270,
"s": 9263,
"text": " Print"
},
{
"code": null,
"e": 9281,
"s": 9270,
"text": " Add Notes"
}
] |
Converting an image from colour to grayscale using OpenCV
|
In this program, we will change the color scheme of an image from rgb to grayscale
Step 1: Import OpenCV.
Step 2: Read the original image using imread().
Step 3: Convert to grayscale using cv2.cvtcolor() function.
import cv2
image = cv2.imread('colourful.jpg')
cv2.imshow('Original',image)
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale', grayscale)
Original Image:
Grayscale Image:
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "In this program, we will change the color scheme of an image from rgb to grayscale"
},
{
"code": null,
"e": 1276,
"s": 1145,
"text": "Step 1: Import OpenCV.\nStep 2: Read the original image using imread().\nStep 3: Convert to grayscale using cv2.cvtcolor() function."
},
{
"code": null,
"e": 1439,
"s": 1276,
"text": "import cv2\nimage = cv2.imread('colourful.jpg')\ncv2.imshow('Original',image)\ngrayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ncv2.imshow('Grayscale', grayscale)"
},
{
"code": null,
"e": 1455,
"s": 1439,
"text": "Original Image:"
},
{
"code": null,
"e": 1472,
"s": 1455,
"text": "Grayscale Image:"
}
] |
Product of non-repeating (distinct) elements in an Array in C++
|
We are given with an array of repeating or duplicate elements and the task is to find the product of all those elements which are non-repeating or distinct in the given array and display the results.
Input-: arr[] = {2, 1, 1, 2, 3, 4, 5, 5 }
Output-: 120
Explanation-: Since 1, 2 and 5 are repeating more than once so we will take them into
consideration for their first occurrence. So result will be 1 * 2 * 3 * 4 * 5 = 120
Input-: arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4 }
Output-: 32400
Explanation-: Since 10 and 4 are repeating more than once so we will take them into consideration
for their first occurrence. So result will be 1 * 10 * 9 * 4 * 2 * 45 = 32400
Approach used in the below program is as follows β
Input the duplicate elements in an array
For the better approach sort the elements of an array in ascending order such that it would be easy to determine which array element is repeating and donβt consider it for the product
Find all the distinct elements in an array and keep multiplying them by storing the result
Display the final result as the product of all the distinct elements in an array
Start
Step 1-> Declare function to find the product of all the distinct elements in an array
int find_Product(int arr[], int size)
Declare and set int prod = 1
Create variable as unordered_set<int> s
Loop For i = 0 and i < size and i++
IF s.find(arr[i]) = s.end()
Set prod *= arr[i]
Call s.insert(arr[i])
End
End
return prod
Step 2 -: In main()
Declare and set int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 }
Calculate the size of an array int size = sizeof(arr) / sizeof(int)
Call find_Product(arr, size)
Stop
include <bits/stdc++.h>
using namespace std;
//function that calculate the product of non-repeating elements
int find_Product(int arr[], int size) {
int prod = 1;
unordered_set<int> s;
for (int i = 0; i < size; i++) {
if (s.find(arr[i]) == s.end()) {
prod *= arr[i];
s.insert(arr[i]);
}
}
return prod;
}
int main() {
int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 };
int size = sizeof(arr) / sizeof(int);
cout<<"product of all non-repeated elements are : "<<find_Product(arr, size);
return 0;
}
product of all non-repeated elements are : 120
|
[
{
"code": null,
"e": 1262,
"s": 1062,
"text": "We are given with an array of repeating or duplicate elements and the task is to find the product of all those elements which are non-repeating or distinct in the given array and display the results."
},
{
"code": null,
"e": 1730,
"s": 1262,
"text": "Input-: arr[] = {2, 1, 1, 2, 3, 4, 5, 5 }\nOutput-: 120\nExplanation-: Since 1, 2 and 5 are repeating more than once so we will take them into \nconsideration for their first occurrence. So result will be 1 * 2 * 3 * 4 * 5 = 120\nInput-: arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4 }\nOutput-: 32400\nExplanation-: Since 10 and 4 are repeating more than once so we will take them into consideration \nfor their first occurrence. So result will be 1 * 10 * 9 * 4 * 2 * 45 = 32400"
},
{
"code": null,
"e": 1781,
"s": 1730,
"text": "Approach used in the below program is as follows β"
},
{
"code": null,
"e": 1822,
"s": 1781,
"text": "Input the duplicate elements in an array"
},
{
"code": null,
"e": 2006,
"s": 1822,
"text": "For the better approach sort the elements of an array in ascending order such that it would be easy to determine which array element is repeating and donβt consider it for the product"
},
{
"code": null,
"e": 2097,
"s": 2006,
"text": "Find all the distinct elements in an array and keep multiplying them by storing the result"
},
{
"code": null,
"e": 2178,
"s": 2097,
"text": "Display the final result as the product of all the distinct elements in an array"
},
{
"code": null,
"e": 2739,
"s": 2178,
"text": "Start\nStep 1-> Declare function to find the product of all the distinct elements in an array\n int find_Product(int arr[], int size)\n Declare and set int prod = 1\n Create variable as unordered_set<int> s\n Loop For i = 0 and i < size and i++\n IF s.find(arr[i]) = s.end()\n Set prod *= arr[i]\n Call s.insert(arr[i])\n End\n End\n return prod\nStep 2 -: In main()\n Declare and set int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 }\n Calculate the size of an array int size = sizeof(arr) / sizeof(int)\n Call find_Product(arr, size)\nStop"
},
{
"code": null,
"e": 3281,
"s": 2739,
"text": "include <bits/stdc++.h>\nusing namespace std;\n//function that calculate the product of non-repeating elements\nint find_Product(int arr[], int size) {\n int prod = 1;\n unordered_set<int> s;\n for (int i = 0; i < size; i++) {\n if (s.find(arr[i]) == s.end()) {\n prod *= arr[i];\n s.insert(arr[i]);\n }\n }\n return prod;\n}\nint main() {\n int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 };\n int size = sizeof(arr) / sizeof(int);\n cout<<\"product of all non-repeated elements are : \"<<find_Product(arr, size);\n return 0;\n}"
},
{
"code": null,
"e": 3328,
"s": 3281,
"text": "product of all non-repeated elements are : 120"
}
] |
AVRO - Serialization
|
Data is serialized for two objectives β
For persistent storage
For persistent storage
To transport the data over network
To transport the data over network
Serialization is the process of translating data structures or objects state into binary or textual form to transport the data over network or to store on some persisten storage. Once the data is transported over network or retrieved from the persistent storage, it needs to be deserialized again. Serialization is termed as marshalling and deserialization is termed as unmarshalling.
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object is written into a file, it can be read from the file and deserialized. That is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
ObjectInputStream and ObjectOutputStream classes are used to serialize and deserialize an object respectively in Java.
Generally in distributed systems like Hadoop, the concept of serialization is used for Interprocess Communication and Persistent Storage.
To establish the interprocess communication between the nodes connected in a network, RPC technique was used.
To establish the interprocess communication between the nodes connected in a network, RPC technique was used.
RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message.
RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message.
The RPC serialization format is required to be as follows β
Compact β To make the best use of network bandwidth, which is the most scarce resource in a data center.
Fast β Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.
Extensible β Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.
Interoperable β The message format should support the nodes that are written in different languages.
The RPC serialization format is required to be as follows β
Compact β To make the best use of network bandwidth, which is the most scarce resource in a data center.
Compact β To make the best use of network bandwidth, which is the most scarce resource in a data center.
Fast β Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.
Fast β Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.
Extensible β Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.
Extensible β Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.
Interoperable β The message format should support the nodes that are written in different languages.
Interoperable β The message format should support the nodes that are written in different languages.
Persistent Storage is a digital storage facility that does not lose its data with the loss of
power supply. Files, folders, databases are the examples of persistent storage.
This is the interface in Hadoop which provides methods for serialization and deserialization. The following table describes the methods β
void readFields(DataInput in)
This method is used to deserialize the fields of the given object.
void write(DataOutput out)
This method is used to serialize the fields of the given object.
It is the combination of Writable and Comparable interfaces. This interface inherits Writable interface of Hadoop as well as Comparable interface of Java. Therefore it provides methods for data serialization, deserialization, and comparison.
int compareTo(class obj)
This method compares current object with the given object obj.
In addition to these classes, Hadoop supports a number of wrapper classes that implement WritableComparable interface. Each class wraps a Java primitive type. The class hierarchy of Hadoop serialization is given below β
These classes are useful to serialize various types of data in Hadoop. For instance, let us consider the IntWritable class. Let us see how this class is used to serialize and deserialize the data in Hadoop.
This class implements Writable, Comparable, and WritableComparable interfaces. It wraps an integer data type in it. This class provides methods used to serialize and deserialize integer type of data.
int get()
Using this method you can get the integer value present in the current object.
void readFields(DataInput in)
This method is used to deserialize the data in the given DataInput object.
void set(int value)
This method is used to set the value of the current IntWritable object.
void write(DataOutput out)
This method is used to serialize the data in the current object to the given DataOutput object.
The procedure to serialize the integer type of data is discussed below.
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate ByteArrayOutputStream class.
Instantiate ByteArrayOutputStream class.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class.
Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class.
The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array.
The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array.
The following example shows how to serialize data of integer type in Hadoop β
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
public class Serialization {
public byte[] serialize() throws IOException{
//Instantiating the IntWritable object
IntWritable intwritable = new IntWritable(12);
//Instantiating ByteArrayOutputStream object
ByteArrayOutputStream byteoutputStream = new ByteArrayOutputStream();
//Instantiating DataOutputStream object
DataOutputStream dataOutputStream = new
DataOutputStream(byteoutputStream);
//Serializing the data
intwritable.write(dataOutputStream);
//storing the serialized object in bytearray
byte[] byteArray = byteoutputStream.toByteArray();
//Closing the OutputStream
dataOutputStream.close();
return(byteArray);
}
public static void main(String args[]) throws IOException{
Serialization serialization= new Serialization();
serialization.serialize();
System.out.println();
}
}
The procedure to deserialize the integer type of data is discussed below β
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate ByteArrayOutputStream class.
Instantiate ByteArrayOutputStream class.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class.
Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class.
The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class.
The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class.
The following example shows how to deserialize the data of integer type in Hadoop β
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import org.apache.hadoop.io.IntWritable;
public class Deserialization {
public void deserialize(byte[]byteArray) throws Exception{
//Instantiating the IntWritable class
IntWritable intwritable =new IntWritable();
//Instantiating ByteArrayInputStream object
ByteArrayInputStream InputStream = new ByteArrayInputStream(byteArray);
//Instantiating DataInputStream object
DataInputStream datainputstream=new DataInputStream(InputStream);
//deserializing the data in DataInputStream
intwritable.readFields(datainputstream);
//printing the serialized data
System.out.println((intwritable).get());
}
public static void main(String args[]) throws Exception {
Deserialization dese = new Deserialization();
dese.deserialize(new Serialization().serialize());
}
}
Hadoopβs Writable-based serialization is capable of reducing the object-creation overhead by reusing the Writable objects, which is not possible with the Javaβs native serialization framework.
To serialize Hadoop data, there are two ways β
You can use the Writable classes, provided by Hadoopβs native library.
You can use the Writable classes, provided by Hadoopβs native library.
You can also use Sequence Files which store the data in binary format.
You can also use Sequence Files which store the data in binary format.
The main drawback of these two mechanisms is that Writables and SequenceFiles have only a Java API and they cannot be written or read in any other language.
Therefore any of the files created in Hadoop with above two mechanisms cannot be read by any other third language, which makes Hadoop as a limited box. To address this drawback, Doug Cutting created Avro, which is a language independent data structure.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1901,
"s": 1861,
"text": "Data is serialized for two objectives β"
},
{
"code": null,
"e": 1924,
"s": 1901,
"text": "For persistent storage"
},
{
"code": null,
"e": 1947,
"s": 1924,
"text": "For persistent storage"
},
{
"code": null,
"e": 1982,
"s": 1947,
"text": "To transport the data over network"
},
{
"code": null,
"e": 2017,
"s": 1982,
"text": "To transport the data over network"
},
{
"code": null,
"e": 2402,
"s": 2017,
"text": "Serialization is the process of translating data structures or objects state into binary or textual form to transport the data over network or to store on some persisten storage. Once the data is transported over network or retrieved from the persistent storage, it needs to be deserialized again. Serialization is termed as marshalling and deserialization is termed as unmarshalling."
},
{
"code": null,
"e": 2638,
"s": 2402,
"text": "Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object."
},
{
"code": null,
"e": 2860,
"s": 2638,
"text": "After a serialized object is written into a file, it can be read from the file and deserialized. That is, the type information and bytes that represent the object and its data can be used to recreate the object in memory."
},
{
"code": null,
"e": 2979,
"s": 2860,
"text": "ObjectInputStream and ObjectOutputStream classes are used to serialize and deserialize an object respectively in Java."
},
{
"code": null,
"e": 3117,
"s": 2979,
"text": "Generally in distributed systems like Hadoop, the concept of serialization is used for Interprocess Communication and Persistent Storage."
},
{
"code": null,
"e": 3227,
"s": 3117,
"text": "To establish the interprocess communication between the nodes connected in a network, RPC technique was used."
},
{
"code": null,
"e": 3337,
"s": 3227,
"text": "To establish the interprocess communication between the nodes connected in a network, RPC technique was used."
},
{
"code": null,
"e": 3554,
"s": 3337,
"text": "RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message."
},
{
"code": null,
"e": 3771,
"s": 3554,
"text": "RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message."
},
{
"code": null,
"e": 4381,
"s": 3771,
"text": "The RPC serialization format is required to be as follows β\n\nCompact β To make the best use of network bandwidth, which is the most scarce resource in a data center.\nFast β Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.\nExtensible β Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.\nInteroperable β The message format should support the nodes that are written in different languages.\n\n"
},
{
"code": null,
"e": 4441,
"s": 4381,
"text": "The RPC serialization format is required to be as follows β"
},
{
"code": null,
"e": 4546,
"s": 4441,
"text": "Compact β To make the best use of network bandwidth, which is the most scarce resource in a data center."
},
{
"code": null,
"e": 4651,
"s": 4546,
"text": "Compact β To make the best use of network bandwidth, which is the most scarce resource in a data center."
},
{
"code": null,
"e": 4823,
"s": 4651,
"text": "Fast β Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead."
},
{
"code": null,
"e": 4995,
"s": 4823,
"text": "Fast β Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead."
},
{
"code": null,
"e": 5164,
"s": 4995,
"text": "Extensible β Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers."
},
{
"code": null,
"e": 5333,
"s": 5164,
"text": "Extensible β Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers."
},
{
"code": null,
"e": 5434,
"s": 5333,
"text": "Interoperable β The message format should support the nodes that are written in different languages."
},
{
"code": null,
"e": 5535,
"s": 5434,
"text": "Interoperable β The message format should support the nodes that are written in different languages."
},
{
"code": null,
"e": 5709,
"s": 5535,
"text": "Persistent Storage is a digital storage facility that does not lose its data with the loss of\npower supply. Files, folders, databases are the examples of persistent storage."
},
{
"code": null,
"e": 5847,
"s": 5709,
"text": "This is the interface in Hadoop which provides methods for serialization and deserialization. The following table describes the methods β"
},
{
"code": null,
"e": 5877,
"s": 5847,
"text": "void readFields(DataInput in)"
},
{
"code": null,
"e": 5944,
"s": 5877,
"text": "This method is used to deserialize the fields of the given object."
},
{
"code": null,
"e": 5971,
"s": 5944,
"text": "void write(DataOutput out)"
},
{
"code": null,
"e": 6036,
"s": 5971,
"text": "This method is used to serialize the fields of the given object."
},
{
"code": null,
"e": 6278,
"s": 6036,
"text": "It is the combination of Writable and Comparable interfaces. This interface inherits Writable interface of Hadoop as well as Comparable interface of Java. Therefore it provides methods for data serialization, deserialization, and comparison."
},
{
"code": null,
"e": 6303,
"s": 6278,
"text": "int compareTo(class obj)"
},
{
"code": null,
"e": 6366,
"s": 6303,
"text": "This method compares current object with the given object obj."
},
{
"code": null,
"e": 6586,
"s": 6366,
"text": "In addition to these classes, Hadoop supports a number of wrapper classes that implement WritableComparable interface. Each class wraps a Java primitive type. The class hierarchy of Hadoop serialization is given below β"
},
{
"code": null,
"e": 6793,
"s": 6586,
"text": "These classes are useful to serialize various types of data in Hadoop. For instance, let us consider the IntWritable class. Let us see how this class is used to serialize and deserialize the data in Hadoop."
},
{
"code": null,
"e": 6993,
"s": 6793,
"text": "This class implements Writable, Comparable, and WritableComparable interfaces. It wraps an integer data type in it. This class provides methods used to serialize and deserialize integer type of data."
},
{
"code": null,
"e": 7003,
"s": 6993,
"text": "int get()"
},
{
"code": null,
"e": 7082,
"s": 7003,
"text": "Using this method you can get the integer value present in the current object."
},
{
"code": null,
"e": 7112,
"s": 7082,
"text": "void readFields(DataInput in)"
},
{
"code": null,
"e": 7187,
"s": 7112,
"text": "This method is used to deserialize the data in the given DataInput object."
},
{
"code": null,
"e": 7207,
"s": 7187,
"text": "void set(int value)"
},
{
"code": null,
"e": 7279,
"s": 7207,
"text": "This method is used to set the value of the current IntWritable object."
},
{
"code": null,
"e": 7306,
"s": 7279,
"text": "void write(DataOutput out)"
},
{
"code": null,
"e": 7402,
"s": 7306,
"text": "This method is used to serialize the data in the current object to the given DataOutput object."
},
{
"code": null,
"e": 7474,
"s": 7402,
"text": "The procedure to serialize the integer type of data is discussed below."
},
{
"code": null,
"e": 7540,
"s": 7474,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 7606,
"s": 7540,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 7647,
"s": 7606,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 7688,
"s": 7647,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 7781,
"s": 7688,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 7874,
"s": 7781,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 8001,
"s": 7874,
"text": "Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class."
},
{
"code": null,
"e": 8128,
"s": 8001,
"text": "Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class."
},
{
"code": null,
"e": 8323,
"s": 8128,
"text": "The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array."
},
{
"code": null,
"e": 8518,
"s": 8323,
"text": "The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array."
},
{
"code": null,
"e": 8596,
"s": 8518,
"text": "The following example shows how to serialize data of integer type in Hadoop β"
},
{
"code": null,
"e": 9662,
"s": 8596,
"text": "import java.io.ByteArrayOutputStream;\nimport java.io.DataOutputStream;\n\nimport java.io.IOException;\n\nimport org.apache.hadoop.io.IntWritable;\n\npublic class Serialization {\n public byte[] serialize() throws IOException{\n\t\t\n //Instantiating the IntWritable object\n IntWritable intwritable = new IntWritable(12);\n \n //Instantiating ByteArrayOutputStream object\n ByteArrayOutputStream byteoutputStream = new ByteArrayOutputStream();\n \n //Instantiating DataOutputStream object\n DataOutputStream dataOutputStream = new\n DataOutputStream(byteoutputStream);\n \n //Serializing the data\n intwritable.write(dataOutputStream);\n \n //storing the serialized object in bytearray\n byte[] byteArray = byteoutputStream.toByteArray();\n \n //Closing the OutputStream\n dataOutputStream.close();\n return(byteArray);\n }\n\t\n public static void main(String args[]) throws IOException{\n Serialization serialization= new Serialization();\n serialization.serialize();\n System.out.println();\n }\n}"
},
{
"code": null,
"e": 9737,
"s": 9662,
"text": "The procedure to deserialize the integer type of data is discussed below β"
},
{
"code": null,
"e": 9803,
"s": 9737,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 9869,
"s": 9803,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 9910,
"s": 9869,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 9951,
"s": 9910,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 10044,
"s": 9951,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 10137,
"s": 10044,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 10239,
"s": 10137,
"text": "Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class."
},
{
"code": null,
"e": 10341,
"s": 10239,
"text": "Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class."
},
{
"code": null,
"e": 10475,
"s": 10341,
"text": "The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class."
},
{
"code": null,
"e": 10609,
"s": 10475,
"text": "The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class."
},
{
"code": null,
"e": 10693,
"s": 10609,
"text": "The following example shows how to deserialize the data of integer type in Hadoop β"
},
{
"code": null,
"e": 11637,
"s": 10693,
"text": "import java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\n\nimport org.apache.hadoop.io.IntWritable;\n\npublic class Deserialization {\n\n public void deserialize(byte[]byteArray) throws Exception{\n \n //Instantiating the IntWritable class\n IntWritable intwritable =new IntWritable();\n \n //Instantiating ByteArrayInputStream object\n ByteArrayInputStream InputStream = new ByteArrayInputStream(byteArray);\n \n //Instantiating DataInputStream object\n DataInputStream datainputstream=new DataInputStream(InputStream);\n \n //deserializing the data in DataInputStream\n intwritable.readFields(datainputstream);\n \n //printing the serialized data\n System.out.println((intwritable).get());\n }\n \n public static void main(String args[]) throws Exception {\n Deserialization dese = new Deserialization();\n dese.deserialize(new Serialization().serialize());\n }\n}"
},
{
"code": null,
"e": 11830,
"s": 11637,
"text": "Hadoopβs Writable-based serialization is capable of reducing the object-creation overhead by reusing the Writable objects, which is not possible with the Javaβs native serialization framework."
},
{
"code": null,
"e": 11877,
"s": 11830,
"text": "To serialize Hadoop data, there are two ways β"
},
{
"code": null,
"e": 11948,
"s": 11877,
"text": "You can use the Writable classes, provided by Hadoopβs native library."
},
{
"code": null,
"e": 12019,
"s": 11948,
"text": "You can use the Writable classes, provided by Hadoopβs native library."
},
{
"code": null,
"e": 12090,
"s": 12019,
"text": "You can also use Sequence Files which store the data in binary format."
},
{
"code": null,
"e": 12161,
"s": 12090,
"text": "You can also use Sequence Files which store the data in binary format."
},
{
"code": null,
"e": 12318,
"s": 12161,
"text": "The main drawback of these two mechanisms is that Writables and SequenceFiles have only a Java API and they cannot be written or read in any other language."
},
{
"code": null,
"e": 12571,
"s": 12318,
"text": "Therefore any of the files created in Hadoop with above two mechanisms cannot be read by any other third language, which makes Hadoop as a limited box. To address this drawback, Doug Cutting created Avro, which is a language independent data structure."
},
{
"code": null,
"e": 12578,
"s": 12571,
"text": " Print"
},
{
"code": null,
"e": 12589,
"s": 12578,
"text": " Add Notes"
}
] |
C | Operators | Question 5 - GeeksforGeeks
|
16 Sep, 2021
#include <stdio.h>int main(){ int i = 3; printf("%d", (++i)++); return 0;}
What is the output of the above program?(A) 3(B) 4(C) 5(D) Compile-time errorAnswer: (D)Explanation: In C, prefix and postfix operators need l-value to perform operation and return r-value. The expression (++i)++ when executed increments the value of variable i(i is a l-value) and returns r-value. The compiler generates the error(l-value required) when it tries to post-increment the value of a r-value.
ankitshaw1112
C-Operators
Operators
C Language
C Quiz
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Function Pointer in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
|
[
{
"code": null,
"e": 26300,
"s": 26272,
"text": "\n16 Sep, 2021"
},
{
"code": "#include <stdio.h>int main(){ int i = 3; printf(\"%d\", (++i)++); return 0;}",
"e": 26384,
"s": 26300,
"text": null
},
{
"code": null,
"e": 26790,
"s": 26384,
"text": "What is the output of the above program?(A) 3(B) 4(C) 5(D) Compile-time errorAnswer: (D)Explanation: In C, prefix and postfix operators need l-value to perform operation and return r-value. The expression (++i)++ when executed increments the value of variable i(i is a l-value) and returns r-value. The compiler generates the error(l-value required) when it tries to post-increment the value of a r-value."
},
{
"code": null,
"e": 26804,
"s": 26790,
"text": "ankitshaw1112"
},
{
"code": null,
"e": 26816,
"s": 26804,
"text": "C-Operators"
},
{
"code": null,
"e": 26826,
"s": 26816,
"text": "Operators"
},
{
"code": null,
"e": 26837,
"s": 26826,
"text": "C Language"
},
{
"code": null,
"e": 26844,
"s": 26837,
"text": "C Quiz"
},
{
"code": null,
"e": 26854,
"s": 26844,
"text": "Operators"
},
{
"code": null,
"e": 26952,
"s": 26854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26987,
"s": 26952,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27033,
"s": 26987,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27045,
"s": 27033,
"text": "fork() in C"
},
{
"code": null,
"e": 27085,
"s": 27045,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27107,
"s": 27085,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27149,
"s": 27107,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 27192,
"s": 27149,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 27223,
"s": 27192,
"text": "C | File Handling | Question 1"
},
{
"code": null,
"e": 27247,
"s": 27223,
"text": "C | Arrays | Question 7"
}
] |
Deep Learning for Diagnosis of Skin Images with fastai | by Aldo von Wangenheim | Towards Data Science
|
We show how to use fast.ai to solve the 2018 Skin Lesion Analysis Towards Melanoma Detection challenge and automatically identify seven kinds of skin pathologies.
Posted by Aldo von Wangenheim β aldo.vw@ufsc.br
This is based upon the following material:
TowardsDataScience::Classifying Skin Lesions with Convolutional Neural Networks β A guide and introduction to deep learning in medicine by Aryan MisraTschandl, Philipp, 2018, βThe HAM10000 dataset, a large collection of multi-source dermatoscopic images of common pigmented skin lesionsβ, https://doi.org/10.7910/DVN/DBW86T, Harvard Dataverse [arXiv preprint version: arXiv:1803.10417 [cs.CV]]Tools for workup of the HAM10000 dataset β GitHub. This repository gives access to the tools created and used for assembling the training dataset.
TowardsDataScience::Classifying Skin Lesions with Convolutional Neural Networks β A guide and introduction to deep learning in medicine by Aryan Misra
Tschandl, Philipp, 2018, βThe HAM10000 dataset, a large collection of multi-source dermatoscopic images of common pigmented skin lesionsβ, https://doi.org/10.7910/DVN/DBW86T, Harvard Dataverse [arXiv preprint version: arXiv:1803.10417 [cs.CV]]
Tools for workup of the HAM10000 dataset β GitHub. This repository gives access to the tools created and used for assembling the training dataset.
The HAM10000 dataset (Human Against Machine with 10000 training images) served as the training set for the ISIC 2018 challenge (Task 3). The official validation- and test-sets of this challenge are available, without ground-truth labels, through the challenge website https://challenge2018.isic-archive.com/. The ISIC-Archive also provides a βLive challengeβ submission site for continuous evaluation of automated classifiers on the official validation- and test-set.
The HAM10000 dataset is also on Kaggle. If you want to compare your results with Kaggle kernels, look here: https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000/kernels Last time I looked (June 2019), there were 55 different solutions posted there.
The notebook with the code shown in this posting (and a few additional cells) is here.
The images look like this:
This dataset contains pigmented skin lesions acquired through standard dermoscopy. These are lesions where the tissue produces melanin, the natural pigment of the human skin, and that are dark. Not all kinds of lesions initially investigated and triaged through dermoscopy are necessarily pigmented lesions. This means that, in a real world situation, a GP or a nurse examining a patient through dermoscopy (or a patient performing self-examination) with the intent to submit these images to a dermatologist for an initial triage, would possibly encounter other lesions than the ones depicted in this dataset here (look at Is there an ISIC 2019? below).
The lesion classes in the HAM10000 Dataset are:
nv: Melanocytic nevi β benign neoplasms of melanocytes [6705 images]mel: Melanoma β a malignant neoplasm derived from melanocytes [1113 images]bkl: Benign keratosis β a generic class that includes seborrheic keratoses, solar lentigo and lichen-planus like keratoses [1099 images];bcc: Basal cell carcinoma β a common variant of epithelial skin cancer that rarely metastasizes but grows destructively if untreated (bccs do not necessarily produce pigmented lesions) [514 images];akiec: Actinic Keratoses and intraepithelial Carcinoma β common non-invasive, variants of squamous cell carcinoma that can be treated locally without surgery [327 images];vasc: Vascular skin lesions ranging from cherry angiomas to angiokeratomas and pyogenic granulomas [142 images];df: Dermatofibroma β a benign skin lesion regarded as either a benign proliferation or an inflammatory reaction to minimal trauma [115 images].
nv: Melanocytic nevi β benign neoplasms of melanocytes [6705 images]
mel: Melanoma β a malignant neoplasm derived from melanocytes [1113 images]
bkl: Benign keratosis β a generic class that includes seborrheic keratoses, solar lentigo and lichen-planus like keratoses [1099 images];
bcc: Basal cell carcinoma β a common variant of epithelial skin cancer that rarely metastasizes but grows destructively if untreated (bccs do not necessarily produce pigmented lesions) [514 images];
akiec: Actinic Keratoses and intraepithelial Carcinoma β common non-invasive, variants of squamous cell carcinoma that can be treated locally without surgery [327 images];
vasc: Vascular skin lesions ranging from cherry angiomas to angiokeratomas and pyogenic granulomas [142 images];
df: Dermatofibroma β a benign skin lesion regarded as either a benign proliferation or an inflammatory reaction to minimal trauma [115 images].
For a more detailed description of each class, look at the Kaggle kernel: Skin Lesion Analyzer + Tensorflow.js Web App β Python notebook using data from Skin Cancer MNIST: HAM10000 and also the paper by Philipp Tschandl, above.
Dermoscopic images alone do not provide enough for data for a dermatological diagnosis or a reliable remote patient triage in a Teledermatology setting. Dermoscopic images lack context. In order to provide context, you will need to perform an image acquisition protocol that includes panoramic whole body images of the patient and also approximation images of each lesion, which are taken with a ruler or other frame of reference visible in the image, in order to provide contextual information about the size of the lesion. Approximation images taken with the ruler are also important for a patient already in treatment in order to allow the accompanying physician to follow the evolution of the lesion. Both panoramic and approximation images, in order to be acquired correctly, need to be performed following a protocol that guarantees that the images are in focus, taken from the correct distance, and with the correct illumination. There are also details that cannot be reliably detected through the standard dermoscopy technique presently being employed and, in several cases, a confirmation biopsy will be necessary.
If you are interested in knowing more about Teledermatology examination acquisition protocols, look here:
Aldo von Wangenheim and Daniel Holthausen Nunes. Creating a Web Infrastructure for the Support of Clinical Protocols and Clinical Management: An Example in Teledermatology. Telemedicine and e-Health. Online Ahead of Print:November 30, 2018. http://doi.org/10.1089/tmj.2018.0197. Thereβs also a preprint available on ResearchGate.
The contact dermoscope used nowadays is the result of an international effort for the standardization of this examination performed during the first half of the 1990s, led by a group of researchers at the University of Munich in Germany. This equipment uses a single lens with a 10x magnification and internal illumination by LEDs. The examination is performed with mineral oil, which is applied on the surface of the lesion before the dermoscope is applied on the lesion and a photograph is taken.
The choosing of a monocular 10x magnification lens as a standard allowed for the development of very small devices that soon became very popular. Analog dermoscopes can be carried in a breast pocket and digital ones can be easily developed as small USB devices or as adapters for digital cameras and smartphones.
The drawback of this standard is that the 10x magnification is not enough for the reliable detection of some pathologies, such as the basal cell carcinoma, which is the most common form of skin cancer. This form of neoplasm is characterized by vascular alterations, called arboriform vascularizations, which cannot be reliably observed with a monocular lens employing a 10x magnification: A confirmation biopsy will always be necessary in order to provide the definitive diagnosis. Reliable detection needs higher magnification and binocular optics [1][2].
Until the 1990s there were other types of dermoscopes being developed, which could provide better imaging quality, but that were larger and not so easy to operate, such as the 50x binocular stereoscopic contact dermoscope. This equipment is better suited for the visual early detection of pathologies such as the basal cell carcinoma [1][2]. The practicality, popularization and standardization of the 10x contact monocular dermoscope, however, stopped these other lines of research.
The ISIC β The International Skin Imaging Collaboration has corrected the lack of some dermatological diagnostic categories in the HAM10000 Dataset publishing a new dataset in the ISIC 2019 challenge: Skin Lesion Analysis Towards Melanoma Detection. The 2019 dataset, released on May 3, 2019, now contains nine different diagnostic categories and 25,331 images:
MelanomaMelanocytic nevusBasal cell carcinomaActinic keratosisBenign keratosis (solar lentigo / seborrheic keratosis / lichen planus-like keratosis)DermatofibromaVascular lesionSquamous cell carcinomaNone of the others
Melanoma
Melanocytic nevus
Basal cell carcinoma
Actinic keratosis
Benign keratosis (solar lentigo / seborrheic keratosis / lichen planus-like keratosis)
Dermatofibroma
Vascular lesion
Squamous cell carcinoma
None of the others
At the moment of the writing of this posting, test metadata for this new dataset are not yet available. They are announced to be released on August 9, 2019.
The ISIC has, up to now, sponsored four challenges in Image Analysis: ISIC 2016 through ISIC 2019, allways with the theme βSkin Lesion Analysis Towards Melanoma Detectionβ. The four challenges can be found at the ISIC Archive.
Letβs start working on the dataset of the 2018 challenge.
Do what is in this section here below once each time you run this notebook...
%reload_ext autoreload%autoreload 2%matplotlib inline
Only to be sure, look at which CUDA driver and which GPU Colab has made available for you. The GPU will typically be either:
a K80 with 11 GB RAM or (if your really lucky)
a Tesla T4 with 14 GB RAM
If Googleβs servers are crowded, youβll eventually have access to only part of a GPU. If your GPU is shared with another Colab notebook, youβll see a smaller amount of memory made available for you.
Tip: Avoid peak times of the US west coast. I live at GMT-3 and we are two hours ahead of the US east coast, so I always try to perform heavy processing in the morning hours.
!/opt/bin/nvidia-smi!nvcc --version
When I started running the experiments described here, I was lucky: I had a whole T4 with 15079 MB RAM! My output looked like this:
Thu May 2 07:36:26 2019 +-----------------------------------------------------------------------------+| NVIDIA-SMI 410.79 Driver Version: 410.79 CUDA Version: 10.0 ||-------------------------------+----------------------+----------------------+| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC || Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. ||===============================+======================+======================|| 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 || N/A 63C P8 17W / 70W | 0MiB / 15079MiB | 0% Default |+-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+| Processes: GPU Memory || GPU PID Type Process name Usage ||=============================================================================|| No running processes found |+-----------------------------------------------------------------------------+nvcc: NVIDIA (R) Cuda compiler driverCopyright (c) 2005-2018 NVIDIA CorporationBuilt on Sat_Aug_25_21:08:01_CDT_2018Cuda compilation tools, release 10.0, V10.0.130
Here we import all the necessary packages. We are going to work with the fastai V1 library which sits on top of Pytorch 1.0. The fastai library provides many useful functions that enable us to quickly and easily build neural networks and train our models.
from fastai.vision import *from fastai.metrics import error_ratefrom fastai.callbacks import SaveModelCallback# Imports for diverse utilitiesfrom shutil import copyfileimport matplotlib.pyplot as pltimport operatorfrom PIL import Imagefrom sys import intern # For the symbol definitions
# Export network for deployment and create a copydef exportStageTo(learn, path): learn.export() # FacΜ§a backup diferenciado copyfile(path/'export.pkl', path/'export-malaria.pkl') #exportStage1(learn, path)# Restoration of a deployment model, for example in order to conitnue fine-tuningdef restoreStageFrom(path): # Restore a backup copyfile(path/'export-malaria.pkl', path/'export.pkl') return load_learner(path) #learn = restoreStage1From(path)
We will download the Kaggle version of this dataset because Google Colab has the Kaggle API preinstalled and it is all organized in one .zip file. In order to download from Kaggle you need:
an account at Kaggle
to install your Kaggle credentials (a .json file) on Colab
To see how to do this, first look at this tutorial and the Kaggle API instructions and generate and upload your credentials to Colab:
TowardsDataScience::Setting Up Kaggle in Google Colab β A Simple Tutorial for the Total Newbie by Anne Bonner
https://github.com/Kaggle/kaggle-api#api-credentials
Run the cell below. It will Create a Folder for your Credentials for the Kaggle API and install your credentials in Colab:
!mkdir .kaggle!mv kaggle.json .kaggle!chmod 600 /content/.kaggle/kaggle.json!cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json!chmod 600 ~/.kaggle/kaggle.json!kaggle config set -n path -v{/content}
For some arcane reason this script sometimes does not work. It seems to have to do with the form Colab names the home folder. If you experience an error message, simply execute it again. The final output should look like this:
- path is now set to: {/content}
Create a βdataβ folder and download the dermatoscopy images into it
!mkdir data!kaggle datasets download kmader/skin-cancer-mnist-ham10000 -p data
This will produce the following output:
Downloading skin-cancer-mnist-ham10000.zip to data100% 2.61G/2.62G [00:52<00:00, 42.3MB/s]100% 2.62G/2.62G [00:52<00:00, 53.4MB/s]
Unzip the whole zipfile into /content/data and then quietly (-q) unzip the image files (you donβt want to verbosely unzip more than 10k images!). We will use the β override option (-o) in order to allow quiet overriding of files that could have been created in some interrupted prior attempt youβve made.
# Unzip the whole zipfile into /content/data!unzip -o data/skin-cancer-mnist-ham10000.zip -d data# Quietly unzip the image files!unzip -o -q data/HAM10000_images_part_1.zip -d data!unzip -o -q data/HAM10000_images_part_2.zip -d data# Tell me how many files I unzipped///!echo files in /content/data: `ls data | wc -l`
If you have a files count of 10,023 files, youβve done it right!
Archive: data/skin-cancer-mnist-ham10000.zip inflating: data/hmnist_28_28_RGB.csv inflating: data/HAM10000_metadata.csv inflating: data/HAM10000_images_part_1.zip inflating: data/hmnist_28_28_L.csv inflating: data/hmnist_8_8_L.csv inflating: data/HAM10000_images_part_2.zip inflating: data/hmnist_8_8_RGB.csv files in /content/data: 10023
Now weβll prepare our data for processing with fast.ai.
In our previous medical image classification posting (Deep Learning and Medical Image Analysis for Malaria Detection with fastai) we have sorted the image categories into folders, one folder for each class.
Here we have all images stored in one folder and the metadata stored in a spreadsheet we will read with the fast.ai ImageDataBunch.from_csv() method from the fast.ai Data Block API.
The HAM10000 dataset does not provide the images sorted into folders according to their classes. Instead, all images are in one folder and a spreadsheet with several metadata for each of the images is provided. In this tutorial we will be reading the class of each image from this .csv spreadsheet, instead of organizing the image files into folders where the name of the folder is the class to which the images belong. fast.ai also provides ready-to-use methods for interpreting spreadsheets and extracting the classification data for the images. In this posting we will be learning how to make use of these methods.
For this purpose we will be using the data block API from fast.ai. Thereβs a very good explanation how it works in the following posting:
Medium::Using the fastai Data Block API by Tom McKenzie
In the original tutorial bove, which employs Keras, thereβs a routine to create training, validation and test folders from the data. With fast.ai it is not necessary: if you only have a βtrainβ folder, you can split it while creating the DataBunch by simply passing a few parameters...
With fast.ai we also can easily work with resolutions that are different from the original ImageNet resolutions employed to pre-train the networks we will be using. In the tutorial listed above the author reduced the dataset image resolution to 224x224, in order to use the Keras MobileNet model. We will be employing a 448x448 resolution:
bs = 64 # Batch size, 64 for medium images on a T4 GPU...size = 448 # Image size, 448x448 is double than the orignal # ImageNetpath = Path("./data") # The path to the 'train' folder you created...# Limit your augmentations: it's medical data! You do not want to phantasize data...# Warping, for example, will let your images badly distorted, so don't do it!# This dataset is big, so don't rotate the images either. Lets stick to flipping...tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_rotate=None, max_warp=None, max_zoom=1.0)# Create the DataBunch!# Remember that you'll have images that are bigger than 128x128 and images that are smaller, # so squish them all in order to occupy exactly 128x128 pixels...data = ImageDataBunch.from_csv('data', csv_labels='HAM10000_metadata.csv', suffix='.jpg', fn_col=1, label_col=2, ds_tfms=tfms, valid_pct = 0.2,size=size, bs=bs)print('Transforms = ', len(tfms))# Save the DataBunch in case the training goes south... so you won't have to regenerate it..# Remember: this DataBunch is tied to the batch size you selected. data.save('imageDataBunch-bs-'+str(bs)+'-size-'+str(size)+'.pkl')# Show the statistics of the Bunch...print(data.classes)data
This will produce the following output:
Transforms = 2['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']ImageDataBunch;Train: LabelList (8012 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListbkl,bkl,bkl,bkl,bklPath: data;Valid: LabelList (2003 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListbkl,nv,nv,nv,nvPath: data;Test: None
data.show_batch(rows=5, figsize=(15,15))
If you do not know what model to use, it is a good choice to start with a Residual Network with 34 layers. Powerful, but not too small and not too big...
In the tutorial listed above the author used a MobileNet implemented in Keras and the networkβs original image resolution of 224x224. In fast.ai the ResNet easily adapts to work with the resolution of 448x448 of our DataBunch.
Now we will start training our model. We will use a convolutional neural network backbone and a fully connected head with a single hidden layer as a classifier. Donβt know what these things mean? Not to worry, we will dive deeper in the coming lessons. For the moment you need to know that we are building a model which will take images as input and will output the predicted probability for each of the categories (in this case, it will have 37 outputs).
We will be using twodifferent metrics to look at our training success:
accuracy: validation accuracy
error_rate: validation error rate
If you want more information, look at https://docs.fast.ai/metrics.html.
learn = cnn_learner(data, models.resnet34, metrics=[accuracy, error_rate, dice(iou=True), fbeta])learn.model
Just pass the data variable, which contains the DataBunch instance, to the cnn_learner() function and fast.ai will automatically adapt the input layer of the new network to the higher image resolution. The model will look like this:
Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (4): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) (1): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) (2): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (5): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (downsample): Sequential( (0): Conv2d(64, 128, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) )......... and so on...
We will employ the fit1cycle method developed by Leslie N. Smith β see below for details:
https://docs.fast.ai/callbacks.one_cycle.html
A disciplined approach to neural network hyper-parameters: Part 1 β learning rate, batch size, momentum, and weight decay β https://arxiv.org/abs/1803.09820
Super-Convergence: Very Fast Training of Residual Networks Using Large Learning Rates β https://arxiv.org/abs/1708.07120
There is also very interesting article from Nachiket Tanksale called Finding Good Learning Rate and The One Cycle Policy where cyclic learning rates and momentum are discussed
Since this method is fast, we will employ only 10 epochs in this first Transfer Learning stage
If you want to to know more about the new learning API in the fast.ai library, look at this notebook prepared by Sylvain Gugger.
We will also save the network each epoch, if the performance gets better: https://docs.fast.ai/callbacks.html#SaveModelCallback
learn.fit_one_cycle(10, callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma-1')])# Salve a rede (necessita regerar o databunch caso a gente continue)learn.save('derma-stage-1')# FacΜ§a o deploy desta rede para podermos usar offline depois para fazer testesexportStageTo(learn, path)
Letβs see what results we have got.
We will first see which were the categories that the model most confused with one another. We will try to see if what the model predicted was reasonable or not. In this case the mistakes look reasonable (none of the mistakes seems obviously naive). This is an indicator that our classifier is working correctly.
Furthermore, when we plot the confusion matrix, we can see that the distribution is heavily skewed: the model makes the same mistakes over and over again but it rarely confuses other categories. This suggests that it just finds it difficult to distinguish some specific categories between each other; this is normal behaviour.
Letβs generate a ClassificationInterpretation and look at some results, the confusion matrix and the loss curves.
interp = ClassificationInterpretation.from_learner(learn)losses,idxs = interp.top_losses()len(data.valid_ds)==len(losses)==len(idxs)
Look at your worst results, first without using a heatmap:
interp.plot_top_losses(9, figsize=(20,11), heatmap=False)
Now, do the same, but highlight the images with a heatmap in order to see which parts of each image induced the wrong classification:
interp.plot_top_losses(9, figsize=(20,11), heatmap=True)
Here we have seven classes and it makes a lot of sense to look at the confusion matrix. Besides, it makes beautiful pictures...
interp.plot_confusion_matrix(figsize=(5,5), dpi=100)
What we can see here is that:
nevi are far the most common occurrences. One can think of reducing the instances of nevi in the training set in order not to skew the results;
there are several benign keratoses (bkl) wrongly classified. This is probably because bkl in this dataset is a generic class that includes seborrheic keratoses, solar lentigo and lichen-planus like keratoses, which are dermatoses that, even if related, look really very different;
there are also several melanomas (mel) that were misclassified. This was a surprise. I expected the network to perform better here.
If you are confused by confusion matrices, look here:
Taking the Confusion Out of Confusion Matrices by Allison Ragan
Simplifying the Confusion Matrix by Madhav Mishra
Plot your losses,in order to see the learning curve:
learn.recorder.plot_losses()
This result is really good. The network oscillated a bit but learned steadilly. Now letβs try to fine-tune the network.
First unfreeze the network and try to find a good range of learning rates for this particular network.
The method learn.lr_find() helps you find an optimal learning rate. It uses the technique developed in the 2015 paper Cyclical Learning Rates for Training Neural Networks (http://arxiv.org/abs/1506.01186), where we simply keep increasing the learning rate from a very small value, until the loss starts decreasing.
If you want to know more about finding the best learning rates, look here:
TowardsDataScience::Speeding up Neural Net Training with a LR-Finder β Finding good initial learning rate for your network by Faizan Ahemad
Letβs do it:
# Unfreeze the networklearn.unfreeze()# Find optimum learning rateslearn.lr_find()# Include suggestion=True in order to obtain a suggestion on where to look...learn.recorder.plot(suggestion=True)
Letβs fine tune the ResNet34. Weβll employ 30 epochs to be sure. The learning rate finder identified 1e-5 as a βsecureβ learning rate. So we will define a range of learning rates using the rule of thumb: ending at the βsecureβ rate 1e-5 and starting at a rate that is one order of magnitude higher: max_lr=slice(1e-4,1e-5).
# Unfreeze the networklearn.unfreeze()learn.fit_one_cycle(30, max_lr=slice(1e-4,1e-5), callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma')])# Agora, salve como estaΜgio 2...learn.save('derma-stage-2')# Deploy definitivoexportStageTo(learn, path)
So we achieved 93% accuracy with our first run. This is very good! The accuracy achieved in the tutorial and kernel above is respectively 85% and 86%.
Now letβs look at our statistics.:
interp = ClassificationInterpretation.from_learner(learn)losses,idxs = interp.top_losses()# Test to see if there's not anything missing (must return True)len(data.valid_ds)==len(losses)==len(idxs)
If this returns True, then plot the confusion matrix for the fine-tuned network:
interp.plot_confusion_matrix(figsize=(5,5), dpi=100)
The melanoma predictions look much better in this matrix! Letβs look at the training curves:
learn.recorder.plot_losses()
We can see that both, train and validation curve oscillated. The training curve seems to arrive at a plateau and it is separating from the validation curve, which is decreasing much slower. This indicates that we probably are moving towards an overfitting of the network. It would be indicated to stop here.
In the notebook we made available on Colab, we trained the network for another 30 epochs, only to be sure. It actually becomes worse, probably due to overfitting. So stopping here is a good choice for the ResNet34.
With the ResNet34 with achieved 92.9% accuracy. Letβs see if with a larger network we can perform better. We will create the DataBunch again, this time with a smaller batch size in order not to overload the GPU memory...
bs = 28 # Batch size, 28 for medium images on a T4 GPU and ResNet50...size = 448 # Image size, 448x448 is double than the orignal # ImageNet size of the pre-trained ResNet we'll be using, # should be easy to train...path = Path("./data") # The path to the 'train' folder you created...# Limit your augmentations: it's medical data! You do not want to phantasize data...# Warping, for example, will let your images badly distorted, so don't do it!# This dataset is big, so don't rotate the images either. Lets stick to flipping...tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_rotate=None, max_warp=None, max_zoom=1.0)# Create the DataBunch!# Remember that you'll have images that are bigger than 128x128 and images that are smaller, # so squish them all in order to occupy exactly 128x128 pixels...data = ImageDataBunch.from_csv('data', csv_labels='HAM10000_metadata.csv', suffix='.jpg', fn_col=1, label_col=2, ds_tfms=tfms, valid_pct = 0.2,size=size, bs=bs)print('Transforms = ', len(tfms))# Save the DataBunch in case the training goes south... so you won't have to regenerate it..# Remember: this DataBunch is tied to the batch size you selected. data.save('imageDataBunch-bs-'+str(bs)+'-size-'+str(size)+'.pkl')# Show the statistics of the Bunch...print(data.classes)data
The output now should look like this:
Transforms = 2['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']ImageDataBunch;Train: LabelList (8012 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListbkl,bkl,bkl,bkl,bklPath: data;Valid: LabelList (2003 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListnv,nv,nv,mel,bklPath: data;Test: None
Now create a ResNet50:
learn50 = cnn_learner(data, models.resnet50, metrics=[accuracy, error_rate])learn50.model
Observe that we included accuracy in the metrics, so we will not need to manually perform the calculation based on the error rate. The model should look like:
Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (4): Sequential( (0): Bottleneck( (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ).........(1): Sequential( (0): AdaptiveConcatPool2d( (ap): AdaptiveAvgPool2d(output_size=1) (mp): AdaptiveMaxPool2d(output_size=1) ) (1): Flatten() (2): BatchNorm1d(4096, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): Dropout(p=0.25) (4): Linear(in_features=4096, out_features=512, bias=True) (5): ReLU(inplace) (6): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (7): Dropout(p=0.5) (8): Linear(in_features=512, out_features=7, bias=True) ))
Put it to learn:
learn50.fit_one_cycle(15, callbacks=[SaveModelCallback(learn50, every='epoch', monitor='accuracy', name='derma50-1')])# Save weightslearn50.save('derma50-stage-1')# Deploy the whole network (with the databunch)exportStageTo(learn50, path)
Look ath the results:
interp = ClassificationInterpretation.from_learner(learn50)losses,idxs = interp.top_losses()interp.plot_confusion_matrix(figsize=(5,5), dpi=100)
Look at the learning curves:
learn50.recorder.plot_losses()
For now, this did not impress: the network oscillated more than the ResNet34 during this first transfer learning phase and the results, even if numerically better (85% x 87% accuracy), actually look worse on a visual analysis of the confusion matrix. Letβs do a fine tuning of the ResNet50 and see if this produces better results.
We will do this in two experiments.
While training a Deep Neural Network selecting a good learning rate is essential for both fast convergence and a lower error. The first step in fine-tuning is to find an adequate range of learn rates:
# Unfreeze the networklearn50.unfreeze()# Find optimum learning rateslearn50.lr_find()# Include suggestion=True in order to obtain a suggestion on where to look...learn50.recorder.plot(suggestion=True)
This will output:
LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.Min numerical gradient: 9.12E-07Min loss divided by 10: 1.10E-07
The lower bound, 9.12E-07, we will round up to 1.0E-06. Now, you can fine-tune using our rule-of-thumb. We will define a range of learning rates using the rule of thumb: ending at the βsecureβ rate 1e-06 and starting at a rate that is one order of magnitude higher:
# Unfreeze the networklearn50.unfreeze()learn50.fit_one_cycle(35, max_lr=slice(1e-5,1e-6), callbacks=[SaveModelCallback(learn50, every='epoch', monitor='accuracy', name='derma50')])# Save the weights of stage 2 each "better" epoch:learn50.save('derma50-stage-2')# Do not overwrite the stage 1 .pkl with stage 2 # We will need it for the ResNet50 Experiment #2# exportStageTo(learn50, path)
So, after 35 epochs and a lot of processing, we arrived at 90% accuracy. This looks unpromising... Letβs look at the confusion matrix and the learning curves:
interp = ClassificationInterpretation.from_learner(learn50)losses,idxs = interp.top_losses()interp.plot_confusion_matrix(figsize=(5,5), dpi=100)
learn50.recorder.plot_losses()
What we see here is a result that is much different from the ResNet34. With the ResNet50 the network learns the training set during the fine-tuning phase, but it is oscilllating all the time: some batches make it perform better, other batches make it turn back and perform worse. This normally means that the data are of bad quality and possess too much noise. In this case however, weβve already seen that we can achieve 93% accuracy with a ResNet34. So, bad data is not the case here. Another possibility is that the network has too much parameters and it is not generalizing, but adapting to individual instances of the training set, thus learning individual examples and de-generalizing. This makes its performance worse for other parts of the data set and so the network acts like a pendulum, going back and forth in the error space. The validation loss, that is much higher than the training loss during the whole fine-tuning process, corroborates this interpretation of the learning curve.
But we are stubborn... Letβs perform another experiment.
In the formar experiment we blindly accepted the suggestion from the analysis algorithm and took a very low learning rate. Maybe this was the reason for the bad learning?
If we look at the learning rate graph, we can see that a plateau is already forming at about 1.0E-4. Then the learning rate plunges into two valleys, one at 1.0E-5 and another at 1.0E-6. What if we take the more stable, flat plateu zone, from 1.0E-4 to 1.0E-5 and make this our learning rate range?
First, restore the network to the state you had when you finished the initial transfer learning:
# Will always load a path/'export.pkl' deployment filelearn50 = restoreStageFrom(path)
Fine-tune it again, now with max_lr=slice(1e-4,1e-5):
# Unfreeze the networklearn50.unfreeze()learn50.fit_one_cycle(35, max_lr=slice(1e-4,1e-5), callbacks=[SaveModelCallback(learn50, every='epoch', monitor='accuracy', name='derma50')])learn50.save('derma50-stage-2')exportStageTo(learn50, path)
Letβs look at the result graphics:
These results are better than before,even if the network oscillated a lot. The confusion matrix, however, shows us that the results for melanoma, which is the most important pathology here, do not look good.
Letβs go in the other direction and experiment with a network that is smaller than ResNet34, instead of larger: ResNet18.
Why not, then, try a much smaller network and see how it behaves? Letβs try a ResNet18 with the dermatoscopic data!
For this purpose we will change our batch size and re-generate the DataBunch. ResNet18s are much smaller and weβll have more memory avilable to us, so it makes sense to use a larger batch size:
bs = 48 # Batch size, 64 for medium images on a T4 GPU and ResNet18...size = 448 # Image size, 448x448 is double than the orignal # ImageNet size of the pre-trained ResNet we'll be using, # should be easy to train...path = Path("./data") # The path to the 'train' folder you created...# Limit your augmentations: it's medical data! You do not want to phantasize data...# Warping, for example, will let your images badly distorted, so don't do it!# This dataset is big, so don't rotate the images either. Lets stick to flipping...tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_rotate=None, max_warp=None, max_zoom=1.0)# Create the DataBunch!# Remember that you'll have images that are bigger than 128x128 and images that are smaller, # so squish them all in order to occupy exactly 128x128 pixels...data = ImageDataBunch.from_csv('data', csv_labels='HAM10000_metadata.csv', suffix='.jpg', fn_col=1, label_col=2, ds_tfms=tfms, valid_pct = 0.2,size=size, bs=bs)print('Transforms = ', len(tfms))# Save the DataBunch in case the training goes south... so you won't have to regenerate it..# Remember: this DataBunch is tied to the batch size you selected. data.save('imageDataBunch-bs-'+str(bs)+'-size-'+str(size)+'.pkl')# Show the statistics of the Bunch...print(data.classes)data
Create the network:
learn = cnn_learner(data, models.resnet18, metrics=[accuracy, error_rate])learn.model
The model will look like this (observe that this smaller ResNet model has only 1024 out features instead of 4096 in the last block):
Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (4): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) )......... (1): Sequential( (0): AdaptiveConcatPool2d( (ap): AdaptiveAvgPool2d(output_size=1) (mp): AdaptiveMaxPool2d(output_size=1) ) (1): Flatten() (2): BatchNorm1d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): Dropout(p=0.25) (4): Linear(in_features=1024, out_features=512, bias=True) (5): ReLU(inplace) (6): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (7): Dropout(p=0.5) (8): Linear(in_features=512, out_features=7, bias=True) ))
Letβs transfer-learn it for 15 epochs:
learn.fit_one_cycle(15, callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma-1')])learn.save('derma-stage-1')exportStageTo(learn, path)
interp = ClassificationInterpretation.from_learner(learn)losses,idxs = interp.top_losses()interp.plot_confusion_matrix(figsize=(5,5), dpi=100)
learn.recorder.plot_losses()
Numerically, this 0.5% better than the ResNet34. Letβs look howit behaves after a fine-tuning:
# Unfreeze the networklearn.unfreeze()# Find optimum learning rateslearn.lr_find()# Include suggestion=True in order to obtain a suggestion on where to look...learn.recorder.plot(suggestion=True)
Again, we have a curve that first achieves a plateau and then plunges into two holes. Only here the holes are deeper down than the plateau. Letβs consider that, in this case, the holes are significant and accept the suggestion of the learning rate finder and make max_lr=slice(1e-5,1e-6):
LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.Min numerical gradient: 1.32E-06Min loss divided by 10: 1.58E-07
# Unfreeze the networklearn.unfreeze()learn.fit_one_cycle(35, max_lr=slice(1e-5,1e-6), callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma18')])learn.save('derma18-stage-2')exportStageTo(learn, path)
88% accuracy! That is much worse than the ResNet34. Letβs plot the learning curves:
learn.recorder.plot_losses()
What we see here is that the ResNet18 oscillates still more than the ResNet50, when we trained it with a too small learning rate. This is an indication that here also the learning rate was too small.
Iβve repeated the fine-tuning experiment #2 we did before with the ResNet50 and set the learning rate range to max_lr=slice(1e-4,1e-5) and trained it again. In this case the ResNet18 achieved a validation accuracy of 0.904643. The results graphics look like this:
This is better than before but still worse than the ResNet34 and the ResNet50. The ResNet18 does not seem to be a good choice for this problem. The code is in our notebook.
What do you do if your training was interrupted? This can happen because you reached your 12 hours of continuous βfreeβ operating time on a Google Colab notebook or because your computer stopped for some reason. I live in Brazil and events of power shortages are common...
The fit_one_cycle method works with varying, adaptive learning rates, following a curve where the rate is first increased and then decreased. If you interrupt a training in epoch #10 of, say, 20 epochs and then start again for more 9 epochs, youβll not have the same result as training uninterruptedly for 20 epochs. You have to be able to record where you stopped and then resume the training cycle from that point and with the correct hyperparameters for that part of the cycle.
The first thing you have to do is to save your network every epoch:
learn.fit_one_cycle(20, max_lr=slice(1e-5,1e-6), callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='saved_net')])
This will have your network be saved every epoch, with the name you provided followed by _#epoch. So at epoch #3, the file saved_net_3.pth will be written. This file you can load after you:
re-created the DataBunch and
re-instantiated the network with it.
After reloading the .pth file, you can restart your training, only youβll tell fit_one_cycle to consider 20 epochs, but to start training from epoch #4.
To learn how this is done, look here:
Divide a long 1cycle policy into smaller ones β a GitHub by PPW
How do you do it?
The fit_one_cycle method in fast.ai has been developed to allow you to tell it from which part of the cycle to resume an interrupted training. The code for resuming a training will look like this:
# Create a new net if training was interrupted and you had to # restart your Colab sessionlearn = cnn_learner(data, models.<your_model_here>, metrics=[accuracy, error_rate])# If you're resuming, only indicating the epoch from which to # resume, indicated by start_epoch=<epoch#> will load the last # saved .pth, it is not necessary to explicitly reload the last # epoch, you only should NOT change the name given in # name=<callback_save_file>:# when resuming fast.ai will try to reload # <callback_save_file>_<previous_epoch>.pth# Unfreeze the networklearn50.unfreeze()# Use start_epoch=<some_epoch> to resume training...learn.fit_one_cycle(20, max_lr=slice(1e-5,1e-6), start_epoch=<next_epoch#>, callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name=<callback_save_file>)])
fast.ai will tell you βLoaded <callback_save_file>_<previous_epoch#>β and resume training.
You can look at all parameters supported by the fit_one_cycle method here:
https://docs.fast.ai/train.html#fit_one_cycle
Employing an image resolution of 448x448 and fast.ai, we obtained a validation accuracy of roughly 93% with two of the three network models we employed in our experiment, ResNet34 and ResNet50. This is much better than the 85% of the tutorial above, which employed a MobileNet, an image resolution of 224x224 and Keras. The (presently) most voted Kernel on Kaggle (employs TensorFlow.js) obtained a precision of 86%.
In the ISIC 2018 challenge final test of task #3 the highest ranking competitor, Jordan Yap from MetaOptima Technology Inc., achieved an accuracy of 95.8% and a balanced multiclass accuracy, the competitor evaluation criterion chosen by ISIC, of 88.5%. Jordan Yap employed a method that based upon:
additional, external data [33,644 images];
images with a low resolution, equivalent to the original ImageNet-resolution;
an ensemble of 19 classification algorithms, of which one was not a neural network (histogram analysis);
an XGBoost Classifier, which was trained on top of the results of this ensemble.
The paper Aleksey Nozdryn-Plotnicki, Jordan Yap and William Yolland, submitted to the ISIC Skin Image Analysis Workshop and Challenge @ MICCAI 2018 together with their results is here.
Our results are not directly comparable to the original ISIC 2018 challenge because there ISIC provided a test set of 1512 images manually extracted from the HAM1000 dataset and all competitors had to employ that test set and submit their results to ISIC. We validated our training with a set of 2003 images randomly extracted from the HAM1000 dataset and trained our networks with the remaining 8012 images.
You can look at the ISIC 2018 results here:
ISIC 2018 β Task 3: Final Test
ISIC Challenge 2018 Leaderboards (click on the βTask 3β pane)
It is, however, interesting to note that the accuracy of 92.9% we achieved with fast.ai and just one network, a ResNet34, and a total training time of 190 minutes on a NVIDIA T4 GPU (4.2 x 10 + 4.3 x 35 minutes), is only 2.9% worse than the accuracy the highest ranking competitor of the ISIC 2018 challenge obtained with a considerably more complex approach, employing a machine learning algorithm on top of 18 different neural networks.
This is most probably due to the fact that we employed twice the image resolution, allowing for much more details, but the HYPOs (hyper parameter optimizations) in fast.ai have probably also played a role.
ResNet34 is a good choice to start: ResNets are really well-managed in fast.ai, with various easy-to-use HYPOs (hyper parameter optimizations). If you do not know which network to use, take the ResNet34, which will be small enough to train relatively fast, even if you do it with your GPU at home, and big enough to represent a large set of problems. How ResNet34 trains will provide hints if you should go up or go down with the size of your network.
Blindly accepting learning rate suggestion is not always the best option: the lr_find() for the ResNet50 produces a long plateau and the method suggested a very low learning rate value in a small valley at the left end of the graphic. When we trained the network with this value, it oscillated and did not produce a good result (90% accuracy only). When we employed a visual analysis of the graph and took as the lower bound for the learning rate range a value one order of magnitude higher, which lied at the beginning of the flatter part of the plateau, the ResNet50 learned much better and achieved the same 93% accuracy of the ResNet34. So, use the suggest=True mode but give it a no-nonsense treatment before you accept it, actually looking at the graphic. This is the second rule-of-thumb of the learning rate range: look at the whole graphic and find the real plateau β your ideal lower bound for the learning rate range will lie towards the beginning of this plateau.
The method learn.lr_find() helps you find an optimal learning rate. It uses the technique developed in the 2015 paper Cyclical Learning Rates for Training Neural Networks (http://arxiv.org/abs/1506.01186), where we simply keep increasing the learning rate from a very small value, until the loss starts decreasing. If you want to know more about finding the best learning rates, look here:
TowardsDataScience::Speeding up Neural Net Training with a LR-Finder β Finding good initial learning rate for your network by Faizan Ahemad
Bigger is not always better: in the end, the ResNet50 perfomed almost identically to the ResNet34, but took much more time to train and showed slightly worse results. It is a bad choice to begin your training space exploration with a large network model.
Image resolution plays a role: employing twice the resolution the highest ranking competitor of the ISIC 2018 Challenge used, we obtained comparable results with a single, relatively simple, ResNet34,while that competitor employed a machine learning method on top of 18 different networks, including a huge ResNet152.
Fast.ai is fast: Finally, compared to the other approaches, with fast.ai we were able to solve the same classification problem employing much less code while using high-level hyperparameter optimization strategies that allowed us to train much faster. At the same time, a set of high level functions allows us also to easily inspect the results both as tables and as graphs. This simplicity allowed us to experiment with three different network models and compare their results. This shows that fast.ai is a very promising alternative to more traditional CNN frameworks, especially if the task at hand is a βstandardβ deep learning task such as image classification, object detection or semantic segmentation, that can be solved by fine-tuning off-the-shelf pre-trained network models.
This work was the result of a collaborative effort of a team of engaged researchers besides me:
Daniel Holthausen Nunes <daniel@floripa.com.br>
Luiz Antonio Buschetto Macarini <luiz.buschetto@posgrad.ufsc.br>
Marcelo Ricardo Stemmer <marcelo.stemmer@ufsc.br>
We wish also to thank to JuΜrgen Kreusch <juergen.kreusch@gmail.com> and Luis Fernando Kopke <luiskopke@uol.com.br>for the stereodermoscopic material.
[1]Kreusch, J. Incident light microscopy: reflections on microscopy of the living skin. Int J Dermatol. 1992 Sep;31(9):618β20.
[2]Kopke, L.F. Dermatoscopy in the early detection, control and surgical planning of basal cell carcinomas. Surg Cosmet Dermatol 2011;3(2):103β8.
|
[
{
"code": null,
"e": 335,
"s": 172,
"text": "We show how to use fast.ai to solve the 2018 Skin Lesion Analysis Towards Melanoma Detection challenge and automatically identify seven kinds of skin pathologies."
},
{
"code": null,
"e": 383,
"s": 335,
"text": "Posted by Aldo von Wangenheim β aldo.vw@ufsc.br"
},
{
"code": null,
"e": 426,
"s": 383,
"text": "This is based upon the following material:"
},
{
"code": null,
"e": 966,
"s": 426,
"text": "TowardsDataScience::Classifying Skin Lesions with Convolutional Neural Networks β A guide and introduction to deep learning in medicine by Aryan MisraTschandl, Philipp, 2018, βThe HAM10000 dataset, a large collection of multi-source dermatoscopic images of common pigmented skin lesionsβ, https://doi.org/10.7910/DVN/DBW86T, Harvard Dataverse [arXiv preprint version: arXiv:1803.10417 [cs.CV]]Tools for workup of the HAM10000 dataset β GitHub. This repository gives access to the tools created and used for assembling the training dataset."
},
{
"code": null,
"e": 1117,
"s": 966,
"text": "TowardsDataScience::Classifying Skin Lesions with Convolutional Neural Networks β A guide and introduction to deep learning in medicine by Aryan Misra"
},
{
"code": null,
"e": 1361,
"s": 1117,
"text": "Tschandl, Philipp, 2018, βThe HAM10000 dataset, a large collection of multi-source dermatoscopic images of common pigmented skin lesionsβ, https://doi.org/10.7910/DVN/DBW86T, Harvard Dataverse [arXiv preprint version: arXiv:1803.10417 [cs.CV]]"
},
{
"code": null,
"e": 1508,
"s": 1361,
"text": "Tools for workup of the HAM10000 dataset β GitHub. This repository gives access to the tools created and used for assembling the training dataset."
},
{
"code": null,
"e": 1976,
"s": 1508,
"text": "The HAM10000 dataset (Human Against Machine with 10000 training images) served as the training set for the ISIC 2018 challenge (Task 3). The official validation- and test-sets of this challenge are available, without ground-truth labels, through the challenge website https://challenge2018.isic-archive.com/. The ISIC-Archive also provides a βLive challengeβ submission site for continuous evaluation of automated classifiers on the official validation- and test-set."
},
{
"code": null,
"e": 2229,
"s": 1976,
"text": "The HAM10000 dataset is also on Kaggle. If you want to compare your results with Kaggle kernels, look here: https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000/kernels Last time I looked (June 2019), there were 55 different solutions posted there."
},
{
"code": null,
"e": 2316,
"s": 2229,
"text": "The notebook with the code shown in this posting (and a few additional cells) is here."
},
{
"code": null,
"e": 2343,
"s": 2316,
"text": "The images look like this:"
},
{
"code": null,
"e": 2997,
"s": 2343,
"text": "This dataset contains pigmented skin lesions acquired through standard dermoscopy. These are lesions where the tissue produces melanin, the natural pigment of the human skin, and that are dark. Not all kinds of lesions initially investigated and triaged through dermoscopy are necessarily pigmented lesions. This means that, in a real world situation, a GP or a nurse examining a patient through dermoscopy (or a patient performing self-examination) with the intent to submit these images to a dermatologist for an initial triage, would possibly encounter other lesions than the ones depicted in this dataset here (look at Is there an ISIC 2019? below)."
},
{
"code": null,
"e": 3045,
"s": 2997,
"text": "The lesion classes in the HAM10000 Dataset are:"
},
{
"code": null,
"e": 3950,
"s": 3045,
"text": "nv: Melanocytic nevi β benign neoplasms of melanocytes [6705 images]mel: Melanoma β a malignant neoplasm derived from melanocytes [1113 images]bkl: Benign keratosis β a generic class that includes seborrheic keratoses, solar lentigo and lichen-planus like keratoses [1099 images];bcc: Basal cell carcinoma β a common variant of epithelial skin cancer that rarely metastasizes but grows destructively if untreated (bccs do not necessarily produce pigmented lesions) [514 images];akiec: Actinic Keratoses and intraepithelial Carcinoma β common non-invasive, variants of squamous cell carcinoma that can be treated locally without surgery [327 images];vasc: Vascular skin lesions ranging from cherry angiomas to angiokeratomas and pyogenic granulomas [142 images];df: Dermatofibroma β a benign skin lesion regarded as either a benign proliferation or an inflammatory reaction to minimal trauma [115 images]."
},
{
"code": null,
"e": 4019,
"s": 3950,
"text": "nv: Melanocytic nevi β benign neoplasms of melanocytes [6705 images]"
},
{
"code": null,
"e": 4095,
"s": 4019,
"text": "mel: Melanoma β a malignant neoplasm derived from melanocytes [1113 images]"
},
{
"code": null,
"e": 4233,
"s": 4095,
"text": "bkl: Benign keratosis β a generic class that includes seborrheic keratoses, solar lentigo and lichen-planus like keratoses [1099 images];"
},
{
"code": null,
"e": 4432,
"s": 4233,
"text": "bcc: Basal cell carcinoma β a common variant of epithelial skin cancer that rarely metastasizes but grows destructively if untreated (bccs do not necessarily produce pigmented lesions) [514 images];"
},
{
"code": null,
"e": 4604,
"s": 4432,
"text": "akiec: Actinic Keratoses and intraepithelial Carcinoma β common non-invasive, variants of squamous cell carcinoma that can be treated locally without surgery [327 images];"
},
{
"code": null,
"e": 4717,
"s": 4604,
"text": "vasc: Vascular skin lesions ranging from cherry angiomas to angiokeratomas and pyogenic granulomas [142 images];"
},
{
"code": null,
"e": 4861,
"s": 4717,
"text": "df: Dermatofibroma β a benign skin lesion regarded as either a benign proliferation or an inflammatory reaction to minimal trauma [115 images]."
},
{
"code": null,
"e": 5089,
"s": 4861,
"text": "For a more detailed description of each class, look at the Kaggle kernel: Skin Lesion Analyzer + Tensorflow.js Web App β Python notebook using data from Skin Cancer MNIST: HAM10000 and also the paper by Philipp Tschandl, above."
},
{
"code": null,
"e": 6213,
"s": 5089,
"text": "Dermoscopic images alone do not provide enough for data for a dermatological diagnosis or a reliable remote patient triage in a Teledermatology setting. Dermoscopic images lack context. In order to provide context, you will need to perform an image acquisition protocol that includes panoramic whole body images of the patient and also approximation images of each lesion, which are taken with a ruler or other frame of reference visible in the image, in order to provide contextual information about the size of the lesion. Approximation images taken with the ruler are also important for a patient already in treatment in order to allow the accompanying physician to follow the evolution of the lesion. Both panoramic and approximation images, in order to be acquired correctly, need to be performed following a protocol that guarantees that the images are in focus, taken from the correct distance, and with the correct illumination. There are also details that cannot be reliably detected through the standard dermoscopy technique presently being employed and, in several cases, a confirmation biopsy will be necessary."
},
{
"code": null,
"e": 6319,
"s": 6213,
"text": "If you are interested in knowing more about Teledermatology examination acquisition protocols, look here:"
},
{
"code": null,
"e": 6649,
"s": 6319,
"text": "Aldo von Wangenheim and Daniel Holthausen Nunes. Creating a Web Infrastructure for the Support of Clinical Protocols and Clinical Management: An Example in Teledermatology. Telemedicine and e-Health. Online Ahead of Print:November 30, 2018. http://doi.org/10.1089/tmj.2018.0197. Thereβs also a preprint available on ResearchGate."
},
{
"code": null,
"e": 7148,
"s": 6649,
"text": "The contact dermoscope used nowadays is the result of an international effort for the standardization of this examination performed during the first half of the 1990s, led by a group of researchers at the University of Munich in Germany. This equipment uses a single lens with a 10x magnification and internal illumination by LEDs. The examination is performed with mineral oil, which is applied on the surface of the lesion before the dermoscope is applied on the lesion and a photograph is taken."
},
{
"code": null,
"e": 7461,
"s": 7148,
"text": "The choosing of a monocular 10x magnification lens as a standard allowed for the development of very small devices that soon became very popular. Analog dermoscopes can be carried in a breast pocket and digital ones can be easily developed as small USB devices or as adapters for digital cameras and smartphones."
},
{
"code": null,
"e": 8018,
"s": 7461,
"text": "The drawback of this standard is that the 10x magnification is not enough for the reliable detection of some pathologies, such as the basal cell carcinoma, which is the most common form of skin cancer. This form of neoplasm is characterized by vascular alterations, called arboriform vascularizations, which cannot be reliably observed with a monocular lens employing a 10x magnification: A confirmation biopsy will always be necessary in order to provide the definitive diagnosis. Reliable detection needs higher magnification and binocular optics [1][2]."
},
{
"code": null,
"e": 8502,
"s": 8018,
"text": "Until the 1990s there were other types of dermoscopes being developed, which could provide better imaging quality, but that were larger and not so easy to operate, such as the 50x binocular stereoscopic contact dermoscope. This equipment is better suited for the visual early detection of pathologies such as the basal cell carcinoma [1][2]. The practicality, popularization and standardization of the 10x contact monocular dermoscope, however, stopped these other lines of research."
},
{
"code": null,
"e": 8864,
"s": 8502,
"text": "The ISIC β The International Skin Imaging Collaboration has corrected the lack of some dermatological diagnostic categories in the HAM10000 Dataset publishing a new dataset in the ISIC 2019 challenge: Skin Lesion Analysis Towards Melanoma Detection. The 2019 dataset, released on May 3, 2019, now contains nine different diagnostic categories and 25,331 images:"
},
{
"code": null,
"e": 9083,
"s": 8864,
"text": "MelanomaMelanocytic nevusBasal cell carcinomaActinic keratosisBenign keratosis (solar lentigo / seborrheic keratosis / lichen planus-like keratosis)DermatofibromaVascular lesionSquamous cell carcinomaNone of the others"
},
{
"code": null,
"e": 9092,
"s": 9083,
"text": "Melanoma"
},
{
"code": null,
"e": 9110,
"s": 9092,
"text": "Melanocytic nevus"
},
{
"code": null,
"e": 9131,
"s": 9110,
"text": "Basal cell carcinoma"
},
{
"code": null,
"e": 9149,
"s": 9131,
"text": "Actinic keratosis"
},
{
"code": null,
"e": 9236,
"s": 9149,
"text": "Benign keratosis (solar lentigo / seborrheic keratosis / lichen planus-like keratosis)"
},
{
"code": null,
"e": 9251,
"s": 9236,
"text": "Dermatofibroma"
},
{
"code": null,
"e": 9267,
"s": 9251,
"text": "Vascular lesion"
},
{
"code": null,
"e": 9291,
"s": 9267,
"text": "Squamous cell carcinoma"
},
{
"code": null,
"e": 9310,
"s": 9291,
"text": "None of the others"
},
{
"code": null,
"e": 9467,
"s": 9310,
"text": "At the moment of the writing of this posting, test metadata for this new dataset are not yet available. They are announced to be released on August 9, 2019."
},
{
"code": null,
"e": 9694,
"s": 9467,
"text": "The ISIC has, up to now, sponsored four challenges in Image Analysis: ISIC 2016 through ISIC 2019, allways with the theme βSkin Lesion Analysis Towards Melanoma Detectionβ. The four challenges can be found at the ISIC Archive."
},
{
"code": null,
"e": 9752,
"s": 9694,
"text": "Letβs start working on the dataset of the 2018 challenge."
},
{
"code": null,
"e": 9830,
"s": 9752,
"text": "Do what is in this section here below once each time you run this notebook..."
},
{
"code": null,
"e": 9884,
"s": 9830,
"text": "%reload_ext autoreload%autoreload 2%matplotlib inline"
},
{
"code": null,
"e": 10009,
"s": 9884,
"text": "Only to be sure, look at which CUDA driver and which GPU Colab has made available for you. The GPU will typically be either:"
},
{
"code": null,
"e": 10056,
"s": 10009,
"text": "a K80 with 11 GB RAM or (if your really lucky)"
},
{
"code": null,
"e": 10082,
"s": 10056,
"text": "a Tesla T4 with 14 GB RAM"
},
{
"code": null,
"e": 10281,
"s": 10082,
"text": "If Googleβs servers are crowded, youβll eventually have access to only part of a GPU. If your GPU is shared with another Colab notebook, youβll see a smaller amount of memory made available for you."
},
{
"code": null,
"e": 10456,
"s": 10281,
"text": "Tip: Avoid peak times of the US west coast. I live at GMT-3 and we are two hours ahead of the US east coast, so I always try to perform heavy processing in the morning hours."
},
{
"code": null,
"e": 10492,
"s": 10456,
"text": "!/opt/bin/nvidia-smi!nvcc --version"
},
{
"code": null,
"e": 10624,
"s": 10492,
"text": "When I started running the experiments described here, I was lucky: I had a whole T4 with 15079 MB RAM! My output looked like this:"
},
{
"code": null,
"e": 12083,
"s": 10624,
"text": "Thu May 2 07:36:26 2019 +-----------------------------------------------------------------------------+| NVIDIA-SMI 410.79 Driver Version: 410.79 CUDA Version: 10.0 ||-------------------------------+----------------------+----------------------+| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC || Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. ||===============================+======================+======================|| 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 || N/A 63C P8 17W / 70W | 0MiB / 15079MiB | 0% Default |+-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+| Processes: GPU Memory || GPU PID Type Process name Usage ||=============================================================================|| No running processes found |+-----------------------------------------------------------------------------+nvcc: NVIDIA (R) Cuda compiler driverCopyright (c) 2005-2018 NVIDIA CorporationBuilt on Sat_Aug_25_21:08:01_CDT_2018Cuda compilation tools, release 10.0, V10.0.130"
},
{
"code": null,
"e": 12339,
"s": 12083,
"text": "Here we import all the necessary packages. We are going to work with the fastai V1 library which sits on top of Pytorch 1.0. The fastai library provides many useful functions that enable us to quickly and easily build neural networks and train our models."
},
{
"code": null,
"e": 12628,
"s": 12339,
"text": "from fastai.vision import *from fastai.metrics import error_ratefrom fastai.callbacks import SaveModelCallback# Imports for diverse utilitiesfrom shutil import copyfileimport matplotlib.pyplot as pltimport operatorfrom PIL import Imagefrom sys import intern # For the symbol definitions"
},
{
"code": null,
"e": 13091,
"s": 12628,
"text": "# Export network for deployment and create a copydef exportStageTo(learn, path): learn.export() # FacΜ§a backup diferenciado copyfile(path/'export.pkl', path/'export-malaria.pkl') #exportStage1(learn, path)# Restoration of a deployment model, for example in order to conitnue fine-tuningdef restoreStageFrom(path): # Restore a backup copyfile(path/'export-malaria.pkl', path/'export.pkl') return load_learner(path) #learn = restoreStage1From(path)"
},
{
"code": null,
"e": 13281,
"s": 13091,
"text": "We will download the Kaggle version of this dataset because Google Colab has the Kaggle API preinstalled and it is all organized in one .zip file. In order to download from Kaggle you need:"
},
{
"code": null,
"e": 13302,
"s": 13281,
"text": "an account at Kaggle"
},
{
"code": null,
"e": 13361,
"s": 13302,
"text": "to install your Kaggle credentials (a .json file) on Colab"
},
{
"code": null,
"e": 13495,
"s": 13361,
"text": "To see how to do this, first look at this tutorial and the Kaggle API instructions and generate and upload your credentials to Colab:"
},
{
"code": null,
"e": 13605,
"s": 13495,
"text": "TowardsDataScience::Setting Up Kaggle in Google Colab β A Simple Tutorial for the Total Newbie by Anne Bonner"
},
{
"code": null,
"e": 13658,
"s": 13605,
"text": "https://github.com/Kaggle/kaggle-api#api-credentials"
},
{
"code": null,
"e": 13781,
"s": 13658,
"text": "Run the cell below. It will Create a Folder for your Credentials for the Kaggle API and install your credentials in Colab:"
},
{
"code": null,
"e": 13983,
"s": 13781,
"text": "!mkdir .kaggle!mv kaggle.json .kaggle!chmod 600 /content/.kaggle/kaggle.json!cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json!chmod 600 ~/.kaggle/kaggle.json!kaggle config set -n path -v{/content}"
},
{
"code": null,
"e": 14210,
"s": 13983,
"text": "For some arcane reason this script sometimes does not work. It seems to have to do with the form Colab names the home folder. If you experience an error message, simply execute it again. The final output should look like this:"
},
{
"code": null,
"e": 14243,
"s": 14210,
"text": "- path is now set to: {/content}"
},
{
"code": null,
"e": 14311,
"s": 14243,
"text": "Create a βdataβ folder and download the dermatoscopy images into it"
},
{
"code": null,
"e": 14390,
"s": 14311,
"text": "!mkdir data!kaggle datasets download kmader/skin-cancer-mnist-ham10000 -p data"
},
{
"code": null,
"e": 14430,
"s": 14390,
"text": "This will produce the following output:"
},
{
"code": null,
"e": 14561,
"s": 14430,
"text": "Downloading skin-cancer-mnist-ham10000.zip to data100% 2.61G/2.62G [00:52<00:00, 42.3MB/s]100% 2.62G/2.62G [00:52<00:00, 53.4MB/s]"
},
{
"code": null,
"e": 14866,
"s": 14561,
"text": "Unzip the whole zipfile into /content/data and then quietly (-q) unzip the image files (you donβt want to verbosely unzip more than 10k images!). We will use the β override option (-o) in order to allow quiet overriding of files that could have been created in some interrupted prior attempt youβve made."
},
{
"code": null,
"e": 15184,
"s": 14866,
"text": "# Unzip the whole zipfile into /content/data!unzip -o data/skin-cancer-mnist-ham10000.zip -d data# Quietly unzip the image files!unzip -o -q data/HAM10000_images_part_1.zip -d data!unzip -o -q data/HAM10000_images_part_2.zip -d data# Tell me how many files I unzipped///!echo files in /content/data: `ls data | wc -l`"
},
{
"code": null,
"e": 15249,
"s": 15184,
"text": "If you have a files count of 10,023 files, youβve done it right!"
},
{
"code": null,
"e": 15610,
"s": 15249,
"text": "Archive: data/skin-cancer-mnist-ham10000.zip inflating: data/hmnist_28_28_RGB.csv inflating: data/HAM10000_metadata.csv inflating: data/HAM10000_images_part_1.zip inflating: data/hmnist_28_28_L.csv inflating: data/hmnist_8_8_L.csv inflating: data/HAM10000_images_part_2.zip inflating: data/hmnist_8_8_RGB.csv files in /content/data: 10023"
},
{
"code": null,
"e": 15666,
"s": 15610,
"text": "Now weβll prepare our data for processing with fast.ai."
},
{
"code": null,
"e": 15873,
"s": 15666,
"text": "In our previous medical image classification posting (Deep Learning and Medical Image Analysis for Malaria Detection with fastai) we have sorted the image categories into folders, one folder for each class."
},
{
"code": null,
"e": 16055,
"s": 15873,
"text": "Here we have all images stored in one folder and the metadata stored in a spreadsheet we will read with the fast.ai ImageDataBunch.from_csv() method from the fast.ai Data Block API."
},
{
"code": null,
"e": 16673,
"s": 16055,
"text": "The HAM10000 dataset does not provide the images sorted into folders according to their classes. Instead, all images are in one folder and a spreadsheet with several metadata for each of the images is provided. In this tutorial we will be reading the class of each image from this .csv spreadsheet, instead of organizing the image files into folders where the name of the folder is the class to which the images belong. fast.ai also provides ready-to-use methods for interpreting spreadsheets and extracting the classification data for the images. In this posting we will be learning how to make use of these methods."
},
{
"code": null,
"e": 16811,
"s": 16673,
"text": "For this purpose we will be using the data block API from fast.ai. Thereβs a very good explanation how it works in the following posting:"
},
{
"code": null,
"e": 16867,
"s": 16811,
"text": "Medium::Using the fastai Data Block API by Tom McKenzie"
},
{
"code": null,
"e": 17153,
"s": 16867,
"text": "In the original tutorial bove, which employs Keras, thereβs a routine to create training, validation and test folders from the data. With fast.ai it is not necessary: if you only have a βtrainβ folder, you can split it while creating the DataBunch by simply passing a few parameters..."
},
{
"code": null,
"e": 17493,
"s": 17153,
"text": "With fast.ai we also can easily work with resolutions that are different from the original ImageNet resolutions employed to pre-train the networks we will be using. In the tutorial listed above the author reduced the dataset image resolution to 224x224, in order to use the Keras MobileNet model. We will be employing a 448x448 resolution:"
},
{
"code": null,
"e": 18756,
"s": 17493,
"text": "bs = 64 # Batch size, 64 for medium images on a T4 GPU...size = 448 # Image size, 448x448 is double than the orignal # ImageNetpath = Path(\"./data\") # The path to the 'train' folder you created...# Limit your augmentations: it's medical data! You do not want to phantasize data...# Warping, for example, will let your images badly distorted, so don't do it!# This dataset is big, so don't rotate the images either. Lets stick to flipping...tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_rotate=None, max_warp=None, max_zoom=1.0)# Create the DataBunch!# Remember that you'll have images that are bigger than 128x128 and images that are smaller, # so squish them all in order to occupy exactly 128x128 pixels...data = ImageDataBunch.from_csv('data', csv_labels='HAM10000_metadata.csv', suffix='.jpg', fn_col=1, label_col=2, ds_tfms=tfms, valid_pct = 0.2,size=size, bs=bs)print('Transforms = ', len(tfms))# Save the DataBunch in case the training goes south... so you won't have to regenerate it..# Remember: this DataBunch is tied to the batch size you selected. data.save('imageDataBunch-bs-'+str(bs)+'-size-'+str(size)+'.pkl')# Show the statistics of the Bunch...print(data.classes)data"
},
{
"code": null,
"e": 18796,
"s": 18756,
"text": "This will produce the following output:"
},
{
"code": null,
"e": 19253,
"s": 18796,
"text": "Transforms = 2['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']ImageDataBunch;Train: LabelList (8012 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListbkl,bkl,bkl,bkl,bklPath: data;Valid: LabelList (2003 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListbkl,nv,nv,nv,nvPath: data;Test: None"
},
{
"code": null,
"e": 19294,
"s": 19253,
"text": "data.show_batch(rows=5, figsize=(15,15))"
},
{
"code": null,
"e": 19448,
"s": 19294,
"text": "If you do not know what model to use, it is a good choice to start with a Residual Network with 34 layers. Powerful, but not too small and not too big..."
},
{
"code": null,
"e": 19675,
"s": 19448,
"text": "In the tutorial listed above the author used a MobileNet implemented in Keras and the networkβs original image resolution of 224x224. In fast.ai the ResNet easily adapts to work with the resolution of 448x448 of our DataBunch."
},
{
"code": null,
"e": 20131,
"s": 19675,
"text": "Now we will start training our model. We will use a convolutional neural network backbone and a fully connected head with a single hidden layer as a classifier. Donβt know what these things mean? Not to worry, we will dive deeper in the coming lessons. For the moment you need to know that we are building a model which will take images as input and will output the predicted probability for each of the categories (in this case, it will have 37 outputs)."
},
{
"code": null,
"e": 20202,
"s": 20131,
"text": "We will be using twodifferent metrics to look at our training success:"
},
{
"code": null,
"e": 20232,
"s": 20202,
"text": "accuracy: validation accuracy"
},
{
"code": null,
"e": 20266,
"s": 20232,
"text": "error_rate: validation error rate"
},
{
"code": null,
"e": 20339,
"s": 20266,
"text": "If you want more information, look at https://docs.fast.ai/metrics.html."
},
{
"code": null,
"e": 20448,
"s": 20339,
"text": "learn = cnn_learner(data, models.resnet34, metrics=[accuracy, error_rate, dice(iou=True), fbeta])learn.model"
},
{
"code": null,
"e": 20681,
"s": 20448,
"text": "Just pass the data variable, which contains the DataBunch instance, to the cnn_learner() function and fast.ai will automatically adapt the input layer of the new network to the higher image resolution. The model will look like this:"
},
{
"code": null,
"e": 23004,
"s": 20681,
"text": "Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (4): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) (1): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) (2): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (5): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (downsample): Sequential( (0): Conv2d(64, 128, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) )......... and so on..."
},
{
"code": null,
"e": 23094,
"s": 23004,
"text": "We will employ the fit1cycle method developed by Leslie N. Smith β see below for details:"
},
{
"code": null,
"e": 23140,
"s": 23094,
"text": "https://docs.fast.ai/callbacks.one_cycle.html"
},
{
"code": null,
"e": 23297,
"s": 23140,
"text": "A disciplined approach to neural network hyper-parameters: Part 1 β learning rate, batch size, momentum, and weight decay β https://arxiv.org/abs/1803.09820"
},
{
"code": null,
"e": 23418,
"s": 23297,
"text": "Super-Convergence: Very Fast Training of Residual Networks Using Large Learning Rates β https://arxiv.org/abs/1708.07120"
},
{
"code": null,
"e": 23594,
"s": 23418,
"text": "There is also very interesting article from Nachiket Tanksale called Finding Good Learning Rate and The One Cycle Policy where cyclic learning rates and momentum are discussed"
},
{
"code": null,
"e": 23689,
"s": 23594,
"text": "Since this method is fast, we will employ only 10 epochs in this first Transfer Learning stage"
},
{
"code": null,
"e": 23818,
"s": 23689,
"text": "If you want to to know more about the new learning API in the fast.ai library, look at this notebook prepared by Sylvain Gugger."
},
{
"code": null,
"e": 23946,
"s": 23818,
"text": "We will also save the network each epoch, if the performance gets better: https://docs.fast.ai/callbacks.html#SaveModelCallback"
},
{
"code": null,
"e": 24259,
"s": 23946,
"text": "learn.fit_one_cycle(10, callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma-1')])# Salve a rede (necessita regerar o databunch caso a gente continue)learn.save('derma-stage-1')# FacΜ§a o deploy desta rede para podermos usar offline depois para fazer testesexportStageTo(learn, path)"
},
{
"code": null,
"e": 24295,
"s": 24259,
"text": "Letβs see what results we have got."
},
{
"code": null,
"e": 24607,
"s": 24295,
"text": "We will first see which were the categories that the model most confused with one another. We will try to see if what the model predicted was reasonable or not. In this case the mistakes look reasonable (none of the mistakes seems obviously naive). This is an indicator that our classifier is working correctly."
},
{
"code": null,
"e": 24934,
"s": 24607,
"text": "Furthermore, when we plot the confusion matrix, we can see that the distribution is heavily skewed: the model makes the same mistakes over and over again but it rarely confuses other categories. This suggests that it just finds it difficult to distinguish some specific categories between each other; this is normal behaviour."
},
{
"code": null,
"e": 25048,
"s": 24934,
"text": "Letβs generate a ClassificationInterpretation and look at some results, the confusion matrix and the loss curves."
},
{
"code": null,
"e": 25181,
"s": 25048,
"text": "interp = ClassificationInterpretation.from_learner(learn)losses,idxs = interp.top_losses()len(data.valid_ds)==len(losses)==len(idxs)"
},
{
"code": null,
"e": 25240,
"s": 25181,
"text": "Look at your worst results, first without using a heatmap:"
},
{
"code": null,
"e": 25298,
"s": 25240,
"text": "interp.plot_top_losses(9, figsize=(20,11), heatmap=False)"
},
{
"code": null,
"e": 25432,
"s": 25298,
"text": "Now, do the same, but highlight the images with a heatmap in order to see which parts of each image induced the wrong classification:"
},
{
"code": null,
"e": 25489,
"s": 25432,
"text": "interp.plot_top_losses(9, figsize=(20,11), heatmap=True)"
},
{
"code": null,
"e": 25617,
"s": 25489,
"text": "Here we have seven classes and it makes a lot of sense to look at the confusion matrix. Besides, it makes beautiful pictures..."
},
{
"code": null,
"e": 25670,
"s": 25617,
"text": "interp.plot_confusion_matrix(figsize=(5,5), dpi=100)"
},
{
"code": null,
"e": 25700,
"s": 25670,
"text": "What we can see here is that:"
},
{
"code": null,
"e": 25844,
"s": 25700,
"text": "nevi are far the most common occurrences. One can think of reducing the instances of nevi in the training set in order not to skew the results;"
},
{
"code": null,
"e": 26125,
"s": 25844,
"text": "there are several benign keratoses (bkl) wrongly classified. This is probably because bkl in this dataset is a generic class that includes seborrheic keratoses, solar lentigo and lichen-planus like keratoses, which are dermatoses that, even if related, look really very different;"
},
{
"code": null,
"e": 26257,
"s": 26125,
"text": "there are also several melanomas (mel) that were misclassified. This was a surprise. I expected the network to perform better here."
},
{
"code": null,
"e": 26311,
"s": 26257,
"text": "If you are confused by confusion matrices, look here:"
},
{
"code": null,
"e": 26375,
"s": 26311,
"text": "Taking the Confusion Out of Confusion Matrices by Allison Ragan"
},
{
"code": null,
"e": 26425,
"s": 26375,
"text": "Simplifying the Confusion Matrix by Madhav Mishra"
},
{
"code": null,
"e": 26478,
"s": 26425,
"text": "Plot your losses,in order to see the learning curve:"
},
{
"code": null,
"e": 26507,
"s": 26478,
"text": "learn.recorder.plot_losses()"
},
{
"code": null,
"e": 26627,
"s": 26507,
"text": "This result is really good. The network oscillated a bit but learned steadilly. Now letβs try to fine-tune the network."
},
{
"code": null,
"e": 26730,
"s": 26627,
"text": "First unfreeze the network and try to find a good range of learning rates for this particular network."
},
{
"code": null,
"e": 27045,
"s": 26730,
"text": "The method learn.lr_find() helps you find an optimal learning rate. It uses the technique developed in the 2015 paper Cyclical Learning Rates for Training Neural Networks (http://arxiv.org/abs/1506.01186), where we simply keep increasing the learning rate from a very small value, until the loss starts decreasing."
},
{
"code": null,
"e": 27120,
"s": 27045,
"text": "If you want to know more about finding the best learning rates, look here:"
},
{
"code": null,
"e": 27260,
"s": 27120,
"text": "TowardsDataScience::Speeding up Neural Net Training with a LR-Finder β Finding good initial learning rate for your network by Faizan Ahemad"
},
{
"code": null,
"e": 27273,
"s": 27260,
"text": "Letβs do it:"
},
{
"code": null,
"e": 27469,
"s": 27273,
"text": "# Unfreeze the networklearn.unfreeze()# Find optimum learning rateslearn.lr_find()# Include suggestion=True in order to obtain a suggestion on where to look...learn.recorder.plot(suggestion=True)"
},
{
"code": null,
"e": 27793,
"s": 27469,
"text": "Letβs fine tune the ResNet34. Weβll employ 30 epochs to be sure. The learning rate finder identified 1e-5 as a βsecureβ learning rate. So we will define a range of learning rates using the rule of thumb: ending at the βsecureβ rate 1e-5 and starting at a rate that is one order of magnitude higher: max_lr=slice(1e-4,1e-5)."
},
{
"code": null,
"e": 28092,
"s": 27793,
"text": "# Unfreeze the networklearn.unfreeze()learn.fit_one_cycle(30, max_lr=slice(1e-4,1e-5), callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma')])# Agora, salve como estaΜgio 2...learn.save('derma-stage-2')# Deploy definitivoexportStageTo(learn, path)"
},
{
"code": null,
"e": 28243,
"s": 28092,
"text": "So we achieved 93% accuracy with our first run. This is very good! The accuracy achieved in the tutorial and kernel above is respectively 85% and 86%."
},
{
"code": null,
"e": 28278,
"s": 28243,
"text": "Now letβs look at our statistics.:"
},
{
"code": null,
"e": 28475,
"s": 28278,
"text": "interp = ClassificationInterpretation.from_learner(learn)losses,idxs = interp.top_losses()# Test to see if there's not anything missing (must return True)len(data.valid_ds)==len(losses)==len(idxs)"
},
{
"code": null,
"e": 28556,
"s": 28475,
"text": "If this returns True, then plot the confusion matrix for the fine-tuned network:"
},
{
"code": null,
"e": 28609,
"s": 28556,
"text": "interp.plot_confusion_matrix(figsize=(5,5), dpi=100)"
},
{
"code": null,
"e": 28702,
"s": 28609,
"text": "The melanoma predictions look much better in this matrix! Letβs look at the training curves:"
},
{
"code": null,
"e": 28731,
"s": 28702,
"text": "learn.recorder.plot_losses()"
},
{
"code": null,
"e": 29039,
"s": 28731,
"text": "We can see that both, train and validation curve oscillated. The training curve seems to arrive at a plateau and it is separating from the validation curve, which is decreasing much slower. This indicates that we probably are moving towards an overfitting of the network. It would be indicated to stop here."
},
{
"code": null,
"e": 29254,
"s": 29039,
"text": "In the notebook we made available on Colab, we trained the network for another 30 epochs, only to be sure. It actually becomes worse, probably due to overfitting. So stopping here is a good choice for the ResNet34."
},
{
"code": null,
"e": 29475,
"s": 29254,
"text": "With the ResNet34 with achieved 92.9% accuracy. Letβs see if with a larger network we can perform better. We will create the DataBunch again, this time with a smaller batch size in order not to overload the GPU memory..."
},
{
"code": null,
"e": 30844,
"s": 29475,
"text": "bs = 28 # Batch size, 28 for medium images on a T4 GPU and ResNet50...size = 448 # Image size, 448x448 is double than the orignal # ImageNet size of the pre-trained ResNet we'll be using, # should be easy to train...path = Path(\"./data\") # The path to the 'train' folder you created...# Limit your augmentations: it's medical data! You do not want to phantasize data...# Warping, for example, will let your images badly distorted, so don't do it!# This dataset is big, so don't rotate the images either. Lets stick to flipping...tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_rotate=None, max_warp=None, max_zoom=1.0)# Create the DataBunch!# Remember that you'll have images that are bigger than 128x128 and images that are smaller, # so squish them all in order to occupy exactly 128x128 pixels...data = ImageDataBunch.from_csv('data', csv_labels='HAM10000_metadata.csv', suffix='.jpg', fn_col=1, label_col=2, ds_tfms=tfms, valid_pct = 0.2,size=size, bs=bs)print('Transforms = ', len(tfms))# Save the DataBunch in case the training goes south... so you won't have to regenerate it..# Remember: this DataBunch is tied to the batch size you selected. data.save('imageDataBunch-bs-'+str(bs)+'-size-'+str(size)+'.pkl')# Show the statistics of the Bunch...print(data.classes)data"
},
{
"code": null,
"e": 30882,
"s": 30844,
"text": "The output now should look like this:"
},
{
"code": null,
"e": 31340,
"s": 30882,
"text": "Transforms = 2['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']ImageDataBunch;Train: LabelList (8012 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListbkl,bkl,bkl,bkl,bklPath: data;Valid: LabelList (2003 items)x: ImageListImage (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448),Image (3, 448, 448)y: CategoryListnv,nv,nv,mel,bklPath: data;Test: None"
},
{
"code": null,
"e": 31363,
"s": 31340,
"text": "Now create a ResNet50:"
},
{
"code": null,
"e": 31453,
"s": 31363,
"text": "learn50 = cnn_learner(data, models.resnet50, metrics=[accuracy, error_rate])learn50.model"
},
{
"code": null,
"e": 31612,
"s": 31453,
"text": "Observe that we included accuracy in the metrics, so we will not need to manually perform the calculation based on the error rate. The model should look like:"
},
{
"code": null,
"e": 34476,
"s": 31612,
"text": "Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (4): Sequential( (0): Bottleneck( (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ).........(1): Sequential( (0): AdaptiveConcatPool2d( (ap): AdaptiveAvgPool2d(output_size=1) (mp): AdaptiveMaxPool2d(output_size=1) ) (1): Flatten() (2): BatchNorm1d(4096, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): Dropout(p=0.25) (4): Linear(in_features=4096, out_features=512, bias=True) (5): ReLU(inplace) (6): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (7): Dropout(p=0.5) (8): Linear(in_features=512, out_features=7, bias=True) ))"
},
{
"code": null,
"e": 34493,
"s": 34476,
"text": "Put it to learn:"
},
{
"code": null,
"e": 34732,
"s": 34493,
"text": "learn50.fit_one_cycle(15, callbacks=[SaveModelCallback(learn50, every='epoch', monitor='accuracy', name='derma50-1')])# Save weightslearn50.save('derma50-stage-1')# Deploy the whole network (with the databunch)exportStageTo(learn50, path)"
},
{
"code": null,
"e": 34754,
"s": 34732,
"text": "Look ath the results:"
},
{
"code": null,
"e": 34899,
"s": 34754,
"text": "interp = ClassificationInterpretation.from_learner(learn50)losses,idxs = interp.top_losses()interp.plot_confusion_matrix(figsize=(5,5), dpi=100)"
},
{
"code": null,
"e": 34928,
"s": 34899,
"text": "Look at the learning curves:"
},
{
"code": null,
"e": 34959,
"s": 34928,
"text": "learn50.recorder.plot_losses()"
},
{
"code": null,
"e": 35290,
"s": 34959,
"text": "For now, this did not impress: the network oscillated more than the ResNet34 during this first transfer learning phase and the results, even if numerically better (85% x 87% accuracy), actually look worse on a visual analysis of the confusion matrix. Letβs do a fine tuning of the ResNet50 and see if this produces better results."
},
{
"code": null,
"e": 35326,
"s": 35290,
"text": "We will do this in two experiments."
},
{
"code": null,
"e": 35527,
"s": 35326,
"text": "While training a Deep Neural Network selecting a good learning rate is essential for both fast convergence and a lower error. The first step in fine-tuning is to find an adequate range of learn rates:"
},
{
"code": null,
"e": 35729,
"s": 35527,
"text": "# Unfreeze the networklearn50.unfreeze()# Find optimum learning rateslearn50.lr_find()# Include suggestion=True in order to obtain a suggestion on where to look...learn50.recorder.plot(suggestion=True)"
},
{
"code": null,
"e": 35747,
"s": 35729,
"text": "This will output:"
},
{
"code": null,
"e": 35888,
"s": 35747,
"text": "LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.Min numerical gradient: 9.12E-07Min loss divided by 10: 1.10E-07"
},
{
"code": null,
"e": 36154,
"s": 35888,
"text": "The lower bound, 9.12E-07, we will round up to 1.0E-06. Now, you can fine-tune using our rule-of-thumb. We will define a range of learning rates using the rule of thumb: ending at the βsecureβ rate 1e-06 and starting at a rate that is one order of magnitude higher:"
},
{
"code": null,
"e": 36565,
"s": 36154,
"text": "# Unfreeze the networklearn50.unfreeze()learn50.fit_one_cycle(35, max_lr=slice(1e-5,1e-6), callbacks=[SaveModelCallback(learn50, every='epoch', monitor='accuracy', name='derma50')])# Save the weights of stage 2 each \"better\" epoch:learn50.save('derma50-stage-2')# Do not overwrite the stage 1 .pkl with stage 2 # We will need it for the ResNet50 Experiment #2# exportStageTo(learn50, path)"
},
{
"code": null,
"e": 36724,
"s": 36565,
"text": "So, after 35 epochs and a lot of processing, we arrived at 90% accuracy. This looks unpromising... Letβs look at the confusion matrix and the learning curves:"
},
{
"code": null,
"e": 36869,
"s": 36724,
"text": "interp = ClassificationInterpretation.from_learner(learn50)losses,idxs = interp.top_losses()interp.plot_confusion_matrix(figsize=(5,5), dpi=100)"
},
{
"code": null,
"e": 36900,
"s": 36869,
"text": "learn50.recorder.plot_losses()"
},
{
"code": null,
"e": 37897,
"s": 36900,
"text": "What we see here is a result that is much different from the ResNet34. With the ResNet50 the network learns the training set during the fine-tuning phase, but it is oscilllating all the time: some batches make it perform better, other batches make it turn back and perform worse. This normally means that the data are of bad quality and possess too much noise. In this case however, weβve already seen that we can achieve 93% accuracy with a ResNet34. So, bad data is not the case here. Another possibility is that the network has too much parameters and it is not generalizing, but adapting to individual instances of the training set, thus learning individual examples and de-generalizing. This makes its performance worse for other parts of the data set and so the network acts like a pendulum, going back and forth in the error space. The validation loss, that is much higher than the training loss during the whole fine-tuning process, corroborates this interpretation of the learning curve."
},
{
"code": null,
"e": 37954,
"s": 37897,
"text": "But we are stubborn... Letβs perform another experiment."
},
{
"code": null,
"e": 38125,
"s": 37954,
"text": "In the formar experiment we blindly accepted the suggestion from the analysis algorithm and took a very low learning rate. Maybe this was the reason for the bad learning?"
},
{
"code": null,
"e": 38424,
"s": 38125,
"text": "If we look at the learning rate graph, we can see that a plateau is already forming at about 1.0E-4. Then the learning rate plunges into two valleys, one at 1.0E-5 and another at 1.0E-6. What if we take the more stable, flat plateu zone, from 1.0E-4 to 1.0E-5 and make this our learning rate range?"
},
{
"code": null,
"e": 38521,
"s": 38424,
"text": "First, restore the network to the state you had when you finished the initial transfer learning:"
},
{
"code": null,
"e": 38608,
"s": 38521,
"text": "# Will always load a path/'export.pkl' deployment filelearn50 = restoreStageFrom(path)"
},
{
"code": null,
"e": 38662,
"s": 38608,
"text": "Fine-tune it again, now with max_lr=slice(1e-4,1e-5):"
},
{
"code": null,
"e": 38923,
"s": 38662,
"text": "# Unfreeze the networklearn50.unfreeze()learn50.fit_one_cycle(35, max_lr=slice(1e-4,1e-5), callbacks=[SaveModelCallback(learn50, every='epoch', monitor='accuracy', name='derma50')])learn50.save('derma50-stage-2')exportStageTo(learn50, path)"
},
{
"code": null,
"e": 38958,
"s": 38923,
"text": "Letβs look at the result graphics:"
},
{
"code": null,
"e": 39166,
"s": 38958,
"text": "These results are better than before,even if the network oscillated a lot. The confusion matrix, however, shows us that the results for melanoma, which is the most important pathology here, do not look good."
},
{
"code": null,
"e": 39288,
"s": 39166,
"text": "Letβs go in the other direction and experiment with a network that is smaller than ResNet34, instead of larger: ResNet18."
},
{
"code": null,
"e": 39404,
"s": 39288,
"text": "Why not, then, try a much smaller network and see how it behaves? Letβs try a ResNet18 with the dermatoscopic data!"
},
{
"code": null,
"e": 39598,
"s": 39404,
"text": "For this purpose we will change our batch size and re-generate the DataBunch. ResNet18s are much smaller and weβll have more memory avilable to us, so it makes sense to use a larger batch size:"
},
{
"code": null,
"e": 40967,
"s": 39598,
"text": "bs = 48 # Batch size, 64 for medium images on a T4 GPU and ResNet18...size = 448 # Image size, 448x448 is double than the orignal # ImageNet size of the pre-trained ResNet we'll be using, # should be easy to train...path = Path(\"./data\") # The path to the 'train' folder you created...# Limit your augmentations: it's medical data! You do not want to phantasize data...# Warping, for example, will let your images badly distorted, so don't do it!# This dataset is big, so don't rotate the images either. Lets stick to flipping...tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_rotate=None, max_warp=None, max_zoom=1.0)# Create the DataBunch!# Remember that you'll have images that are bigger than 128x128 and images that are smaller, # so squish them all in order to occupy exactly 128x128 pixels...data = ImageDataBunch.from_csv('data', csv_labels='HAM10000_metadata.csv', suffix='.jpg', fn_col=1, label_col=2, ds_tfms=tfms, valid_pct = 0.2,size=size, bs=bs)print('Transforms = ', len(tfms))# Save the DataBunch in case the training goes south... so you won't have to regenerate it..# Remember: this DataBunch is tied to the batch size you selected. data.save('imageDataBunch-bs-'+str(bs)+'-size-'+str(size)+'.pkl')# Show the statistics of the Bunch...print(data.classes)data"
},
{
"code": null,
"e": 40987,
"s": 40967,
"text": "Create the network:"
},
{
"code": null,
"e": 41073,
"s": 40987,
"text": "learn = cnn_learner(data, models.resnet18, metrics=[accuracy, error_rate])learn.model"
},
{
"code": null,
"e": 41206,
"s": 41073,
"text": "The model will look like this (observe that this smaller ResNet model has only 1024 out features instead of 4096 in the last block):"
},
{
"code": null,
"e": 42509,
"s": 41206,
"text": "Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (4): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) )......... (1): Sequential( (0): AdaptiveConcatPool2d( (ap): AdaptiveAvgPool2d(output_size=1) (mp): AdaptiveMaxPool2d(output_size=1) ) (1): Flatten() (2): BatchNorm1d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): Dropout(p=0.25) (4): Linear(in_features=1024, out_features=512, bias=True) (5): ReLU(inplace) (6): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (7): Dropout(p=0.5) (8): Linear(in_features=512, out_features=7, bias=True) ))"
},
{
"code": null,
"e": 42548,
"s": 42509,
"text": "Letβs transfer-learn it for 15 epochs:"
},
{
"code": null,
"e": 42714,
"s": 42548,
"text": "learn.fit_one_cycle(15, callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma-1')])learn.save('derma-stage-1')exportStageTo(learn, path)"
},
{
"code": null,
"e": 42857,
"s": 42714,
"text": "interp = ClassificationInterpretation.from_learner(learn)losses,idxs = interp.top_losses()interp.plot_confusion_matrix(figsize=(5,5), dpi=100)"
},
{
"code": null,
"e": 42886,
"s": 42857,
"text": "learn.recorder.plot_losses()"
},
{
"code": null,
"e": 42981,
"s": 42886,
"text": "Numerically, this 0.5% better than the ResNet34. Letβs look howit behaves after a fine-tuning:"
},
{
"code": null,
"e": 43177,
"s": 42981,
"text": "# Unfreeze the networklearn.unfreeze()# Find optimum learning rateslearn.lr_find()# Include suggestion=True in order to obtain a suggestion on where to look...learn.recorder.plot(suggestion=True)"
},
{
"code": null,
"e": 43466,
"s": 43177,
"text": "Again, we have a curve that first achieves a plateau and then plunges into two holes. Only here the holes are deeper down than the plateau. Letβs consider that, in this case, the holes are significant and accept the suggestion of the learning rate finder and make max_lr=slice(1e-5,1e-6):"
},
{
"code": null,
"e": 43607,
"s": 43466,
"text": "LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.Min numerical gradient: 1.32E-06Min loss divided by 10: 1.58E-07"
},
{
"code": null,
"e": 43858,
"s": 43607,
"text": "# Unfreeze the networklearn.unfreeze()learn.fit_one_cycle(35, max_lr=slice(1e-5,1e-6), callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='derma18')])learn.save('derma18-stage-2')exportStageTo(learn, path)"
},
{
"code": null,
"e": 43942,
"s": 43858,
"text": "88% accuracy! That is much worse than the ResNet34. Letβs plot the learning curves:"
},
{
"code": null,
"e": 43971,
"s": 43942,
"text": "learn.recorder.plot_losses()"
},
{
"code": null,
"e": 44171,
"s": 43971,
"text": "What we see here is that the ResNet18 oscillates still more than the ResNet50, when we trained it with a too small learning rate. This is an indication that here also the learning rate was too small."
},
{
"code": null,
"e": 44435,
"s": 44171,
"text": "Iβve repeated the fine-tuning experiment #2 we did before with the ResNet50 and set the learning rate range to max_lr=slice(1e-4,1e-5) and trained it again. In this case the ResNet18 achieved a validation accuracy of 0.904643. The results graphics look like this:"
},
{
"code": null,
"e": 44608,
"s": 44435,
"text": "This is better than before but still worse than the ResNet34 and the ResNet50. The ResNet18 does not seem to be a good choice for this problem. The code is in our notebook."
},
{
"code": null,
"e": 44881,
"s": 44608,
"text": "What do you do if your training was interrupted? This can happen because you reached your 12 hours of continuous βfreeβ operating time on a Google Colab notebook or because your computer stopped for some reason. I live in Brazil and events of power shortages are common..."
},
{
"code": null,
"e": 45362,
"s": 44881,
"text": "The fit_one_cycle method works with varying, adaptive learning rates, following a curve where the rate is first increased and then decreased. If you interrupt a training in epoch #10 of, say, 20 epochs and then start again for more 9 epochs, youβll not have the same result as training uninterruptedly for 20 epochs. You have to be able to record where you stopped and then resume the training cycle from that point and with the correct hyperparameters for that part of the cycle."
},
{
"code": null,
"e": 45430,
"s": 45362,
"text": "The first thing you have to do is to save your network every epoch:"
},
{
"code": null,
"e": 45596,
"s": 45430,
"text": "learn.fit_one_cycle(20, max_lr=slice(1e-5,1e-6), callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name='saved_net')])"
},
{
"code": null,
"e": 45786,
"s": 45596,
"text": "This will have your network be saved every epoch, with the name you provided followed by _#epoch. So at epoch #3, the file saved_net_3.pth will be written. This file you can load after you:"
},
{
"code": null,
"e": 45815,
"s": 45786,
"text": "re-created the DataBunch and"
},
{
"code": null,
"e": 45852,
"s": 45815,
"text": "re-instantiated the network with it."
},
{
"code": null,
"e": 46005,
"s": 45852,
"text": "After reloading the .pth file, you can restart your training, only youβll tell fit_one_cycle to consider 20 epochs, but to start training from epoch #4."
},
{
"code": null,
"e": 46043,
"s": 46005,
"text": "To learn how this is done, look here:"
},
{
"code": null,
"e": 46107,
"s": 46043,
"text": "Divide a long 1cycle policy into smaller ones β a GitHub by PPW"
},
{
"code": null,
"e": 46125,
"s": 46107,
"text": "How do you do it?"
},
{
"code": null,
"e": 46322,
"s": 46125,
"text": "The fit_one_cycle method in fast.ai has been developed to allow you to tell it from which part of the cycle to resume an interrupted training. The code for resuming a training will look like this:"
},
{
"code": null,
"e": 47219,
"s": 46322,
"text": "# Create a new net if training was interrupted and you had to # restart your Colab sessionlearn = cnn_learner(data, models.<your_model_here>, metrics=[accuracy, error_rate])# If you're resuming, only indicating the epoch from which to # resume, indicated by start_epoch=<epoch#> will load the last # saved .pth, it is not necessary to explicitly reload the last # epoch, you only should NOT change the name given in # name=<callback_save_file>:# when resuming fast.ai will try to reload # <callback_save_file>_<previous_epoch>.pth# Unfreeze the networklearn50.unfreeze()# Use start_epoch=<some_epoch> to resume training...learn.fit_one_cycle(20, max_lr=slice(1e-5,1e-6), start_epoch=<next_epoch#>, callbacks=[SaveModelCallback(learn, every='epoch', monitor='accuracy', name=<callback_save_file>)])"
},
{
"code": null,
"e": 47310,
"s": 47219,
"text": "fast.ai will tell you βLoaded <callback_save_file>_<previous_epoch#>β and resume training."
},
{
"code": null,
"e": 47385,
"s": 47310,
"text": "You can look at all parameters supported by the fit_one_cycle method here:"
},
{
"code": null,
"e": 47431,
"s": 47385,
"text": "https://docs.fast.ai/train.html#fit_one_cycle"
},
{
"code": null,
"e": 47848,
"s": 47431,
"text": "Employing an image resolution of 448x448 and fast.ai, we obtained a validation accuracy of roughly 93% with two of the three network models we employed in our experiment, ResNet34 and ResNet50. This is much better than the 85% of the tutorial above, which employed a MobileNet, an image resolution of 224x224 and Keras. The (presently) most voted Kernel on Kaggle (employs TensorFlow.js) obtained a precision of 86%."
},
{
"code": null,
"e": 48147,
"s": 47848,
"text": "In the ISIC 2018 challenge final test of task #3 the highest ranking competitor, Jordan Yap from MetaOptima Technology Inc., achieved an accuracy of 95.8% and a balanced multiclass accuracy, the competitor evaluation criterion chosen by ISIC, of 88.5%. Jordan Yap employed a method that based upon:"
},
{
"code": null,
"e": 48190,
"s": 48147,
"text": "additional, external data [33,644 images];"
},
{
"code": null,
"e": 48268,
"s": 48190,
"text": "images with a low resolution, equivalent to the original ImageNet-resolution;"
},
{
"code": null,
"e": 48373,
"s": 48268,
"text": "an ensemble of 19 classification algorithms, of which one was not a neural network (histogram analysis);"
},
{
"code": null,
"e": 48454,
"s": 48373,
"text": "an XGBoost Classifier, which was trained on top of the results of this ensemble."
},
{
"code": null,
"e": 48639,
"s": 48454,
"text": "The paper Aleksey Nozdryn-Plotnicki, Jordan Yap and William Yolland, submitted to the ISIC Skin Image Analysis Workshop and Challenge @ MICCAI 2018 together with their results is here."
},
{
"code": null,
"e": 49048,
"s": 48639,
"text": "Our results are not directly comparable to the original ISIC 2018 challenge because there ISIC provided a test set of 1512 images manually extracted from the HAM1000 dataset and all competitors had to employ that test set and submit their results to ISIC. We validated our training with a set of 2003 images randomly extracted from the HAM1000 dataset and trained our networks with the remaining 8012 images."
},
{
"code": null,
"e": 49092,
"s": 49048,
"text": "You can look at the ISIC 2018 results here:"
},
{
"code": null,
"e": 49123,
"s": 49092,
"text": "ISIC 2018 β Task 3: Final Test"
},
{
"code": null,
"e": 49185,
"s": 49123,
"text": "ISIC Challenge 2018 Leaderboards (click on the βTask 3β pane)"
},
{
"code": null,
"e": 49624,
"s": 49185,
"text": "It is, however, interesting to note that the accuracy of 92.9% we achieved with fast.ai and just one network, a ResNet34, and a total training time of 190 minutes on a NVIDIA T4 GPU (4.2 x 10 + 4.3 x 35 minutes), is only 2.9% worse than the accuracy the highest ranking competitor of the ISIC 2018 challenge obtained with a considerably more complex approach, employing a machine learning algorithm on top of 18 different neural networks."
},
{
"code": null,
"e": 49830,
"s": 49624,
"text": "This is most probably due to the fact that we employed twice the image resolution, allowing for much more details, but the HYPOs (hyper parameter optimizations) in fast.ai have probably also played a role."
},
{
"code": null,
"e": 50282,
"s": 49830,
"text": "ResNet34 is a good choice to start: ResNets are really well-managed in fast.ai, with various easy-to-use HYPOs (hyper parameter optimizations). If you do not know which network to use, take the ResNet34, which will be small enough to train relatively fast, even if you do it with your GPU at home, and big enough to represent a large set of problems. How ResNet34 trains will provide hints if you should go up or go down with the size of your network."
},
{
"code": null,
"e": 51258,
"s": 50282,
"text": "Blindly accepting learning rate suggestion is not always the best option: the lr_find() for the ResNet50 produces a long plateau and the method suggested a very low learning rate value in a small valley at the left end of the graphic. When we trained the network with this value, it oscillated and did not produce a good result (90% accuracy only). When we employed a visual analysis of the graph and took as the lower bound for the learning rate range a value one order of magnitude higher, which lied at the beginning of the flatter part of the plateau, the ResNet50 learned much better and achieved the same 93% accuracy of the ResNet34. So, use the suggest=True mode but give it a no-nonsense treatment before you accept it, actually looking at the graphic. This is the second rule-of-thumb of the learning rate range: look at the whole graphic and find the real plateau β your ideal lower bound for the learning rate range will lie towards the beginning of this plateau."
},
{
"code": null,
"e": 51648,
"s": 51258,
"text": "The method learn.lr_find() helps you find an optimal learning rate. It uses the technique developed in the 2015 paper Cyclical Learning Rates for Training Neural Networks (http://arxiv.org/abs/1506.01186), where we simply keep increasing the learning rate from a very small value, until the loss starts decreasing. If you want to know more about finding the best learning rates, look here:"
},
{
"code": null,
"e": 51788,
"s": 51648,
"text": "TowardsDataScience::Speeding up Neural Net Training with a LR-Finder β Finding good initial learning rate for your network by Faizan Ahemad"
},
{
"code": null,
"e": 52043,
"s": 51788,
"text": "Bigger is not always better: in the end, the ResNet50 perfomed almost identically to the ResNet34, but took much more time to train and showed slightly worse results. It is a bad choice to begin your training space exploration with a large network model."
},
{
"code": null,
"e": 52361,
"s": 52043,
"text": "Image resolution plays a role: employing twice the resolution the highest ranking competitor of the ISIC 2018 Challenge used, we obtained comparable results with a single, relatively simple, ResNet34,while that competitor employed a machine learning method on top of 18 different networks, including a huge ResNet152."
},
{
"code": null,
"e": 53147,
"s": 52361,
"text": "Fast.ai is fast: Finally, compared to the other approaches, with fast.ai we were able to solve the same classification problem employing much less code while using high-level hyperparameter optimization strategies that allowed us to train much faster. At the same time, a set of high level functions allows us also to easily inspect the results both as tables and as graphs. This simplicity allowed us to experiment with three different network models and compare their results. This shows that fast.ai is a very promising alternative to more traditional CNN frameworks, especially if the task at hand is a βstandardβ deep learning task such as image classification, object detection or semantic segmentation, that can be solved by fine-tuning off-the-shelf pre-trained network models."
},
{
"code": null,
"e": 53243,
"s": 53147,
"text": "This work was the result of a collaborative effort of a team of engaged researchers besides me:"
},
{
"code": null,
"e": 53291,
"s": 53243,
"text": "Daniel Holthausen Nunes <daniel@floripa.com.br>"
},
{
"code": null,
"e": 53356,
"s": 53291,
"text": "Luiz Antonio Buschetto Macarini <luiz.buschetto@posgrad.ufsc.br>"
},
{
"code": null,
"e": 53406,
"s": 53356,
"text": "Marcelo Ricardo Stemmer <marcelo.stemmer@ufsc.br>"
},
{
"code": null,
"e": 53557,
"s": 53406,
"text": "We wish also to thank to JuΜrgen Kreusch <juergen.kreusch@gmail.com> and Luis Fernando Kopke <luiskopke@uol.com.br>for the stereodermoscopic material."
},
{
"code": null,
"e": 53684,
"s": 53557,
"text": "[1]Kreusch, J. Incident light microscopy: reflections on microscopy of the living skin. Int J Dermatol. 1992 Sep;31(9):618β20."
}
] |
Portfolio Optimization for Minimum Risk with Scipy β Efficient Frontier Explained | by J Li | Towards Data Science
|
(This post is also available in my blog)
Given 4 assetsβ risk and return as following, what could be the risk-return for any portfolio built with the assets. One may think that all possible values have to fall inside the convex hull. But it is possible to go beyond the bond, if you consider the correlation coefficient among the assets. Thatβs being said combining inversely correlated assets can construct a portfolio with lower risk. More details can be found in my previous post.
To demonstrate portfolio risk-return can go beyond the area, I get 3000 samples of randomly-weighted portfolio and plot their risk-return.
Follow step 1 in this post
This is tutorial, we pick 4 stocks BA (Boeing), C (Citigroup), AAL (American Airlines Group), NFLX (Netflix) from 4 different sectors for analysis. As my previous post, risk is measured by daily returnβs standard deviation. The return is computed as below
K * (expected return β expected risk free rate)
K is the square root of frequency of sampling. That means if we measure with daily return, K is sqrt(250) (There are roughly 250 trading days in a year). Treasury rate is commonly used as risk free rate. In this tutorial, we will use 0.
scatter plotting the individual asset risk-return
import pandas_datareader.data as webimport pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom scipy.optimize import minimizedef get_risk(prices): return (prices / prices.shift(1) - 1).dropna().std().valuesdef get_return(prices): return ((prices / prices.shift(1) - 1).dropna().mean() * np.sqrt(250)).valuessymbols = ['BA', 'C', 'AAL', 'NFLX']prices = pd.DataFrame(index=pd.date_range(start, end))for symbol in symbols: portfolio = web.DataReader(name=symbol, data_source='quandl', start=start, end=end) close = portfolio[['AdjClose']] close = close.rename(columns={'AdjClose': symbol}) prices = prices.join(close) portfolio.to_csv("~/workspace/{}.csv".format(symbol))prices = prices.dropna()risk_v = get_risk(prices)return_v = get_return(prices)fig, ax = plt.subplots()ax.scatter(x=risk_v, y=return_v, alpha=0.5)ax.set(title='Return and Risk', xlabel='Risk', ylabel='Return')for i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))plt.show()
def random_weights(n): weights = np.random.rand(n) return weights / sum(weights)def get_portfolio_risk(weights, normalized_prices): portfolio_val = (normalized_prices * weights).sum(axis=1) portfolio = pd.DataFrame(index=normalized_prices.index, data={'portfolio': portfolio_val}) return (portfolio / portfolio.shift(1) - 1).dropna().std().values[0]def get_portfolio_return(weights, normalized_prices): portfolio_val = (normalized_prices * weights).sum(axis=1) portfolio = pd.DataFrame(index=normalized_prices.index, data={'portfolio': portfolio_val}) ret = get_return(portfolio) return ret[0]risk_all = np.array([])return_all = np.array([])# for demo purpose, plot 3000 random portoflionp.random.seed(0)normalized_prices = prices / prices.ix[0, :]for _ in range(0, 3000): weights = random_weights(len(symbols)) portfolio_val = (normalized_prices * weights).sum(axis=1) portfolio = pd.DataFrame(index=prices.index, data={'portfolio': portfolio_val}) risk = get_risk(portfolio) ret = get_return(portfolio) risk_all = np.append(risk_all, risk) return_all = np.append(return_all, ret) p = get_portfolio_risk(weights=weights, normalized_prices=normalized_prices)fig, ax = plt.subplots()ax.scatter(x=risk_all, y=return_all, alpha=0.5)ax.set(title='Return and Risk', xlabel='Risk', ylabel='Return')for i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))ax.scatter(x=risk_v, y=return_v, alpha=0.5, color='red')ax.set(title='Return and Risk', xlabel='Risk', ylabel='Return')ax.grid()plt.show()
Risk comes from not knowing what you are doing β Warren Buffett
Letβs look at the risk and return. we do see that there are blue dots outside of the area. So diversification does help reduce the risk. But how do we find the best or efficient weight?
From wikipedia, in modern portfolio theory, the efficient frontier (or portfolio frontier) is an investment portfolio which occupies the βefficientβ parts of the risk-return spectrum.
Here we will use scipyβs optimizer to get optimal weights for different targeted return. Note that, we have bounds that make sure weight are in range [0, 1] and constraints to ensure sum of weights is 1, also portfolio return meets our target return. With all this condition, scipy optimizer is able to find the best allocation.
# optimizerdef optimize(prices, symbols, target_return=0.1): normalized_prices = prices / prices.ix[0, :] init_guess = np.ones(len(symbols)) * (1.0 / len(symbols)) bounds = ((0.0, 1.0),) * len(symbols) weights = minimize(get_portfolio_risk, init_guess, args=(normalized_prices,), method='SLSQP', options={'disp': False}, constraints=({'type': 'eq', 'fun': lambda inputs: 1.0 - np.sum(inputs)}, {'type': 'eq', 'args': (normalized_prices,), 'fun': lambda inputs, normalized_prices: target_return - get_portfolio_return(weights=inputs, normalized_prices=normalized_prices)}), bounds=bounds) return weights.xoptimal_risk_all = np.array([])optimal_return_all = np.array([])for target_return in np.arange(0.005, .0402, .0005): opt_w = optimize(prices=prices, symbols=symbols, target_return=target_return) optimal_risk_all = np.append(optimal_risk_all, get_portfolio_risk(opt_w, normalized_prices)) optimal_return_all = np.append(optimal_return_all, get_portfolio_return(opt_w, normalized_prices))# plottingfig, ax = plt.subplots()# random portfolio risk returnax.scatter(x=risk_all, y=return_all, alpha=0.5)# optimal portfolio risk returnfor i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))ax.plot(optimal_risk_all, optimal_return_all, '-', color='green')# symbol risk returnfor i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))ax.scatter(x=risk_v, y=return_v, color='red')ax.set(title='Efficient Frontier', xlabel='Risk', ylabel='Return')ax.grid()plt.savefig('return_risk_efficient_frontier.png', bbox_inches='tight')
The green line indicate the efficient frontier. Now we know the best allocation with a given target return. Next question, what is the best allocation overall? Portfolio performance can be evaluated with return/risk ratio (known as Sharpe Ratio). High Sharpe Ratio indicates good balance of return and risk. This allocation can be found by drawing a Capital Allocation line that tangent to the efficient frontier. The tangent point is the allocation yields highest Sharpe ratio. To learn more, you can take a look at this article on how to find the highest sharpe ratio from the efficient frontier with Capital Allocation Line (CAL).
Now we know why diversification can help your investment. If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc. Happy investment and coding!
My next post β Trading Strategy: Technical Analysis with Python TA-Lib.
Note from Towards Data Scienceβs editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each authorβs contribution. You should not rely on an authorβs works without seeking professional advice. See our Reader Terms for details.
Recommended reading:
Hands-On Machine Learning
Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython
What Hedge Funds Really Do
My posts:
My posts about FAANG interview
My YouTube Channel
My posts about Finance and Tech
From CRUD web app dev to SDE in voice assistant β My ongoing Journey to Machine Learning
Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA
Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda
Full Stack Development Tutorial: Visualize Trading Data on Angular SPA (1)
Reinforcement Learning: Introduction to Q Learning
|
[
{
"code": null,
"e": 212,
"s": 171,
"text": "(This post is also available in my blog)"
},
{
"code": null,
"e": 655,
"s": 212,
"text": "Given 4 assetsβ risk and return as following, what could be the risk-return for any portfolio built with the assets. One may think that all possible values have to fall inside the convex hull. But it is possible to go beyond the bond, if you consider the correlation coefficient among the assets. Thatβs being said combining inversely correlated assets can construct a portfolio with lower risk. More details can be found in my previous post."
},
{
"code": null,
"e": 794,
"s": 655,
"text": "To demonstrate portfolio risk-return can go beyond the area, I get 3000 samples of randomly-weighted portfolio and plot their risk-return."
},
{
"code": null,
"e": 821,
"s": 794,
"text": "Follow step 1 in this post"
},
{
"code": null,
"e": 1077,
"s": 821,
"text": "This is tutorial, we pick 4 stocks BA (Boeing), C (Citigroup), AAL (American Airlines Group), NFLX (Netflix) from 4 different sectors for analysis. As my previous post, risk is measured by daily returnβs standard deviation. The return is computed as below"
},
{
"code": null,
"e": 1125,
"s": 1077,
"text": "K * (expected return β expected risk free rate)"
},
{
"code": null,
"e": 1362,
"s": 1125,
"text": "K is the square root of frequency of sampling. That means if we measure with daily return, K is sqrt(250) (There are roughly 250 trading days in a year). Treasury rate is commonly used as risk free rate. In this tutorial, we will use 0."
},
{
"code": null,
"e": 1412,
"s": 1362,
"text": "scatter plotting the individual asset risk-return"
},
{
"code": null,
"e": 2419,
"s": 1412,
"text": "import pandas_datareader.data as webimport pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom scipy.optimize import minimizedef get_risk(prices): return (prices / prices.shift(1) - 1).dropna().std().valuesdef get_return(prices): return ((prices / prices.shift(1) - 1).dropna().mean() * np.sqrt(250)).valuessymbols = ['BA', 'C', 'AAL', 'NFLX']prices = pd.DataFrame(index=pd.date_range(start, end))for symbol in symbols: portfolio = web.DataReader(name=symbol, data_source='quandl', start=start, end=end) close = portfolio[['AdjClose']] close = close.rename(columns={'AdjClose': symbol}) prices = prices.join(close) portfolio.to_csv(\"~/workspace/{}.csv\".format(symbol))prices = prices.dropna()risk_v = get_risk(prices)return_v = get_return(prices)fig, ax = plt.subplots()ax.scatter(x=risk_v, y=return_v, alpha=0.5)ax.set(title='Return and Risk', xlabel='Risk', ylabel='Return')for i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))plt.show()"
},
{
"code": null,
"e": 3986,
"s": 2419,
"text": "def random_weights(n): weights = np.random.rand(n) return weights / sum(weights)def get_portfolio_risk(weights, normalized_prices): portfolio_val = (normalized_prices * weights).sum(axis=1) portfolio = pd.DataFrame(index=normalized_prices.index, data={'portfolio': portfolio_val}) return (portfolio / portfolio.shift(1) - 1).dropna().std().values[0]def get_portfolio_return(weights, normalized_prices): portfolio_val = (normalized_prices * weights).sum(axis=1) portfolio = pd.DataFrame(index=normalized_prices.index, data={'portfolio': portfolio_val}) ret = get_return(portfolio) return ret[0]risk_all = np.array([])return_all = np.array([])# for demo purpose, plot 3000 random portoflionp.random.seed(0)normalized_prices = prices / prices.ix[0, :]for _ in range(0, 3000): weights = random_weights(len(symbols)) portfolio_val = (normalized_prices * weights).sum(axis=1) portfolio = pd.DataFrame(index=prices.index, data={'portfolio': portfolio_val}) risk = get_risk(portfolio) ret = get_return(portfolio) risk_all = np.append(risk_all, risk) return_all = np.append(return_all, ret) p = get_portfolio_risk(weights=weights, normalized_prices=normalized_prices)fig, ax = plt.subplots()ax.scatter(x=risk_all, y=return_all, alpha=0.5)ax.set(title='Return and Risk', xlabel='Risk', ylabel='Return')for i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))ax.scatter(x=risk_v, y=return_v, alpha=0.5, color='red')ax.set(title='Return and Risk', xlabel='Risk', ylabel='Return')ax.grid()plt.show()"
},
{
"code": null,
"e": 4050,
"s": 3986,
"text": "Risk comes from not knowing what you are doing β Warren Buffett"
},
{
"code": null,
"e": 4236,
"s": 4050,
"text": "Letβs look at the risk and return. we do see that there are blue dots outside of the area. So diversification does help reduce the risk. But how do we find the best or efficient weight?"
},
{
"code": null,
"e": 4420,
"s": 4236,
"text": "From wikipedia, in modern portfolio theory, the efficient frontier (or portfolio frontier) is an investment portfolio which occupies the βefficientβ parts of the risk-return spectrum."
},
{
"code": null,
"e": 4749,
"s": 4420,
"text": "Here we will use scipyβs optimizer to get optimal weights for different targeted return. Note that, we have bounds that make sure weight are in range [0, 1] and constraints to ensure sum of weights is 1, also portfolio return meets our target return. With all this condition, scipy optimizer is able to find the best allocation."
},
{
"code": null,
"e": 6619,
"s": 4749,
"text": "# optimizerdef optimize(prices, symbols, target_return=0.1): normalized_prices = prices / prices.ix[0, :] init_guess = np.ones(len(symbols)) * (1.0 / len(symbols)) bounds = ((0.0, 1.0),) * len(symbols) weights = minimize(get_portfolio_risk, init_guess, args=(normalized_prices,), method='SLSQP', options={'disp': False}, constraints=({'type': 'eq', 'fun': lambda inputs: 1.0 - np.sum(inputs)}, {'type': 'eq', 'args': (normalized_prices,), 'fun': lambda inputs, normalized_prices: target_return - get_portfolio_return(weights=inputs, normalized_prices=normalized_prices)}), bounds=bounds) return weights.xoptimal_risk_all = np.array([])optimal_return_all = np.array([])for target_return in np.arange(0.005, .0402, .0005): opt_w = optimize(prices=prices, symbols=symbols, target_return=target_return) optimal_risk_all = np.append(optimal_risk_all, get_portfolio_risk(opt_w, normalized_prices)) optimal_return_all = np.append(optimal_return_all, get_portfolio_return(opt_w, normalized_prices))# plottingfig, ax = plt.subplots()# random portfolio risk returnax.scatter(x=risk_all, y=return_all, alpha=0.5)# optimal portfolio risk returnfor i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))ax.plot(optimal_risk_all, optimal_return_all, '-', color='green')# symbol risk returnfor i, symbol in enumerate(symbols): ax.annotate(symbol, (risk_v[i], return_v[i]))ax.scatter(x=risk_v, y=return_v, color='red')ax.set(title='Efficient Frontier', xlabel='Risk', ylabel='Return')ax.grid()plt.savefig('return_risk_efficient_frontier.png', bbox_inches='tight')"
},
{
"code": null,
"e": 7253,
"s": 6619,
"text": "The green line indicate the efficient frontier. Now we know the best allocation with a given target return. Next question, what is the best allocation overall? Portfolio performance can be evaluated with return/risk ratio (known as Sharpe Ratio). High Sharpe Ratio indicates good balance of return and risk. This allocation can be found by drawing a Capital Allocation line that tangent to the efficient frontier. The tangent point is the allocation yields highest Sharpe ratio. To learn more, you can take a look at this article on how to find the highest sharpe ratio from the efficient frontier with Capital Allocation Line (CAL)."
},
{
"code": null,
"e": 7519,
"s": 7253,
"text": "Now we know why diversification can help your investment. If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc. Happy investment and coding!"
},
{
"code": null,
"e": 7591,
"s": 7519,
"text": "My next post β Trading Strategy: Technical Analysis with Python TA-Lib."
},
{
"code": null,
"e": 7891,
"s": 7591,
"text": "Note from Towards Data Scienceβs editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each authorβs contribution. You should not rely on an authorβs works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 7912,
"s": 7891,
"text": "Recommended reading:"
},
{
"code": null,
"e": 7938,
"s": 7912,
"text": "Hands-On Machine Learning"
},
{
"code": null,
"e": 8011,
"s": 7938,
"text": "Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython"
},
{
"code": null,
"e": 8038,
"s": 8011,
"text": "What Hedge Funds Really Do"
},
{
"code": null,
"e": 8048,
"s": 8038,
"text": "My posts:"
},
{
"code": null,
"e": 8079,
"s": 8048,
"text": "My posts about FAANG interview"
},
{
"code": null,
"e": 8098,
"s": 8079,
"text": "My YouTube Channel"
},
{
"code": null,
"e": 8130,
"s": 8098,
"text": "My posts about Finance and Tech"
},
{
"code": null,
"e": 8219,
"s": 8130,
"text": "From CRUD web app dev to SDE in voice assistant β My ongoing Journey to Machine Learning"
},
{
"code": null,
"e": 8309,
"s": 8219,
"text": "Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA"
},
{
"code": null,
"e": 8410,
"s": 8309,
"text": "Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda"
},
{
"code": null,
"e": 8485,
"s": 8410,
"text": "Full Stack Development Tutorial: Visualize Trading Data on Angular SPA (1)"
}
] |
Select all except the first character in a string in MySQL?
|
To select all except the first character in a string, you can use SUBSTR() method. Let us first create a table β
mysql> create table DemoTable
(
FirstName varchar(20)
);
Query OK, 0 rows affected (0.63 sec)
Insert records in the table using insert command β
mysql> insert into DemoTable values('Larry');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.14 sec)
Display records from the table using select command β
mysql> select *from DemoTable;
This will produce the following output β
+-----------+
| FirstName |
+-----------+
| Larry |
| Carol |
| Robert |
| David |
+-----------+
4 rows in set (0.00 sec)
Here is the query to select all except the first character in a string β
mysql> select substr(FirstName,2) from DemoTable;
This will produce the following output β
+---------------------+
| substr(FirstName,2) |
+---------------------+
| arry |
| arol |
| obert |
| avid |
+---------------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "To select all except the first character in a string, you can use SUBSTR() method. Let us first create a table β"
},
{
"code": null,
"e": 1272,
"s": 1175,
"text": "mysql> create table DemoTable\n(\n FirstName varchar(20)\n);\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1323,
"s": 1272,
"text": "Insert records in the table using insert command β"
},
{
"code": null,
"e": 1652,
"s": 1323,
"text": "mysql> insert into DemoTable values('Larry');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable values('Carol');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Robert');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('David');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1706,
"s": 1652,
"text": "Display records from the table using select command β"
},
{
"code": null,
"e": 1737,
"s": 1706,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1778,
"s": 1737,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1915,
"s": 1778,
"text": "+-----------+\n| FirstName |\n+-----------+\n| Larry |\n| Carol |\n| Robert |\n| David |\n+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1988,
"s": 1915,
"text": "Here is the query to select all except the first character in a string β"
},
{
"code": null,
"e": 2038,
"s": 1988,
"text": "mysql> select substr(FirstName,2) from DemoTable;"
},
{
"code": null,
"e": 2079,
"s": 2038,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2296,
"s": 2079,
"text": "+---------------------+\n| substr(FirstName,2) |\n+---------------------+\n| arry |\n| arol |\n| obert |\n| avid |\n+---------------------+\n4 rows in set (0.00 sec)"
}
] |
C program to check if a given string is Keyword or not?
|
Keyword is a predefined or reserved word which is available in C++ library with a fixed meaning and used to perform an internal operation. C++ Language supports more than 64 keywords.
Every Keyword exists in lower case letters like auto, break, case, const, continue, int etc.
32 Keywords in C++ Language which is also available in the C language.
These are 30 reserved words that were not in C, but added to C++
Input: str=βforβ
Output: for is a keyword
Keywords are reserved words which cannot be used as variable names in program.
Keywords are reserved words which cannot be used as variable names in program.
There are 32 keywords in the C programming language.
There are 32 keywords in the C programming language.
Compare the string with each keyword if the string is same then string is keyword
Live Demo
#include <stdio.h>
#include <string.h>
int main() {
char keyword[32][10]={
"auto","double","int","struct","break","else","long",
"switch","case","enum","register","typedef","char",
"extern","return","union","const","float","short",
"unsigned","continue","for","signed","void","default",
"goto","sizeof","voltile","do","if","static","while"
} ;
char str[]="which";
int flag=0,i;
for(i = 0; i < 32; i++) {
if(strcmp(str,keyword[i])==0) {
flag=1;
}
}
if(flag==1)
printf("%s is a keyword",str);
else
printf("%s is not a keyword",str);
}
which is a keyword
|
[
{
"code": null,
"e": 1246,
"s": 1062,
"text": "Keyword is a predefined or reserved word which is available in C++ library with a fixed meaning and used to perform an internal operation. C++ Language supports more than 64 keywords."
},
{
"code": null,
"e": 1339,
"s": 1246,
"text": "Every Keyword exists in lower case letters like auto, break, case, const, continue, int etc."
},
{
"code": null,
"e": 1410,
"s": 1339,
"text": "32 Keywords in C++ Language which is also available in the C language."
},
{
"code": null,
"e": 1475,
"s": 1410,
"text": "These are 30 reserved words that were not in C, but added to C++"
},
{
"code": null,
"e": 1517,
"s": 1475,
"text": "Input: str=βforβ\nOutput: for is a keyword"
},
{
"code": null,
"e": 1596,
"s": 1517,
"text": "Keywords are reserved words which cannot be used as variable names in program."
},
{
"code": null,
"e": 1675,
"s": 1596,
"text": "Keywords are reserved words which cannot be used as variable names in program."
},
{
"code": null,
"e": 1728,
"s": 1675,
"text": "There are 32 keywords in the C programming language."
},
{
"code": null,
"e": 1781,
"s": 1728,
"text": "There are 32 keywords in the C programming language."
},
{
"code": null,
"e": 1863,
"s": 1781,
"text": "Compare the string with each keyword if the string is same then string is keyword"
},
{
"code": null,
"e": 1874,
"s": 1863,
"text": " Live Demo"
},
{
"code": null,
"e": 2494,
"s": 1874,
"text": "#include <stdio.h>\n#include <string.h>\nint main() {\n char keyword[32][10]={\n \"auto\",\"double\",\"int\",\"struct\",\"break\",\"else\",\"long\",\n \"switch\",\"case\",\"enum\",\"register\",\"typedef\",\"char\",\n \"extern\",\"return\",\"union\",\"const\",\"float\",\"short\",\n \"unsigned\",\"continue\",\"for\",\"signed\",\"void\",\"default\",\n \"goto\",\"sizeof\",\"voltile\",\"do\",\"if\",\"static\",\"while\"\n } ;\n char str[]=\"which\";\n int flag=0,i;\n for(i = 0; i < 32; i++) {\n if(strcmp(str,keyword[i])==0) {\n flag=1;\n }\n }\n if(flag==1)\n printf(\"%s is a keyword\",str);\n else\n printf(\"%s is not a keyword\",str);\n}"
},
{
"code": null,
"e": 2513,
"s": 2494,
"text": "which is a keyword"
}
] |
Program to find the largest sum of the path between two nodes in a binary tree in Python
|
Suppose we have a binary tree; we have to find the maximum sum of any path between any two nodes.
So, if the input is like
then the output will be 62 as the nodes are [12,13,14,16,7].
To solve this, we will follow these steps β
Define a function utils() . This will take root
Define a function utils() . This will take root
if root null, thenreturn 0
if root null, then
return 0
return 0
l := utils(left of root)
l := utils(left of root)
r := utils(right of root)
r := utils(right of root)
max_single := maximum of (max of l and r) + value of root) and value of root
max_single := maximum of (max of l and r) + value of root) and value of root
max_top := maximum of max_single and l + r + value of root
max_top := maximum of max_single and l + r + value of root
res := maximum of res and max_top
res := maximum of res and max_top
return max_single
return max_single
From the main method, do the following β
From the main method, do the following β
if root is null, thenreturn 0
if root is null, then
return 0
return 0
res := infinity
res := infinity
utils(root)
utils(root)
return res
return res
Let us see the following implementation to get better understanding β
Live Demo
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Solution:
def solve(self, root):
if root is None:
return 0
self.res = float("-inf")
self.utils(root)
return self.res
def utils(self, root):
if root is None:
return 0
l = self.utils(root.left)
r = self.utils(root.right)
max_single = max(max(l, r) + root.val, root.val)
max_top = max(max_single, l + r + root.val)
self.res = max(self.res, max_top)
return max_single
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print(ob.solve(root))
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
62
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "Suppose we have a binary tree; we have to find the maximum sum of any path between any two nodes."
},
{
"code": null,
"e": 1185,
"s": 1160,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1246,
"s": 1185,
"text": "then the output will be 62 as the nodes are [12,13,14,16,7]."
},
{
"code": null,
"e": 1290,
"s": 1246,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1338,
"s": 1290,
"text": "Define a function utils() . This will take root"
},
{
"code": null,
"e": 1386,
"s": 1338,
"text": "Define a function utils() . This will take root"
},
{
"code": null,
"e": 1413,
"s": 1386,
"text": "if root null, thenreturn 0"
},
{
"code": null,
"e": 1432,
"s": 1413,
"text": "if root null, then"
},
{
"code": null,
"e": 1441,
"s": 1432,
"text": "return 0"
},
{
"code": null,
"e": 1450,
"s": 1441,
"text": "return 0"
},
{
"code": null,
"e": 1475,
"s": 1450,
"text": "l := utils(left of root)"
},
{
"code": null,
"e": 1500,
"s": 1475,
"text": "l := utils(left of root)"
},
{
"code": null,
"e": 1526,
"s": 1500,
"text": "r := utils(right of root)"
},
{
"code": null,
"e": 1552,
"s": 1526,
"text": "r := utils(right of root)"
},
{
"code": null,
"e": 1629,
"s": 1552,
"text": "max_single := maximum of (max of l and r) + value of root) and value of root"
},
{
"code": null,
"e": 1706,
"s": 1629,
"text": "max_single := maximum of (max of l and r) + value of root) and value of root"
},
{
"code": null,
"e": 1765,
"s": 1706,
"text": "max_top := maximum of max_single and l + r + value of root"
},
{
"code": null,
"e": 1824,
"s": 1765,
"text": "max_top := maximum of max_single and l + r + value of root"
},
{
"code": null,
"e": 1858,
"s": 1824,
"text": "res := maximum of res and max_top"
},
{
"code": null,
"e": 1892,
"s": 1858,
"text": "res := maximum of res and max_top"
},
{
"code": null,
"e": 1910,
"s": 1892,
"text": "return max_single"
},
{
"code": null,
"e": 1928,
"s": 1910,
"text": "return max_single"
},
{
"code": null,
"e": 1969,
"s": 1928,
"text": "From the main method, do the following β"
},
{
"code": null,
"e": 2010,
"s": 1969,
"text": "From the main method, do the following β"
},
{
"code": null,
"e": 2040,
"s": 2010,
"text": "if root is null, thenreturn 0"
},
{
"code": null,
"e": 2062,
"s": 2040,
"text": "if root is null, then"
},
{
"code": null,
"e": 2071,
"s": 2062,
"text": "return 0"
},
{
"code": null,
"e": 2080,
"s": 2071,
"text": "return 0"
},
{
"code": null,
"e": 2096,
"s": 2080,
"text": "res := infinity"
},
{
"code": null,
"e": 2112,
"s": 2096,
"text": "res := infinity"
},
{
"code": null,
"e": 2124,
"s": 2112,
"text": "utils(root)"
},
{
"code": null,
"e": 2136,
"s": 2124,
"text": "utils(root)"
},
{
"code": null,
"e": 2147,
"s": 2136,
"text": "return res"
},
{
"code": null,
"e": 2158,
"s": 2147,
"text": "return res"
},
{
"code": null,
"e": 2228,
"s": 2158,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 2239,
"s": 2228,
"text": " Live Demo"
},
{
"code": null,
"e": 3058,
"s": 2239,
"text": "class TreeNode:\n def __init__(self, value):\n self.val = value\n self.left = None\n self.right = None\nclass Solution:\n def solve(self, root):\n if root is None:\n return 0\n self.res = float(\"-inf\")\n self.utils(root)\n return self.res\n def utils(self, root):\n if root is None:\n return 0\n l = self.utils(root.left)\n r = self.utils(root.right)\n max_single = max(max(l, r) + root.val, root.val)\n max_top = max(max_single, l + r + root.val)\n self.res = max(self.res, max_top)\n return max_single\nob = Solution()\nroot = TreeNode(13)\nroot.left = TreeNode(12)\nroot.right = TreeNode(14)\nroot.right.left = TreeNode(16)\nroot.right.right = TreeNode(22)\nroot.right.left.left = TreeNode(4)\nroot.right.left.right = TreeNode(7)\nprint(ob.solve(root))"
},
{
"code": null,
"e": 3263,
"s": 3058,
"text": "root = TreeNode(13)\nroot.left = TreeNode(12)\nroot.right = TreeNode(14)\nroot.right.left = TreeNode(16)\nroot.right.right = TreeNode(22)\nroot.right.left.left = TreeNode(4)\nroot.right.left.right = TreeNode(7)"
},
{
"code": null,
"e": 3266,
"s": 3263,
"text": "62"
}
] |
How to replace the values in a matrix with another value based on a condition in R?
|
A matrix has only numeric values and sometimes these values are either incorrectly entered or we might want to replace some of the values in a matrix based on some conditions. For example, if we have few fives in a matrix then we might want to replace all fives to an another number which is greater than 5 or less than 5.
Consider the below matrix β
set.seed(123)
M <-matrix(sample(1:50,25),nrow=5)
M
[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 4
[4,] 3 25 28 7 45
[5,] 42 26 9 10 17
Replacing values based on different conditions β
M[M <5]<-10
M
[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 42 26 9 10 17
M[M=5] <-15
M
[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 15 26 9 10 17
M[M==5] <-15
M
[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 15 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 15 26 9 10 17
M[M<10&M>5]<-21
M
[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 15 21 19
[3,] 14 48 40 41 10
[4,] 10 25 28 21 45
[5,] 15 26 21 10 17
M[M >30]<-25
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 14 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 17
M[M==14] <-25
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 17
M[M==17] <-15
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 15
M[M>25&M <30]<-25
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 25 25 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 25 21 25
[5,] 15 25 21 10 15
|
[
{
"code": null,
"e": 1385,
"s": 1062,
"text": "A matrix has only numeric values and sometimes these values are either incorrectly entered or we might want to replace some of the values in a matrix based on some conditions. For example, if we have few fives in a matrix then we might want to replace all fives to an another number which is greater than 5 or less than 5."
},
{
"code": null,
"e": 1413,
"s": 1385,
"text": "Consider the below matrix β"
},
{
"code": null,
"e": 1464,
"s": 1413,
"text": "set.seed(123)\nM <-matrix(sample(1:50,25),nrow=5)\nM"
},
{
"code": null,
"e": 1585,
"s": 1464,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 31 43 27 29 36\n[2,] 15 37 5 8 19\n[3,] 14 48 40 41 4\n[4,] 3 25 28 7 45\n[5,] 42 26 9 10 17"
},
{
"code": null,
"e": 1634,
"s": 1585,
"text": "Replacing values based on different conditions β"
},
{
"code": null,
"e": 1648,
"s": 1634,
"text": "M[M <5]<-10\nM"
},
{
"code": null,
"e": 1769,
"s": 1648,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 31 43 27 29 36\n[2,] 15 37 5 8 19\n[3,] 14 48 40 41 10\n[4,] 10 25 28 7 45\n[5,] 42 26 9 10 17"
},
{
"code": null,
"e": 1783,
"s": 1769,
"text": "M[M=5] <-15\nM"
},
{
"code": null,
"e": 1906,
"s": 1783,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 31 43 27 29 36\n[2,] 15 37 5 8 19\n[3,] 14 48 40 41 10\n[4,] 10 25 28 7 45\n[5,] 15 26 9 10 17"
},
{
"code": null,
"e": 1921,
"s": 1906,
"text": "M[M==5] <-15\nM"
},
{
"code": null,
"e": 2045,
"s": 1921,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 31 43 27 29 36\n[2,] 15 37 15 8 19\n[3,] 14 48 40 41 10\n[4,] 10 25 28 7 45\n[5,] 15 26 9 10 17"
},
{
"code": null,
"e": 2063,
"s": 2045,
"text": "M[M<10&M>5]<-21\nM"
},
{
"code": null,
"e": 2188,
"s": 2063,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 31 43 27 29 36\n[2,] 15 37 15 21 19\n[3,] 14 48 40 41 10\n[4,] 10 25 28 21 45\n[5,] 15 26 21 10 17"
},
{
"code": null,
"e": 2203,
"s": 2188,
"text": "M[M >30]<-25\nM"
},
{
"code": null,
"e": 2328,
"s": 2203,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 25 25 27 29 25\n[2,] 15 25 15 21 19\n[3,] 14 25 25 25 10\n[4,] 10 25 28 21 25\n[5,] 15 26 21 10 17"
},
{
"code": null,
"e": 2344,
"s": 2328,
"text": "M[M==14] <-25\nM"
},
{
"code": null,
"e": 2469,
"s": 2344,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 25 25 27 29 25\n[2,] 15 25 15 21 19\n[3,] 25 25 25 25 10\n[4,] 10 25 28 21 25\n[5,] 15 26 21 10 17"
},
{
"code": null,
"e": 2485,
"s": 2469,
"text": "M[M==17] <-15\nM"
},
{
"code": null,
"e": 2610,
"s": 2485,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 25 25 27 29 25\n[2,] 15 25 15 21 19\n[3,] 25 25 25 25 10\n[4,] 10 25 28 21 25\n[5,] 15 26 21 10 15"
},
{
"code": null,
"e": 2630,
"s": 2610,
"text": "M[M>25&M <30]<-25\nM"
},
{
"code": null,
"e": 2755,
"s": 2630,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 25 25 25 25 25\n[2,] 15 25 15 21 19\n[3,] 25 25 25 25 10\n[4,] 10 25 25 21 25\n[5,] 15 25 21 10 15"
}
] |
PyQt - QLabel Widget
|
A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. Plain text, hyperlink or rich text can be displayed on the label.
The following table lists the important methods defined in QLabel class β
Given below are the most commonly used methods of QLabel.
setAlignment()
Aligns the text as per alignment constants
Qt.AlignLeft
Qt.AlignRight
Qt.AlignCenter
Qt.AlignJustify
setIndent()
Sets the labels text indent
setPixmap()
Displays an image
Text()
Displays the caption of the label
setText()
Programmatically sets the caption
selectedText()
Displays the selected text from the label (The textInteractionFlag must be set to TextSelectableByMouse)
setBuddy()
Associates the label with any input widget
setWordWrap()
Enables or disables wrapping text in the label
In this example, QLabel objects l2 and l4 have the caption containing hyperlink. setOpenExternalLinks for l2 is set to true. Hence, if this label is clicked, the associated URL will open in the browser. linkHovered signal of l4 is connected to hovered() function. So, whenever the mouse hovers over it, the function will be executed.
QPixmap object prepares offscreen image from python.jpg file. It is displayed as label l3 by using setPixmap() method.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def window():
app = QApplication(sys.argv)
win = QWidget()
l1 = QLabel()
l2 = QLabel()
l3 = QLabel()
l4 = QLabel()
l1.setText("Hello World")
l4.setText("TutorialsPoint")
l2.setText("welcome to Python GUI Programming")
l1.setAlignment(Qt.AlignCenter)
l3.setAlignment(Qt.AlignCenter)
l4.setAlignment(Qt.AlignRight)
l3.setPixmap(QPixmap("python.jpg"))
vbox = QVBoxLayout()
vbox.addWidget(l1)
vbox.addStretch()
vbox.addWidget(l2)
vbox.addStretch()
vbox.addWidget(l3)
vbox.addStretch()
vbox.addWidget(l4)
l1.setOpenExternalLinks(True)
l4.linkActivated.connect(clicked)
l2.linkHovered.connect(hovered)
l1.setTextInteractionFlags(Qt.TextSelectableByMouse)
win.setLayout(vbox)
win.setWindowTitle("QLabel Demo")
win.show()
sys.exit(app.exec_())
def hovered():
print "hovering"
def clicked():
print "clicked"
if __name__ == '__main__':
window()
The above code produces the following output β
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2154,
"s": 1926,
"text": "A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. Plain text, hyperlink or rich text can be displayed on the label."
},
{
"code": null,
"e": 2228,
"s": 2154,
"text": "The following table lists the important methods defined in QLabel class β"
},
{
"code": null,
"e": 2286,
"s": 2228,
"text": "Given below are the most commonly used methods of QLabel."
},
{
"code": null,
"e": 2301,
"s": 2286,
"text": "setAlignment()"
},
{
"code": null,
"e": 2344,
"s": 2301,
"text": "Aligns the text as per alignment constants"
},
{
"code": null,
"e": 2357,
"s": 2344,
"text": "Qt.AlignLeft"
},
{
"code": null,
"e": 2371,
"s": 2357,
"text": "Qt.AlignRight"
},
{
"code": null,
"e": 2386,
"s": 2371,
"text": "Qt.AlignCenter"
},
{
"code": null,
"e": 2402,
"s": 2386,
"text": "Qt.AlignJustify"
},
{
"code": null,
"e": 2414,
"s": 2402,
"text": "setIndent()"
},
{
"code": null,
"e": 2442,
"s": 2414,
"text": "Sets the labels text indent"
},
{
"code": null,
"e": 2454,
"s": 2442,
"text": "setPixmap()"
},
{
"code": null,
"e": 2472,
"s": 2454,
"text": "Displays an image"
},
{
"code": null,
"e": 2479,
"s": 2472,
"text": "Text()"
},
{
"code": null,
"e": 2513,
"s": 2479,
"text": "Displays the caption of the label"
},
{
"code": null,
"e": 2523,
"s": 2513,
"text": "setText()"
},
{
"code": null,
"e": 2557,
"s": 2523,
"text": "Programmatically sets the caption"
},
{
"code": null,
"e": 2572,
"s": 2557,
"text": "selectedText()"
},
{
"code": null,
"e": 2677,
"s": 2572,
"text": "Displays the selected text from the label (The textInteractionFlag must be set to TextSelectableByMouse)"
},
{
"code": null,
"e": 2688,
"s": 2677,
"text": "setBuddy()"
},
{
"code": null,
"e": 2731,
"s": 2688,
"text": "Associates the label with any input widget"
},
{
"code": null,
"e": 2745,
"s": 2731,
"text": "setWordWrap()"
},
{
"code": null,
"e": 2792,
"s": 2745,
"text": "Enables or disables wrapping text in the label"
},
{
"code": null,
"e": 3126,
"s": 2792,
"text": "In this example, QLabel objects l2 and l4 have the caption containing hyperlink. setOpenExternalLinks for l2 is set to true. Hence, if this label is clicked, the associated URL will open in the browser. linkHovered signal of l4 is connected to hovered() function. So, whenever the mouse hovers over it, the function will be executed."
},
{
"code": null,
"e": 3245,
"s": 3126,
"text": "QPixmap object prepares offscreen image from python.jpg file. It is displayed as label l3 by using setPixmap() method."
},
{
"code": null,
"e": 4258,
"s": 3245,
"text": "import sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\ndef window():\n app = QApplication(sys.argv)\n win = QWidget() \n\t\n l1 = QLabel()\n l2 = QLabel()\n l3 = QLabel()\n l4 = QLabel()\n\t\n l1.setText(\"Hello World\")\n l4.setText(\"TutorialsPoint\")\n l2.setText(\"welcome to Python GUI Programming\")\n\t\n l1.setAlignment(Qt.AlignCenter)\n l3.setAlignment(Qt.AlignCenter)\n l4.setAlignment(Qt.AlignRight)\n l3.setPixmap(QPixmap(\"python.jpg\"))\n\t\n vbox = QVBoxLayout()\n vbox.addWidget(l1)\n vbox.addStretch()\n vbox.addWidget(l2)\n vbox.addStretch()\n vbox.addWidget(l3)\n vbox.addStretch()\n vbox.addWidget(l4)\n\t\n l1.setOpenExternalLinks(True)\n l4.linkActivated.connect(clicked)\n l2.linkHovered.connect(hovered)\n l1.setTextInteractionFlags(Qt.TextSelectableByMouse)\n win.setLayout(vbox)\n\t\n win.setWindowTitle(\"QLabel Demo\")\n win.show()\n sys.exit(app.exec_())\n\t\ndef hovered():\n print \"hovering\"\ndef clicked():\n print \"clicked\"\n\t\nif __name__ == '__main__':\n window()"
},
{
"code": null,
"e": 4305,
"s": 4258,
"text": "The above code produces the following output β"
},
{
"code": null,
"e": 4342,
"s": 4305,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 4352,
"s": 4342,
"text": " ALAA EID"
},
{
"code": null,
"e": 4359,
"s": 4352,
"text": " Print"
},
{
"code": null,
"e": 4370,
"s": 4359,
"text": " Add Notes"
}
] |
Groovy - Operators
|
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
Groovy has the following types of operators β
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy β
Show Example
int x = 5;
x++;
x will give 6
int x = 5;
x--;
x will give 4
Relational operators allow of the comparison of objects. Following are the relational operators available in Groovy β
Show Example
Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy β
Show Example
Groovy provides four bitwise operators. Following are the bitwise operators available in Groovy β
Show Example
&
This is the bitwise βandβ operator
|
This is the bitwise βorβ operator
^
This is the bitwise βxorβ or Exclusive or operator
~
This is the bitwise negation operator
Here is the truth table showcasing these operators.
The Groovy language also provides assignment operators. Following are the assignment operators available in Groovy β
Show Example
def A = 5
A+=3
Output will be 8
def A = 5
A-=3
Output will be 2
def A = 5
A*=3
Output will be 15
def A = 6
A/=3
Output will be 2
def A = 5
A%=3
Output will be 2
Groovy supports the concept of ranges and provides a notation of range operators with the help of the .. notation. A simple example of the range operator is given below.
def range = 0..5
This just defines a simple range of integers, stored into a local variable called range with a lower bound of 0 and an upper bound of 5.
The following code snippet shows how the various operators can be used.
class Example {
static void main(String[] args) {
def range = 5..10;
println(range);
println(range.get(2));
}
}
When we run the above program, we will get the following result β
From the println statement, you can see that the entire range of numbers which are defined in the range statement are displayed.
The get statement is used to get an object from the range defined which takes in an index value as the parameter.
[5, 6, 7, 8, 9, 10]
7
The following table lists all groovy operators in order of precedence.
++ -- + -
pre increment/decrement, unary plus, unary minus
* / %
multiply, div, modulo
+ -
addition, subtraction
== != <=>
equals, not equals, compare to
&
binary/bitwise and
^
binary/bitwise xor
|
binary/bitwise or
&&
logical and
||
logical or
= **= *= /= %= += -= <<= >>= >>>= &= ^= |=
Various assignment operators
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2345,
"s": 2238,
"text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations."
},
{
"code": null,
"e": 2391,
"s": 2345,
"text": "Groovy has the following types of operators β"
},
{
"code": null,
"e": 2412,
"s": 2391,
"text": "Arithmetic operators"
},
{
"code": null,
"e": 2433,
"s": 2412,
"text": "Relational operators"
},
{
"code": null,
"e": 2451,
"s": 2433,
"text": "Logical operators"
},
{
"code": null,
"e": 2469,
"s": 2451,
"text": "Bitwise operators"
},
{
"code": null,
"e": 2490,
"s": 2469,
"text": "Assignment operators"
},
{
"code": null,
"e": 2633,
"s": 2490,
"text": "The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy β"
},
{
"code": null,
"e": 2646,
"s": 2633,
"text": "Show Example"
},
{
"code": null,
"e": 2657,
"s": 2646,
"text": "int x = 5;"
},
{
"code": null,
"e": 2662,
"s": 2657,
"text": "x++;"
},
{
"code": null,
"e": 2676,
"s": 2662,
"text": "x will give 6"
},
{
"code": null,
"e": 2687,
"s": 2676,
"text": "int x = 5;"
},
{
"code": null,
"e": 2692,
"s": 2687,
"text": "x--;"
},
{
"code": null,
"e": 2706,
"s": 2692,
"text": "x will give 4"
},
{
"code": null,
"e": 2824,
"s": 2706,
"text": "Relational operators allow of the comparison of objects. Following are the relational operators available in Groovy β"
},
{
"code": null,
"e": 2837,
"s": 2824,
"text": "Show Example"
},
{
"code": null,
"e": 2955,
"s": 2837,
"text": "Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy β"
},
{
"code": null,
"e": 2968,
"s": 2955,
"text": "Show Example"
},
{
"code": null,
"e": 3066,
"s": 2968,
"text": "Groovy provides four bitwise operators. Following are the bitwise operators available in Groovy β"
},
{
"code": null,
"e": 3079,
"s": 3066,
"text": "Show Example"
},
{
"code": null,
"e": 3081,
"s": 3079,
"text": "&"
},
{
"code": null,
"e": 3116,
"s": 3081,
"text": "This is the bitwise βandβ operator"
},
{
"code": null,
"e": 3118,
"s": 3116,
"text": "|"
},
{
"code": null,
"e": 3152,
"s": 3118,
"text": "This is the bitwise βorβ operator"
},
{
"code": null,
"e": 3154,
"s": 3152,
"text": "^"
},
{
"code": null,
"e": 3205,
"s": 3154,
"text": "This is the bitwise βxorβ or Exclusive or operator"
},
{
"code": null,
"e": 3207,
"s": 3205,
"text": "~"
},
{
"code": null,
"e": 3245,
"s": 3207,
"text": "This is the bitwise negation operator"
},
{
"code": null,
"e": 3297,
"s": 3245,
"text": "Here is the truth table showcasing these operators."
},
{
"code": null,
"e": 3414,
"s": 3297,
"text": "The Groovy language also provides assignment operators. Following are the assignment operators available in Groovy β"
},
{
"code": null,
"e": 3427,
"s": 3414,
"text": "Show Example"
},
{
"code": null,
"e": 3437,
"s": 3427,
"text": "def A = 5"
},
{
"code": null,
"e": 3442,
"s": 3437,
"text": "A+=3"
},
{
"code": null,
"e": 3459,
"s": 3442,
"text": "Output will be 8"
},
{
"code": null,
"e": 3469,
"s": 3459,
"text": "def A = 5"
},
{
"code": null,
"e": 3474,
"s": 3469,
"text": "A-=3"
},
{
"code": null,
"e": 3491,
"s": 3474,
"text": "Output will be 2"
},
{
"code": null,
"e": 3501,
"s": 3491,
"text": "def A = 5"
},
{
"code": null,
"e": 3506,
"s": 3501,
"text": "A*=3"
},
{
"code": null,
"e": 3524,
"s": 3506,
"text": "Output will be 15"
},
{
"code": null,
"e": 3534,
"s": 3524,
"text": "def A = 6"
},
{
"code": null,
"e": 3539,
"s": 3534,
"text": "A/=3"
},
{
"code": null,
"e": 3556,
"s": 3539,
"text": "Output will be 2"
},
{
"code": null,
"e": 3566,
"s": 3556,
"text": "def A = 5"
},
{
"code": null,
"e": 3571,
"s": 3566,
"text": "A%=3"
},
{
"code": null,
"e": 3588,
"s": 3571,
"text": "Output will be 2"
},
{
"code": null,
"e": 3758,
"s": 3588,
"text": "Groovy supports the concept of ranges and provides a notation of range operators with the help of the .. notation. A simple example of the range operator is given below."
},
{
"code": null,
"e": 3777,
"s": 3758,
"text": "def range = 0..5 \n"
},
{
"code": null,
"e": 3914,
"s": 3777,
"text": "This just defines a simple range of integers, stored into a local variable called range with a lower bound of 0 and an upper bound of 5."
},
{
"code": null,
"e": 3986,
"s": 3914,
"text": "The following code snippet shows how the various operators can be used."
},
{
"code": null,
"e": 4128,
"s": 3986,
"text": "class Example { \n static void main(String[] args) { \n def range = 5..10; \n println(range); \n println(range.get(2)); \n } \n}"
},
{
"code": null,
"e": 4194,
"s": 4128,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 4323,
"s": 4194,
"text": "From the println statement, you can see that the entire range of numbers which are defined in the range statement are displayed."
},
{
"code": null,
"e": 4437,
"s": 4323,
"text": "The get statement is used to get an object from the range defined which takes in an index value as the parameter."
},
{
"code": null,
"e": 4461,
"s": 4437,
"text": "[5, 6, 7, 8, 9, 10] \n7\n"
},
{
"code": null,
"e": 4532,
"s": 4461,
"text": "The following table lists all groovy operators in order of precedence."
},
{
"code": null,
"e": 4548,
"s": 4532,
"text": "++ -- + -"
},
{
"code": null,
"e": 4597,
"s": 4548,
"text": "pre increment/decrement, unary plus, unary minus"
},
{
"code": null,
"e": 4607,
"s": 4597,
"text": "* / %"
},
{
"code": null,
"e": 4629,
"s": 4607,
"text": "multiply, div, modulo"
},
{
"code": null,
"e": 4635,
"s": 4629,
"text": "+ -"
},
{
"code": null,
"e": 4657,
"s": 4635,
"text": "addition, subtraction"
},
{
"code": null,
"e": 4671,
"s": 4657,
"text": "== != <=>"
},
{
"code": null,
"e": 4702,
"s": 4671,
"text": "equals, not equals, compare to"
},
{
"code": null,
"e": 4704,
"s": 4702,
"text": "&"
},
{
"code": null,
"e": 4723,
"s": 4704,
"text": "binary/bitwise and"
},
{
"code": null,
"e": 4725,
"s": 4723,
"text": "^"
},
{
"code": null,
"e": 4744,
"s": 4725,
"text": "binary/bitwise xor"
},
{
"code": null,
"e": 4746,
"s": 4744,
"text": "|"
},
{
"code": null,
"e": 4764,
"s": 4746,
"text": "binary/bitwise or"
},
{
"code": null,
"e": 4767,
"s": 4764,
"text": "&&"
},
{
"code": null,
"e": 4779,
"s": 4767,
"text": "logical and"
},
{
"code": null,
"e": 4782,
"s": 4779,
"text": "||"
},
{
"code": null,
"e": 4793,
"s": 4782,
"text": "logical or"
},
{
"code": null,
"e": 4860,
"s": 4793,
"text": "= **= *= /= %= += -= <<= >>= >>>= &= ^= |="
},
{
"code": null,
"e": 4889,
"s": 4860,
"text": "Various assignment operators"
},
{
"code": null,
"e": 4922,
"s": 4889,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4940,
"s": 4922,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 4975,
"s": 4940,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4993,
"s": 4975,
"text": " Packt Publishing"
},
{
"code": null,
"e": 5000,
"s": 4993,
"text": " Print"
},
{
"code": null,
"e": 5011,
"s": 5000,
"text": " Add Notes"
}
] |
Guide to Custom Recurrent Modeling in Keras | by Mohit Mayank | Towards Data Science
|
The initial set of layers for recurrent neural operations universally begins with LSTM, GRU and RNN. But with an increase in the complexity of the task, we should use more complex models. That said, before moving directly to different and relatively complex models like attention or transformers, we should first ask a simple question β can we still do something quickly with the basic recurrent layers? In this article, I will focus on the same philosophy that β we should first exhaust the simple solutions before going for the more complex ones. In the next sections, we will explore the same old set of recurrent layers (albeit with some interesting arrangements) to get better inference on the data. In total, we will discuss 12 such arrangements (including the original set). Finally, we will conclude with testing all of our models on a Text Sentiment Detection task to compare their performance. Letβs get started!
Before going further, letβs discuss a few topics which we should know to completely appreciate this article. One more thing, I use arrangement and model interchangeably, because all the discussed models are nothing but compositions of basic recurrent layers, which acts as the smallest building blocks.
Any recurrent layer has the option to return two types of outputs β (1) Last state output (1 output) and (2) All state output (N outputs). Actually, the 2nd type is more generic as it also contains the last state output (i.e. the 1st type), but usually, popular deep learning libraryβs implementation provides options to return both the types of outputs. In case of Keras, the default is the 1st type and you can set the parameter return_sequence=True to shift to type 2. Note here, by "state" I mean hidden state of the recurrent layer and the N number of output is usually the number of time steps in your dataset. To know more about the internals of the recurrent layers and about the hidden states, I would suggest this excellent article. Now coming back to the topic, what's interesting is that while the 2nd type contains more info (which is usually a good thing), it could also be overwhelming as we don't know what exactly to do with it. As most of the downstream application still needs one output, we end up consolidating all state's output to a single final output (possible techniques β using AveragePooling or MaxPooling ). And in a way, LSTM or GRU does the same, they use the previous state's output (and current input) to create the next state's output. Then the interesting question is, "What is better - trusting LSTM/GRU to consolidate the state outputs or applying our own logic?". We will try to answer this in later sections, for now, let's move forward.
A recurrent layer takes sequential input and processes them to return one or many outputs (state vectors). Now as the output (if we return all stateβs output) also follow the sense of sequence, they can be thought of as some transformed original input and can be passed on to another layer of LSTM/GRU to be further processed. This is called stacking and here the main intuition is that β just like vanilla Deep Neural Network where you add more dense layers or with CNNs where you add multiple convolution layers one after the another, in recurrent layering you can stack multiple layers one in top of another. Ideally more layers give you more tunable parameters hence more learning power. But be wary of adding too many stacks, as it may lead to overfitting (too complex network for too simple learning requirement). The main question we can ask here is βDoes adding stacking layers results in better performance?β.
One interesting arrangement is when you have two recurrent layers (they are not stacked), and in one layer data is passed left-to-right for training and this direction is reversed for the other layer. This is the bidirectional recurrent layer and the intuition is that β in contrast to a normal layer with only forward training and left context, having both left and right context while preparing the state vector output could lead to higher performance. Usually, this is true for tasks where you expect the complete data (bidirectional context) to be present, so this is valid for sentiment detection β as we have the complete sentence string available, but not true for time-series forecasting β as we donβt have future dateβs data if we want to todayβs value (say temperature). As bidirectional systems use 2 recurrent layers, we compare it against the stacking architectures and ask, βWhich is better β a 2 layer stacked recurrent layer or a bi-directional recurrent layer?β.
Moving forward, now letβs try to define and group the different arrangements we can create using the models we knew (basic recurrent layers) and the techniques we learned above. At the higher layer, we group all of our arrangements into two broad classes β
Single stack (SS): wherein we only use one recurrent layerMultiple stacks (MS): wherein we use multiple recurrent layers. To keep analysis simple, I will only use 2 layered arrangements.
Single stack (SS): wherein we only use one recurrent layer
Multiple stacks (MS): wherein we use multiple recurrent layers. To keep analysis simple, I will only use 2 layered arrangements.
Also, as RNNs have given way to βbetterβ recurrent layers, we will only consider LSTM and GRU in our analysis. Now in case of SS, we can use either LSTM or GRU, also we can add flavour by taking only 1 output or N outputs for each. This gives us 2x2=4 different arrangements we may want to consider. Moving forward, in case of MS (only 2 for this article), lets first start with 1 and N outputs. For each such setting, we can either use a 2 layer stacked or a bidirectional LSTM and GRU. This gives us 2x2x2=8 different arrangements. The grouping of all 12 arrangement is shown below. Note, by "Return Sequence False" I mean 1 output as you are only returning one output and not the complete sequence.
Now let us see how we can code up the different arrangements in Keras. For the sake of brevity, I will only show the code for the LSTM recurrent layer. Shifting to GRU is as easy as replacing LSTM with GRU in the code (donβt forget to import GRU though). I will also only cover 4 different varieties as rest can be easily built after minor modifications. Getting started with SS_RSF_LSTM i.e. single stacked β return sequence false β LSTM layer π
SS_RSF_LSTM
# import from tensorflow.keras import layersfrom tensorflow import keras# modelinputs = keras.Input(shape=(99, )) # input layer - shape should be defined by user.embedding = layers.Embedding(num_words, 64)(inputs) # embedding layerrl = layers.LSTM(128)(embedding) # our LSTM layer - default return sequence is Falsedense = layers.Dense(64)(rl) # a dense layer on the output of LSTMoutput = layers.Dense(1, activation='sigmoid')(dense) # final layer which gives classification resultself.model = keras.Model(inputs=inputs, outputs=output, name="SS_RSF_LSTM") # stitching everything together
Few things to note,
The code has been created with the sentiment classification task in mind (next section). Hence the final output layer is of size=1 with a sigmoid activation to return a probability as output.
We define an input where we say shape=99 i.e. the timestep size we expect in our data. Here this means the number of words in each sentence.
We use the embedding layer to transform words into a vector representation. We could have used ready-made word embeddings like Glove or Word2Vec, but we initialized a new one which will train specifically for this task. The size of each vector is 64 and num_words is the vocabulary size of the dataset we are using.
We use one LSTM layer with state output of size=128. Note, as per default return sequence is False, so we only get one output i.e. of the last state of the LSTM.
We connect the last state output with a dense layer of size=64. This is used to enhance the complex thresholding on the output of LSTM.
SS_RST_LSTM
The only difference here is that we return all stateβs output from LSTM. We can do this as follows,
inputs = keras.Input(shape=(99, ))embedding = layers.Embedding(num_words, 64)(inputs)rl = layers.LSTM(128, return_sequences=True)(embedding)avg = tf.keras.layers.AveragePooling1D(pool_size=99)(rl)dense = layers.Dense(64)(avg)output = layers.Dense(1, activation='sigmoid')(dense)self.model = keras.Model(inputs=inputs, outputs=output, name="SS_RST_LSTM")
Points to note,
The first change is the addition of return_sequence=True in LSTM definition.
Next, we need to consolidate our 99x128 matrix into 1x128 sized vector. While there are many ways to do so we will pick AveragePooling1D which simply takes the average of each 99 timestep vectors to return 1 vector output. Here pool_size is to specify that we are taking an average of each 99 timesteps.
MS_RSF_biLSTM
To have a bidirectional layer, all we need to do is add a Bidirectional function on top of LSTM.
inputs = keras.Input(shape=(99, ))embedding = layers.Embedding(num_words, 64)(inputs)rl = layers.Bidirectional(layers.LSTM(128))(embedding)dense = layers.Dense(64)(rl)output = layers.Dense(1, activation='sigmoid')(dense)self.model = keras.Model(inputs=inputs, outputs=output, name="MS_RSF_biLSTM")
Note to move to MS_RST_biLSTM you need to do 2 things β (1) add return_sequence=True inside the LSTM layer, and (2) add the AveragePooling1D logic after the bidirectional LSTM layer as done above.
MS_RST_LSTM
inputs = keras.Input(shape=(99, ))embedding = layers.Embedding(num_words, 64)(inputs)rl = layers.LSTM(128, return_sequences=True)(embedding)rl = layers.LSTM(128, return_sequences=True)(rl)avg = tf.keras.layers.AveragePooling1D(pool_size=99)(rl)dense = layers.Dense(64)(avg)output = layers.Dense(1, activation='sigmoid')(dense)self.model = keras.Model(inputs=inputs, outputs=output, name="MS_RST_LSTM")
Points to note,
To stack multiple LSTMs, it is mandatory for all the lower LSTMs to have return_sequence=True , as they will be fed as input to the next LSTM.
For the topmost LSTM, its userβs choice. As we are seeing an RST example, the code is returning all of the state sequences which is later averaged.
To stack more layers in this fashion, all we need to do is copy-paste the rl = layers.LSTM(128, return_sequences=True)(rl) line again and again. Here as we have 2 such lines, we have 2 layers stacked LSTM.
The remaining arrangements can be coded up pretty easily by following the hints shared above. I leave this as an exercise and also share the complete code here for reference.
For testing our models, I have selected IMDB sentiment classification datasets which contain 25,000 highly polar movie reviews with binary sentiment represented by labels 0 and 1. To be little easier on my laptop, I have further trimmed the data by considering only the top 5000 words by frequency and truncating sentence over 100 words. As the data API is exposed by Keras, all of this can be done by,
# importimport tensorflow as tf# set parametersnum_words = 5000maxlen = 100# fetch data(x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=num_words, maxlen=maxlen)
Also, Keras has already transformed the words into integer representation, making it easier to be fed to our models. All thatβs remaining is to make sure all of the sentences are of the same size, as there could be some sentence with size less than maxlen. This can be done by padding the smaller sentences with a dummy number (say 0). You can add padding on the left or right of the short sentences, I have chosen left. The code to do so is,
## perform paddingx_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, padding="pre")x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, padding="pre")
To compare the performance score across all models, we will train each model for a specified number of epochs on the prepared data and report accuracy. To handle variation in case of training, we will repeat the training process multiple times (runs) and also report the variation in accuracy score observed in each run along with max and min scores. Lastly, to make sure that the variation in our model performance is not introduced by random weight initialization, we will use the same initial weights for each run. Then the major difference introduced is in model fitting and its internal train-validation data split.
Each experiment (for one model) ran 5 times and each time we ran for 5 epochs. In total, we ran 12 such experiments (for all of our models). The consolidated performance report card is shown below,
Now, let us try to answer the questions we raised before,
Q1: Does different recurrent output types matter? β Short answer: Yes! To understand why, letβs compare each RSF model with its counterpart RST models. All such possible comparisons and the difference (right minus left) is shown above. As evident, 4/6 models perform better. In fact, our best model is MS_RST_LSTM, which has over ~3% improvement over its RSF version.
Q2: Does stacking multiple layers matters? β Yes again! See the second comparison table with all positive difference. Adding more layers does results in additional tunable parameters and hence more learning power. But be vary, this doesnβt mean you can stack 100 layers and expect it to work better than before β at some point, it will converge i.e. adding more layers will not help. But stacking few layers does help, as shown here.
Q3: Does bidirectional layering performs better against normal stacking? β Interestingly no! 3/4 times stacking layers perform better. This may be because multiple stack layers have more training parameters, hence better inference on data.
Let me start with a disclaimer β while I am (or rather the experiment results are) saying that one arrangement works better than another, I am not implying that you should only train βgoodβ models and ignore the rest. Please remember, every task and its data is different and may result in different result from the ones reported above. Take Bi-direction as an example, usually, I find bi-direction competing toe-to-toe with stacking layers and in some cases even perform better. This is in contrast to what we saw before and thatβs going on to prove that every data is different. That said, the purpose of this article was two folds β (1) to showcase the different varieties of layering arrangements that can be made by just using basic recurrent layers, and (2) based on experiments to help prioritize arrangements rather than ignoring them. So next time you have a text classification project, you can start with MS_RST_LSTM model and with time (if you have) experiments on others.
Cheers!
Connect with me on LinkedIn or read more such articles on my website.
|
[
{
"code": null,
"e": 1095,
"s": 172,
"text": "The initial set of layers for recurrent neural operations universally begins with LSTM, GRU and RNN. But with an increase in the complexity of the task, we should use more complex models. That said, before moving directly to different and relatively complex models like attention or transformers, we should first ask a simple question β can we still do something quickly with the basic recurrent layers? In this article, I will focus on the same philosophy that β we should first exhaust the simple solutions before going for the more complex ones. In the next sections, we will explore the same old set of recurrent layers (albeit with some interesting arrangements) to get better inference on the data. In total, we will discuss 12 such arrangements (including the original set). Finally, we will conclude with testing all of our models on a Text Sentiment Detection task to compare their performance. Letβs get started!"
},
{
"code": null,
"e": 1398,
"s": 1095,
"text": "Before going further, letβs discuss a few topics which we should know to completely appreciate this article. One more thing, I use arrangement and model interchangeably, because all the discussed models are nothing but compositions of basic recurrent layers, which acts as the smallest building blocks."
},
{
"code": null,
"e": 2875,
"s": 1398,
"text": "Any recurrent layer has the option to return two types of outputs β (1) Last state output (1 output) and (2) All state output (N outputs). Actually, the 2nd type is more generic as it also contains the last state output (i.e. the 1st type), but usually, popular deep learning libraryβs implementation provides options to return both the types of outputs. In case of Keras, the default is the 1st type and you can set the parameter return_sequence=True to shift to type 2. Note here, by \"state\" I mean hidden state of the recurrent layer and the N number of output is usually the number of time steps in your dataset. To know more about the internals of the recurrent layers and about the hidden states, I would suggest this excellent article. Now coming back to the topic, what's interesting is that while the 2nd type contains more info (which is usually a good thing), it could also be overwhelming as we don't know what exactly to do with it. As most of the downstream application still needs one output, we end up consolidating all state's output to a single final output (possible techniques β using AveragePooling or MaxPooling ). And in a way, LSTM or GRU does the same, they use the previous state's output (and current input) to create the next state's output. Then the interesting question is, \"What is better - trusting LSTM/GRU to consolidate the state outputs or applying our own logic?\". We will try to answer this in later sections, for now, let's move forward."
},
{
"code": null,
"e": 3794,
"s": 2875,
"text": "A recurrent layer takes sequential input and processes them to return one or many outputs (state vectors). Now as the output (if we return all stateβs output) also follow the sense of sequence, they can be thought of as some transformed original input and can be passed on to another layer of LSTM/GRU to be further processed. This is called stacking and here the main intuition is that β just like vanilla Deep Neural Network where you add more dense layers or with CNNs where you add multiple convolution layers one after the another, in recurrent layering you can stack multiple layers one in top of another. Ideally more layers give you more tunable parameters hence more learning power. But be wary of adding too many stacks, as it may lead to overfitting (too complex network for too simple learning requirement). The main question we can ask here is βDoes adding stacking layers results in better performance?β."
},
{
"code": null,
"e": 4774,
"s": 3794,
"text": "One interesting arrangement is when you have two recurrent layers (they are not stacked), and in one layer data is passed left-to-right for training and this direction is reversed for the other layer. This is the bidirectional recurrent layer and the intuition is that β in contrast to a normal layer with only forward training and left context, having both left and right context while preparing the state vector output could lead to higher performance. Usually, this is true for tasks where you expect the complete data (bidirectional context) to be present, so this is valid for sentiment detection β as we have the complete sentence string available, but not true for time-series forecasting β as we donβt have future dateβs data if we want to todayβs value (say temperature). As bidirectional systems use 2 recurrent layers, we compare it against the stacking architectures and ask, βWhich is better β a 2 layer stacked recurrent layer or a bi-directional recurrent layer?β."
},
{
"code": null,
"e": 5031,
"s": 4774,
"text": "Moving forward, now letβs try to define and group the different arrangements we can create using the models we knew (basic recurrent layers) and the techniques we learned above. At the higher layer, we group all of our arrangements into two broad classes β"
},
{
"code": null,
"e": 5218,
"s": 5031,
"text": "Single stack (SS): wherein we only use one recurrent layerMultiple stacks (MS): wherein we use multiple recurrent layers. To keep analysis simple, I will only use 2 layered arrangements."
},
{
"code": null,
"e": 5277,
"s": 5218,
"text": "Single stack (SS): wherein we only use one recurrent layer"
},
{
"code": null,
"e": 5406,
"s": 5277,
"text": "Multiple stacks (MS): wherein we use multiple recurrent layers. To keep analysis simple, I will only use 2 layered arrangements."
},
{
"code": null,
"e": 6108,
"s": 5406,
"text": "Also, as RNNs have given way to βbetterβ recurrent layers, we will only consider LSTM and GRU in our analysis. Now in case of SS, we can use either LSTM or GRU, also we can add flavour by taking only 1 output or N outputs for each. This gives us 2x2=4 different arrangements we may want to consider. Moving forward, in case of MS (only 2 for this article), lets first start with 1 and N outputs. For each such setting, we can either use a 2 layer stacked or a bidirectional LSTM and GRU. This gives us 2x2x2=8 different arrangements. The grouping of all 12 arrangement is shown below. Note, by \"Return Sequence False\" I mean 1 output as you are only returning one output and not the complete sequence."
},
{
"code": null,
"e": 6555,
"s": 6108,
"text": "Now let us see how we can code up the different arrangements in Keras. For the sake of brevity, I will only show the code for the LSTM recurrent layer. Shifting to GRU is as easy as replacing LSTM with GRU in the code (donβt forget to import GRU though). I will also only cover 4 different varieties as rest can be easily built after minor modifications. Getting started with SS_RSF_LSTM i.e. single stacked β return sequence false β LSTM layer π"
},
{
"code": null,
"e": 6567,
"s": 6555,
"text": "SS_RSF_LSTM"
},
{
"code": null,
"e": 7157,
"s": 6567,
"text": "# import from tensorflow.keras import layersfrom tensorflow import keras# modelinputs = keras.Input(shape=(99, )) # input layer - shape should be defined by user.embedding = layers.Embedding(num_words, 64)(inputs) # embedding layerrl = layers.LSTM(128)(embedding) # our LSTM layer - default return sequence is Falsedense = layers.Dense(64)(rl) # a dense layer on the output of LSTMoutput = layers.Dense(1, activation='sigmoid')(dense) # final layer which gives classification resultself.model = keras.Model(inputs=inputs, outputs=output, name=\"SS_RSF_LSTM\") # stitching everything together"
},
{
"code": null,
"e": 7177,
"s": 7157,
"text": "Few things to note,"
},
{
"code": null,
"e": 7369,
"s": 7177,
"text": "The code has been created with the sentiment classification task in mind (next section). Hence the final output layer is of size=1 with a sigmoid activation to return a probability as output."
},
{
"code": null,
"e": 7510,
"s": 7369,
"text": "We define an input where we say shape=99 i.e. the timestep size we expect in our data. Here this means the number of words in each sentence."
},
{
"code": null,
"e": 7826,
"s": 7510,
"text": "We use the embedding layer to transform words into a vector representation. We could have used ready-made word embeddings like Glove or Word2Vec, but we initialized a new one which will train specifically for this task. The size of each vector is 64 and num_words is the vocabulary size of the dataset we are using."
},
{
"code": null,
"e": 7988,
"s": 7826,
"text": "We use one LSTM layer with state output of size=128. Note, as per default return sequence is False, so we only get one output i.e. of the last state of the LSTM."
},
{
"code": null,
"e": 8124,
"s": 7988,
"text": "We connect the last state output with a dense layer of size=64. This is used to enhance the complex thresholding on the output of LSTM."
},
{
"code": null,
"e": 8136,
"s": 8124,
"text": "SS_RST_LSTM"
},
{
"code": null,
"e": 8236,
"s": 8136,
"text": "The only difference here is that we return all stateβs output from LSTM. We can do this as follows,"
},
{
"code": null,
"e": 8590,
"s": 8236,
"text": "inputs = keras.Input(shape=(99, ))embedding = layers.Embedding(num_words, 64)(inputs)rl = layers.LSTM(128, return_sequences=True)(embedding)avg = tf.keras.layers.AveragePooling1D(pool_size=99)(rl)dense = layers.Dense(64)(avg)output = layers.Dense(1, activation='sigmoid')(dense)self.model = keras.Model(inputs=inputs, outputs=output, name=\"SS_RST_LSTM\")"
},
{
"code": null,
"e": 8606,
"s": 8590,
"text": "Points to note,"
},
{
"code": null,
"e": 8683,
"s": 8606,
"text": "The first change is the addition of return_sequence=True in LSTM definition."
},
{
"code": null,
"e": 8987,
"s": 8683,
"text": "Next, we need to consolidate our 99x128 matrix into 1x128 sized vector. While there are many ways to do so we will pick AveragePooling1D which simply takes the average of each 99 timestep vectors to return 1 vector output. Here pool_size is to specify that we are taking an average of each 99 timesteps."
},
{
"code": null,
"e": 9001,
"s": 8987,
"text": "MS_RSF_biLSTM"
},
{
"code": null,
"e": 9098,
"s": 9001,
"text": "To have a bidirectional layer, all we need to do is add a Bidirectional function on top of LSTM."
},
{
"code": null,
"e": 9396,
"s": 9098,
"text": "inputs = keras.Input(shape=(99, ))embedding = layers.Embedding(num_words, 64)(inputs)rl = layers.Bidirectional(layers.LSTM(128))(embedding)dense = layers.Dense(64)(rl)output = layers.Dense(1, activation='sigmoid')(dense)self.model = keras.Model(inputs=inputs, outputs=output, name=\"MS_RSF_biLSTM\")"
},
{
"code": null,
"e": 9593,
"s": 9396,
"text": "Note to move to MS_RST_biLSTM you need to do 2 things β (1) add return_sequence=True inside the LSTM layer, and (2) add the AveragePooling1D logic after the bidirectional LSTM layer as done above."
},
{
"code": null,
"e": 9605,
"s": 9593,
"text": "MS_RST_LSTM"
},
{
"code": null,
"e": 10007,
"s": 9605,
"text": "inputs = keras.Input(shape=(99, ))embedding = layers.Embedding(num_words, 64)(inputs)rl = layers.LSTM(128, return_sequences=True)(embedding)rl = layers.LSTM(128, return_sequences=True)(rl)avg = tf.keras.layers.AveragePooling1D(pool_size=99)(rl)dense = layers.Dense(64)(avg)output = layers.Dense(1, activation='sigmoid')(dense)self.model = keras.Model(inputs=inputs, outputs=output, name=\"MS_RST_LSTM\")"
},
{
"code": null,
"e": 10023,
"s": 10007,
"text": "Points to note,"
},
{
"code": null,
"e": 10166,
"s": 10023,
"text": "To stack multiple LSTMs, it is mandatory for all the lower LSTMs to have return_sequence=True , as they will be fed as input to the next LSTM."
},
{
"code": null,
"e": 10314,
"s": 10166,
"text": "For the topmost LSTM, its userβs choice. As we are seeing an RST example, the code is returning all of the state sequences which is later averaged."
},
{
"code": null,
"e": 10520,
"s": 10314,
"text": "To stack more layers in this fashion, all we need to do is copy-paste the rl = layers.LSTM(128, return_sequences=True)(rl) line again and again. Here as we have 2 such lines, we have 2 layers stacked LSTM."
},
{
"code": null,
"e": 10695,
"s": 10520,
"text": "The remaining arrangements can be coded up pretty easily by following the hints shared above. I leave this as an exercise and also share the complete code here for reference."
},
{
"code": null,
"e": 11098,
"s": 10695,
"text": "For testing our models, I have selected IMDB sentiment classification datasets which contain 25,000 highly polar movie reviews with binary sentiment represented by labels 0 and 1. To be little easier on my laptop, I have further trimmed the data by considering only the top 5000 words by frequency and truncating sentence over 100 words. As the data API is exposed by Keras, all of this can be done by,"
},
{
"code": null,
"e": 11365,
"s": 11098,
"text": "# importimport tensorflow as tf# set parametersnum_words = 5000maxlen = 100# fetch data(x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=num_words, maxlen=maxlen)"
},
{
"code": null,
"e": 11808,
"s": 11365,
"text": "Also, Keras has already transformed the words into integer representation, making it easier to be fed to our models. All thatβs remaining is to make sure all of the sentences are of the same size, as there could be some sentence with size less than maxlen. This can be done by padding the smaller sentences with a dummy number (say 0). You can add padding on the left or right of the short sentences, I have chosen left. The code to do so is,"
},
{
"code": null,
"e": 11983,
"s": 11808,
"text": "## perform paddingx_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, padding=\"pre\")x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, padding=\"pre\")"
},
{
"code": null,
"e": 12604,
"s": 11983,
"text": "To compare the performance score across all models, we will train each model for a specified number of epochs on the prepared data and report accuracy. To handle variation in case of training, we will repeat the training process multiple times (runs) and also report the variation in accuracy score observed in each run along with max and min scores. Lastly, to make sure that the variation in our model performance is not introduced by random weight initialization, we will use the same initial weights for each run. Then the major difference introduced is in model fitting and its internal train-validation data split."
},
{
"code": null,
"e": 12802,
"s": 12604,
"text": "Each experiment (for one model) ran 5 times and each time we ran for 5 epochs. In total, we ran 12 such experiments (for all of our models). The consolidated performance report card is shown below,"
},
{
"code": null,
"e": 12860,
"s": 12802,
"text": "Now, let us try to answer the questions we raised before,"
},
{
"code": null,
"e": 13228,
"s": 12860,
"text": "Q1: Does different recurrent output types matter? β Short answer: Yes! To understand why, letβs compare each RSF model with its counterpart RST models. All such possible comparisons and the difference (right minus left) is shown above. As evident, 4/6 models perform better. In fact, our best model is MS_RST_LSTM, which has over ~3% improvement over its RSF version."
},
{
"code": null,
"e": 13662,
"s": 13228,
"text": "Q2: Does stacking multiple layers matters? β Yes again! See the second comparison table with all positive difference. Adding more layers does results in additional tunable parameters and hence more learning power. But be vary, this doesnβt mean you can stack 100 layers and expect it to work better than before β at some point, it will converge i.e. adding more layers will not help. But stacking few layers does help, as shown here."
},
{
"code": null,
"e": 13902,
"s": 13662,
"text": "Q3: Does bidirectional layering performs better against normal stacking? β Interestingly no! 3/4 times stacking layers perform better. This may be because multiple stack layers have more training parameters, hence better inference on data."
},
{
"code": null,
"e": 14887,
"s": 13902,
"text": "Let me start with a disclaimer β while I am (or rather the experiment results are) saying that one arrangement works better than another, I am not implying that you should only train βgoodβ models and ignore the rest. Please remember, every task and its data is different and may result in different result from the ones reported above. Take Bi-direction as an example, usually, I find bi-direction competing toe-to-toe with stacking layers and in some cases even perform better. This is in contrast to what we saw before and thatβs going on to prove that every data is different. That said, the purpose of this article was two folds β (1) to showcase the different varieties of layering arrangements that can be made by just using basic recurrent layers, and (2) based on experiments to help prioritize arrangements rather than ignoring them. So next time you have a text classification project, you can start with MS_RST_LSTM model and with time (if you have) experiments on others."
},
{
"code": null,
"e": 14895,
"s": 14887,
"text": "Cheers!"
}
] |
Java Generics - Map
|
Java has provided generic support in Map interface.
Set<T> set = new HashSet<T>();
Where
set β object of Set Interface.
set β object of Set Interface.
T β The generic type parameter passed during set declaration.
T β The generic type parameter passed during set declaration.
The T is a type parameter passed to the generic interface Set and its implemenation class HashSet.
Create the following java program using any editor of your choice.
package com.tutorialspoint;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class GenericsTester {
public static void main(String[] args) {
Map<Integer,Integer> integerMap
= new HashMap<Integer,Integer>();
integerMap.put(1, 10);
integerMap.put(2, 11);
Map<String,String> stringMap = new HashMap<String,String>();
stringMap.put("1", "Hello World");
stringMap.put("2","Hi World");
System.out.printf("Integer Value :%d\n", integerMap.get(1));
System.out.printf("String Value :%s\n", stringMap.get("1"));
// iterate keys.
Iterator<Integer> integerIterator = integerMap.keySet().iterator();
while(integerIterator.hasNext()) {
System.out.printf("Integer Value :%d\n", integerIterator.next());
}
// iterate values.
Iterator<String> stringIterator = stringMap.values().iterator();
while(stringIterator.hasNext()) {
System.out.printf("String Value :%s\n", stringIterator.next());
}
}
}
This will produce the following result β
Integer Value :10
String Value :Hello World
Integer Value :1
Integer Value :2
String Value :Hello World
String Value :Hi World
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2692,
"s": 2640,
"text": "Java has provided generic support in Map interface."
},
{
"code": null,
"e": 2724,
"s": 2692,
"text": "Set<T> set = new HashSet<T>();\n"
},
{
"code": null,
"e": 2730,
"s": 2724,
"text": "Where"
},
{
"code": null,
"e": 2761,
"s": 2730,
"text": "set β object of Set Interface."
},
{
"code": null,
"e": 2792,
"s": 2761,
"text": "set β object of Set Interface."
},
{
"code": null,
"e": 2854,
"s": 2792,
"text": "T β The generic type parameter passed during set declaration."
},
{
"code": null,
"e": 2916,
"s": 2854,
"text": "T β The generic type parameter passed during set declaration."
},
{
"code": null,
"e": 3015,
"s": 2916,
"text": "The T is a type parameter passed to the generic interface Set and its implemenation class HashSet."
},
{
"code": null,
"e": 3082,
"s": 3015,
"text": "Create the following java program using any editor of your choice."
},
{
"code": null,
"e": 4148,
"s": 3082,
"text": "package com.tutorialspoint;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n\n Map<Integer,Integer> integerMap \n = new HashMap<Integer,Integer>();\n \n integerMap.put(1, 10);\n integerMap.put(2, 11);\n\n Map<String,String> stringMap = new HashMap<String,String>();\n \n stringMap.put(\"1\", \"Hello World\");\n stringMap.put(\"2\",\"Hi World\");\n \n\n System.out.printf(\"Integer Value :%d\\n\", integerMap.get(1));\n System.out.printf(\"String Value :%s\\n\", stringMap.get(\"1\"));\n\n // iterate keys.\n Iterator<Integer> integerIterator = integerMap.keySet().iterator();\n\n while(integerIterator.hasNext()) {\n System.out.printf(\"Integer Value :%d\\n\", integerIterator.next());\n }\n\n // iterate values.\n Iterator<String> stringIterator = stringMap.values().iterator();\n\n while(stringIterator.hasNext()) {\n System.out.printf(\"String Value :%s\\n\", stringIterator.next());\n }\n } \n}"
},
{
"code": null,
"e": 4189,
"s": 4148,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 4317,
"s": 4189,
"text": "Integer Value :10\nString Value :Hello World\nInteger Value :1\nInteger Value :2\nString Value :Hello World\nString Value :Hi World\n"
},
{
"code": null,
"e": 4350,
"s": 4317,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4366,
"s": 4350,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4399,
"s": 4366,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4415,
"s": 4399,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4450,
"s": 4415,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4464,
"s": 4450,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4498,
"s": 4464,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4512,
"s": 4498,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4549,
"s": 4512,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4564,
"s": 4549,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4597,
"s": 4564,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4616,
"s": 4597,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4623,
"s": 4616,
"text": " Print"
},
{
"code": null,
"e": 4634,
"s": 4623,
"text": " Add Notes"
}
] |
A Machine Learning Approach To Credit Risk Assessment | by Sarah Beshr | Towards Data Science
|
Credit default risk is simply known as the possibility of a loss for a lender due to a borrowerβs failure to repay a loan. Credit analysts are typically responsible for assessing this risk by thoroughly analyzing a borrowerβs capability to repay a loan β but long gone are the days of credit analysts, itβs the machine learning age! Machine learning algorithms have a lot to offer to the world of credit risk assessment due to their unparalleled predictive power and speed. In this article, we will be utilizing machine learningβs power to predict whether a borrower will default on a loan or not and to predict their probability of default. Letβs get started.
The dataset weβre using can be found on Kaggle and it contains data for 32,581 borrowers and 11 variables related to each borrower. Letβs have a look at what those variables are:
Age β numerical variable; age in years
Income β numerical variable; annual income in dollars
Home status β categorical variable; βrentβ, βmortgageβ or βownβ
Employment length β numerical variable; employment length in years
Loan intent β categorical variable; βeducationβ, βmedicalβ, βventureβ, βhome improvementβ, βpersonalβ or βdebt consolidationβ
Loan amount β numerical variable; loan amount in dollars
Loan grade β categorical variable; βAβ, βBβ, βCβ, βDβ, βEβ, βFβ or βGβ
Interest rate β numerical variable; interest rate in percentage
Loan to income ratio β numerical variable; between 0 and 1
Historical default β binary, categorical variable; βYβ or βNβ
Loan status β binary, numerical variable; 0 (no default) or 1 (default) β this is going to be our target variable
Now that we know what kind of variables weβre dealing with here, letβs get to the nitty-gritty of things.
First, letβs go ahead and check for missing values in our dataset.
#Checking for missing valuesdata.isnull().sum()Age 0 Income 0 Home_Status 0 Employment_Length 895 Loan_Intent 0 loan_Grade 0 Loan_Amount 0 Interest_Rate 3116 Loan_Status 0 loan_percent_income 0 Historical_Default 0 dtype: int64
We can see that employment length and interest rate both have missing values. Given that the missing values represent a small percentage of the dataset, we will remove the rows that contain missing values.
#Dropping missing valuesdata = data.dropna(axis=0)
Next, we will look for outliers in our dataset so we can remedy them accordingly. We will do this using the describe() method which is used for calculating descriptive statistics. Not only will it help identify outliers, but it will also give us a better understanding of how our data is distributed. Weβll also be using a scatterplot matrix, a grid of scatterplots used to visualize bivariate relationships between combinations of variables, to visually detect outliers.
data.describe()
I donβt know about you but I didnβt come across that many people who have lived until the age of 144 or have been employed for 123 years. Wit aside, outliers from variables age and employment length could negatively affect our model and so should be removed. Before we do so, weβll look for more outliers using the scatterplot matrix.
#Scatterplot matrixfig = px.scatter_matrix(data, dimensions=["Age","Income","Employment_Length","Loan_Amount","Interest_Rate"],labels={col:col.replace('_', ' ') for col in data.columns}, height=900, color="Loan_Status", color_continuous_scale=px.colors.diverging.Tealrose)fig.show()
Itβs now clear that income also has an outlier that needs to be removed. Weβll now remove all the outliers using the following lines of code.
#Removing outliersdata = data[data["Age"]<=100]data = data[data["Employment_Length"]<=100]data = data[data["Income"]<= 4000000]
Given the nature of our dataset, weβd expect that weβre dealing with an imbalanced classification problem, meaning that we have considerably more non-default cases than default cases. Using the code below, we confirm that this is indeed the case with 78.4% of our dataset containing non-default cases.
#Percentage of non-default casesdata_0 = data[data.Loan_Status == 0].Loan_Status.count() / data.Loan_Status.count()data_0
With this in mind, weβll now further explore how loan status is related to other variables in our dataset.
#Box plotfig = px.box(data, x="loan_Grade", y="loan_percent_income", color="Loan_Status",color_discrete_sequence=px.colors.qualitative.Dark24,labels={col:col.replace('_', ' ') for col in data.columns},category_orders={"loan_Grade":["A","B","C","D","E","F","G"]})fig.update_layout(legend=dict(orientation="h", yanchor="bottom",y=1.02, xanchor="right", x=1))fig.show()
Two things quickly stand out when we look at this box plot. We can clearly see that those who donβt default have a lower loan to income ratio mean value across all loan grades; which doesnβt come as a surprise. We can also see that no borrowers with loan grade G were able to repay their loan!
Using a parallel category diagram, we can understand how different categorical variables in our dataset are related to each other and we can map out these relationships on the basis of loan status.
#Parallel category diagramfig = px.parallel_categories(data, color_continuous_scale=px.colors.sequential.RdBu, color="Loan_Status",dimensions=['Home_Status', 'Loan_Intent', "loan_Grade", 'Historical_Default'], labels={col:col.replace('_', ' ') for col in data.columns})fig.show()
Main takeaways from the above diagram:
Our dataset is primarily composed of borrowers who have not defaulted on a loan before;
Loan grades βAβ and βBβ are the most common grades while βFβ and βGβ are the least common;
Home renters defaulted more often on their loans than those with a mortgage, whereas homeowners defaulted the least;
Borrowers took out a loan for home improvement the least and for education the most. Also, defaults were more common for loans that were taken up for covering medical expenses and debt consolidation.
Before we get into our model training, we need to make sure that all of our variables are numerical given that some of the models weβre going to use cannot operate on label data. We can simply do this using the one-hot encoding method.
#One hot encoding of categorical variablesdf = pd.get_dummies(data=data,columns=['Home_Status','Loan_Intent','loan_Grade','Historical_Default'])
Now itβs time to split our dataset into a train and test split and weβll be all ready to start building some models.
#Train and test splitY = df['Loan_Status']X = df.drop('Loan_Status',axis=1)x_train, x_test, y_train, y_test = model_selection.train_test_split(X, Y, random_state=0, test_size=.20)
In this section, weβll be training and testing 3 models, namely KNN, logistic regression and XGBoost. Weβll also evaluate their performance at predicting loan defaults and their probability.
First, weβll build the models and look at some evaluation metrics for assessing the modelβs ability to predict class labels, i.e., default or no default.
def model_assess(model, name='Default'):model.fit(x_train, y_train)preds = model.predict(x_test)preds_proba = model.predict_proba(x_test)print(' ', name, '\n',classification_report(y_test, model.predict(x_test)))#KNNknn = KNeighborsClassifier(n_neighbors=151)model_assess(knn, name='KNN')#Logistic Regressionlg = LogisticRegression(random_state=0)model_assess(lg, 'Logistic Regression')#XGBxgb = XGBClassifier(n_estimators=1000, learning_rate=0.05)model_assess(xgb, 'XGBoost')
Weβve identified earlier that we are dealing with an imbalanced dataset and so we need to make sure weβre using the appropriate evaluation metrics for our case. For this reason, weβll be looking at the common Accuracy metric with a grain of salt. To illustrate why this is the case, accuracy calculates the ratio of total truly predicted values to the total number of input samples, meaning that our model would get pretty high accuracy by predicting the majority class but would fail to capture the minority class, default, which is no bueno. This is why the evaluation metrics that weβll be focusing on to assess the classification performance of our models are Precision, Recall and F1 score.
Firstly, Precision gives us the ratio of true positives to the total positives predicted by a classifier where positives denote default cases in our context. Given that theyβre the minority class in our dataset, we can see that our models do a good job at correctly predicting those minor instances. Moreover, Recall, a.k.a true positive rate, gives us the number of true positives divided by the total number of elements that actually belong to the positive class. In our case, Recall is a more important metric as opposed to Precision given that weβre more concerned with false negatives (our model predicting that someone is not gonna default but they do) than false positives (our model predicting that someone is gonna default but they donβt). Lastly, F1 Score provides a single score to measure both Precision and Recall. Now that we know what to look for, we can clearly see that XGboost performs the best across all 3 metrics. Although it scored better on Precision as opposed to Recall, it still has a pretty good F1 score of 0.81.
Weβll now have a look at ROC which is a probability curve with False Positive Rate (FPR) on the x-axis and True Positive Rate (TPR, recall) on the y-axis. The best model should maximize the TPR to 1 and minimize FPR to 0. With this said, we can compare classifiers using the area under the curve of the ROC curve, AUC, where the higher its value, the better the model is at predicting 0s as 0s and 1s as 1s.
#ROC AUCfig = plt.figure(figsize=(14,10))plt.plot([0, 1], [0, 1],'r--')#KNNpreds_proba_knn = knn.predict_proba(x_test)probsknn = preds_proba_knn[:, 1]fpr, tpr, thresh = metrics.roc_curve(y_test, probsknn)aucknn = roc_auc_score(y_test, probsknn)plt.plot(fpr, tpr, label=f'KNN, AUC = {str(round(aucknn,3))}')#Logistic Regressionpreds_proba_lg = lg.predict_proba(x_test)probslg = preds_proba_lg[:, 1]fpr, tpr, thresh = metrics.roc_curve(y_test, probslg)auclg = roc_auc_score(y_test, probslg)plt.plot(fpr, tpr, label=f'Logistic Regression, AUC = {str(round(auclg,3))}')#XGBoostpreds_proba_xgb = xgb.predict_proba(x_test)probsxgb = preds_proba_xgb[:, 1]fpr, tpr, thresh = metrics.roc_curve(y_test, probsxgb)aucxgb = roc_auc_score(y_test, probsxgb)plt.plot(fpr, tpr, label=f'XGBoost, AUC = {str(round(aucxgb,3))}')plt.ylabel("True Positive Rate")plt.xlabel("False Positive Rate")plt.title("ROC curve")plt.rcParams['axes.titlesize'] = 18plt.legend()plt.show()
We can once again see that XGBoost performs best as it has the highest AUC and so is the best classifier in distinguishing between default and no default classes.
So far, weβve looked at each modelβs ability to predict class labels, weβll now evaluate their performance at predicting the probability of the sample belonging to the positive class, i.e., probability of default. For this task, weβll use a Reliability Plot and Brier Score, where the former creates a diagram of the actual probabilities versus the predicted probabilities on a test set and the latter calculates the mean squared error between predicted probabilities and their respective positive class values. Given that the Brier Score is a cost function, a lower Brier Score indicates a more accurate prediction.
#Reliability plot and Brier Scorefig = plt.figure(figsize=(14,10))plt.plot([0, 1], [0, 1], color="black")#KNNknn_y, knn_x = calibration_curve(y_test, preds_proba_knn[:,1], n_bins=10, normalize=True)loss_knn = brier_score_loss(y_test, preds_proba_knn[:,1])plt.plot(knn_x, knn_y, marker='o', label=f'KNN, Brier score = {str(round(loss_knn,3))}')#Logistic Regressionlg_y, lg_x = calibration_curve(y_test, preds_proba_lg[:,1], n_bins=10, normalize=True)loss_lg = brier_score_loss(y_test, preds_proba_lg[:,1])plt.plot(lg_x, lg_y, marker='o',label=f'Logistic Regression, Brier score = {str(round(loss_lg,3))}')#XGBoostpreds_proba_xgb = xgb.predict_proba(x_test)xgb_y, xgb_x = calibration_curve(y_test, preds_proba_xgb[:,1], n_bins=10, normalize=True)loss_xgb = brier_score_loss(y_test, preds_proba_xgb[:,1])plt.plot(xgb_x, xgb_y, marker='o', label=f'XGBoost, Brier score = {str(round(loss_xgb,3))}')plt.ylabel("Actual probabilty")plt.xlabel("Predicted probability")plt.title("Reliability plot")plt.rcParams['axes.titlesize'] = 18plt.legend()plt.show()
We can see from the above Brier Score that the XGBoost performs best once again, which doesn't come as a surprise by now, in comparison to other models. From this score and the plot, we conclude that our model is well-calibrated for probability prediction, meaning that predicted probabilities closely match the expected distribution of probabilities for each class, and so doesn't require further calibration.
Itβs needless to say which model was chosen as our best performer at predicting class labels and the probability of default. If you've somehow skipped all previous steps and found yourself here, which you should go back and read btw, itβs XGBoost.
Last but not least, itβs time to identify which features were most influential in predicting our target variable. For this task, weβll be using feature importance by information gain which measures each featureβs contribution for each tree in XGBoost.
#Feature importance plotfig, (ax1, ax2) = plt.subplots(figsize = (15, 17), ncols=1, nrows=2)plt.subplots_adjust(left=0.125, right=0.9, bottom=0.1, top = 0.9, wspace=0, hspace = 0.5)plot_importance(xgb, importance_type='gain', ax = ax1)ax1.set_title('Feature Importance by Information Gain', fontsize = 18)ax1.set_xlabel('Gain')
We can see from the figure above that rent as a home status, loan to income ratio and loan grade C are the top 3 most important features for predicting loan default and its probability.
Aaand thatβs it!
To sum up, weβve analyzed and pre-processed our data, trained and evaluated 3 models, namley KNN, logistic regression and XGBoost, for their ability to predict loan defaults and their probability. We used Precision, Recall, F1 and ROCAUC to evaluate the modelsβ performance at predicting class labels. We used these metrics in particular and discarded Accuracy given that weβre dealing with an imbalanced dataset. We also used a Reliability Plot and Brier Score to assess the calibration of our models. After having identified that XGBoost performed best on all metrics, we investigated which features were most important to our predictions using feature importance by information gain. With this said, we can round up our demonstration of how machine learning can be applied to the world of credit risk assessment.
Hope that you found this article insightful!
|
[
{
"code": null,
"e": 832,
"s": 171,
"text": "Credit default risk is simply known as the possibility of a loss for a lender due to a borrowerβs failure to repay a loan. Credit analysts are typically responsible for assessing this risk by thoroughly analyzing a borrowerβs capability to repay a loan β but long gone are the days of credit analysts, itβs the machine learning age! Machine learning algorithms have a lot to offer to the world of credit risk assessment due to their unparalleled predictive power and speed. In this article, we will be utilizing machine learningβs power to predict whether a borrower will default on a loan or not and to predict their probability of default. Letβs get started."
},
{
"code": null,
"e": 1011,
"s": 832,
"text": "The dataset weβre using can be found on Kaggle and it contains data for 32,581 borrowers and 11 variables related to each borrower. Letβs have a look at what those variables are:"
},
{
"code": null,
"e": 1050,
"s": 1011,
"text": "Age β numerical variable; age in years"
},
{
"code": null,
"e": 1104,
"s": 1050,
"text": "Income β numerical variable; annual income in dollars"
},
{
"code": null,
"e": 1168,
"s": 1104,
"text": "Home status β categorical variable; βrentβ, βmortgageβ or βownβ"
},
{
"code": null,
"e": 1235,
"s": 1168,
"text": "Employment length β numerical variable; employment length in years"
},
{
"code": null,
"e": 1361,
"s": 1235,
"text": "Loan intent β categorical variable; βeducationβ, βmedicalβ, βventureβ, βhome improvementβ, βpersonalβ or βdebt consolidationβ"
},
{
"code": null,
"e": 1418,
"s": 1361,
"text": "Loan amount β numerical variable; loan amount in dollars"
},
{
"code": null,
"e": 1489,
"s": 1418,
"text": "Loan grade β categorical variable; βAβ, βBβ, βCβ, βDβ, βEβ, βFβ or βGβ"
},
{
"code": null,
"e": 1553,
"s": 1489,
"text": "Interest rate β numerical variable; interest rate in percentage"
},
{
"code": null,
"e": 1612,
"s": 1553,
"text": "Loan to income ratio β numerical variable; between 0 and 1"
},
{
"code": null,
"e": 1674,
"s": 1612,
"text": "Historical default β binary, categorical variable; βYβ or βNβ"
},
{
"code": null,
"e": 1788,
"s": 1674,
"text": "Loan status β binary, numerical variable; 0 (no default) or 1 (default) β this is going to be our target variable"
},
{
"code": null,
"e": 1894,
"s": 1788,
"text": "Now that we know what kind of variables weβre dealing with here, letβs get to the nitty-gritty of things."
},
{
"code": null,
"e": 1961,
"s": 1894,
"text": "First, letβs go ahead and check for missing values in our dataset."
},
{
"code": null,
"e": 2329,
"s": 1961,
"text": "#Checking for missing valuesdata.isnull().sum()Age 0 Income 0 Home_Status 0 Employment_Length 895 Loan_Intent 0 loan_Grade 0 Loan_Amount 0 Interest_Rate 3116 Loan_Status 0 loan_percent_income 0 Historical_Default 0 dtype: int64"
},
{
"code": null,
"e": 2535,
"s": 2329,
"text": "We can see that employment length and interest rate both have missing values. Given that the missing values represent a small percentage of the dataset, we will remove the rows that contain missing values."
},
{
"code": null,
"e": 2586,
"s": 2535,
"text": "#Dropping missing valuesdata = data.dropna(axis=0)"
},
{
"code": null,
"e": 3058,
"s": 2586,
"text": "Next, we will look for outliers in our dataset so we can remedy them accordingly. We will do this using the describe() method which is used for calculating descriptive statistics. Not only will it help identify outliers, but it will also give us a better understanding of how our data is distributed. Weβll also be using a scatterplot matrix, a grid of scatterplots used to visualize bivariate relationships between combinations of variables, to visually detect outliers."
},
{
"code": null,
"e": 3074,
"s": 3058,
"text": "data.describe()"
},
{
"code": null,
"e": 3409,
"s": 3074,
"text": "I donβt know about you but I didnβt come across that many people who have lived until the age of 144 or have been employed for 123 years. Wit aside, outliers from variables age and employment length could negatively affect our model and so should be removed. Before we do so, weβll look for more outliers using the scatterplot matrix."
},
{
"code": null,
"e": 3702,
"s": 3409,
"text": "#Scatterplot matrixfig = px.scatter_matrix(data, dimensions=[\"Age\",\"Income\",\"Employment_Length\",\"Loan_Amount\",\"Interest_Rate\"],labels={col:col.replace('_', ' ') for col in data.columns}, height=900, color=\"Loan_Status\", color_continuous_scale=px.colors.diverging.Tealrose)fig.show()"
},
{
"code": null,
"e": 3844,
"s": 3702,
"text": "Itβs now clear that income also has an outlier that needs to be removed. Weβll now remove all the outliers using the following lines of code."
},
{
"code": null,
"e": 3972,
"s": 3844,
"text": "#Removing outliersdata = data[data[\"Age\"]<=100]data = data[data[\"Employment_Length\"]<=100]data = data[data[\"Income\"]<= 4000000]"
},
{
"code": null,
"e": 4274,
"s": 3972,
"text": "Given the nature of our dataset, weβd expect that weβre dealing with an imbalanced classification problem, meaning that we have considerably more non-default cases than default cases. Using the code below, we confirm that this is indeed the case with 78.4% of our dataset containing non-default cases."
},
{
"code": null,
"e": 4396,
"s": 4274,
"text": "#Percentage of non-default casesdata_0 = data[data.Loan_Status == 0].Loan_Status.count() / data.Loan_Status.count()data_0"
},
{
"code": null,
"e": 4503,
"s": 4396,
"text": "With this in mind, weβll now further explore how loan status is related to other variables in our dataset."
},
{
"code": null,
"e": 4870,
"s": 4503,
"text": "#Box plotfig = px.box(data, x=\"loan_Grade\", y=\"loan_percent_income\", color=\"Loan_Status\",color_discrete_sequence=px.colors.qualitative.Dark24,labels={col:col.replace('_', ' ') for col in data.columns},category_orders={\"loan_Grade\":[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"]})fig.update_layout(legend=dict(orientation=\"h\", yanchor=\"bottom\",y=1.02, xanchor=\"right\", x=1))fig.show()"
},
{
"code": null,
"e": 5164,
"s": 4870,
"text": "Two things quickly stand out when we look at this box plot. We can clearly see that those who donβt default have a lower loan to income ratio mean value across all loan grades; which doesnβt come as a surprise. We can also see that no borrowers with loan grade G were able to repay their loan!"
},
{
"code": null,
"e": 5362,
"s": 5164,
"text": "Using a parallel category diagram, we can understand how different categorical variables in our dataset are related to each other and we can map out these relationships on the basis of loan status."
},
{
"code": null,
"e": 5642,
"s": 5362,
"text": "#Parallel category diagramfig = px.parallel_categories(data, color_continuous_scale=px.colors.sequential.RdBu, color=\"Loan_Status\",dimensions=['Home_Status', 'Loan_Intent', \"loan_Grade\", 'Historical_Default'], labels={col:col.replace('_', ' ') for col in data.columns})fig.show()"
},
{
"code": null,
"e": 5681,
"s": 5642,
"text": "Main takeaways from the above diagram:"
},
{
"code": null,
"e": 5769,
"s": 5681,
"text": "Our dataset is primarily composed of borrowers who have not defaulted on a loan before;"
},
{
"code": null,
"e": 5860,
"s": 5769,
"text": "Loan grades βAβ and βBβ are the most common grades while βFβ and βGβ are the least common;"
},
{
"code": null,
"e": 5977,
"s": 5860,
"text": "Home renters defaulted more often on their loans than those with a mortgage, whereas homeowners defaulted the least;"
},
{
"code": null,
"e": 6177,
"s": 5977,
"text": "Borrowers took out a loan for home improvement the least and for education the most. Also, defaults were more common for loans that were taken up for covering medical expenses and debt consolidation."
},
{
"code": null,
"e": 6413,
"s": 6177,
"text": "Before we get into our model training, we need to make sure that all of our variables are numerical given that some of the models weβre going to use cannot operate on label data. We can simply do this using the one-hot encoding method."
},
{
"code": null,
"e": 6558,
"s": 6413,
"text": "#One hot encoding of categorical variablesdf = pd.get_dummies(data=data,columns=['Home_Status','Loan_Intent','loan_Grade','Historical_Default'])"
},
{
"code": null,
"e": 6675,
"s": 6558,
"text": "Now itβs time to split our dataset into a train and test split and weβll be all ready to start building some models."
},
{
"code": null,
"e": 6855,
"s": 6675,
"text": "#Train and test splitY = df['Loan_Status']X = df.drop('Loan_Status',axis=1)x_train, x_test, y_train, y_test = model_selection.train_test_split(X, Y, random_state=0, test_size=.20)"
},
{
"code": null,
"e": 7046,
"s": 6855,
"text": "In this section, weβll be training and testing 3 models, namely KNN, logistic regression and XGBoost. Weβll also evaluate their performance at predicting loan defaults and their probability."
},
{
"code": null,
"e": 7200,
"s": 7046,
"text": "First, weβll build the models and look at some evaluation metrics for assessing the modelβs ability to predict class labels, i.e., default or no default."
},
{
"code": null,
"e": 7695,
"s": 7200,
"text": "def model_assess(model, name='Default'):model.fit(x_train, y_train)preds = model.predict(x_test)preds_proba = model.predict_proba(x_test)print(' ', name, '\\n',classification_report(y_test, model.predict(x_test)))#KNNknn = KNeighborsClassifier(n_neighbors=151)model_assess(knn, name='KNN')#Logistic Regressionlg = LogisticRegression(random_state=0)model_assess(lg, 'Logistic Regression')#XGBxgb = XGBClassifier(n_estimators=1000, learning_rate=0.05)model_assess(xgb, 'XGBoost')"
},
{
"code": null,
"e": 8391,
"s": 7695,
"text": "Weβve identified earlier that we are dealing with an imbalanced dataset and so we need to make sure weβre using the appropriate evaluation metrics for our case. For this reason, weβll be looking at the common Accuracy metric with a grain of salt. To illustrate why this is the case, accuracy calculates the ratio of total truly predicted values to the total number of input samples, meaning that our model would get pretty high accuracy by predicting the majority class but would fail to capture the minority class, default, which is no bueno. This is why the evaluation metrics that weβll be focusing on to assess the classification performance of our models are Precision, Recall and F1 score."
},
{
"code": null,
"e": 9432,
"s": 8391,
"text": "Firstly, Precision gives us the ratio of true positives to the total positives predicted by a classifier where positives denote default cases in our context. Given that theyβre the minority class in our dataset, we can see that our models do a good job at correctly predicting those minor instances. Moreover, Recall, a.k.a true positive rate, gives us the number of true positives divided by the total number of elements that actually belong to the positive class. In our case, Recall is a more important metric as opposed to Precision given that weβre more concerned with false negatives (our model predicting that someone is not gonna default but they do) than false positives (our model predicting that someone is gonna default but they donβt). Lastly, F1 Score provides a single score to measure both Precision and Recall. Now that we know what to look for, we can clearly see that XGboost performs the best across all 3 metrics. Although it scored better on Precision as opposed to Recall, it still has a pretty good F1 score of 0.81."
},
{
"code": null,
"e": 9840,
"s": 9432,
"text": "Weβll now have a look at ROC which is a probability curve with False Positive Rate (FPR) on the x-axis and True Positive Rate (TPR, recall) on the y-axis. The best model should maximize the TPR to 1 and minimize FPR to 0. With this said, we can compare classifiers using the area under the curve of the ROC curve, AUC, where the higher its value, the better the model is at predicting 0s as 0s and 1s as 1s."
},
{
"code": null,
"e": 10793,
"s": 9840,
"text": "#ROC AUCfig = plt.figure(figsize=(14,10))plt.plot([0, 1], [0, 1],'r--')#KNNpreds_proba_knn = knn.predict_proba(x_test)probsknn = preds_proba_knn[:, 1]fpr, tpr, thresh = metrics.roc_curve(y_test, probsknn)aucknn = roc_auc_score(y_test, probsknn)plt.plot(fpr, tpr, label=f'KNN, AUC = {str(round(aucknn,3))}')#Logistic Regressionpreds_proba_lg = lg.predict_proba(x_test)probslg = preds_proba_lg[:, 1]fpr, tpr, thresh = metrics.roc_curve(y_test, probslg)auclg = roc_auc_score(y_test, probslg)plt.plot(fpr, tpr, label=f'Logistic Regression, AUC = {str(round(auclg,3))}')#XGBoostpreds_proba_xgb = xgb.predict_proba(x_test)probsxgb = preds_proba_xgb[:, 1]fpr, tpr, thresh = metrics.roc_curve(y_test, probsxgb)aucxgb = roc_auc_score(y_test, probsxgb)plt.plot(fpr, tpr, label=f'XGBoost, AUC = {str(round(aucxgb,3))}')plt.ylabel(\"True Positive Rate\")plt.xlabel(\"False Positive Rate\")plt.title(\"ROC curve\")plt.rcParams['axes.titlesize'] = 18plt.legend()plt.show()"
},
{
"code": null,
"e": 10956,
"s": 10793,
"text": "We can once again see that XGBoost performs best as it has the highest AUC and so is the best classifier in distinguishing between default and no default classes."
},
{
"code": null,
"e": 11573,
"s": 10956,
"text": "So far, weβve looked at each modelβs ability to predict class labels, weβll now evaluate their performance at predicting the probability of the sample belonging to the positive class, i.e., probability of default. For this task, weβll use a Reliability Plot and Brier Score, where the former creates a diagram of the actual probabilities versus the predicted probabilities on a test set and the latter calculates the mean squared error between predicted probabilities and their respective positive class values. Given that the Brier Score is a cost function, a lower Brier Score indicates a more accurate prediction."
},
{
"code": null,
"e": 12619,
"s": 11573,
"text": "#Reliability plot and Brier Scorefig = plt.figure(figsize=(14,10))plt.plot([0, 1], [0, 1], color=\"black\")#KNNknn_y, knn_x = calibration_curve(y_test, preds_proba_knn[:,1], n_bins=10, normalize=True)loss_knn = brier_score_loss(y_test, preds_proba_knn[:,1])plt.plot(knn_x, knn_y, marker='o', label=f'KNN, Brier score = {str(round(loss_knn,3))}')#Logistic Regressionlg_y, lg_x = calibration_curve(y_test, preds_proba_lg[:,1], n_bins=10, normalize=True)loss_lg = brier_score_loss(y_test, preds_proba_lg[:,1])plt.plot(lg_x, lg_y, marker='o',label=f'Logistic Regression, Brier score = {str(round(loss_lg,3))}')#XGBoostpreds_proba_xgb = xgb.predict_proba(x_test)xgb_y, xgb_x = calibration_curve(y_test, preds_proba_xgb[:,1], n_bins=10, normalize=True)loss_xgb = brier_score_loss(y_test, preds_proba_xgb[:,1])plt.plot(xgb_x, xgb_y, marker='o', label=f'XGBoost, Brier score = {str(round(loss_xgb,3))}')plt.ylabel(\"Actual probabilty\")plt.xlabel(\"Predicted probability\")plt.title(\"Reliability plot\")plt.rcParams['axes.titlesize'] = 18plt.legend()plt.show()"
},
{
"code": null,
"e": 13030,
"s": 12619,
"text": "We can see from the above Brier Score that the XGBoost performs best once again, which doesn't come as a surprise by now, in comparison to other models. From this score and the plot, we conclude that our model is well-calibrated for probability prediction, meaning that predicted probabilities closely match the expected distribution of probabilities for each class, and so doesn't require further calibration."
},
{
"code": null,
"e": 13278,
"s": 13030,
"text": "Itβs needless to say which model was chosen as our best performer at predicting class labels and the probability of default. If you've somehow skipped all previous steps and found yourself here, which you should go back and read btw, itβs XGBoost."
},
{
"code": null,
"e": 13530,
"s": 13278,
"text": "Last but not least, itβs time to identify which features were most influential in predicting our target variable. For this task, weβll be using feature importance by information gain which measures each featureβs contribution for each tree in XGBoost."
},
{
"code": null,
"e": 13858,
"s": 13530,
"text": "#Feature importance plotfig, (ax1, ax2) = plt.subplots(figsize = (15, 17), ncols=1, nrows=2)plt.subplots_adjust(left=0.125, right=0.9, bottom=0.1, top = 0.9, wspace=0, hspace = 0.5)plot_importance(xgb, importance_type='gain', ax = ax1)ax1.set_title('Feature Importance by Information Gain', fontsize = 18)ax1.set_xlabel('Gain')"
},
{
"code": null,
"e": 14044,
"s": 13858,
"text": "We can see from the figure above that rent as a home status, loan to income ratio and loan grade C are the top 3 most important features for predicting loan default and its probability."
},
{
"code": null,
"e": 14061,
"s": 14044,
"text": "Aaand thatβs it!"
},
{
"code": null,
"e": 14877,
"s": 14061,
"text": "To sum up, weβve analyzed and pre-processed our data, trained and evaluated 3 models, namley KNN, logistic regression and XGBoost, for their ability to predict loan defaults and their probability. We used Precision, Recall, F1 and ROCAUC to evaluate the modelsβ performance at predicting class labels. We used these metrics in particular and discarded Accuracy given that weβre dealing with an imbalanced dataset. We also used a Reliability Plot and Brier Score to assess the calibration of our models. After having identified that XGBoost performed best on all metrics, we investigated which features were most important to our predictions using feature importance by information gain. With this said, we can round up our demonstration of how machine learning can be applied to the world of credit risk assessment."
}
] |
How to check if the string begins with specific substring in Java?
|
A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created.
We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.
public boolean startsWith(String prefix)
public class StringStartsWithSubStringTest {
public static void main(String[] args) {
String str = "WelcomeToTutorialsPoint";
if(str.startsWith("Welcome")) {
System.out.println("Begins with the specified word!");
}
else {
System.out.println("Does not begin with the specified word!");
}
}
}
Begins with the specified word!
|
[
{
"code": null,
"e": 1304,
"s": 1062,
"text": "A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created."
},
{
"code": null,
"e": 1456,
"s": 1304,
"text": "We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false."
},
{
"code": null,
"e": 1497,
"s": 1456,
"text": "public boolean startsWith(String prefix)"
},
{
"code": null,
"e": 1842,
"s": 1497,
"text": "public class StringStartsWithSubStringTest {\n public static void main(String[] args) {\n String str = \"WelcomeToTutorialsPoint\";\n if(str.startsWith(\"Welcome\")) {\n System.out.println(\"Begins with the specified word!\");\n }\n else {\n System.out.println(\"Does not begin with the specified word!\");\n }\n }\n}"
},
{
"code": null,
"e": 1874,
"s": 1842,
"text": "Begins with the specified word!"
}
] |
ASMNet: a Lightweight Deep Neural Network for Face Alignment and Pose Estimation | by Ali Pourramezan Fard | Towards Data Science
|
This article explains the ASMNet, a lightweight Convolutional Neural Network (CNN) for facial landmark points detection (a.k.a Face Alignment) and face pose estimation in the wild.
The code and the pre-trained models are available on Github here. You can also read the original paper here.
Facial Landmark Points Detection is an essential task in many facial image analyses and applications. It is crucial for facial image alignment, face recognition, pose estimation, and facial expression recognition. Several methods have been proposed for facial landmark points detection such as Constrained Local ModelBased Methods [1, 2], AAM [3, 4], part models [5], and Deep Learning (DL) based methods [6, 7]. Although DL-based methods are considered state-of-the-art methods, facial landmark points detection is still challenging for faces with large pose variations. Accordingly, the price to pay to achieve a high accuracy is the rise in computational complexity and the fall in the efficiency.
Furthermore, the information contained in the features is distributed throughout deep neural networks hierarchically. More specifically, while lower layers contain information about edges and corners and hence are more appropriate for localization tasks such as facial landmark points detection and pose estimation, deeper layers contain more abstract information which is more suitable for classification tasks. Inspired by the idea of multi-task learning, we design our CNN model and hence the associated loss function to learn multiple correlated tasks simultaneously.
Recent methods have focused on improving accuracy and this is normally achieved by introducing new layers and increasing the number of parameters and longer inference time. These methods are accurate and successful in desktop and server applications, but with the growth of IoT, mobile devices, and robotics, there is a growing need for more accurate and efficient algorithms.
We propose a new network structure that is inspired by MobileNetV2 and is specifically designed for facial landmark points detection with the focus on making the network shallow and small without losing much accuracy. To achieve this goal we propose a new loss function that employs ASM as an assistant loss and uses multi-task learning to improve the accuracy. Fig. 1 depicts a general framework of our proposed idea. We tested our proposed method with the challenging 300W [8] dataset and the Wider Facial Landmarks in the Wild (WFLW) [9] dataset. Our experimental results show that the accuracy of facial landmark points detection and pose estimation is comparable with the state-of-the-art methods while the size of the network is 2 times smaller than MobileNetV2.
We have designed a network that is about two times smaller than MobileNetV2 [33], both in terms of the number of parameters and FLOPs. In designing ASMNet, we only use the first 15 blocks of MobileNetV2 [33] while the main architecture has 16 blocks. Nevertheless, creating a shallow network would eventually lower the final accuracy of the system. To avoid this problem we purposefully add a few new layers. Fig. 1 shows the architecture of ASMNet.
Besides that, in a CNN, lower layers have features such as edges, and corners which are more suitable for tasks like landmark localization and pose estimation, and deeper layers contain more abstract features that are more suitable for tasks like image classification and image detection. Accordingly, training a network for correlated tasks simultaneously builds a synergy that can improve the performance of each task.
Accordingly, we designed a multitask CNN to detect facial landmarks as well as estimating the pose of the faces (pitch, roll, and yaw) simultaneously. In order to use features from different layers, we have created shortcuts from block-1-batch-normalization, block-3-batch-normalization, block-6-batch-normalization, block-10-batch-normalization, and finally block-13-batch-normalization. We connect each of these shortcuts to the output of block 15 of MobileNetV2, block-15-add, using a global average pooling layer. Finally, we concatenate all the global average pooling layers. Such architecture enables us to use features that are available in different layers of the network while keeping the number of the FLOPs small. In other words, since the original MobileNetV2 is designed for image classification task β where the more abstract features are required β it might not be suitable for face alignment task β which needs both abstract features that are available in the deeper layers as well as features that are available in the lower layers such as edges and corners.
Furthermore, we add another correlated task to the network. As Fig. 1 shows, the proposed network predicts 2 different outputs: the facial landmark points (the main output of the network), as well as the face pose. While the correlation and the synergy between these two tasks can result in more accurate results, we also wanted our lightweight ASMNet to be able to predict face pose as well so that it might be used in more applications.
We first review the Active Shape Model (ASM) algorithm and then we explain our customized loss function based on ASM that improves the accuracy of the network.
Active Shape Model is a statistical model of shape objects. Each shape is represented as n points as well as S set is defined in Eq. 1 in the following:
To simplify the problem and learn shape components, Principal Component Analysis (PCA) is applied to the covariance matrix calculated from a set of K training shape samples. Once the model is built, an approximation of any training sample (S) is calculated using Eq. 2:
Consequently, a set of parameters of a deformable model is defined by vector b, so that by varying the elements of the vector, the shape of the model is changed. Consider that the statistical variance (i.e., eigenvalue) of the ith parameter of b is Ξ»i . To make sure the generated image after applying ASM is relatively similar to the ground truth, the parameter bi of vector b is usually limited to Β±3βΞ»i [7]. This constraint ensures that the generated shape is similar to those in the original training set. Hence, we create a new shapeSN ew after applying this constraint, according to Eq. 3:
where bΜ is the constrained b. We also define ASM operator according to Eq. 4:
ASM transforms each input point (Px i , Py i ) to a new point (Aix , Aiy ) using Eqs. 1, 2, and 3.
We describe the loss functions for two different tasks. These tasks are responsible for facial landmark points detection and pose estimation.
Facial landmark points detection task: The common loss function for facial landmark points detection is Mean Square Error (MSE). We propose a new loss function that including MSE, as the main loss as well as the assistant loss which utilizes ASM to improve the accuracy of the network called ASM-LOSS.
The proposed ASM-LOSS guides the network to first learn the smoothed distribution of the facial landmark points. In other words, during the training process, the loss function compares the predicted facial landmark points with their corresponding ground truth as well as the smoothed version of the ground truth which is generated using ASM. Given this, in the early stage of training, we set a bigger weight to the ASM-LOSS in comparison to the main loss β which is MSE β, since the variation of the smoothed facial landmark points are much lower than the original landmark points, and as a rule of thumb, easier to be learned by a CNN. Then, by gradually decrease the weight of the ASM-LOSS, we lead the network to focus more on the original landmark points. In practice, we figured out that this method, which is also can be taken to account as transfer learning, works out well and results in more accurate models.
We also discover that although face pose estimation has a heavy reliance on face alignment, it can achieve good accuracy with the assistance of smoothed facial landmark points as well. In other words, if the performance of the facial landmark point detection task is acceptable, which means the network can predict facial landmarks such that the whole shape of the face is correct, the pose estimation can achieve good accuracy. Accordingly, using smoothed landmark points and training network using ASM-LOSS will results in more accuracy in pose estimation task.
Consider that for each image in the training set, there exist n landmark points in a set called G such that (Gxi , Gyi) is the coordinates for the ith landmark point. Similarly, the predicted set P contains n points such that (Px i , Py i ) is the predicted coordinates for the ith landmark point.
We apply PCA on the training set and calculate eigenvectors and eigenvalues. Then, we calculate set A, which contains n points and each point is the transformation of the corresponding point in G, by applying the ASM operatoraccording to Eq. 4:
We define the main facial landmark point loss, Eq. 7, asthe Mean Square Error between the ground truth (G) andthe predicted landmark points (P)
where N is the total number of images in the training set and Gij = (Gix , Giy ) shows the ith landmark of the j th sample in the training set. We calculate ASM-LOSS as the error between ASM points (Aset ), and predicted landmark points (Pset ) using Eq. 8:
Finally, we calculate the total loss for the facial landmark task with according to Eq. 9:
The accuracy of PCA have a heavy reliance on the ASM points (Aset ), which means that the more accurate the PCA, the less the discrepancy between the ground truth (G) and the ASM points (Aset ). To be more detailed, by reducing the accuracy of PCA, the generated ASM points (Aset ), will be more similar to the average point set, which is the average of all the ground truth face objects in the training sets. Consequently, predicting points in Aset is easier than the points in the Gset since the variation of latter is lower than the variation of the former. We use this feature to design our loss function such that we first guide the network towards learning the distribution of the smoothed landmark pointsβ which is easier to be learned β and gradually harden the problem by decreasing the weight of ASM-LOSS.We define Ξ± as ASM-LOSS weight using Eq. 10:
where i is the epoch number and l is the total number of training epochs. As shown in Eqs. 9, at the beginning of the training, the value of Ξ± is higher, which means we put more emphasis on ASM-LOSS. Hence, the network focuses more on predicting a simpler task and converges faster. Then after one-third of the total epochs, we reduce Ξ± to 1 and put equal emphasis on the main MSE loss ASM-LOSS. Finally, after two-third of total epochs, by reducingΞ± to 0.5, we direct the network toward predicting the main ground truths, while considering the smoothed points generated using ASM as an assistant.
Pose estimation task: We use mean square error to calculate the loss for the head pose estimation task. Eq. 11 defines the loss function Lpose, where yaw(yp), pitch(pp) and roll(rp) are the predicted poses and yt, pt , and rt are the corresponding ground truths.
The code is available on Github here. All the documentation about the code is also available.
Installing the requirements
In order to run the code, you need to install python >= 3.5. The requirements and the libraries needed to run the code can be installed using the following command:
pip install -r requirements.txt
Using the pre-trained models
You can test and use the pre-trained models using the following codes which are available in the following file: https://github.com/aliprf/ASMNet/blob/master/main.py
tester = Test() tester.test_model(ds_name=DatasetName.w300, pretrained_model_path='./pre_trained_models/ASMNet/ASM_loss/ASMNet_300W_ASMLoss.h5')
Preparing Data
Data needs to be normalized and saved in npy format.
PCA creation
You can use the pca_utility.py class to create the eigenvalues, eigenvectors, and the meanvector:
pca_calc = PCAUtility() pca_calc.create_pca_from_npy(dataset_name=DatasetName.w300, labels_npy_path='./data/w300/normalized_labels/', pca_percentages=90)
Training
The training implementation is located in train.py class. You can use the following code to start the training:
trainer = Train(arch=ModelArch.ASMNet, dataset_name=DatasetName.w300, save_path='./', asm_accuracy=90)
ASMNet can perform face alignment and pose estimation with a very high visual accuracy. Please visit my GitHub or the original paper for the sample images.
We proposed ASMNet, a lightweight CNN architecture with multi-task learning for facial landmark points detection and pose estimation. We proposed a loss function that is assisted using ASM that increases the network accuracy. We built our network (called ASMNet) using a small portion of MobileNetV2. The proposed ASMNet architecture is about 2 times smaller than MobileNetV2, while the accuracy remains at the same rat
@inproceedings{fard2021asmnet, title={ASMNet: A Lightweight Deep Neural Network for Face Alignment and Pose Estimation}, author={Fard, Ali Pourramezan and Abdollahi, Hojjat and Mahoor, Mohammad}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, pages={1521--1530}, year={2021} }
[1] A. Asthana, S. Zafeiriou, S. Cheng, and M. Pantic. Robust discriminative response map fitting with constrained local models. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 3444β3451, 2013.
[2] D. Cristinacce and T. F. Cootes. Feature detection and tracking with constrained local models. In Bmvc, volume 1, page 3. Citeseer, 2006.
[3] T. F. Cootes, G. J. Edwards, and C. J. Taylor. Active appearance models. In European conference on computer vision, pages 484β498. Springer, 1998.
[4] P. Martins, R. Caseiro, and J. Batista. Generative face alignment through 2.5 d active appearance models. Computer Vision and Image Understanding, 117(3):250β268, 2013.
[5] X. Zhu and D. Ramanan. Face detection, pose estimation,and landmark localization in the wild. In 2012 IEEE Conference on Computer Vision and Pattern Recognition, pages 2879β2886, June 2012.
[6] J. Zhang, S. Shan, M. Kan, and X. Chen. Coarse-to-fine autoencoder networks (cfan) for real-time face alignment. In European conference on computer vision, pages 1β16. Springer, 2014.
[7] Z. Zhang, P. Luo, C. C. Loy, and X. Tang. Facial landmark detection by deep multi-task learning. In European conference on computer vision, pages 94β108. Springer, 2014.
[8] C. Sagonas, G. Tzimiropoulos, S. Zafeiriou, and M. Pantic. 300 faces in-the-wild challenge: The first facial landmark localization challenge. In Proceedings of the IEEE International Conference on Computer Vision Workshops, pages 397β403, 2013.
[9] W. Wu, C. Qian, S. Yang, Q. Wang, Y. Cai, and Q. Zhou. Look at boundary: A boundary-aware face alignment algorithm. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 2129β2138, 2018.
|
[
{
"code": null,
"e": 352,
"s": 171,
"text": "This article explains the ASMNet, a lightweight Convolutional Neural Network (CNN) for facial landmark points detection (a.k.a Face Alignment) and face pose estimation in the wild."
},
{
"code": null,
"e": 461,
"s": 352,
"text": "The code and the pre-trained models are available on Github here. You can also read the original paper here."
},
{
"code": null,
"e": 1162,
"s": 461,
"text": "Facial Landmark Points Detection is an essential task in many facial image analyses and applications. It is crucial for facial image alignment, face recognition, pose estimation, and facial expression recognition. Several methods have been proposed for facial landmark points detection such as Constrained Local ModelBased Methods [1, 2], AAM [3, 4], part models [5], and Deep Learning (DL) based methods [6, 7]. Although DL-based methods are considered state-of-the-art methods, facial landmark points detection is still challenging for faces with large pose variations. Accordingly, the price to pay to achieve a high accuracy is the rise in computational complexity and the fall in the efficiency."
},
{
"code": null,
"e": 1734,
"s": 1162,
"text": "Furthermore, the information contained in the features is distributed throughout deep neural networks hierarchically. More specifically, while lower layers contain information about edges and corners and hence are more appropriate for localization tasks such as facial landmark points detection and pose estimation, deeper layers contain more abstract information which is more suitable for classification tasks. Inspired by the idea of multi-task learning, we design our CNN model and hence the associated loss function to learn multiple correlated tasks simultaneously."
},
{
"code": null,
"e": 2111,
"s": 1734,
"text": "Recent methods have focused on improving accuracy and this is normally achieved by introducing new layers and increasing the number of parameters and longer inference time. These methods are accurate and successful in desktop and server applications, but with the growth of IoT, mobile devices, and robotics, there is a growing need for more accurate and efficient algorithms."
},
{
"code": null,
"e": 2880,
"s": 2111,
"text": "We propose a new network structure that is inspired by MobileNetV2 and is specifically designed for facial landmark points detection with the focus on making the network shallow and small without losing much accuracy. To achieve this goal we propose a new loss function that employs ASM as an assistant loss and uses multi-task learning to improve the accuracy. Fig. 1 depicts a general framework of our proposed idea. We tested our proposed method with the challenging 300W [8] dataset and the Wider Facial Landmarks in the Wild (WFLW) [9] dataset. Our experimental results show that the accuracy of facial landmark points detection and pose estimation is comparable with the state-of-the-art methods while the size of the network is 2 times smaller than MobileNetV2."
},
{
"code": null,
"e": 3330,
"s": 2880,
"text": "We have designed a network that is about two times smaller than MobileNetV2 [33], both in terms of the number of parameters and FLOPs. In designing ASMNet, we only use the first 15 blocks of MobileNetV2 [33] while the main architecture has 16 blocks. Nevertheless, creating a shallow network would eventually lower the final accuracy of the system. To avoid this problem we purposefully add a few new layers. Fig. 1 shows the architecture of ASMNet."
},
{
"code": null,
"e": 3751,
"s": 3330,
"text": "Besides that, in a CNN, lower layers have features such as edges, and corners which are more suitable for tasks like landmark localization and pose estimation, and deeper layers contain more abstract features that are more suitable for tasks like image classification and image detection. Accordingly, training a network for correlated tasks simultaneously builds a synergy that can improve the performance of each task."
},
{
"code": null,
"e": 4827,
"s": 3751,
"text": "Accordingly, we designed a multitask CNN to detect facial landmarks as well as estimating the pose of the faces (pitch, roll, and yaw) simultaneously. In order to use features from different layers, we have created shortcuts from block-1-batch-normalization, block-3-batch-normalization, block-6-batch-normalization, block-10-batch-normalization, and finally block-13-batch-normalization. We connect each of these shortcuts to the output of block 15 of MobileNetV2, block-15-add, using a global average pooling layer. Finally, we concatenate all the global average pooling layers. Such architecture enables us to use features that are available in different layers of the network while keeping the number of the FLOPs small. In other words, since the original MobileNetV2 is designed for image classification task β where the more abstract features are required β it might not be suitable for face alignment task β which needs both abstract features that are available in the deeper layers as well as features that are available in the lower layers such as edges and corners."
},
{
"code": null,
"e": 5266,
"s": 4827,
"text": "Furthermore, we add another correlated task to the network. As Fig. 1 shows, the proposed network predicts 2 different outputs: the facial landmark points (the main output of the network), as well as the face pose. While the correlation and the synergy between these two tasks can result in more accurate results, we also wanted our lightweight ASMNet to be able to predict face pose as well so that it might be used in more applications."
},
{
"code": null,
"e": 5426,
"s": 5266,
"text": "We first review the Active Shape Model (ASM) algorithm and then we explain our customized loss function based on ASM that improves the accuracy of the network."
},
{
"code": null,
"e": 5579,
"s": 5426,
"text": "Active Shape Model is a statistical model of shape objects. Each shape is represented as n points as well as S set is defined in Eq. 1 in the following:"
},
{
"code": null,
"e": 5849,
"s": 5579,
"text": "To simplify the problem and learn shape components, Principal Component Analysis (PCA) is applied to the covariance matrix calculated from a set of K training shape samples. Once the model is built, an approximation of any training sample (S) is calculated using Eq. 2:"
},
{
"code": null,
"e": 6445,
"s": 5849,
"text": "Consequently, a set of parameters of a deformable model is defined by vector b, so that by varying the elements of the vector, the shape of the model is changed. Consider that the statistical variance (i.e., eigenvalue) of the ith parameter of b is Ξ»i . To make sure the generated image after applying ASM is relatively similar to the ground truth, the parameter bi of vector b is usually limited to Β±3βΞ»i [7]. This constraint ensures that the generated shape is similar to those in the original training set. Hence, we create a new shapeSN ew after applying this constraint, according to Eq. 3:"
},
{
"code": null,
"e": 6524,
"s": 6445,
"text": "where bΜ is the constrained b. We also define ASM operator according to Eq. 4:"
},
{
"code": null,
"e": 6623,
"s": 6524,
"text": "ASM transforms each input point (Px i , Py i ) to a new point (Aix , Aiy ) using Eqs. 1, 2, and 3."
},
{
"code": null,
"e": 6765,
"s": 6623,
"text": "We describe the loss functions for two different tasks. These tasks are responsible for facial landmark points detection and pose estimation."
},
{
"code": null,
"e": 7067,
"s": 6765,
"text": "Facial landmark points detection task: The common loss function for facial landmark points detection is Mean Square Error (MSE). We propose a new loss function that including MSE, as the main loss as well as the assistant loss which utilizes ASM to improve the accuracy of the network called ASM-LOSS."
},
{
"code": null,
"e": 7986,
"s": 7067,
"text": "The proposed ASM-LOSS guides the network to first learn the smoothed distribution of the facial landmark points. In other words, during the training process, the loss function compares the predicted facial landmark points with their corresponding ground truth as well as the smoothed version of the ground truth which is generated using ASM. Given this, in the early stage of training, we set a bigger weight to the ASM-LOSS in comparison to the main loss β which is MSE β, since the variation of the smoothed facial landmark points are much lower than the original landmark points, and as a rule of thumb, easier to be learned by a CNN. Then, by gradually decrease the weight of the ASM-LOSS, we lead the network to focus more on the original landmark points. In practice, we figured out that this method, which is also can be taken to account as transfer learning, works out well and results in more accurate models."
},
{
"code": null,
"e": 8550,
"s": 7986,
"text": "We also discover that although face pose estimation has a heavy reliance on face alignment, it can achieve good accuracy with the assistance of smoothed facial landmark points as well. In other words, if the performance of the facial landmark point detection task is acceptable, which means the network can predict facial landmarks such that the whole shape of the face is correct, the pose estimation can achieve good accuracy. Accordingly, using smoothed landmark points and training network using ASM-LOSS will results in more accuracy in pose estimation task."
},
{
"code": null,
"e": 8848,
"s": 8550,
"text": "Consider that for each image in the training set, there exist n landmark points in a set called G such that (Gxi , Gyi) is the coordinates for the ith landmark point. Similarly, the predicted set P contains n points such that (Px i , Py i ) is the predicted coordinates for the ith landmark point."
},
{
"code": null,
"e": 9093,
"s": 8848,
"text": "We apply PCA on the training set and calculate eigenvectors and eigenvalues. Then, we calculate set A, which contains n points and each point is the transformation of the corresponding point in G, by applying the ASM operatoraccording to Eq. 4:"
},
{
"code": null,
"e": 9237,
"s": 9093,
"text": "We define the main facial landmark point loss, Eq. 7, asthe Mean Square Error between the ground truth (G) andthe predicted landmark points (P)"
},
{
"code": null,
"e": 9495,
"s": 9237,
"text": "where N is the total number of images in the training set and Gij = (Gix , Giy ) shows the ith landmark of the j th sample in the training set. We calculate ASM-LOSS as the error between ASM points (Aset ), and predicted landmark points (Pset ) using Eq. 8:"
},
{
"code": null,
"e": 9586,
"s": 9495,
"text": "Finally, we calculate the total loss for the facial landmark task with according to Eq. 9:"
},
{
"code": null,
"e": 10446,
"s": 9586,
"text": "The accuracy of PCA have a heavy reliance on the ASM points (Aset ), which means that the more accurate the PCA, the less the discrepancy between the ground truth (G) and the ASM points (Aset ). To be more detailed, by reducing the accuracy of PCA, the generated ASM points (Aset ), will be more similar to the average point set, which is the average of all the ground truth face objects in the training sets. Consequently, predicting points in Aset is easier than the points in the Gset since the variation of latter is lower than the variation of the former. We use this feature to design our loss function such that we first guide the network towards learning the distribution of the smoothed landmark pointsβ which is easier to be learned β and gradually harden the problem by decreasing the weight of ASM-LOSS.We define Ξ± as ASM-LOSS weight using Eq. 10:"
},
{
"code": null,
"e": 11044,
"s": 10446,
"text": "where i is the epoch number and l is the total number of training epochs. As shown in Eqs. 9, at the beginning of the training, the value of Ξ± is higher, which means we put more emphasis on ASM-LOSS. Hence, the network focuses more on predicting a simpler task and converges faster. Then after one-third of the total epochs, we reduce Ξ± to 1 and put equal emphasis on the main MSE loss ASM-LOSS. Finally, after two-third of total epochs, by reducingΞ± to 0.5, we direct the network toward predicting the main ground truths, while considering the smoothed points generated using ASM as an assistant."
},
{
"code": null,
"e": 11307,
"s": 11044,
"text": "Pose estimation task: We use mean square error to calculate the loss for the head pose estimation task. Eq. 11 defines the loss function Lpose, where yaw(yp), pitch(pp) and roll(rp) are the predicted poses and yt, pt , and rt are the corresponding ground truths."
},
{
"code": null,
"e": 11401,
"s": 11307,
"text": "The code is available on Github here. All the documentation about the code is also available."
},
{
"code": null,
"e": 11429,
"s": 11401,
"text": "Installing the requirements"
},
{
"code": null,
"e": 11594,
"s": 11429,
"text": "In order to run the code, you need to install python >= 3.5. The requirements and the libraries needed to run the code can be installed using the following command:"
},
{
"code": null,
"e": 11626,
"s": 11594,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 11655,
"s": 11626,
"text": "Using the pre-trained models"
},
{
"code": null,
"e": 11821,
"s": 11655,
"text": "You can test and use the pre-trained models using the following codes which are available in the following file: https://github.com/aliprf/ASMNet/blob/master/main.py"
},
{
"code": null,
"e": 11987,
"s": 11821,
"text": "tester = Test() tester.test_model(ds_name=DatasetName.w300, pretrained_model_path='./pre_trained_models/ASMNet/ASM_loss/ASMNet_300W_ASMLoss.h5')"
},
{
"code": null,
"e": 12002,
"s": 11987,
"text": "Preparing Data"
},
{
"code": null,
"e": 12055,
"s": 12002,
"text": "Data needs to be normalized and saved in npy format."
},
{
"code": null,
"e": 12068,
"s": 12055,
"text": "PCA creation"
},
{
"code": null,
"e": 12166,
"s": 12068,
"text": "You can use the pca_utility.py class to create the eigenvalues, eigenvectors, and the meanvector:"
},
{
"code": null,
"e": 12387,
"s": 12166,
"text": "pca_calc = PCAUtility() pca_calc.create_pca_from_npy(dataset_name=DatasetName.w300, labels_npy_path='./data/w300/normalized_labels/', pca_percentages=90)"
},
{
"code": null,
"e": 12396,
"s": 12387,
"text": "Training"
},
{
"code": null,
"e": 12508,
"s": 12396,
"text": "The training implementation is located in train.py class. You can use the following code to start the training:"
},
{
"code": null,
"e": 12668,
"s": 12508,
"text": "trainer = Train(arch=ModelArch.ASMNet, dataset_name=DatasetName.w300, save_path='./', asm_accuracy=90)"
},
{
"code": null,
"e": 12824,
"s": 12668,
"text": "ASMNet can perform face alignment and pose estimation with a very high visual accuracy. Please visit my GitHub or the original paper for the sample images."
},
{
"code": null,
"e": 13244,
"s": 12824,
"text": "We proposed ASMNet, a lightweight CNN architecture with multi-task learning for facial landmark points detection and pose estimation. We proposed a loss function that is assisted using ASM that increases the network accuracy. We built our network (called ASMNet) using a small portion of MobileNetV2. The proposed ASMNet architecture is about 2 times smaller than MobileNetV2, while the accuracy remains at the same rat"
},
{
"code": null,
"e": 13605,
"s": 13244,
"text": "@inproceedings{fard2021asmnet, title={ASMNet: A Lightweight Deep Neural Network for Face Alignment and Pose Estimation}, author={Fard, Ali Pourramezan and Abdollahi, Hojjat and Mahoor, Mohammad}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, pages={1521--1530}, year={2021} }"
},
{
"code": null,
"e": 13839,
"s": 13605,
"text": "[1] A. Asthana, S. Zafeiriou, S. Cheng, and M. Pantic. Robust discriminative response map fitting with constrained local models. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 3444β3451, 2013."
},
{
"code": null,
"e": 13981,
"s": 13839,
"text": "[2] D. Cristinacce and T. F. Cootes. Feature detection and tracking with constrained local models. In Bmvc, volume 1, page 3. Citeseer, 2006."
},
{
"code": null,
"e": 14132,
"s": 13981,
"text": "[3] T. F. Cootes, G. J. Edwards, and C. J. Taylor. Active appearance models. In European conference on computer vision, pages 484β498. Springer, 1998."
},
{
"code": null,
"e": 14305,
"s": 14132,
"text": "[4] P. Martins, R. Caseiro, and J. Batista. Generative face alignment through 2.5 d active appearance models. Computer Vision and Image Understanding, 117(3):250β268, 2013."
},
{
"code": null,
"e": 14499,
"s": 14305,
"text": "[5] X. Zhu and D. Ramanan. Face detection, pose estimation,and landmark localization in the wild. In 2012 IEEE Conference on Computer Vision and Pattern Recognition, pages 2879β2886, June 2012."
},
{
"code": null,
"e": 14687,
"s": 14499,
"text": "[6] J. Zhang, S. Shan, M. Kan, and X. Chen. Coarse-to-fine autoencoder networks (cfan) for real-time face alignment. In European conference on computer vision, pages 1β16. Springer, 2014."
},
{
"code": null,
"e": 14861,
"s": 14687,
"text": "[7] Z. Zhang, P. Luo, C. C. Loy, and X. Tang. Facial landmark detection by deep multi-task learning. In European conference on computer vision, pages 94β108. Springer, 2014."
},
{
"code": null,
"e": 15110,
"s": 14861,
"text": "[8] C. Sagonas, G. Tzimiropoulos, S. Zafeiriou, and M. Pantic. 300 faces in-the-wild challenge: The first facial landmark localization challenge. In Proceedings of the IEEE International Conference on Computer Vision Workshops, pages 397β403, 2013."
}
] |
Count of substrings of given string with frequency of each character at most K - GeeksforGeeks
|
14 Dec, 2021
Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K.
Examples:
Input: str = βababβ, K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are βaβ, βbβ, βaβ, βbβ, βabβ, βbaβ and βabβ.
Input: str[] = βxxyyzzxxβ, K = 2Output: 33
Approach: The given problem can be solved using the two-pointer technique. Iterate through each character of the string in the range [0, N) and maintain the frequency of each character in an unordered map. Create a variable ptr, which stores the index of the starting point of the current window. Initially, the value of ptr is 0. For index i, if the frequency of str[i] is less than or equal to K, add (i β ptr + 1) into the substring count, otherwise, increment the value of ptr until str[i] > K.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of// substrings such that frequency// of each character is atmost Kint cntSubstr(string str, int K){ // Stores the size of string int N = str.size(); // Stores the final count int ans = 0; // Stores the starting index int ptr = 0; // Stores the frequency of // characters of string unordered_map<char, int> m; // Loop to iterate through string for (int i = 0; i < N; i++) { // Increment the frequency of // the current character m[str[i]]++; // While the frequency of char is // greater than K, increment ptr while (m[str[i]] > K && ptr <= i) { m[str[ptr]]--; ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans;} // Driver Codeint main(){ string str = "abab"; int K = 1; cout << cntSubstr(str, K); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the count of// substrings such that frequency// of each character is atmost Kstatic int cntSubstr(String str, int K){ // Stores the size of string int N = str.length(); // Stores the final count int ans = 0; // Stores the starting index int ptr = 0; // Stores the frequency of // characters of string HashMap<Character, Integer> m = new HashMap<Character, Integer>(); // Loop to iterate through string for(int i = 0; i < N; i++) { // Increment the frequency of // the current character int count = 0; if (m.containsKey(str.charAt(i))) { count = m.get(str.charAt(i)); } m.put(str.charAt(i), count + 1); // While the frequency of char is // greater than K, increment ptr while (m.get(str.charAt(i)) > K && ptr <= i) { m.put(str.charAt(ptr), m.get(str.charAt(ptr)) - 1); ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans;} // Driver Codepublic static void main(String[] args){ String str = "abab"; int K = 1; System.out.println(cntSubstr(str, K));}} // This code is contributed by ukasp
# Python Program to implement# the above approach # Function to find the count of# substrings such that frequency# of each character is atmost Kdef cntSubstr(str, K): # Stores the size of string N = len(str) # Stores the final count ans = 0 # Stores the starting index ptr = 0 # Stores the frequency of # characters of string m = {} # Loop to iterate through string for i in range(N) : # Increment the frequency of # the current character if (str[i] in m): m[str[i]] += 1 else: m[str[i]] = 1 # While the frequency of char is # greater than K, increment ptr while (m[str[i]] > K and ptr <= i): m[str[ptr]] -= 1 ptr += 1 # Update count ans += (i - ptr + 1) # Return Answer return ans # Driver Codestr = "abab"K = 1print(cntSubstr(str, K)) # This code is contributed by Saurabh Jaiswal
// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find the count of// substrings such that frequency// of each character is atmost Kstatic int cntSubstr(string str, int K){ // Stores the size of string int N = str.Length; // Stores the final count int ans = 0; // Stores the starting index int ptr = 0; // Stores the frequency of // characters of string Dictionary<char, int> m = new Dictionary<char, int>(); // Loop to iterate through string for (int i = 0; i < N; i++) { // Increment the frequency of // the current character int count = 0; if (m.ContainsKey(str[i])) { count = m[str[i]]; } m[str[i]] = count + 1; // While the frequency of char is // greater than K, increment ptr while (m[str[i]] > K && ptr <= i) { m[str[ptr]]--; ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans;} // Driver Codepublic static void Main(){ string str = "abab"; int K = 1; Console.Write(cntSubstr(str, K)); }} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript Program to implement // the above approach // Function to find the count of // substrings such that frequency // of each character is atmost K function cntSubstr(str, K) { // Stores the size of string let N = str.length; // Stores the final count let ans = 0; // Stores the starting index let ptr = 0; // Stores the frequency of // characters of string let m = new Map(); // Loop to iterate through string for (let i = 0; i < N; i++) { // Increment the frequency of // the current character if (m.has(str.charAt(i))) m.set(str[i], m.get(str[i]) + 1); else m.set(str[i], 1); // While the frequency of char is // greater than K, increment ptr while (m.get(str[i]) > K && ptr <= i) { m.set(str[ptr], m.get(str[ptr]) - 1); ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans; } // Driver Code let str = "abab"; let K = 1; document.write(cntSubstr(str, K)); // This code is contributed by Potta Lokesh </script>
7
Time Complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
samim2000
mostaptname
_saurabh_jaiswal
ukasp
frequency-counting
substring
Arrays
Hash
Strings
Arrays
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Building Heap from Array
Trapping Rain Water
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 24953,
"s": 24796,
"text": "Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K."
},
{
"code": null,
"e": 24963,
"s": 24953,
"text": "Examples:"
},
{
"code": null,
"e": 25125,
"s": 24963,
"text": "Input: str = βababβ, K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are βaβ, βbβ, βaβ, βbβ, βabβ, βbaβ and βabβ."
},
{
"code": null,
"e": 25168,
"s": 25125,
"text": "Input: str[] = βxxyyzzxxβ, K = 2Output: 33"
},
{
"code": null,
"e": 25668,
"s": 25168,
"text": "Approach: The given problem can be solved using the two-pointer technique. Iterate through each character of the string in the range [0, N) and maintain the frequency of each character in an unordered map. Create a variable ptr, which stores the index of the starting point of the current window. Initially, the value of ptr is 0. For index i, if the frequency of str[i] is less than or equal to K, add (i β ptr + 1) into the substring count, otherwise, increment the value of ptr until str[i] > K. "
},
{
"code": null,
"e": 25719,
"s": 25668,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25723,
"s": 25719,
"text": "C++"
},
{
"code": null,
"e": 25728,
"s": 25723,
"text": "Java"
},
{
"code": null,
"e": 25736,
"s": 25728,
"text": "Python3"
},
{
"code": null,
"e": 25739,
"s": 25736,
"text": "C#"
},
{
"code": null,
"e": 25750,
"s": 25739,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of// substrings such that frequency// of each character is atmost Kint cntSubstr(string str, int K){ // Stores the size of string int N = str.size(); // Stores the final count int ans = 0; // Stores the starting index int ptr = 0; // Stores the frequency of // characters of string unordered_map<char, int> m; // Loop to iterate through string for (int i = 0; i < N; i++) { // Increment the frequency of // the current character m[str[i]]++; // While the frequency of char is // greater than K, increment ptr while (m[str[i]] > K && ptr <= i) { m[str[ptr]]--; ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans;} // Driver Codeint main(){ string str = \"abab\"; int K = 1; cout << cntSubstr(str, K); return 0;}",
"e": 26746,
"s": 25750,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the count of// substrings such that frequency// of each character is atmost Kstatic int cntSubstr(String str, int K){ // Stores the size of string int N = str.length(); // Stores the final count int ans = 0; // Stores the starting index int ptr = 0; // Stores the frequency of // characters of string HashMap<Character, Integer> m = new HashMap<Character, Integer>(); // Loop to iterate through string for(int i = 0; i < N; i++) { // Increment the frequency of // the current character int count = 0; if (m.containsKey(str.charAt(i))) { count = m.get(str.charAt(i)); } m.put(str.charAt(i), count + 1); // While the frequency of char is // greater than K, increment ptr while (m.get(str.charAt(i)) > K && ptr <= i) { m.put(str.charAt(ptr), m.get(str.charAt(ptr)) - 1); ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans;} // Driver Codepublic static void main(String[] args){ String str = \"abab\"; int K = 1; System.out.println(cntSubstr(str, K));}} // This code is contributed by ukasp",
"e": 28117,
"s": 26746,
"text": null
},
{
"code": "# Python Program to implement# the above approach # Function to find the count of# substrings such that frequency# of each character is atmost Kdef cntSubstr(str, K): # Stores the size of string N = len(str) # Stores the final count ans = 0 # Stores the starting index ptr = 0 # Stores the frequency of # characters of string m = {} # Loop to iterate through string for i in range(N) : # Increment the frequency of # the current character if (str[i] in m): m[str[i]] += 1 else: m[str[i]] = 1 # While the frequency of char is # greater than K, increment ptr while (m[str[i]] > K and ptr <= i): m[str[ptr]] -= 1 ptr += 1 # Update count ans += (i - ptr + 1) # Return Answer return ans # Driver Codestr = \"abab\"K = 1print(cntSubstr(str, K)) # This code is contributed by Saurabh Jaiswal",
"e": 29065,
"s": 28117,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find the count of// substrings such that frequency// of each character is atmost Kstatic int cntSubstr(string str, int K){ // Stores the size of string int N = str.Length; // Stores the final count int ans = 0; // Stores the starting index int ptr = 0; // Stores the frequency of // characters of string Dictionary<char, int> m = new Dictionary<char, int>(); // Loop to iterate through string for (int i = 0; i < N; i++) { // Increment the frequency of // the current character int count = 0; if (m.ContainsKey(str[i])) { count = m[str[i]]; } m[str[i]] = count + 1; // While the frequency of char is // greater than K, increment ptr while (m[str[i]] > K && ptr <= i) { m[str[ptr]]--; ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans;} // Driver Codepublic static void Main(){ string str = \"abab\"; int K = 1; Console.Write(cntSubstr(str, K)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 30347,
"s": 29065,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach // Function to find the count of // substrings such that frequency // of each character is atmost K function cntSubstr(str, K) { // Stores the size of string let N = str.length; // Stores the final count let ans = 0; // Stores the starting index let ptr = 0; // Stores the frequency of // characters of string let m = new Map(); // Loop to iterate through string for (let i = 0; i < N; i++) { // Increment the frequency of // the current character if (m.has(str.charAt(i))) m.set(str[i], m.get(str[i]) + 1); else m.set(str[i], 1); // While the frequency of char is // greater than K, increment ptr while (m.get(str[i]) > K && ptr <= i) { m.set(str[ptr], m.get(str[ptr]) - 1); ptr++; } // Update count ans += (i - ptr + 1); } // Return Answer return ans; } // Driver Code let str = \"abab\"; let K = 1; document.write(cntSubstr(str, K)); // This code is contributed by Potta Lokesh </script>",
"e": 31737,
"s": 30347,
"text": null
},
{
"code": null,
"e": 31739,
"s": 31737,
"text": "7"
},
{
"code": null,
"e": 31782,
"s": 31739,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 31798,
"s": 31784,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31808,
"s": 31798,
"text": "samim2000"
},
{
"code": null,
"e": 31820,
"s": 31808,
"text": "mostaptname"
},
{
"code": null,
"e": 31837,
"s": 31820,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31843,
"s": 31837,
"text": "ukasp"
},
{
"code": null,
"e": 31862,
"s": 31843,
"text": "frequency-counting"
},
{
"code": null,
"e": 31872,
"s": 31862,
"text": "substring"
},
{
"code": null,
"e": 31879,
"s": 31872,
"text": "Arrays"
},
{
"code": null,
"e": 31884,
"s": 31879,
"text": "Hash"
},
{
"code": null,
"e": 31892,
"s": 31884,
"text": "Strings"
},
{
"code": null,
"e": 31899,
"s": 31892,
"text": "Arrays"
},
{
"code": null,
"e": 31904,
"s": 31899,
"text": "Hash"
},
{
"code": null,
"e": 31912,
"s": 31904,
"text": "Strings"
},
{
"code": null,
"e": 32010,
"s": 31912,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32035,
"s": 32010,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32060,
"s": 32035,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 32080,
"s": 32060,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32129,
"s": 32080,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32167,
"s": 32129,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32203,
"s": 32167,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 32234,
"s": 32203,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 32268,
"s": 32234,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 32295,
"s": 32268,
"text": "Count pairs with given sum"
}
] |
GATE | GATE-CS-2016 (Set 1) | Question 25 - GeeksforGeeks
|
12 Aug, 2021
Consider the following C program.
#include<stdio.h>void mystery(int *ptra, int *ptrb) { int *temp; temp = ptrb; ptrb = ptra; ptra = temp;}int main() { int a=2016, b=0, c=4, d=42; mystery(&a, &b); if (a < c) mystery(&c, &a); mystery(&a, &d); printf("%d\n", a);}
The output of the program _____________
Note : This question was asked as Numerical Answer Type.
(A) 2016(B) 0(C) 4(D) 8Answer: (A)Explanation: Note that a and d are not swapped as the function mystery() doesnβt change values, but pointers which are local to the function.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2016 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0021:27 / 1:07:54β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Key2RKhzRGY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
|
[
{
"code": null,
"e": 24243,
"s": 24215,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 24277,
"s": 24243,
"text": "Consider the following C program."
},
{
"code": "#include<stdio.h>void mystery(int *ptra, int *ptrb) { int *temp; temp = ptrb; ptrb = ptra; ptra = temp;}int main() { int a=2016, b=0, c=4, d=42; mystery(&a, &b); if (a < c) mystery(&c, &a); mystery(&a, &d); printf(\"%d\\n\", a);}",
"e": 24533,
"s": 24277,
"text": null
},
{
"code": null,
"e": 24573,
"s": 24533,
"text": "The output of the program _____________"
},
{
"code": null,
"e": 24631,
"s": 24573,
"text": " Note : This question was asked as Numerical Answer Type."
},
{
"code": null,
"e": 24807,
"s": 24631,
"text": "(A) 2016(B) 0(C) 4(D) 8Answer: (A)Explanation: Note that a and d are not swapped as the function mystery() doesnβt change values, but pointers which are local to the function."
},
{
"code": null,
"e": 25698,
"s": 24807,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2016 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0021:27 / 1:07:54β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Key2RKhzRGY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 25719,
"s": 25698,
"text": "GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 25745,
"s": 25719,
"text": "GATE-GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 25750,
"s": 25745,
"text": "GATE"
},
{
"code": null,
"e": 25848,
"s": 25750,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25857,
"s": 25848,
"text": "Comments"
},
{
"code": null,
"e": 25870,
"s": 25857,
"text": "Old Comments"
},
{
"code": null,
"e": 25912,
"s": 25870,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25954,
"s": 25912,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25988,
"s": 25954,
"text": "GATE | GATE-CS-2001 | Question 23"
},
{
"code": null,
"e": 26030,
"s": 25988,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 26064,
"s": 26030,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 26106,
"s": 26064,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 26148,
"s": 26106,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 26202,
"s": 26148,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 26235,
"s": 26202,
"text": "GATE | GATE-CS-2004 | Question 3"
}
] |
Is there a goto statement available in bash on Linux?
|
Long story short, Linuxβs bash doesnβt have goto statements and no information about the control structures exists in the official documentation. It should also be noted that we can make use of the break and continue statement to achieve the same behaviour that goto statement provides us.
A simple behaviour of the goto can be achieved with a few tweaks and using the simple if condition in bash.
The script will look something like this
# ... Code You want to run here ...
if false; then
# ... Code You want to skip here ...
fi
# ... You want to resume here ...
Another idea is to make use of a bash script that is slightly more complicated, then the one mentioned above but works like a charm.
#!/bin/bash
function goto
{
label=$1
cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
eval "$cmd"
exit
}
startFunc=${1:-"startFunc"}
goto $startFunc
startFunc:
x=100
goto foo
mid:
x=101
echo "Not printed!"
foo:
x=${x:-10}
echo x is $x
$ ./sample.sh
x is 100
$ ./sample.sh foo
x is 11
$ ./sample.sh mid
Not printed!
x is 101
|
[
{
"code": null,
"e": 1352,
"s": 1062,
"text": "Long story short, Linuxβs bash doesnβt have goto statements and no information about the control structures exists in the official documentation. It should also be noted that we can make use of the break and continue statement to achieve the same behaviour that goto statement provides us."
},
{
"code": null,
"e": 1460,
"s": 1352,
"text": "A simple behaviour of the goto can be achieved with a few tweaks and using the simple if condition in bash."
},
{
"code": null,
"e": 1501,
"s": 1460,
"text": "The script will look something like this"
},
{
"code": null,
"e": 1630,
"s": 1501,
"text": "# ... Code You want to run here ...\n\nif false; then\n\n# ... Code You want to skip here ...\n\nfi\n\n# ... You want to resume here ..."
},
{
"code": null,
"e": 1763,
"s": 1630,
"text": "Another idea is to make use of a bash script that is slightly more complicated, then the one mentioned above but works like a charm."
},
{
"code": null,
"e": 2023,
"s": 1763,
"text": "#!/bin/bash\n\nfunction goto\n{\n label=$1\n cmd=$(sed -n \"/$label:/{:a;n;p;ba};\" $0 | grep -v ':$')\n eval \"$cmd\"\n exit\n}\nstartFunc=${1:-\"startFunc\"}\n\ngoto $startFunc\n\nstartFunc:\n\nx=100\ngoto foo\n\nmid:\nx=101\necho \"Not printed!\"\n\nfoo:\nx=${x:-10}\necho x is $x"
},
{
"code": null,
"e": 2112,
"s": 2023,
"text": "$ ./sample.sh\nx is 100\n$ ./sample.sh foo\nx is 11\n$ ./sample.sh mid\nNot printed!\nx is 101"
}
] |
PHP - MYSQL : sum() operation - GeeksforGeeks
|
01 Oct, 2021
Problem Statement:
In this article, we are going to perform sum() aggregate operation on our database using PHP with xampp server.
So we are considering the food_order database and perform database sum() operation.
Requirements:
xampp
Introduction:
PHP stands for hypertext preprocessor which is a server-side scripting language connect with databases.
it is connected with MySQL to perform manipulations in a database.
MySQL is a database query language for managing databases.
sum()
sum() function is an aggregation operation used to add the particular column based on the given condition.
Syntax:
SELECT SUM(column1),column2,...column1 from
table_name;
It can be also used with GROUP BY & HAVING clause.
Example query:
Consider the table:
Find the total cost of food items
SELECT SUM(cost) from food;
Output:
Total cost: 2935
Find the total weight of food items
SELECT SUM(weight) from food;
Total weight: 382
Find the total cost of food items with respect to items
SELECT food_item, SUM(cost) FROM food GROUP BY food_item;
Total cakes = 1365
Total chocos = 200
Total chocoss = 705
Total fry = 345
Total milk = 320
Approach
Create a database
Create a table
PHP code to perform sum() operation
Steps
Start xampp server
Create a database named geek and create a table named food
Table structure:
Refer this for how to insert records in xampp
https://www.geeksforgeeks.org/performing-database-operations-in-xampp/
Finally, the food table contains
PHP code to perform sum function
form.php
After writing code type βlocalhost/form.phpβ to view the output in the browser.
PHP
<html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//geek is the database name$dbname = "geek"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "<h1>"; echo "sum() aggregate Demo "; echo"</h1>";echo "<h2>";echo " Find the total cost of food items ";echo "</h2>";//sql query$sql = "SELECT SUM(cost) from food";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " Total cost: ". $row['SUM(cost)']; echo "<br>";} echo "<h2>";echo " Find the total weight of food items ";echo "</h2>";//sql query$sql = "SELECT SUM(weight) from food";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " Total weight: ". $row['SUM(weight)']; echo "<br>";} //close the connection $conn->close();?></body></html>
Output:
Example: sum() with group by clause
form1.php
PHP
<html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//geek is the database name$dbname = "geek"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "<h1>"; echo "sum() aggregate with group by Demo "; echo"</h1>";echo "<h2>";echo " ";echo "</h2>";//sql query$sql = "SELECT food_item, SUM(cost) FROM food GROUP BY food_item";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo "Total ". $row['food_item']. " = ". $row['SUM(cost)']; echo "<br />";}//close the connection $conn->close();?></body></html>
Output:
adnanirshad158
DBMS-SQL
PHP
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
Different ways for passing data to view in Laravel
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
PHP | shell_exec() vs exec() Function
How to generate PDF file using PHP ?
PHP | Ternary Operator
PHP | file_exists( ) Function
|
[
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 26236,
"s": 26217,
"text": "Problem Statement:"
},
{
"code": null,
"e": 26348,
"s": 26236,
"text": "In this article, we are going to perform sum() aggregate operation on our database using PHP with xampp server."
},
{
"code": null,
"e": 26432,
"s": 26348,
"text": "So we are considering the food_order database and perform database sum() operation."
},
{
"code": null,
"e": 26446,
"s": 26432,
"text": "Requirements:"
},
{
"code": null,
"e": 26452,
"s": 26446,
"text": "xampp"
},
{
"code": null,
"e": 26466,
"s": 26452,
"text": "Introduction:"
},
{
"code": null,
"e": 26570,
"s": 26466,
"text": "PHP stands for hypertext preprocessor which is a server-side scripting language connect with databases."
},
{
"code": null,
"e": 26637,
"s": 26570,
"text": "it is connected with MySQL to perform manipulations in a database."
},
{
"code": null,
"e": 26696,
"s": 26637,
"text": "MySQL is a database query language for managing databases."
},
{
"code": null,
"e": 26702,
"s": 26696,
"text": "sum()"
},
{
"code": null,
"e": 26809,
"s": 26702,
"text": "sum() function is an aggregation operation used to add the particular column based on the given condition."
},
{
"code": null,
"e": 26817,
"s": 26809,
"text": "Syntax:"
},
{
"code": null,
"e": 26873,
"s": 26817,
"text": "SELECT SUM(column1),column2,...column1 from\ntable_name;"
},
{
"code": null,
"e": 26924,
"s": 26873,
"text": "It can be also used with GROUP BY & HAVING clause."
},
{
"code": null,
"e": 26939,
"s": 26924,
"text": "Example query:"
},
{
"code": null,
"e": 26959,
"s": 26939,
"text": "Consider the table:"
},
{
"code": null,
"e": 26993,
"s": 26959,
"text": "Find the total cost of food items"
},
{
"code": null,
"e": 27022,
"s": 26993,
"text": "SELECT SUM(cost) from food;"
},
{
"code": null,
"e": 27030,
"s": 27022,
"text": "Output:"
},
{
"code": null,
"e": 27047,
"s": 27030,
"text": "Total cost: 2935"
},
{
"code": null,
"e": 27083,
"s": 27047,
"text": "Find the total weight of food items"
},
{
"code": null,
"e": 27114,
"s": 27083,
"text": "SELECT SUM(weight) from food;"
},
{
"code": null,
"e": 27132,
"s": 27114,
"text": "Total weight: 382"
},
{
"code": null,
"e": 27188,
"s": 27132,
"text": "Find the total cost of food items with respect to items"
},
{
"code": null,
"e": 27337,
"s": 27188,
"text": "SELECT food_item, SUM(cost) FROM food GROUP BY food_item;\nTotal cakes = 1365\nTotal chocos = 200\nTotal chocoss = 705\nTotal fry = 345\nTotal milk = 320"
},
{
"code": null,
"e": 27346,
"s": 27337,
"text": "Approach"
},
{
"code": null,
"e": 27365,
"s": 27346,
"text": "Create a database"
},
{
"code": null,
"e": 27380,
"s": 27365,
"text": "Create a table"
},
{
"code": null,
"e": 27416,
"s": 27380,
"text": "PHP code to perform sum() operation"
},
{
"code": null,
"e": 27422,
"s": 27416,
"text": "Steps"
},
{
"code": null,
"e": 27441,
"s": 27422,
"text": "Start xampp server"
},
{
"code": null,
"e": 27500,
"s": 27441,
"text": "Create a database named geek and create a table named food"
},
{
"code": null,
"e": 27517,
"s": 27500,
"text": "Table structure:"
},
{
"code": null,
"e": 27563,
"s": 27517,
"text": "Refer this for how to insert records in xampp"
},
{
"code": null,
"e": 27634,
"s": 27563,
"text": "https://www.geeksforgeeks.org/performing-database-operations-in-xampp/"
},
{
"code": null,
"e": 27667,
"s": 27634,
"text": "Finally, the food table contains"
},
{
"code": null,
"e": 27700,
"s": 27667,
"text": "PHP code to perform sum function"
},
{
"code": null,
"e": 27709,
"s": 27700,
"text": "form.php"
},
{
"code": null,
"e": 27789,
"s": 27709,
"text": "After writing code type βlocalhost/form.phpβ to view the output in the browser."
},
{
"code": null,
"e": 27793,
"s": 27789,
"text": "PHP"
},
{
"code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//geek is the database name$dbname = \"geek\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"<h1>\"; echo \"sum() aggregate Demo \"; echo\"</h1>\";echo \"<h2>\";echo \" Find the total cost of food items \";echo \"</h2>\";//sql query$sql = \"SELECT SUM(cost) from food\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" Total cost: \". $row['SUM(cost)']; echo \"<br>\";} echo \"<h2>\";echo \" Find the total weight of food items \";echo \"</h2>\";//sql query$sql = \"SELECT SUM(weight) from food\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" Total weight: \". $row['SUM(weight)']; echo \"<br>\";} //close the connection $conn->close();?></body></html>",
"e": 28745,
"s": 27793,
"text": null
},
{
"code": null,
"e": 28753,
"s": 28745,
"text": "Output:"
},
{
"code": null,
"e": 28789,
"s": 28753,
"text": "Example: sum() with group by clause"
},
{
"code": null,
"e": 28799,
"s": 28789,
"text": "form1.php"
},
{
"code": null,
"e": 28803,
"s": 28799,
"text": "PHP"
},
{
"code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//geek is the database name$dbname = \"geek\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"<h1>\"; echo \"sum() aggregate with group by Demo \"; echo\"</h1>\";echo \"<h2>\";echo \" \";echo \"</h2>\";//sql query$sql = \"SELECT food_item, SUM(cost) FROM food GROUP BY food_item\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \"Total \". $row['food_item']. \" = \". $row['SUM(cost)']; echo \"<br />\";}//close the connection $conn->close();?></body></html>",
"e": 29501,
"s": 28803,
"text": null
},
{
"code": null,
"e": 29509,
"s": 29501,
"text": "Output:"
},
{
"code": null,
"e": 29524,
"s": 29509,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29533,
"s": 29524,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 29537,
"s": 29533,
"text": "PHP"
},
{
"code": null,
"e": 29541,
"s": 29537,
"text": "PHP"
},
{
"code": null,
"e": 29639,
"s": 29541,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29721,
"s": 29639,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 29763,
"s": 29721,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 29790,
"s": 29763,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 29841,
"s": 29790,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 29905,
"s": 29841,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 29979,
"s": 29905,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 30017,
"s": 29979,
"text": "PHP | shell_exec() vs exec() Function"
},
{
"code": null,
"e": 30054,
"s": 30017,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 30077,
"s": 30054,
"text": "PHP | Ternary Operator"
}
] |
C# | Sort the elements in the ArrayList - GeeksforGeeks
|
09 Jul, 2021
ArrayList.Sort Method is used to sorts the elements in the ArrayList. There are total 3 methods in the overload list of this method as follows:
Sort()Sort(IComparer)Sort(Int32, Int32, IComparer)
Sort()
Sort(IComparer)
Sort(Int32, Int32, IComparer)
This method is used to Sort the elements in the entire ArrayList. It uses the QuickSort algorithm to sort the elements of the ArrayList.
Note: This method is an O(n log n) operation, where n is Count and in the worst case, it is an O(n^2) operation.
Syntax:
public virtual void Sort ();
Exception: This method will give NotSupportedException if the ArrayList is read-only.
Example:
C#
// C# program to illustrate Sort() Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // create and initialize new ArrayList ArrayList mylist = new ArrayList(); mylist.Add("Welcome"); mylist.Add("to"); mylist.Add("Geeks"); mylist.Add("for"); mylist.Add("Geeks"); mylist.Add("2"); // ArrayList before sorting Console.WriteLine("ArrayList before sort:"); foreach(string i in mylist) { Console.WriteLine(i); } Console.WriteLine(); Console.WriteLine("ArrayList after sort:"); // sort the ArrayList // using Sort() method mylist.Sort(); // ArrayList after sort foreach(string i in mylist) { Console.WriteLine(i); } }}
Output:
ArrayList before sort:
Welcome
to
Geeks
for
Geeks
2
ArrayList after sort:
2
for
Geeks
Geeks
to
Welcome
This method is used to sort the elements in the entire ArrayList using the specified comparer. This method is an O(n log n) operation, where n is Count; in the worst case, it is an O(n^2) operation.
Syntax:
public virtual void Sort (IComparer comparer);
Here, IComparer implementation is used when comparing the elements.
Exceptions:
NotSupportedException: If the ArrayList is read-only.
InvalidOperationException: Due to an error occurred while comparing two elements.
ArgumentException: If the null is passed for the comparer and the elements in the list do not implement IComparable.
Example:
C#
// C# program to illustrate Sort(IComparer) Methodusing System;using System.Collections; class GFG { // Calls CaseInsensitiveComparer.Compare // with the parameters reversed. public class myClass : IComparer { int IComparer.Compare(Object a, Object b) { return ((new CaseInsensitiveComparer()).Compare(b, a)); } } // Main method public static void Main() { // create and initialize new ArrayList, i.e. mylist ArrayList mylist = new ArrayList(); mylist.Add("Welcome"); mylist.Add("to"); mylist.Add("geeks"); mylist.Add("for"); mylist.Add("geeks"); mylist.Add("2"); IComparer Comp1 = new myClass(); // sort the value of ArrayList // using Sort(IComparer) method mylist.Sort(Comp1); foreach(Object ob in mylist) { Console.WriteLine(ob); } }}
Output:
Welcome
to
geeks
geeks
for
2
This method is used to sort the elements in a range of elements in ArrayList using the specified comparer. Note: This method is an O(n log n) operation, where n is count and in the worst case, it is an O(n^2) operation.
Syntax:
public virtual void Sort (int index, int count, IComparer comparer);
Parameters:
index: It the zero-based starting index of the range to sort and the type of this parameter is System.Int32.
count: It count the length of the range to sort and the type of this parameter is System.Int32.
comparer: It is the IComparer implementation which is used during the comparison of the elements.
Exceptions:
NotSupportedException: If the ArrayList is read-only.
InvalidOperationException: Due to an error occurred while comparing two elements.
ArgumentException: If the index and count do not specify a valid range in the ArrayList.
ArgumentOutOfRangeException: If the index is less than zero.
Example:
C#
// C# program to illustrate the use of// Sort(Int32, Int32, IComparer) Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // create and initialize new ArrayList ArrayList mylist = new ArrayList(); mylist.Add("Welcome"); mylist.Add("to"); mylist.Add("geeks"); mylist.Add("for"); mylist.Add("GFG"); mylist.Add("2"); // sort the value of ArrayList from 0 to 4 // using Sort( Int32, Int32, IComparer) method // here the value of IComparer is null mylist.Sort(0, 4, null); // Display the sorted string foreach(string ob in mylist) { Console.WriteLine(ob); } }}
Output:
for
geeks
to
Welcome
GFG
2
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.sort?view=netframework-4.7.2
Akanksha_Rai
simmytarika5
rajeev0719singh
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25573,
"s": 25545,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 25717,
"s": 25573,
"text": "ArrayList.Sort Method is used to sorts the elements in the ArrayList. There are total 3 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 25768,
"s": 25717,
"text": "Sort()Sort(IComparer)Sort(Int32, Int32, IComparer)"
},
{
"code": null,
"e": 25775,
"s": 25768,
"text": "Sort()"
},
{
"code": null,
"e": 25791,
"s": 25775,
"text": "Sort(IComparer)"
},
{
"code": null,
"e": 25821,
"s": 25791,
"text": "Sort(Int32, Int32, IComparer)"
},
{
"code": null,
"e": 25959,
"s": 25821,
"text": "This method is used to Sort the elements in the entire ArrayList. It uses the QuickSort algorithm to sort the elements of the ArrayList. "
},
{
"code": null,
"e": 26072,
"s": 25959,
"text": "Note: This method is an O(n log n) operation, where n is Count and in the worst case, it is an O(n^2) operation."
},
{
"code": null,
"e": 26082,
"s": 26072,
"text": "Syntax: "
},
{
"code": null,
"e": 26111,
"s": 26082,
"text": "public virtual void Sort ();"
},
{
"code": null,
"e": 26197,
"s": 26111,
"text": "Exception: This method will give NotSupportedException if the ArrayList is read-only."
},
{
"code": null,
"e": 26207,
"s": 26197,
"text": "Example: "
},
{
"code": null,
"e": 26210,
"s": 26207,
"text": "C#"
},
{
"code": "// C# program to illustrate Sort() Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // create and initialize new ArrayList ArrayList mylist = new ArrayList(); mylist.Add(\"Welcome\"); mylist.Add(\"to\"); mylist.Add(\"Geeks\"); mylist.Add(\"for\"); mylist.Add(\"Geeks\"); mylist.Add(\"2\"); // ArrayList before sorting Console.WriteLine(\"ArrayList before sort:\"); foreach(string i in mylist) { Console.WriteLine(i); } Console.WriteLine(); Console.WriteLine(\"ArrayList after sort:\"); // sort the ArrayList // using Sort() method mylist.Sort(); // ArrayList after sort foreach(string i in mylist) { Console.WriteLine(i); } }}",
"e": 27083,
"s": 26210,
"text": null
},
{
"code": null,
"e": 27092,
"s": 27083,
"text": "Output: "
},
{
"code": null,
"e": 27196,
"s": 27092,
"text": "ArrayList before sort:\nWelcome\nto\nGeeks\nfor\nGeeks\n2\n\nArrayList after sort:\n2\nfor\nGeeks\nGeeks\nto\nWelcome"
},
{
"code": null,
"e": 27395,
"s": 27196,
"text": "This method is used to sort the elements in the entire ArrayList using the specified comparer. This method is an O(n log n) operation, where n is Count; in the worst case, it is an O(n^2) operation."
},
{
"code": null,
"e": 27405,
"s": 27395,
"text": "Syntax: "
},
{
"code": null,
"e": 27452,
"s": 27405,
"text": "public virtual void Sort (IComparer comparer);"
},
{
"code": null,
"e": 27521,
"s": 27452,
"text": "Here, IComparer implementation is used when comparing the elements. "
},
{
"code": null,
"e": 27535,
"s": 27521,
"text": "Exceptions: "
},
{
"code": null,
"e": 27589,
"s": 27535,
"text": "NotSupportedException: If the ArrayList is read-only."
},
{
"code": null,
"e": 27671,
"s": 27589,
"text": "InvalidOperationException: Due to an error occurred while comparing two elements."
},
{
"code": null,
"e": 27788,
"s": 27671,
"text": "ArgumentException: If the null is passed for the comparer and the elements in the list do not implement IComparable."
},
{
"code": null,
"e": 27798,
"s": 27788,
"text": "Example: "
},
{
"code": null,
"e": 27801,
"s": 27798,
"text": "C#"
},
{
"code": "// C# program to illustrate Sort(IComparer) Methodusing System;using System.Collections; class GFG { // Calls CaseInsensitiveComparer.Compare // with the parameters reversed. public class myClass : IComparer { int IComparer.Compare(Object a, Object b) { return ((new CaseInsensitiveComparer()).Compare(b, a)); } } // Main method public static void Main() { // create and initialize new ArrayList, i.e. mylist ArrayList mylist = new ArrayList(); mylist.Add(\"Welcome\"); mylist.Add(\"to\"); mylist.Add(\"geeks\"); mylist.Add(\"for\"); mylist.Add(\"geeks\"); mylist.Add(\"2\"); IComparer Comp1 = new myClass(); // sort the value of ArrayList // using Sort(IComparer) method mylist.Sort(Comp1); foreach(Object ob in mylist) { Console.WriteLine(ob); } }}",
"e": 28735,
"s": 27801,
"text": null
},
{
"code": null,
"e": 28744,
"s": 28735,
"text": "Output: "
},
{
"code": null,
"e": 28773,
"s": 28744,
"text": "Welcome\nto\ngeeks\ngeeks\nfor\n2"
},
{
"code": null,
"e": 28993,
"s": 28773,
"text": "This method is used to sort the elements in a range of elements in ArrayList using the specified comparer. Note: This method is an O(n log n) operation, where n is count and in the worst case, it is an O(n^2) operation."
},
{
"code": null,
"e": 29003,
"s": 28993,
"text": "Syntax: "
},
{
"code": null,
"e": 29072,
"s": 29003,
"text": "public virtual void Sort (int index, int count, IComparer comparer);"
},
{
"code": null,
"e": 29086,
"s": 29072,
"text": "Parameters: "
},
{
"code": null,
"e": 29195,
"s": 29086,
"text": "index: It the zero-based starting index of the range to sort and the type of this parameter is System.Int32."
},
{
"code": null,
"e": 29291,
"s": 29195,
"text": "count: It count the length of the range to sort and the type of this parameter is System.Int32."
},
{
"code": null,
"e": 29389,
"s": 29291,
"text": "comparer: It is the IComparer implementation which is used during the comparison of the elements."
},
{
"code": null,
"e": 29402,
"s": 29389,
"text": "Exceptions: "
},
{
"code": null,
"e": 29456,
"s": 29402,
"text": "NotSupportedException: If the ArrayList is read-only."
},
{
"code": null,
"e": 29538,
"s": 29456,
"text": "InvalidOperationException: Due to an error occurred while comparing two elements."
},
{
"code": null,
"e": 29627,
"s": 29538,
"text": "ArgumentException: If the index and count do not specify a valid range in the ArrayList."
},
{
"code": null,
"e": 29688,
"s": 29627,
"text": "ArgumentOutOfRangeException: If the index is less than zero."
},
{
"code": null,
"e": 29698,
"s": 29688,
"text": "Example: "
},
{
"code": null,
"e": 29701,
"s": 29698,
"text": "C#"
},
{
"code": "// C# program to illustrate the use of// Sort(Int32, Int32, IComparer) Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // create and initialize new ArrayList ArrayList mylist = new ArrayList(); mylist.Add(\"Welcome\"); mylist.Add(\"to\"); mylist.Add(\"geeks\"); mylist.Add(\"for\"); mylist.Add(\"GFG\"); mylist.Add(\"2\"); // sort the value of ArrayList from 0 to 4 // using Sort( Int32, Int32, IComparer) method // here the value of IComparer is null mylist.Sort(0, 4, null); // Display the sorted string foreach(string ob in mylist) { Console.WriteLine(ob); } }}",
"e": 30453,
"s": 29701,
"text": null
},
{
"code": null,
"e": 30462,
"s": 30453,
"text": "Output: "
},
{
"code": null,
"e": 30489,
"s": 30462,
"text": "for\ngeeks\nto\nWelcome\nGFG\n2"
},
{
"code": null,
"e": 30502,
"s": 30489,
"text": "Reference: "
},
{
"code": null,
"e": 30604,
"s": 30502,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.sort?view=netframework-4.7.2"
},
{
"code": null,
"e": 30619,
"s": 30606,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30632,
"s": 30619,
"text": "simmytarika5"
},
{
"code": null,
"e": 30648,
"s": 30632,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 30677,
"s": 30648,
"text": "CSharp-Collections-ArrayList"
},
{
"code": null,
"e": 30706,
"s": 30677,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 30720,
"s": 30706,
"text": "CSharp-method"
},
{
"code": null,
"e": 30723,
"s": 30720,
"text": "C#"
},
{
"code": null,
"e": 30821,
"s": 30723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30844,
"s": 30821,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30872,
"s": 30844,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 30889,
"s": 30872,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 30911,
"s": 30889,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 30940,
"s": 30911,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 30980,
"s": 30940,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 31003,
"s": 30980,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 31043,
"s": 31003,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 31086,
"s": 31043,
"text": "C# | How to insert an element in an Array?"
}
] |
Flutter - Widget Tree and Element Tree - GeeksforGeeks
|
14 May, 2021
As we know, the user interface of an application when it is designed in Flutter contains a set of widgets. So that means the whole application is set to be made out of widgets. A widget describes what the view of the app would look like in the given state.
Now, as the user interface contains several widgets, those several widgets are combined to form a widget tree. Now, to each widget that the user creates, an element is created simultaneously by the flutter framework, so now these elements when combined will be called an element tree.
So that means that the widget tree has all the widget configuration and the element tree has all rendered widgets on the screen. There is one more tree named render tree, but the user doesnβt have to interact with it. Render tree is basically a low-level layout, painting system that inherits from the render objects. You wonβt need to inherit directly to the render tree, and you will be interacting with the widgets.
Now the widget tree can also be divided into 2 small trees depending on what widget the user has chosen for their code.
Stateless widget treeStateful widget tree
Stateless widget tree
Stateful widget tree
Stateless widget is the widget that is used by the user to create a non-dynamic application. A stateless widget is formed by a combination of several small widgets. Each widget that is created here will have a corresponding stateless element. So several widgets combined under stateless widgets will be called stateless widget trees and the corresponding elements will make an element tree. Flutter uses the createElement method to create the elements. Each element created will have a unique id assigned by the flutter back-end.
Following is the sample code:
Dart
class TextList extends StatelessWidget { @override Widget build(BuildContext context){ return Row( children: <Widget>[ Icon(), Text(), ], ); }}
Here in this code, we have created a simple class called TextList which extends the stateless widget, which contains several other widgets like row, icon, and text. For each widget in this widget tree, a stateless element is created and the combination of these elements makes it an element tree.
A stateful widget is a widget that is used by the user to create a dynamic application. The stateful widget also works similar to the stateless widget, but here when the framework calls the createElement method, a state object is created. The reason behind creating the state object is that as this has to be a dynamic application the states would change while keeping the previous state unharmed and enhancing the performance.
We make use of the setState method to set the new data values or to update the state objects.
setState ( ( ) {
name = _newvalue;
});
Following is the example code:-
Dart
class _TextListState extend State<TextList> { String note = 'Trip A'; void _onPressed() { setState( () { note = 'Trip B'; }); } @override Widget build (BuildContext xontext){ return Column( children : <Widget> [ Icon(); Text('$note), FlatButton( onPressed : _onPressed, ), ], ); }}
Here in this code, we have created _TextListState class that extends the state TextList. We have used the setState method because we have to keep the initial state in the element tree even after changing the state.
Flutter-widgets
Picked
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Positioned Widget
Format Dates in Flutter
Flutter - Managing the MediaQuery Object
Flutter - BorderRadius Widget
Flutter - Padding Widget
Flutter - Card Widget
Flutter - Google Sign in UI and Authentication
Flutter - Fetching Data From the Internet
TextSpan Widget in Flutter
Flutter - Expanded Widget
|
[
{
"code": null,
"e": 25383,
"s": 25355,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 25641,
"s": 25383,
"text": "As we know, the user interface of an application when it is designed in Flutter contains a set of widgets. So that means the whole application is set to be made out of widgets. A widget describes what the view of the app would look like in the given state. "
},
{
"code": null,
"e": 25927,
"s": 25641,
"text": "Now, as the user interface contains several widgets, those several widgets are combined to form a widget tree. Now, to each widget that the user creates, an element is created simultaneously by the flutter framework, so now these elements when combined will be called an element tree. "
},
{
"code": null,
"e": 26346,
"s": 25927,
"text": "So that means that the widget tree has all the widget configuration and the element tree has all rendered widgets on the screen. There is one more tree named render tree, but the user doesnβt have to interact with it. Render tree is basically a low-level layout, painting system that inherits from the render objects. You wonβt need to inherit directly to the render tree, and you will be interacting with the widgets."
},
{
"code": null,
"e": 26466,
"s": 26346,
"text": "Now the widget tree can also be divided into 2 small trees depending on what widget the user has chosen for their code."
},
{
"code": null,
"e": 26508,
"s": 26466,
"text": "Stateless widget treeStateful widget tree"
},
{
"code": null,
"e": 26530,
"s": 26508,
"text": "Stateless widget tree"
},
{
"code": null,
"e": 26551,
"s": 26530,
"text": "Stateful widget tree"
},
{
"code": null,
"e": 27081,
"s": 26551,
"text": "Stateless widget is the widget that is used by the user to create a non-dynamic application. A stateless widget is formed by a combination of several small widgets. Each widget that is created here will have a corresponding stateless element. So several widgets combined under stateless widgets will be called stateless widget trees and the corresponding elements will make an element tree. Flutter uses the createElement method to create the elements. Each element created will have a unique id assigned by the flutter back-end."
},
{
"code": null,
"e": 27111,
"s": 27081,
"text": "Following is the sample code:"
},
{
"code": null,
"e": 27116,
"s": 27111,
"text": "Dart"
},
{
"code": "class TextList extends StatelessWidget { @override Widget build(BuildContext context){ return Row( children: <Widget>[ Icon(), Text(), ], ); }}",
"e": 27293,
"s": 27116,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27293,
"text": "Here in this code, we have created a simple class called TextList which extends the stateless widget, which contains several other widgets like row, icon, and text. For each widget in this widget tree, a stateless element is created and the combination of these elements makes it an element tree."
},
{
"code": null,
"e": 28018,
"s": 27590,
"text": "A stateful widget is a widget that is used by the user to create a dynamic application. The stateful widget also works similar to the stateless widget, but here when the framework calls the createElement method, a state object is created. The reason behind creating the state object is that as this has to be a dynamic application the states would change while keeping the previous state unharmed and enhancing the performance."
},
{
"code": null,
"e": 28112,
"s": 28018,
"text": "We make use of the setState method to set the new data values or to update the state objects."
},
{
"code": null,
"e": 28154,
"s": 28112,
"text": "setState ( ( ) {\n name = _newvalue;\n});"
},
{
"code": null,
"e": 28186,
"s": 28154,
"text": "Following is the example code:-"
},
{
"code": null,
"e": 28191,
"s": 28186,
"text": "Dart"
},
{
"code": "class _TextListState extend State<TextList> { String note = 'Trip A'; void _onPressed() { setState( () { note = 'Trip B'; }); } @override Widget build (BuildContext xontext){ return Column( children : <Widget> [ Icon(); Text('$note), FlatButton( onPressed : _onPressed, ), ], ); }}",
"e": 28546,
"s": 28191,
"text": null
},
{
"code": null,
"e": 28762,
"s": 28546,
"text": "Here in this code, we have created _TextListState class that extends the state TextList. We have used the setState method because we have to keep the initial state in the element tree even after changing the state. "
},
{
"code": null,
"e": 28778,
"s": 28762,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 28785,
"s": 28778,
"text": "Picked"
},
{
"code": null,
"e": 28793,
"s": 28785,
"text": "Flutter"
},
{
"code": null,
"e": 28891,
"s": 28793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28919,
"s": 28891,
"text": "Flutter - Positioned Widget"
},
{
"code": null,
"e": 28943,
"s": 28919,
"text": "Format Dates in Flutter"
},
{
"code": null,
"e": 28984,
"s": 28943,
"text": "Flutter - Managing the MediaQuery Object"
},
{
"code": null,
"e": 29014,
"s": 28984,
"text": "Flutter - BorderRadius Widget"
},
{
"code": null,
"e": 29039,
"s": 29014,
"text": "Flutter - Padding Widget"
},
{
"code": null,
"e": 29061,
"s": 29039,
"text": "Flutter - Card Widget"
},
{
"code": null,
"e": 29108,
"s": 29061,
"text": "Flutter - Google Sign in UI and Authentication"
},
{
"code": null,
"e": 29150,
"s": 29108,
"text": "Flutter - Fetching Data From the Internet"
},
{
"code": null,
"e": 29177,
"s": 29150,
"text": "TextSpan Widget in Flutter"
}
] |
Efficiently compute sums of diagonals of a matrix - GeeksforGeeks
|
19 May, 2021
Given a 2D square matrix, find the sum of elements in Principal and Secondary diagonals. For example, consider the following 4 X 4 input matrix.
A00 A01 A02 A03
A10 A11 A12 A13
A20 A21 A22 A23
A30 A31 A32 A33
The primary diagonal is formed by the elements A00, A11, A22, A33.
Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30.Condition for Secondary Diagonal: The row-column condition is row = numberOfRows β column -1.
Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30.
Condition for Secondary Diagonal: The row-column condition is row = numberOfRows β column -1.
Examples :
Input :
4
1 2 3 4
4 3 2 1
7 8 9 6
6 5 4 3
Output :
Principal Diagonal: 16
Secondary Diagonal: 20
Input :
3
1 1 1
1 1 1
1 1 1
Output :
Principal Diagonal: 3
Secondary Diagonal: 3
Method 1 (O(n ^ 2) :
In this method, we use two loops i.e. a loop for columns and a loop for rows and in the inner loop we check for the condition stated above:
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to find sum of diagonals#include <bits/stdc++.h>using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n){ int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) principal += mat[i][j]; // Condition for secondary diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } cout << "Principal Diagonal:" << principal << endl; cout << "Secondary Diagonal:" << secondary << endl;} // Driver codeint main(){ int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0;}
// A simple java program to find// sum of diagonalsimport java.io.*; public class GFG { static void printDiagonalSums(int [][]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal // diagonal if (i == j) principal += mat[i][j]; // Condition for secondary // diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } System.out.println("Principal Diagonal:" + principal); System.out.println("Secondary Diagonal:" + secondary); } // Driver code static public void main (String[] args) { int [][]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.
# A simple Python program to# find sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0; for i in range(0, n): for j in range(0, n): # Condition for principal diagonal if (i == j): principal += mat[i][j] # Condition for secondary diagonal if ((i + j) == (n - 1)): secondary += mat[i][j] print("Principal Diagonal:", principal) print("Secondary Diagonal:", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik
// A simple C# program to find sum// of diagonalsusing System; public class GFG { static void printDiagonalSums(int [,]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal // diagonal if (i == j) principal += mat[i,j]; // Condition for secondary // diagonal if ((i + j) == (n - 1)) secondary += mat[i,j]; } } Console.WriteLine("Principal Diagonal:" + principal); Console.WriteLine("Secondary Diagonal:" + secondary); } // Driver code static public void Main () { int [,]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.
<?php// A simple PHP program to// find sum of diagonals$MAX = 100; function printDiagonalSums($mat, $n){ global $MAX; $principal = 0; $secondary = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // Condition for // principal diagonal if ($i == $j) $principal += $mat[$i][$j]; // Condition for // secondary diagonal if (($i + $j) == ($n - 1)) $secondary += $mat[$i][$j]; } } echo "Principal Diagonal:" , $principal ,"\n"; echo "Secondary Diagonal:", $secondary ,"\n";} // Driver code$a = array (array ( 1, 2, 3, 4 ), array ( 5, 6, 7, 8 ), array ( 1, 2, 3, 4 ), array ( 5, 6, 7, 8 ));printDiagonalSums($a, 4); // This code is contributed by ajit?>
<script>// A simple Javascript program to find sum of diagonals const MAX = 100; void printDiagonalSums(mat, n){ let principal = 0, secondary = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) principal += mat[i][j]; // Condition for secondary diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } document.write("Principal Diagonal:" + principal + "<br>"); document.write("Secondary Diagonal:" + secondary + "<br>");} // Driver code let a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]; printDiagonalSums(a, 4); // This code is contributed by subhammahato348.</script>
Output:
Principal Diagonal:18
Secondary Diagonal:18
This code takes O(n^2) time and O(1) auxiliary space
Method 2 (O(n) :
In this method we use one loop i.e. a loop for calculating sum of both the principal and secondary diagonals:
C++
Java
Python3
C#
PHP
Javascript
// An efficient C++ program to find sum of diagonals#include <bits/stdc++.h>using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n){ int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } cout << "Principal Diagonal:" << principal << endl; cout << "Secondary Diagonal:" << secondary << endl;} // Driver codeint main(){ int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0;}
// An efficient java program to find// sum of diagonalsimport java.io.*; public class GFG { static void printDiagonalSums(int [][]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } System.out.println("Principal Diagonal:" + principal); System.out.println("Secondary Diagonal:" + secondary); } // Driver code static public void main (String[] args) { int [][]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.
# A simple Python3 program to find# sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0 for i in range(0, n): principal += mat[i][i] secondary += mat[i][n - i - 1] print("Principal Diagonal:", principal) print("Secondary Diagonal:", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik
// An efficient C#program to find// sum of diagonalsusing System; public class GFG { static void printDiagonalSums(int [,]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i,i]; secondary += mat[i,n - i - 1]; } Console.WriteLine("Principal Diagonal:" + principal); Console.WriteLine("Secondary Diagonal:" + secondary); } // Driver code static public void Main () { int [,]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.
<?php// An efficient PHP program// to find sum of diagonals$MAX = 100; function printDiagonalSums($mat, $n){ global $MAX; $principal = 0; $secondary = 0; for ($i = 0; $i < $n; $i++) { $principal += $mat[$i][$i]; $secondary += $mat[$i][$n - $i - 1]; } echo "Principal Diagonal:" , $principal ,"\n"; echo "Secondary Diagonal:" , $secondary ,"\n";} // Driver Code$a = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(1, 2, 3, 4), array(5, 6, 7, 8));printDiagonalSums($a, 4); // This code is contributed by aj_36?>
<script> // An efficient Javascript program to find// sum of diagonals function printDiagonalSums(mat,n) { let principal = 0, secondary = 0; for (let i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } document.write("Principal Diagonal:" + principal+"<br>"); document.write("Secondary Diagonal:" + secondary); } // Driver code let a = [[ 1, 2, 3, 4 ], [5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]; printDiagonalSums(a, 4); // This code is contributed Bobby </script>
Output :
Principal Diagonal:18
Secondary Diagonal:18
This code takes O(n) time and O(1) auxiliary spaceThis article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
ihritik
subham348
gottumukkalabobby
surinderdawra388
CBSE - Class 11
school-programming
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
Min Cost Path | DP-6
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Python program to multiply two matrices
The Celebrity Problem
Search in a row wise and column wise sorted matrix
Real-time application of Data Structures
|
[
{
"code": null,
"e": 26262,
"s": 26234,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 26408,
"s": 26262,
"text": "Given a 2D square matrix, find the sum of elements in Principal and Secondary diagonals. For example, consider the following 4 X 4 input matrix. "
},
{
"code": null,
"e": 26472,
"s": 26408,
"text": "A00 A01 A02 A03\nA10 A11 A12 A13\nA20 A21 A22 A23\nA30 A31 A32 A33"
},
{
"code": null,
"e": 26541,
"s": 26472,
"text": "The primary diagonal is formed by the elements A00, A11, A22, A33. "
},
{
"code": null,
"e": 26779,
"s": 26541,
"text": "Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30.Condition for Secondary Diagonal: The row-column condition is row = numberOfRows β column -1."
},
{
"code": null,
"e": 26924,
"s": 26779,
"text": "Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30."
},
{
"code": null,
"e": 27018,
"s": 26924,
"text": "Condition for Secondary Diagonal: The row-column condition is row = numberOfRows β column -1."
},
{
"code": null,
"e": 27031,
"s": 27018,
"text": "Examples : "
},
{
"code": null,
"e": 27211,
"s": 27031,
"text": "Input : \n4\n1 2 3 4\n4 3 2 1\n7 8 9 6\n6 5 4 3\nOutput :\nPrincipal Diagonal: 16\nSecondary Diagonal: 20\n\nInput :\n3\n1 1 1\n1 1 1\n1 1 1\nOutput :\nPrincipal Diagonal: 3\nSecondary Diagonal: 3"
},
{
"code": null,
"e": 27236,
"s": 27215,
"text": "Method 1 (O(n ^ 2) :"
},
{
"code": null,
"e": 27377,
"s": 27236,
"text": "In this method, we use two loops i.e. a loop for columns and a loop for rows and in the inner loop we check for the condition stated above: "
},
{
"code": null,
"e": 27381,
"s": 27377,
"text": "C++"
},
{
"code": null,
"e": 27386,
"s": 27381,
"text": "Java"
},
{
"code": null,
"e": 27394,
"s": 27386,
"text": "Python3"
},
{
"code": null,
"e": 27397,
"s": 27394,
"text": "C#"
},
{
"code": null,
"e": 27401,
"s": 27397,
"text": "PHP"
},
{
"code": null,
"e": 27412,
"s": 27401,
"text": "Javascript"
},
{
"code": "// A simple C++ program to find sum of diagonals#include <bits/stdc++.h>using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n){ int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) principal += mat[i][j]; // Condition for secondary diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } cout << \"Principal Diagonal:\" << principal << endl; cout << \"Secondary Diagonal:\" << secondary << endl;} // Driver codeint main(){ int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0;}",
"e": 28211,
"s": 27412,
"text": null
},
{
"code": "// A simple java program to find// sum of diagonalsimport java.io.*; public class GFG { static void printDiagonalSums(int [][]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal // diagonal if (i == j) principal += mat[i][j]; // Condition for secondary // diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } System.out.println(\"Principal Diagonal:\" + principal); System.out.println(\"Secondary Diagonal:\" + secondary); } // Driver code static public void main (String[] args) { int [][]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.",
"e": 29402,
"s": 28211,
"text": null
},
{
"code": "# A simple Python program to# find sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0; for i in range(0, n): for j in range(0, n): # Condition for principal diagonal if (i == j): principal += mat[i][j] # Condition for secondary diagonal if ((i + j) == (n - 1)): secondary += mat[i][j] print(\"Principal Diagonal:\", principal) print(\"Secondary Diagonal:\", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik",
"e": 30066,
"s": 29402,
"text": null
},
{
"code": "// A simple C# program to find sum// of diagonalsusing System; public class GFG { static void printDiagonalSums(int [,]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal // diagonal if (i == j) principal += mat[i,j]; // Condition for secondary // diagonal if ((i + j) == (n - 1)) secondary += mat[i,j]; } } Console.WriteLine(\"Principal Diagonal:\" + principal); Console.WriteLine(\"Secondary Diagonal:\" + secondary); } // Driver code static public void Main () { int [,]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.",
"e": 31214,
"s": 30066,
"text": null
},
{
"code": "<?php// A simple PHP program to// find sum of diagonals$MAX = 100; function printDiagonalSums($mat, $n){ global $MAX; $principal = 0; $secondary = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // Condition for // principal diagonal if ($i == $j) $principal += $mat[$i][$j]; // Condition for // secondary diagonal if (($i + $j) == ($n - 1)) $secondary += $mat[$i][$j]; } } echo \"Principal Diagonal:\" , $principal ,\"\\n\"; echo \"Secondary Diagonal:\", $secondary ,\"\\n\";} // Driver code$a = array (array ( 1, 2, 3, 4 ), array ( 5, 6, 7, 8 ), array ( 1, 2, 3, 4 ), array ( 5, 6, 7, 8 ));printDiagonalSums($a, 4); // This code is contributed by ajit?>",
"e": 32079,
"s": 31214,
"text": null
},
{
"code": "<script>// A simple Javascript program to find sum of diagonals const MAX = 100; void printDiagonalSums(mat, n){ let principal = 0, secondary = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) principal += mat[i][j]; // Condition for secondary diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } document.write(\"Principal Diagonal:\" + principal + \"<br>\"); document.write(\"Secondary Diagonal:\" + secondary + \"<br>\");} // Driver code let a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]; printDiagonalSums(a, 4); // This code is contributed by subhammahato348.</script>",
"e": 32871,
"s": 32079,
"text": null
},
{
"code": null,
"e": 32881,
"s": 32871,
"text": "Output: "
},
{
"code": null,
"e": 32925,
"s": 32881,
"text": "Principal Diagonal:18\nSecondary Diagonal:18"
},
{
"code": null,
"e": 32979,
"s": 32925,
"text": "This code takes O(n^2) time and O(1) auxiliary space "
},
{
"code": null,
"e": 32996,
"s": 32979,
"text": "Method 2 (O(n) :"
},
{
"code": null,
"e": 33108,
"s": 32996,
"text": "In this method we use one loop i.e. a loop for calculating sum of both the principal and secondary diagonals: "
},
{
"code": null,
"e": 33112,
"s": 33108,
"text": "C++"
},
{
"code": null,
"e": 33117,
"s": 33112,
"text": "Java"
},
{
"code": null,
"e": 33125,
"s": 33117,
"text": "Python3"
},
{
"code": null,
"e": 33128,
"s": 33125,
"text": "C#"
},
{
"code": null,
"e": 33132,
"s": 33128,
"text": "PHP"
},
{
"code": null,
"e": 33143,
"s": 33132,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to find sum of diagonals#include <bits/stdc++.h>using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n){ int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } cout << \"Principal Diagonal:\" << principal << endl; cout << \"Secondary Diagonal:\" << secondary << endl;} // Driver codeint main(){ int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0;}",
"e": 33746,
"s": 33143,
"text": null
},
{
"code": "// An efficient java program to find// sum of diagonalsimport java.io.*; public class GFG { static void printDiagonalSums(int [][]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } System.out.println(\"Principal Diagonal:\" + principal); System.out.println(\"Secondary Diagonal:\" + secondary); } // Driver code static public void main (String[] args) { int [][]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.",
"e": 34640,
"s": 33746,
"text": null
},
{
"code": "# A simple Python3 program to find# sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0 for i in range(0, n): principal += mat[i][i] secondary += mat[i][n - i - 1] print(\"Principal Diagonal:\", principal) print(\"Secondary Diagonal:\", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik",
"e": 35112,
"s": 34640,
"text": null
},
{
"code": "// An efficient C#program to find// sum of diagonalsusing System; public class GFG { static void printDiagonalSums(int [,]mat, int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i,i]; secondary += mat[i,n - i - 1]; } Console.WriteLine(\"Principal Diagonal:\" + principal); Console.WriteLine(\"Secondary Diagonal:\" + secondary); } // Driver code static public void Main () { int [,]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); }} // This code is contributed by vt_m.",
"e": 35990,
"s": 35112,
"text": null
},
{
"code": "<?php// An efficient PHP program// to find sum of diagonals$MAX = 100; function printDiagonalSums($mat, $n){ global $MAX; $principal = 0; $secondary = 0; for ($i = 0; $i < $n; $i++) { $principal += $mat[$i][$i]; $secondary += $mat[$i][$n - $i - 1]; } echo \"Principal Diagonal:\" , $principal ,\"\\n\"; echo \"Secondary Diagonal:\" , $secondary ,\"\\n\";} // Driver Code$a = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(1, 2, 3, 4), array(5, 6, 7, 8));printDiagonalSums($a, 4); // This code is contributed by aj_36?>",
"e": 36600,
"s": 35990,
"text": null
},
{
"code": "<script> // An efficient Javascript program to find// sum of diagonals function printDiagonalSums(mat,n) { let principal = 0, secondary = 0; for (let i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } document.write(\"Principal Diagonal:\" + principal+\"<br>\"); document.write(\"Secondary Diagonal:\" + secondary); } // Driver code let a = [[ 1, 2, 3, 4 ], [5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]; printDiagonalSums(a, 4); // This code is contributed Bobby </script>",
"e": 37363,
"s": 36600,
"text": null
},
{
"code": null,
"e": 37374,
"s": 37363,
"text": "Output : "
},
{
"code": null,
"e": 37418,
"s": 37374,
"text": "Principal Diagonal:18\nSecondary Diagonal:18"
},
{
"code": null,
"e": 37889,
"s": 37418,
"text": "This code takes O(n) time and O(1) auxiliary spaceThis article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37894,
"s": 37889,
"text": "vt_m"
},
{
"code": null,
"e": 37900,
"s": 37894,
"text": "jit_t"
},
{
"code": null,
"e": 37908,
"s": 37900,
"text": "ihritik"
},
{
"code": null,
"e": 37918,
"s": 37908,
"text": "subham348"
},
{
"code": null,
"e": 37936,
"s": 37918,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 37953,
"s": 37936,
"text": "surinderdawra388"
},
{
"code": null,
"e": 37969,
"s": 37953,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 37988,
"s": 37969,
"text": "school-programming"
},
{
"code": null,
"e": 37995,
"s": 37988,
"text": "Matrix"
},
{
"code": null,
"e": 38002,
"s": 37995,
"text": "Matrix"
},
{
"code": null,
"e": 38100,
"s": 38002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38124,
"s": 38100,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 38186,
"s": 38124,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 38219,
"s": 38186,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 38270,
"s": 38219,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 38291,
"s": 38270,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 38373,
"s": 38291,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 38413,
"s": 38373,
"text": "Python program to multiply two matrices"
},
{
"code": null,
"e": 38435,
"s": 38413,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 38486,
"s": 38435,
"text": "Search in a row wise and column wise sorted matrix"
}
] |
Python - Convert Coordinate Dictionary to Matrix - GeeksforGeeks
|
30 Dec, 2020
Sometimes, while working with Python Matrix, we can have problem in which we have dictionary records with key as matrix position and its value, and we wish to convert that to actual Matrix. This can have applications in many domains including competitive programming and day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + max() + list comprehensionThe combination of above methods can be used to solve this problem. In this, we use max() to get the dimensions of matrix, list comprehension to create matrix and loop to assign values.
# Python3 code to demonstrate working of # Convert Coordinate Dictionary to Matrix# Using loop + max() + list comprehension # initializing dictionarytest_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Coordinate Dictionary to Matrix# Using loop + max() + list comprehensiontemp_x = max([cord[0] for cord in test_dict.keys()])temp_y = max([cord[1] for cord in test_dict.keys()])res = [[0] * (temp_y + 1) for ele in range(temp_x + 1)] for (i, j), val in test_dict.items(): res[i][j] = val # printing result print("The dictionary after creation of Matrix : " + str(res))
The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]
Method #2 : Using list comprehensionThis is yet another way in which this task can be performed. This performs task similar to above function, just the difference is that it is shorthand to above method.
# Python3 code to demonstrate working of # Convert Coordinate Dictionary to Matrix# Using list comprehension # initializing dictionarytest_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Coordinate Dictionary to Matrix# Using list comprehensiontemp_x, temp_y = map(max, zip(*test_dict))res = [[test_dict.get((j, i), 0) for i in range(temp_y + 1)] for j in range(temp_x + 1)] # printing result print("The dictionary after creation of Matrix : " + str(res))
The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]
Python dictionary-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative)
Python | Convert a list into a tuple
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 25892,
"s": 25537,
"text": "Sometimes, while working with Python Matrix, we can have problem in which we have dictionary records with key as matrix position and its value, and we wish to convert that to actual Matrix. This can have applications in many domains including competitive programming and day-day programming. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26129,
"s": 25892,
"text": "Method #1 : Using loop + max() + list comprehensionThe combination of above methods can be used to solve this problem. In this, we use max() to get the dimensions of matrix, list comprehension to create matrix and loop to assign values."
},
{
"code": "# Python3 code to demonstrate working of # Convert Coordinate Dictionary to Matrix# Using loop + max() + list comprehension # initializing dictionarytest_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Coordinate Dictionary to Matrix# Using loop + max() + list comprehensiontemp_x = max([cord[0] for cord in test_dict.keys()])temp_y = max([cord[1] for cord in test_dict.keys()])res = [[0] * (temp_y + 1) for ele in range(temp_x + 1)] for (i, j), val in test_dict.items(): res[i][j] = val # printing result print(\"The dictionary after creation of Matrix : \" + str(res)) ",
"e": 26826,
"s": 26129,
"text": null
},
{
"code": null,
"e": 27001,
"s": 26826,
"text": "The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]"
},
{
"code": null,
"e": 27207,
"s": 27003,
"text": "Method #2 : Using list comprehensionThis is yet another way in which this task can be performed. This performs task similar to above function, just the difference is that it is shorthand to above method."
},
{
"code": "# Python3 code to demonstrate working of # Convert Coordinate Dictionary to Matrix# Using list comprehension # initializing dictionarytest_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Coordinate Dictionary to Matrix# Using list comprehensiontemp_x, temp_y = map(max, zip(*test_dict))res = [[test_dict.get((j, i), 0) for i in range(temp_y + 1)] for j in range(temp_x + 1)] # printing result print(\"The dictionary after creation of Matrix : \" + str(res)) ",
"e": 27821,
"s": 27207,
"text": null
},
{
"code": null,
"e": 27996,
"s": 27821,
"text": "The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]"
},
{
"code": null,
"e": 28023,
"s": 27996,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 28045,
"s": 28023,
"text": "Python matrix-program"
},
{
"code": null,
"e": 28052,
"s": 28045,
"text": "Python"
},
{
"code": null,
"e": 28068,
"s": 28052,
"text": "Python Programs"
},
{
"code": null,
"e": 28166,
"s": 28068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28188,
"s": 28166,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28220,
"s": 28188,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28236,
"s": 28220,
"text": "Deque in Python"
},
{
"code": null,
"e": 28259,
"s": 28236,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 28301,
"s": 28259,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28323,
"s": 28301,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28362,
"s": 28323,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28408,
"s": 28362,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28467,
"s": 28408,
"text": "Python Program for Binary Search (Recursive and Iterative)"
}
] |
Python | os.wait() method - GeeksforGeeks
|
26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonβs standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.wait() method in Python is used by a process to wait for completion of a child process.This method returns a tuple containing its PID and exit status indication. The exit status of child process is indicated by a 16 bit number whose lower byte is the signal number that killed the process and higher byte is the exit status (if the signal number is zero).
Syntax: os.wait()
Parameter: No parameter is required.
Return type: This method returns a tuple which contains terminated childβs PID and exit status indication.
Code: Use of os.wait() method
# Python program to explain os.wait() method # importing os module import os # Create a child process# using os.fork() method pid = os.fork() # a Non-zero process id (pid)# indicates the parent process if pid : # Wait for the completion of # child process using # os.wait() method status = os.wait() print("\nIn parent process-") print("Terminated child's process id:", status[0]) print("Signal number that killed the child process:", status[1]) else : print("In Child process-") print("Process ID:", os.getpid()) print("Hello ! Geeks") print("Exiting") # using os.wait() method # Parent process will wait till # the completion of child process# and then only it will # begin its execution
In Child process-
Process ID: 6276
Hello! Geeks
Exiting
In parent process-
Terminated child's process id: 6276
Signal number that killed the child process: 0
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 25756,
"s": 25537,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Pythonβs standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 26115,
"s": 25756,
"text": "os.wait() method in Python is used by a process to wait for completion of a child process.This method returns a tuple containing its PID and exit status indication. The exit status of child process is indicated by a 16 bit number whose lower byte is the signal number that killed the process and higher byte is the exit status (if the signal number is zero)."
},
{
"code": null,
"e": 26133,
"s": 26115,
"text": "Syntax: os.wait()"
},
{
"code": null,
"e": 26170,
"s": 26133,
"text": "Parameter: No parameter is required."
},
{
"code": null,
"e": 26277,
"s": 26170,
"text": "Return type: This method returns a tuple which contains terminated childβs PID and exit status indication."
},
{
"code": null,
"e": 26307,
"s": 26277,
"text": "Code: Use of os.wait() method"
},
{
"code": "# Python program to explain os.wait() method # importing os module import os # Create a child process# using os.fork() method pid = os.fork() # a Non-zero process id (pid)# indicates the parent process if pid : # Wait for the completion of # child process using # os.wait() method status = os.wait() print(\"\\nIn parent process-\") print(\"Terminated child's process id:\", status[0]) print(\"Signal number that killed the child process:\", status[1]) else : print(\"In Child process-\") print(\"Process ID:\", os.getpid()) print(\"Hello ! Geeks\") print(\"Exiting\") # using os.wait() method # Parent process will wait till # the completion of child process# and then only it will # begin its execution",
"e": 27059,
"s": 26307,
"text": null
},
{
"code": null,
"e": 27219,
"s": 27059,
"text": "In Child process-\nProcess ID: 6276\nHello! Geeks\nExiting\n\nIn parent process-\nTerminated child's process id: 6276\nSignal number that killed the child process: 0\n"
},
{
"code": null,
"e": 27236,
"s": 27219,
"text": "python-os-module"
},
{
"code": null,
"e": 27243,
"s": 27236,
"text": "Python"
},
{
"code": null,
"e": 27341,
"s": 27243,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27373,
"s": 27341,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27415,
"s": 27373,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27457,
"s": 27415,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27484,
"s": 27457,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27540,
"s": 27484,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27562,
"s": 27540,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27601,
"s": 27562,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27632,
"s": 27601,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27661,
"s": 27632,
"text": "Create a directory in Python"
}
] |
Datasets And Dataloaders in Pytorch - GeeksforGeeks
|
18 Jul, 2021
PyTorch is a Python library developed by Facebook to run and train machine learning and deep learning models. Training a deep learning model requires us to convert the data into the format that can be processed by the model. PyTorch provides the torch.utils.data library to make data loading easy with DataSets and Dataloader class.
Dataset is itself the argument of DataLoader constructor which indicates a dataset object to load from. There are two types of datasets:
map-style datasets: This data set provides two functions __getitem__( ), __len__( ) that returns the indices of the sample data referred to and the numbers of samples respectively. In the example, we will use this type of dataset.
iterable-style datasets: Datasets that can be represented in a set of iterable data samples, for this we use __iter__( )function.
Dataloader on the other hand, not only allows us to iterate through the dataset in batches but also gives us access to inbuilt functions for multiprocessing(allows us to load multiple batches of data in parallel, rather than loading one batch at a time), shuffling, etc.
Syntax:
DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, *, prefetch_factor=2, persistent_workers=False)
Dataset Used: heart
Let us deal with an example so that the concept becomes clearer.
First import all required libraries and the dataset to work with. Load dataset in torch tensors which are accessed through __getitem__( ) protocol, to get the index of the particular dataset. Then we unpack the data and print corresponding features and labels.
Example:
Python3
# importing librariesimport torchimport torchvisionfrom torch.utils.data import Dataset, DataLoaderimport numpy as npimport math # class to represent datasetclass HeartDataSet(): def __init__(self): # loading the csv file from the folder path data1 = np.loadtxt('heart.csv', delimiter=',', dtype=np.float32, skiprows=1) # here the 13th column is class label and rest # are features self.x = torch.from_numpy(data1[:, :13]) self.y = torch.from_numpy(data1[:, [13]]) self.n_samples = data1.shape[0] # support indexing such that dataset[i] can # be used to get i-th sample def __getitem__(self, index): return self.x[index], self.y[index] # we can call len(dataset) to return the size def __len__(self): return self.n_samples dataset = HeartDataSet() # get the first sample and unpackfirst_data = dataset[0]features, labels = first_dataprint(features, labels)
Output:
tensor([ 63.0000, 1.0000, 3.0000, 145.0000, 233.0000, 1.0000, 0.0000,
150.0000, 0.0000, 2.3000, 0.0000, 0.0000, 1.0000]) tensor([1.])
The torch dataLoader takes this dataset as input, along with other arguments for batch_size, shuffle, etc, calculate nums_samples per batch, then print out the targets and labels in batches.
Example:
Python3
# Loading whole dataset with DataLoader# shuffle the data, which is good for trainingdataloader = DataLoader(dataset=dataset, batch_size=4, shuffle=True) # total samples of data and number of iterations performedtotal_samples = len(dataset)n_iterations = total_samples//4print(total_samples, n_iterations)for i, (targets, labels) in enumerate(dataloader): print(targets, labels)
Output:
We now train the data by first looping over the epoch and then over samples after that printing out the number of epochs, input tensor and label tensor with each iteration.
Example:
Python3
num_epochs = 2 for epoch in range(num_epochs): for i, (inputs, labels) in enumerate(dataloader): # here: 303 samples, batch_size = 4, n_iters=303/4=75 iterations # Run our training process if (i+1) % 5 == 0: print(f'Epoch: {epoch+1}/{num_epochs}, Step {i+1}/{n_iterations}|\ Inputs {inputs.shape} | Labels {labels.shape}')
Output:
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 25871,
"s": 25537,
"text": "PyTorch is a Python library developed by Facebook to run and train machine learning and deep learning models. Training a deep learning model requires us to convert the data into the format that can be processed by the model. PyTorch provides the torch.utils.data library to make data loading easy with DataSets and Dataloader class."
},
{
"code": null,
"e": 26008,
"s": 25871,
"text": "Dataset is itself the argument of DataLoader constructor which indicates a dataset object to load from. There are two types of datasets:"
},
{
"code": null,
"e": 26240,
"s": 26008,
"text": "map-style datasets: This data set provides two functions __getitem__( ), __len__( ) that returns the indices of the sample data referred to and the numbers of samples respectively. In the example, we will use this type of dataset."
},
{
"code": null,
"e": 26370,
"s": 26240,
"text": "iterable-style datasets: Datasets that can be represented in a set of iterable data samples, for this we use __iter__( )function."
},
{
"code": null,
"e": 26641,
"s": 26370,
"text": "Dataloader on the other hand, not only allows us to iterate through the dataset in batches but also gives us access to inbuilt functions for multiprocessing(allows us to load multiple batches of data in parallel, rather than loading one batch at a time), shuffling, etc."
},
{
"code": null,
"e": 26649,
"s": 26641,
"text": "Syntax:"
},
{
"code": null,
"e": 26879,
"s": 26649,
"text": "DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, *, prefetch_factor=2, persistent_workers=False)"
},
{
"code": null,
"e": 26899,
"s": 26879,
"text": "Dataset Used: heart"
},
{
"code": null,
"e": 26965,
"s": 26899,
"text": "Let us deal with an example so that the concept becomes clearer. "
},
{
"code": null,
"e": 27226,
"s": 26965,
"text": "First import all required libraries and the dataset to work with. Load dataset in torch tensors which are accessed through __getitem__( ) protocol, to get the index of the particular dataset. Then we unpack the data and print corresponding features and labels."
},
{
"code": null,
"e": 27237,
"s": 27226,
"text": " Example: "
},
{
"code": null,
"e": 27245,
"s": 27237,
"text": "Python3"
},
{
"code": "# importing librariesimport torchimport torchvisionfrom torch.utils.data import Dataset, DataLoaderimport numpy as npimport math # class to represent datasetclass HeartDataSet(): def __init__(self): # loading the csv file from the folder path data1 = np.loadtxt('heart.csv', delimiter=',', dtype=np.float32, skiprows=1) # here the 13th column is class label and rest # are features self.x = torch.from_numpy(data1[:, :13]) self.y = torch.from_numpy(data1[:, [13]]) self.n_samples = data1.shape[0] # support indexing such that dataset[i] can # be used to get i-th sample def __getitem__(self, index): return self.x[index], self.y[index] # we can call len(dataset) to return the size def __len__(self): return self.n_samples dataset = HeartDataSet() # get the first sample and unpackfirst_data = dataset[0]features, labels = first_dataprint(features, labels)",
"e": 28251,
"s": 27245,
"text": null
},
{
"code": null,
"e": 28259,
"s": 28251,
"text": "Output:"
},
{
"code": null,
"e": 28337,
"s": 28259,
"text": "tensor([ 63.0000, 1.0000, 3.0000, 145.0000, 233.0000, 1.0000, 0.0000,"
},
{
"code": null,
"e": 28419,
"s": 28337,
"text": " 150.0000, 0.0000, 2.3000, 0.0000, 0.0000, 1.0000]) tensor([1.])"
},
{
"code": null,
"e": 28610,
"s": 28419,
"text": "The torch dataLoader takes this dataset as input, along with other arguments for batch_size, shuffle, etc, calculate nums_samples per batch, then print out the targets and labels in batches."
},
{
"code": null,
"e": 28619,
"s": 28610,
"text": "Example:"
},
{
"code": null,
"e": 28627,
"s": 28619,
"text": "Python3"
},
{
"code": "# Loading whole dataset with DataLoader# shuffle the data, which is good for trainingdataloader = DataLoader(dataset=dataset, batch_size=4, shuffle=True) # total samples of data and number of iterations performedtotal_samples = len(dataset)n_iterations = total_samples//4print(total_samples, n_iterations)for i, (targets, labels) in enumerate(dataloader): print(targets, labels)",
"e": 29010,
"s": 28627,
"text": null
},
{
"code": null,
"e": 29018,
"s": 29010,
"text": "Output:"
},
{
"code": null,
"e": 29191,
"s": 29018,
"text": "We now train the data by first looping over the epoch and then over samples after that printing out the number of epochs, input tensor and label tensor with each iteration."
},
{
"code": null,
"e": 29200,
"s": 29191,
"text": "Example:"
},
{
"code": null,
"e": 29208,
"s": 29200,
"text": "Python3"
},
{
"code": "num_epochs = 2 for epoch in range(num_epochs): for i, (inputs, labels) in enumerate(dataloader): # here: 303 samples, batch_size = 4, n_iters=303/4=75 iterations # Run our training process if (i+1) % 5 == 0: print(f'Epoch: {epoch+1}/{num_epochs}, Step {i+1}/{n_iterations}|\\ Inputs {inputs.shape} | Labels {labels.shape}')",
"e": 29584,
"s": 29208,
"text": null
},
{
"code": null,
"e": 29592,
"s": 29584,
"text": "Output:"
},
{
"code": null,
"e": 29599,
"s": 29592,
"text": "Picked"
},
{
"code": null,
"e": 29614,
"s": 29599,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 29621,
"s": 29614,
"text": "Python"
},
{
"code": null,
"e": 29719,
"s": 29621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29751,
"s": 29719,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29793,
"s": 29751,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29835,
"s": 29793,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29862,
"s": 29835,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29918,
"s": 29862,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29940,
"s": 29918,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29979,
"s": 29940,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30010,
"s": 29979,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30039,
"s": 30010,
"text": "Create a directory in Python"
}
] |
SQLite Datatypes and its Corresponding Python Types - GeeksforGeeks
|
21 Apr, 2021
SQLite is a C-language-based library that provides a portable and serverless SQL database engine. It has a file-based architecture; hence it reads and writes to a disk. Since SQLite is a zero-configuration database, no installation or setup is needed before its usage. Starting from Python 2.5.x, SQLite3 comes default with python.
In this article, we will discuss SQLite DataTypes and their corresponding Python Types
A storage class can be called a collection of similar DataTypes. SQLite provides the following storage classes:
Storage Class
Value Stored
NULL
NULL
INTEGER
Signed Integer (1, 2, 3, 4, 5, or 8 bytes depending on magnitude)
REAL
Floating point value (8 byte IEEE floating-point numbers)
TEXT
TEXT string (encoded in UTF-8, UTF-16BE or UTF-16LE
BLOB (Binary Large Object)
Data stored exactly the way it was input, generally in binary format
The term Storage Class can be used mutually with DataType.
The SQLite DataTypes and their corresponding Python types are as follows
Storage Class
Python Datatype
NULL
None
INTEGER
int
REAL
float
TEXT
str
BLOB
bytes
The type() function can be used in python to get the class of an argument. In the program below, the type() function is used to print the classes of every value we store in a database.
Note: The program below uses the GeeksforGeeks logo as logo.png from this page for a demonstration.
Letβs take an example in which we are creating a database with the name βgfgβ and then create a table named exam_hall having some columns which are as follows:
NAME (TEXT),PIN (INTEGER),OCCUPANCY (REAL),LOGO (BLOB).
NAME (TEXT),
PIN (INTEGER),
OCCUPANCY (REAL),
LOGO (BLOB).
Then we insert some rows in it and check the data types of the values fetched with the help of SQL queries in Python.
Python3
# Python3 program to demonstrate SQLite3 datatypes# and corresponding Python3 types # import the sqlite3 packageimport sqlite3 # create connection to databasecnt = sqlite3.connect('gfg.db') # Create a exam_hall relationcnt.execute('''CREATE TABLE exam_hall(NAME TEXT,PIN INTEGER,OCCUPANCY REAL,LOGO BLOB);''') # Open the logo file in read, binary mode# read the image as binary data into a variablefileh = open('/content/JSBinCollaborativeJavaScriptDebugging6-300x160.png', 'rb')img = fileh.read() # Insert tuples for the relationcnt.execute('''INSERT INTO exam_hall VALUES('centre-a',1125,98.6,?)''', (img,))cnt.execute('''INSERT INTO exam_hall VALUES(NULL,1158,80.5,?)''', (img,)) # Query the data, print the data and its type# note: Printing the image binary data is impractical due to its huge size# instead number of bytes are being printed using len()cursor = cnt.execute('''SELECT * FROM exam_hall;''')for i in cursor: print(str(i[0])+" "+str(i[1])+" "+str(i[2])+" "+str(len(i[3]))) print(str(type(i[0]))+" "+str(type(i[1]))+" " + str(type(i[2]))+" "+str(type(i[3]))+"\n")
Output:
From the output of this program, the following observations can be made:
βcentre-aβ that was inserted as TEXT has been interpreted by python as str1125, 1158 that were inserted as INTEGER have been interpreted by python as int98.6, 80.5 that were inserted as REAL have been interpreted by python as floatNULL was interpreted by python as NoneTypeThe logo image which was inserted in binary format as BLOB has been interpreted by python as bytes.
βcentre-aβ that was inserted as TEXT has been interpreted by python as str
1125, 1158 that were inserted as INTEGER have been interpreted by python as int
98.6, 80.5 that were inserted as REAL have been interpreted by python as float
NULL was interpreted by python as NoneType
The logo image which was inserted in binary format as BLOB has been interpreted by python as bytes.
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25869,
"s": 25537,
"text": "SQLite is a C-language-based library that provides a portable and serverless SQL database engine. It has a file-based architecture; hence it reads and writes to a disk. Since SQLite is a zero-configuration database, no installation or setup is needed before its usage. Starting from Python 2.5.x, SQLite3 comes default with python."
},
{
"code": null,
"e": 25956,
"s": 25869,
"text": "In this article, we will discuss SQLite DataTypes and their corresponding Python Types"
},
{
"code": null,
"e": 26068,
"s": 25956,
"text": "A storage class can be called a collection of similar DataTypes. SQLite provides the following storage classes:"
},
{
"code": null,
"e": 26082,
"s": 26068,
"text": "Storage Class"
},
{
"code": null,
"e": 26095,
"s": 26082,
"text": "Value Stored"
},
{
"code": null,
"e": 26100,
"s": 26095,
"text": "NULL"
},
{
"code": null,
"e": 26105,
"s": 26100,
"text": "NULL"
},
{
"code": null,
"e": 26113,
"s": 26105,
"text": "INTEGER"
},
{
"code": null,
"e": 26179,
"s": 26113,
"text": "Signed Integer (1, 2, 3, 4, 5, or 8 bytes depending on magnitude)"
},
{
"code": null,
"e": 26184,
"s": 26179,
"text": "REAL"
},
{
"code": null,
"e": 26242,
"s": 26184,
"text": "Floating point value (8 byte IEEE floating-point numbers)"
},
{
"code": null,
"e": 26247,
"s": 26242,
"text": "TEXT"
},
{
"code": null,
"e": 26299,
"s": 26247,
"text": "TEXT string (encoded in UTF-8, UTF-16BE or UTF-16LE"
},
{
"code": null,
"e": 26326,
"s": 26299,
"text": "BLOB (Binary Large Object)"
},
{
"code": null,
"e": 26395,
"s": 26326,
"text": "Data stored exactly the way it was input, generally in binary format"
},
{
"code": null,
"e": 26454,
"s": 26395,
"text": "The term Storage Class can be used mutually with DataType."
},
{
"code": null,
"e": 26527,
"s": 26454,
"text": "The SQLite DataTypes and their corresponding Python types are as follows"
},
{
"code": null,
"e": 26541,
"s": 26527,
"text": "Storage Class"
},
{
"code": null,
"e": 26557,
"s": 26541,
"text": "Python Datatype"
},
{
"code": null,
"e": 26562,
"s": 26557,
"text": "NULL"
},
{
"code": null,
"e": 26567,
"s": 26562,
"text": "None"
},
{
"code": null,
"e": 26575,
"s": 26567,
"text": "INTEGER"
},
{
"code": null,
"e": 26579,
"s": 26575,
"text": "int"
},
{
"code": null,
"e": 26584,
"s": 26579,
"text": "REAL"
},
{
"code": null,
"e": 26590,
"s": 26584,
"text": "float"
},
{
"code": null,
"e": 26595,
"s": 26590,
"text": "TEXT"
},
{
"code": null,
"e": 26599,
"s": 26595,
"text": "str"
},
{
"code": null,
"e": 26604,
"s": 26599,
"text": "BLOB"
},
{
"code": null,
"e": 26610,
"s": 26604,
"text": "bytes"
},
{
"code": null,
"e": 26795,
"s": 26610,
"text": "The type() function can be used in python to get the class of an argument. In the program below, the type() function is used to print the classes of every value we store in a database."
},
{
"code": null,
"e": 26895,
"s": 26795,
"text": "Note: The program below uses the GeeksforGeeks logo as logo.png from this page for a demonstration."
},
{
"code": null,
"e": 27055,
"s": 26895,
"text": "Letβs take an example in which we are creating a database with the name βgfgβ and then create a table named exam_hall having some columns which are as follows:"
},
{
"code": null,
"e": 27111,
"s": 27055,
"text": "NAME (TEXT),PIN (INTEGER),OCCUPANCY (REAL),LOGO (BLOB)."
},
{
"code": null,
"e": 27124,
"s": 27111,
"text": "NAME (TEXT),"
},
{
"code": null,
"e": 27139,
"s": 27124,
"text": "PIN (INTEGER),"
},
{
"code": null,
"e": 27157,
"s": 27139,
"text": "OCCUPANCY (REAL),"
},
{
"code": null,
"e": 27170,
"s": 27157,
"text": "LOGO (BLOB)."
},
{
"code": null,
"e": 27288,
"s": 27170,
"text": "Then we insert some rows in it and check the data types of the values fetched with the help of SQL queries in Python."
},
{
"code": null,
"e": 27296,
"s": 27288,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate SQLite3 datatypes# and corresponding Python3 types # import the sqlite3 packageimport sqlite3 # create connection to databasecnt = sqlite3.connect('gfg.db') # Create a exam_hall relationcnt.execute('''CREATE TABLE exam_hall(NAME TEXT,PIN INTEGER,OCCUPANCY REAL,LOGO BLOB);''') # Open the logo file in read, binary mode# read the image as binary data into a variablefileh = open('/content/JSBinCollaborativeJavaScriptDebugging6-300x160.png', 'rb')img = fileh.read() # Insert tuples for the relationcnt.execute('''INSERT INTO exam_hall VALUES('centre-a',1125,98.6,?)''', (img,))cnt.execute('''INSERT INTO exam_hall VALUES(NULL,1158,80.5,?)''', (img,)) # Query the data, print the data and its type# note: Printing the image binary data is impractical due to its huge size# instead number of bytes are being printed using len()cursor = cnt.execute('''SELECT * FROM exam_hall;''')for i in cursor: print(str(i[0])+\" \"+str(i[1])+\" \"+str(i[2])+\" \"+str(len(i[3]))) print(str(type(i[0]))+\" \"+str(type(i[1]))+\" \" + str(type(i[2]))+\" \"+str(type(i[3]))+\"\\n\")",
"e": 28401,
"s": 27296,
"text": null
},
{
"code": null,
"e": 28409,
"s": 28401,
"text": "Output:"
},
{
"code": null,
"e": 28482,
"s": 28409,
"text": "From the output of this program, the following observations can be made:"
},
{
"code": null,
"e": 28855,
"s": 28482,
"text": "βcentre-aβ that was inserted as TEXT has been interpreted by python as str1125, 1158 that were inserted as INTEGER have been interpreted by python as int98.6, 80.5 that were inserted as REAL have been interpreted by python as floatNULL was interpreted by python as NoneTypeThe logo image which was inserted in binary format as BLOB has been interpreted by python as bytes."
},
{
"code": null,
"e": 28930,
"s": 28855,
"text": "βcentre-aβ that was inserted as TEXT has been interpreted by python as str"
},
{
"code": null,
"e": 29010,
"s": 28930,
"text": "1125, 1158 that were inserted as INTEGER have been interpreted by python as int"
},
{
"code": null,
"e": 29089,
"s": 29010,
"text": "98.6, 80.5 that were inserted as REAL have been interpreted by python as float"
},
{
"code": null,
"e": 29132,
"s": 29089,
"text": "NULL was interpreted by python as NoneType"
},
{
"code": null,
"e": 29232,
"s": 29132,
"text": "The logo image which was inserted in binary format as BLOB has been interpreted by python as bytes."
},
{
"code": null,
"e": 29239,
"s": 29232,
"text": "Picked"
},
{
"code": null,
"e": 29253,
"s": 29239,
"text": "Python-SQLite"
},
{
"code": null,
"e": 29260,
"s": 29253,
"text": "Python"
},
{
"code": null,
"e": 29358,
"s": 29260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29390,
"s": 29358,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29432,
"s": 29390,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29474,
"s": 29432,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29501,
"s": 29474,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29557,
"s": 29501,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29596,
"s": 29557,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29618,
"s": 29596,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29649,
"s": 29618,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29678,
"s": 29649,
"text": "Create a directory in Python"
}
] |
How to find the version of an installed npm package in node.js ? - GeeksforGeeks
|
11 Feb, 2021
NPM is a default package manager for Node.js. NPM manages all the internal as well as external packages or modules that we use in various node.js applications. Default Packages in NPM cannot fulfill the needs of the developer, so we need external packages, and we can install either locally in a particular directory on our machine or globally that are easily accessible in any location on our machine.
Installing npm package locally using the below command: This command will install the mentioned package in our local directory.
npm install <package-name>
Installing npm package globally using the below command: This command will install the mentioned package globally. Global packages are all installed in a single location on our machine thatβs why a globally installed package is accessible in any directory on our machine.
npm install -g <package-name>
Methods to check the installed version of Node.js. packages on our machine:
Checking locally installed Node.js packages in a particular directory using the below command.npm lsOutput:Checking globally installed packages on our machine using the below command.npm list -gOutput:Checking specific package globally installed node.js package using below command.npm ls -g <package_name>Output:Checking Local top-level domain of packages only and not all sub-packages using the below command.npm list --depth=0Output:Checking Globally Top-level domain node.js packages using the below command.npm list --depth=0 -g
Checking locally installed Node.js packages in a particular directory using the below command.npm lsOutput:
Checking locally installed Node.js packages in a particular directory using the below command.
npm ls
Output:
Checking globally installed packages on our machine using the below command.npm list -gOutput:
Checking globally installed packages on our machine using the below command.
npm list -g
Output:
Checking specific package globally installed node.js package using below command.npm ls -g <package_name>Output:
Checking specific package globally installed node.js package using below command.
npm ls -g <package_name>
Output:
Checking Local top-level domain of packages only and not all sub-packages using the below command.npm list --depth=0Output:
Checking Local top-level domain of packages only and not all sub-packages using the below command.
npm list --depth=0
Output:
Checking Globally Top-level domain node.js packages using the below command.npm list --depth=0 -g
Checking Globally Top-level domain node.js packages using the below command.
npm list --depth=0 -g
mridulmanochagfg
Node-npm
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Node.js Export Module
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 26672,
"s": 26267,
"text": "NPM is a default package manager for Node.js. NPM manages all the internal as well as external packages or modules that we use in various node.js applications. Default Packages in NPM cannot fulfill the needs of the developer, so we need external packages, and we can install either locally in a particular directory on our machine or globally that are easily accessible in any location on our machine. "
},
{
"code": null,
"e": 26800,
"s": 26672,
"text": "Installing npm package locally using the below command: This command will install the mentioned package in our local directory."
},
{
"code": null,
"e": 26828,
"s": 26800,
"text": "npm install <package-name> "
},
{
"code": null,
"e": 27100,
"s": 26828,
"text": "Installing npm package globally using the below command: This command will install the mentioned package globally. Global packages are all installed in a single location on our machine thatβs why a globally installed package is accessible in any directory on our machine."
},
{
"code": null,
"e": 27130,
"s": 27100,
"text": "npm install -g <package-name>"
},
{
"code": null,
"e": 27206,
"s": 27130,
"text": "Methods to check the installed version of Node.js. packages on our machine:"
},
{
"code": null,
"e": 27741,
"s": 27206,
"text": "Checking locally installed Node.js packages in a particular directory using the below command.npm lsOutput:Checking globally installed packages on our machine using the below command.npm list -gOutput:Checking specific package globally installed node.js package using below command.npm ls -g <package_name>Output:Checking Local top-level domain of packages only and not all sub-packages using the below command.npm list --depth=0Output:Checking Globally Top-level domain node.js packages using the below command.npm list --depth=0 -g"
},
{
"code": null,
"e": 27850,
"s": 27741,
"text": "Checking locally installed Node.js packages in a particular directory using the below command.npm lsOutput:"
},
{
"code": null,
"e": 27946,
"s": 27850,
"text": "Checking locally installed Node.js packages in a particular directory using the below command."
},
{
"code": null,
"e": 27953,
"s": 27946,
"text": "npm ls"
},
{
"code": null,
"e": 27961,
"s": 27953,
"text": "Output:"
},
{
"code": null,
"e": 28056,
"s": 27961,
"text": "Checking globally installed packages on our machine using the below command.npm list -gOutput:"
},
{
"code": null,
"e": 28133,
"s": 28056,
"text": "Checking globally installed packages on our machine using the below command."
},
{
"code": null,
"e": 28145,
"s": 28133,
"text": "npm list -g"
},
{
"code": null,
"e": 28153,
"s": 28145,
"text": "Output:"
},
{
"code": null,
"e": 28266,
"s": 28153,
"text": "Checking specific package globally installed node.js package using below command.npm ls -g <package_name>Output:"
},
{
"code": null,
"e": 28348,
"s": 28266,
"text": "Checking specific package globally installed node.js package using below command."
},
{
"code": null,
"e": 28373,
"s": 28348,
"text": "npm ls -g <package_name>"
},
{
"code": null,
"e": 28381,
"s": 28373,
"text": "Output:"
},
{
"code": null,
"e": 28505,
"s": 28381,
"text": "Checking Local top-level domain of packages only and not all sub-packages using the below command.npm list --depth=0Output:"
},
{
"code": null,
"e": 28604,
"s": 28505,
"text": "Checking Local top-level domain of packages only and not all sub-packages using the below command."
},
{
"code": null,
"e": 28623,
"s": 28604,
"text": "npm list --depth=0"
},
{
"code": null,
"e": 28631,
"s": 28623,
"text": "Output:"
},
{
"code": null,
"e": 28729,
"s": 28631,
"text": "Checking Globally Top-level domain node.js packages using the below command.npm list --depth=0 -g"
},
{
"code": null,
"e": 28806,
"s": 28729,
"text": "Checking Globally Top-level domain node.js packages using the below command."
},
{
"code": null,
"e": 28828,
"s": 28806,
"text": "npm list --depth=0 -g"
},
{
"code": null,
"e": 28845,
"s": 28828,
"text": "mridulmanochagfg"
},
{
"code": null,
"e": 28854,
"s": 28845,
"text": "Node-npm"
},
{
"code": null,
"e": 28871,
"s": 28854,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 28878,
"s": 28871,
"text": "Picked"
},
{
"code": null,
"e": 28886,
"s": 28878,
"text": "Node.js"
},
{
"code": null,
"e": 28903,
"s": 28886,
"text": "Web Technologies"
},
{
"code": null,
"e": 29001,
"s": 28903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29040,
"s": 29001,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 29062,
"s": 29040,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 29132,
"s": 29062,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 29159,
"s": 29132,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29184,
"s": 29159,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 29224,
"s": 29184,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29269,
"s": 29224,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29312,
"s": 29269,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29374,
"s": 29312,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Commonly Asked Java Programming Interview Questions | Set 2 - GeeksforGeeks
|
28 Jan, 2022
In this article, some of the most important Java Interview Questions and Answers are discussed, to give you the cutting edge in your interviews. Java is one of the most popular and widely used programming language and platform. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner. This is why you should master these questions if you want to stand out.
Let us start by taking a look at some of the most frequently asked Java interview questions,
Can we Overload or Override static methods in Java?
Why the main method is static in java?
What happens if you remove static modifier from the main method?
What is the scope of variables in Java in following cases?
What is βthisβ keyword in java?
What is an abstract class? How abstract classes are similar or different in Java from C++?
Which class is the superclass for every class?
Can we overload main() method?
What is object cloning?
How is inheritance in C++ different from Java?
Why method overloading is not possible by changing the return type in java?
Can we override private methods in Java?
What is blank final variable?
What is βsuperβ keyword in java?
What is static variable in Java?
Differences between HashMap and HashTable in Java.
How are Java objects stored in memory?
What are C++ features missing in Java?
So letβs get started with the set of Java Interview Questions.
Q1. Can we Overload or Override static methods in java?
Overriding : Overriding is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in superclass (or base class) at runtime.
Overloading: Overloading is related to compile time (or static) polymorphism. This feature allows different methods to have same name, but different signatures, especially number of input parameters and type of input parameters.
Can we overload static methods? The answer is βYesβ. We can have two ore more static methods with same name, but differences in input parameters
Can we Override static methods in java? We can declare static methods with same signature in subclass, but it is not considered overriding as there wonβt be any run-time polymorphism. Hence the answer is βNoβ. Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. runtime) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).
Read more
Q2. Why the main method is static in java? The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:
public class JavaClass
{
protected JavaClass(int x)
{ }
public void main(String[] args)
{
}
}
Should the JVM call new JavaClass(int)? What should it pass for x? If not, should the JVM instantiate JavaClass without running any constructor method? because that will special-case your entire class β sometimes you have an instance that hasnβt been initialized, and you have to check for it in every method that could be called. There are just too many edge-cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. Thatβs why main is static.
Q3. What happens if you remove static modifier from the main method? Program compiles successfully. But at runtime throws an error βNoSuchMethodErrorβ.
Q4. What is the scope of variables in Java in following cases?
Member Variables (Class Level Scope) : The member variables must be declared inside class (outside any function). They can be directly accessed anywhere in class
Local Variables (Method Level Scope) : Variables declared inside a method have method level scope and canβt be accessed outside the method.
Loop Variables (Block Scope) : A variable declared inside pair of brackets β{β and β}β in a method has scope within the brackets only.
Read more
Q5. What is βthisβ keyword in java? Within an instance method or a constructor, this is a reference to the current object β the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Usage of this keyword
Used to refer current class instance variable.
To invoke current class constructor.
It can be passed as an argument in the method call.
It can be passed as argument in the constructor call.
Used to return the current class instance.
Used to invoke current class method (implicitly)
Q6. What is an abstract class? How abstract classes are similar or different in Java from C++? Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Like C++, in Java, an instance of an abstract class cannot be created, we can have references of abstract class type though.
Like C++, an abstract class can contain constructors in Java. And a constructor of abstract class is called when an instance of a inherited class is created
In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited.
Abstract classes can also have final methods (methods that cannot be overridden). For example, the following program compiles and runs fine.
Read more
Q7. Which class is the superclass for every class? Object class
Q8. Can we overload main() method? The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded in a similar manner, JVM always looks for the method signature to launch the program.
The normal main method acts as an entry point for the JVM to start the execution of program.
We can overload the main method in Java. But the program doesnβt execute the overloaded main method when we run your program, we need to call the overloaded main method from the actual main method only.
Read more
Q9. What is object cloning? Object cloning means to create an exact copy of the original object. If a class needs to support cloning, it must implement java.lang.Cloneable interface and override clone() method from Object class. Syntax of the clone() method is :
protected Object clone() throws CloneNotSupportedException
If the objectβs class doesnβt implement Cloneable interface then it throws an exception βCloneNotSupportedExceptionβ .
Read more
Q10. How is inheritance in C++ different from Java?
In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is the root of the tree.In Java, members of the grandparent class are not directly accessible. See this G-Fact for more details.The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class βAβ are accessible in other class βBβ of the same package, even if B doesnβt inherit from A (they both have to be in the same package).Java uses extends keyword for inheritance. Unlike C++, Java doesnβt provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of the base class in Java, if some data member is public or protected in base class then it remains public or protected in the derived class. Like C++, private members of base class are not accessible in the derived class. Unlike C++, in Java, we donβt have to remember those rules of inheritance which are the combination of base class access specifier and inheritance specifier.In Java, methods are virtual by default. In C++, we explicitly use virtual keyword. See this G-Fact for more details.Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions.Unlike C++, Java doesnβt support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though.In C++, default constructor of parent class is automatically called, but if we want to call parameterized constructor of a parent class, we must use Initializer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parameterized constructor then we must use super to call the parent constructor.
In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is the root of the tree.
In Java, members of the grandparent class are not directly accessible. See this G-Fact for more details.
The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class βAβ are accessible in other class βBβ of the same package, even if B doesnβt inherit from A (they both have to be in the same package).
Java uses extends keyword for inheritance. Unlike C++, Java doesnβt provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of the base class in Java, if some data member is public or protected in base class then it remains public or protected in the derived class. Like C++, private members of base class are not accessible in the derived class. Unlike C++, in Java, we donβt have to remember those rules of inheritance which are the combination of base class access specifier and inheritance specifier.
In Java, methods are virtual by default. In C++, we explicitly use virtual keyword. See this G-Fact for more details.
Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions.
Unlike C++, Java doesnβt support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though.
In C++, default constructor of parent class is automatically called, but if we want to call parameterized constructor of a parent class, we must use Initializer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parameterized constructor then we must use super to call the parent constructor.
See examples here
Q11. Why method overloading is not possible by changing the return type in java? In C++ and Java, functions can not be overloaded if they differ only in the return type. The return type of functions is not a part of the mangled name which is generated by the compiler for uniquely identifying each function. The No of arguments, Type of arguments & Sequence of arguments are the parameters which are used to generate the unique mangled name for each function. It is on the basis of these unique mangled names that compiler can understand which function to call even if the names are same(overloading).
Q12. Can we override private methods in Java? No, a private method cannot be overridden since it is not visible from any other class. Read more
Q13. What is blank final variable? A final variable in Java can be assigned a value only once, we can assign a value either in declaration or later.
final int i = 10;
i = 30; // Error because i is final.
A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final.
// A simple blank final example
final int i;
i = 30;
Read more
Q14. What is βsuperβ keyword in java? The super keyword in java is a reference variable that is used to refer parent class objects. The keyword βsuperβ came into the picture with the concept of Inheritance. Whenever you create the instance of a subclass, an instance of parent class is created implicitly i.e. referred by super reference variable. Various scenarios of using java super Keyword:
super is used to refer immediate parent instance variable
super is used to call parent class method
super() is used to call immediate parent constructor
Read more
Q15. What is static variable in Java? The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than the instance of the class.
The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class
Q16. Differences between HashMap and HashTable in Java. 1. HashMap is non synchronized. It is not-thread safe and canβt be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads. 2. HashMap allows one null key and multiple null values whereas Hashtable doesnβt allow any null key or value. 3. HashMap is generally preferred over HashTable if thread synchronization is not needed Read more
Q17. How are Java objects stored in memory? In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate object using new(), the object is allocated on Heap, otherwise on Stack if not global or static. In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on the heap. Read more
Q18. What are C++ features missing in Java? Try to answer this on your own before seeing the answer β here.
See also:
Frequently Asked Java Interview Questions | Set 1
Interview Questions for Java Professionals
Java Multiple Choice Questions
Practice Coding Questions
Java articles
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
interview-preparation
java-basics
Java-Interview
Interview Experiences
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
HashMap in Java with Examples
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 25765,
"s": 25737,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 26249,
"s": 25765,
"text": "In this article, some of the most important Java Interview Questions and Answers are discussed, to give you the cutting edge in your interviews. Java is one of the most popular and widely used programming language and platform. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner. This is why you should master these questions if you want to stand out. "
},
{
"code": null,
"e": 26343,
"s": 26249,
"text": "Let us start by taking a look at some of the most frequently asked Java interview questions, "
},
{
"code": null,
"e": 26395,
"s": 26343,
"text": "Can we Overload or Override static methods in Java?"
},
{
"code": null,
"e": 26434,
"s": 26395,
"text": "Why the main method is static in java?"
},
{
"code": null,
"e": 26499,
"s": 26434,
"text": "What happens if you remove static modifier from the main method?"
},
{
"code": null,
"e": 26558,
"s": 26499,
"text": "What is the scope of variables in Java in following cases?"
},
{
"code": null,
"e": 26590,
"s": 26558,
"text": "What is βthisβ keyword in java?"
},
{
"code": null,
"e": 26681,
"s": 26590,
"text": "What is an abstract class? How abstract classes are similar or different in Java from C++?"
},
{
"code": null,
"e": 26728,
"s": 26681,
"text": "Which class is the superclass for every class?"
},
{
"code": null,
"e": 26759,
"s": 26728,
"text": "Can we overload main() method?"
},
{
"code": null,
"e": 26783,
"s": 26759,
"text": "What is object cloning?"
},
{
"code": null,
"e": 26830,
"s": 26783,
"text": "How is inheritance in C++ different from Java?"
},
{
"code": null,
"e": 26906,
"s": 26830,
"text": "Why method overloading is not possible by changing the return type in java?"
},
{
"code": null,
"e": 26947,
"s": 26906,
"text": "Can we override private methods in Java?"
},
{
"code": null,
"e": 26977,
"s": 26947,
"text": "What is blank final variable?"
},
{
"code": null,
"e": 27010,
"s": 26977,
"text": "What is βsuperβ keyword in java?"
},
{
"code": null,
"e": 27043,
"s": 27010,
"text": "What is static variable in Java?"
},
{
"code": null,
"e": 27094,
"s": 27043,
"text": "Differences between HashMap and HashTable in Java."
},
{
"code": null,
"e": 27133,
"s": 27094,
"text": "How are Java objects stored in memory?"
},
{
"code": null,
"e": 27173,
"s": 27133,
"text": "What are C++ features missing in Java? "
},
{
"code": null,
"e": 27237,
"s": 27173,
"text": "So letβs get started with the set of Java Interview Questions. "
},
{
"code": null,
"e": 27294,
"s": 27237,
"text": "Q1. Can we Overload or Override static methods in java? "
},
{
"code": null,
"e": 27474,
"s": 27294,
"text": "Overriding : Overriding is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in superclass (or base class) at runtime."
},
{
"code": null,
"e": 27703,
"s": 27474,
"text": "Overloading: Overloading is related to compile time (or static) polymorphism. This feature allows different methods to have same name, but different signatures, especially number of input parameters and type of input parameters."
},
{
"code": null,
"e": 27850,
"s": 27703,
"text": "Can we overload static methods? The answer is βYesβ. We can have two ore more static methods with same name, but differences in input parameters"
},
{
"code": null,
"e": 28275,
"s": 27850,
"text": "Can we Override static methods in java? We can declare static methods with same signature in subclass, but it is not considered overriding as there wonβt be any run-time polymorphism. Hence the answer is βNoβ. Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. runtime) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time)."
},
{
"code": null,
"e": 28286,
"s": 28275,
"text": "Read more "
},
{
"code": null,
"e": 28473,
"s": 28286,
"text": "Q2. Why the main method is static in java? The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this: "
},
{
"code": null,
"e": 28585,
"s": 28473,
"text": "public class JavaClass\n{\n protected JavaClass(int x)\n { }\n public void main(String[] args) \n {\n\n }\n}"
},
{
"code": null,
"e": 29093,
"s": 28585,
"text": "Should the JVM call new JavaClass(int)? What should it pass for x? If not, should the JVM instantiate JavaClass without running any constructor method? because that will special-case your entire class β sometimes you have an instance that hasnβt been initialized, and you have to check for it in every method that could be called. There are just too many edge-cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. Thatβs why main is static. "
},
{
"code": null,
"e": 29246,
"s": 29093,
"text": "Q3. What happens if you remove static modifier from the main method? Program compiles successfully. But at runtime throws an error βNoSuchMethodErrorβ. "
},
{
"code": null,
"e": 29313,
"s": 29246,
"text": " Q4. What is the scope of variables in Java in following cases? "
},
{
"code": null,
"e": 29475,
"s": 29313,
"text": "Member Variables (Class Level Scope) : The member variables must be declared inside class (outside any function). They can be directly accessed anywhere in class"
},
{
"code": null,
"e": 29615,
"s": 29475,
"text": "Local Variables (Method Level Scope) : Variables declared inside a method have method level scope and canβt be accessed outside the method."
},
{
"code": null,
"e": 29750,
"s": 29615,
"text": "Loop Variables (Block Scope) : A variable declared inside pair of brackets β{β and β}β in a method has scope within the brackets only."
},
{
"code": null,
"e": 29761,
"s": 29750,
"text": "Read more "
},
{
"code": null,
"e": 30079,
"s": 29761,
"text": " Q5. What is βthisβ keyword in java? Within an instance method or a constructor, this is a reference to the current object β the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Usage of this keyword "
},
{
"code": null,
"e": 30126,
"s": 30079,
"text": "Used to refer current class instance variable."
},
{
"code": null,
"e": 30163,
"s": 30126,
"text": "To invoke current class constructor."
},
{
"code": null,
"e": 30215,
"s": 30163,
"text": "It can be passed as an argument in the method call."
},
{
"code": null,
"e": 30269,
"s": 30215,
"text": "It can be passed as argument in the constructor call."
},
{
"code": null,
"e": 30312,
"s": 30269,
"text": "Used to return the current class instance."
},
{
"code": null,
"e": 30361,
"s": 30312,
"text": "Used to invoke current class method (implicitly)"
},
{
"code": null,
"e": 30727,
"s": 30361,
"text": "Q6. What is an abstract class? How abstract classes are similar or different in Java from C++? Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. "
},
{
"code": null,
"e": 30852,
"s": 30727,
"text": "Like C++, in Java, an instance of an abstract class cannot be created, we can have references of abstract class type though."
},
{
"code": null,
"e": 31009,
"s": 30852,
"text": "Like C++, an abstract class can contain constructors in Java. And a constructor of abstract class is called when an instance of a inherited class is created"
},
{
"code": null,
"e": 31166,
"s": 31009,
"text": "In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited."
},
{
"code": null,
"e": 31307,
"s": 31166,
"text": "Abstract classes can also have final methods (methods that cannot be overridden). For example, the following program compiles and runs fine."
},
{
"code": null,
"e": 31318,
"s": 31307,
"text": "Read more "
},
{
"code": null,
"e": 31383,
"s": 31318,
"text": "Q7. Which class is the superclass for every class? Object class "
},
{
"code": null,
"e": 31644,
"s": 31383,
"text": "Q8. Can we overload main() method? The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded in a similar manner, JVM always looks for the method signature to launch the program. "
},
{
"code": null,
"e": 31737,
"s": 31644,
"text": "The normal main method acts as an entry point for the JVM to start the execution of program."
},
{
"code": null,
"e": 31940,
"s": 31737,
"text": "We can overload the main method in Java. But the program doesnβt execute the overloaded main method when we run your program, we need to call the overloaded main method from the actual main method only."
},
{
"code": null,
"e": 31951,
"s": 31940,
"text": "Read more "
},
{
"code": null,
"e": 32216,
"s": 31951,
"text": "Q9. What is object cloning? Object cloning means to create an exact copy of the original object. If a class needs to support cloning, it must implement java.lang.Cloneable interface and override clone() method from Object class. Syntax of the clone() method is : "
},
{
"code": null,
"e": 32275,
"s": 32216,
"text": "protected Object clone() throws CloneNotSupportedException"
},
{
"code": null,
"e": 32395,
"s": 32275,
"text": "If the objectβs class doesnβt implement Cloneable interface then it throws an exception βCloneNotSupportedExceptionβ . "
},
{
"code": null,
"e": 32406,
"s": 32395,
"text": "Read more "
},
{
"code": null,
"e": 32460,
"s": 32406,
"text": "Q10. How is inheritance in C++ different from Java? "
},
{
"code": null,
"e": 34326,
"s": 32460,
"text": "In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is the root of the tree.In Java, members of the grandparent class are not directly accessible. See this G-Fact for more details.The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class βAβ are accessible in other class βBβ of the same package, even if B doesnβt inherit from A (they both have to be in the same package).Java uses extends keyword for inheritance. Unlike C++, Java doesnβt provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of the base class in Java, if some data member is public or protected in base class then it remains public or protected in the derived class. Like C++, private members of base class are not accessible in the derived class. Unlike C++, in Java, we donβt have to remember those rules of inheritance which are the combination of base class access specifier and inheritance specifier.In Java, methods are virtual by default. In C++, we explicitly use virtual keyword. See this G-Fact for more details.Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions.Unlike C++, Java doesnβt support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though.In C++, default constructor of parent class is automatically called, but if we want to call parameterized constructor of a parent class, we must use Initializer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parameterized constructor then we must use super to call the parent constructor."
},
{
"code": null,
"e": 34516,
"s": 34326,
"text": "In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is the root of the tree."
},
{
"code": null,
"e": 34621,
"s": 34516,
"text": "In Java, members of the grandparent class are not directly accessible. See this G-Fact for more details."
},
{
"code": null,
"e": 34875,
"s": 34621,
"text": "The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class βAβ are accessible in other class βBβ of the same package, even if B doesnβt inherit from A (they both have to be in the same package)."
},
{
"code": null,
"e": 35452,
"s": 34875,
"text": "Java uses extends keyword for inheritance. Unlike C++, Java doesnβt provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of the base class in Java, if some data member is public or protected in base class then it remains public or protected in the derived class. Like C++, private members of base class are not accessible in the derived class. Unlike C++, in Java, we donβt have to remember those rules of inheritance which are the combination of base class access specifier and inheritance specifier."
},
{
"code": null,
"e": 35570,
"s": 35452,
"text": "In Java, methods are virtual by default. In C++, we explicitly use virtual keyword. See this G-Fact for more details."
},
{
"code": null,
"e": 35691,
"s": 35570,
"text": "Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions."
},
{
"code": null,
"e": 35845,
"s": 35691,
"text": "Unlike C++, Java doesnβt support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though."
},
{
"code": null,
"e": 36199,
"s": 35845,
"text": "In C++, default constructor of parent class is automatically called, but if we want to call parameterized constructor of a parent class, we must use Initializer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parameterized constructor then we must use super to call the parent constructor."
},
{
"code": null,
"e": 36218,
"s": 36199,
"text": "See examples here "
},
{
"code": null,
"e": 36821,
"s": 36218,
"text": "Q11. Why method overloading is not possible by changing the return type in java? In C++ and Java, functions can not be overloaded if they differ only in the return type. The return type of functions is not a part of the mangled name which is generated by the compiler for uniquely identifying each function. The No of arguments, Type of arguments & Sequence of arguments are the parameters which are used to generate the unique mangled name for each function. It is on the basis of these unique mangled names that compiler can understand which function to call even if the names are same(overloading). "
},
{
"code": null,
"e": 36968,
"s": 36821,
"text": " Q12. Can we override private methods in Java? No, a private method cannot be overridden since it is not visible from any other class. Read more "
},
{
"code": null,
"e": 37120,
"s": 36968,
"text": " Q13. What is blank final variable? A final variable in Java can be assigned a value only once, we can assign a value either in declaration or later. "
},
{
"code": null,
"e": 37183,
"s": 37120,
"text": " final int i = 10;\n i = 30; // Error because i is final."
},
{
"code": null,
"e": 37322,
"s": 37183,
"text": "A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final. "
},
{
"code": null,
"e": 37388,
"s": 37322,
"text": " // A simple blank final example \n final int i;\n i = 30;"
},
{
"code": null,
"e": 37399,
"s": 37388,
"text": "Read more "
},
{
"code": null,
"e": 37796,
"s": 37399,
"text": "Q14. What is βsuperβ keyword in java? The super keyword in java is a reference variable that is used to refer parent class objects. The keyword βsuperβ came into the picture with the concept of Inheritance. Whenever you create the instance of a subclass, an instance of parent class is created implicitly i.e. referred by super reference variable. Various scenarios of using java super Keyword: "
},
{
"code": null,
"e": 37854,
"s": 37796,
"text": "super is used to refer immediate parent instance variable"
},
{
"code": null,
"e": 37896,
"s": 37854,
"text": "super is used to call parent class method"
},
{
"code": null,
"e": 37949,
"s": 37896,
"text": "super() is used to call immediate parent constructor"
},
{
"code": null,
"e": 37960,
"s": 37949,
"text": "Read more "
},
{
"code": null,
"e": 38219,
"s": 37960,
"text": "Q15. What is static variable in Java? The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than the instance of the class. "
},
{
"code": null,
"e": 38240,
"s": 38219,
"text": "The static can be: "
},
{
"code": null,
"e": 38280,
"s": 38240,
"text": "variable (also known as class variable)"
},
{
"code": null,
"e": 38316,
"s": 38280,
"text": "method (also known as class method)"
},
{
"code": null,
"e": 38322,
"s": 38316,
"text": "block"
},
{
"code": null,
"e": 38335,
"s": 38322,
"text": "nested class"
},
{
"code": null,
"e": 38824,
"s": 38335,
"text": " Q16. Differences between HashMap and HashTable in Java. 1. HashMap is non synchronized. It is not-thread safe and canβt be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads. 2. HashMap allows one null key and multiple null values whereas Hashtable doesnβt allow any null key or value. 3. HashMap is generally preferred over HashTable if thread synchronization is not needed Read more "
},
{
"code": null,
"e": 39385,
"s": 38824,
"text": "Q17. How are Java objects stored in memory? In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate object using new(), the object is allocated on Heap, otherwise on Stack if not global or static. In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on the heap. Read more "
},
{
"code": null,
"e": 39496,
"s": 39385,
"text": " Q18. What are C++ features missing in Java? Try to answer this on your own before seeing the answer β here. "
},
{
"code": null,
"e": 39508,
"s": 39496,
"text": "See also: "
},
{
"code": null,
"e": 39558,
"s": 39508,
"text": "Frequently Asked Java Interview Questions | Set 1"
},
{
"code": null,
"e": 39601,
"s": 39558,
"text": "Interview Questions for Java Professionals"
},
{
"code": null,
"e": 39632,
"s": 39601,
"text": "Java Multiple Choice Questions"
},
{
"code": null,
"e": 39658,
"s": 39632,
"text": "Practice Coding Questions"
},
{
"code": null,
"e": 39672,
"s": 39658,
"text": "Java articles"
},
{
"code": null,
"e": 39797,
"s": 39672,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 39819,
"s": 39797,
"text": "interview-preparation"
},
{
"code": null,
"e": 39831,
"s": 39819,
"text": "java-basics"
},
{
"code": null,
"e": 39846,
"s": 39831,
"text": "Java-Interview"
},
{
"code": null,
"e": 39868,
"s": 39846,
"text": "Interview Experiences"
},
{
"code": null,
"e": 39873,
"s": 39868,
"text": "Java"
},
{
"code": null,
"e": 39878,
"s": 39873,
"text": "Java"
},
{
"code": null,
"e": 39976,
"s": 39878,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40027,
"s": 39976,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 40069,
"s": 40027,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 40105,
"s": 40069,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 40161,
"s": 40105,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 40189,
"s": 40161,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 40204,
"s": 40189,
"text": "Arrays in Java"
},
{
"code": null,
"e": 40248,
"s": 40204,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 40270,
"s": 40248,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 40300,
"s": 40270,
"text": "HashMap in Java with Examples"
}
] |
Drag and Drop Files in ElectronJS - GeeksforGeeks
|
01 Feb, 2022
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.There are several differences between a Drag-and-Drop Operation in traditional web applications and Electron. One of the major differences is that Electron applications work with the native filesystem in the OS environment. Hence we need to obtain the absolute file path for any files dragged onto the Electron application from the native file dialog on the userβs machine. Once we have obtained the file path, we can perform file operations using the NodeJS fs module or upload the file to a server. Electron makes use of the HTML5 File API to work with files in the native filesystem. This tutorial will demonstrate how to implement Drag-and-Drop functionality for native files in an Electron application.We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
Project Structure:
Example: We will start by building the basic Electron Application by following the given steps.
Step 1: Navigate to an Empty Directory to setup the project, and run the following command,
npm init
To generate the package.json file. Install Electron using npm if it is not installed.
npm install electron --save
This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Create the assets folder according to the project structure. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file. This image file will be dragged-and-dropped onto the BrowserWindow of the Electron application. package.json:
{
"name": "electron-drag",
"version": "1.0.0",
"description": "File Drag and Drop in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js:
javascript
const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your// app's specific main process code. You can also// put them in separate files and require them here.
Step 3: Create the index.html file and index.js file within the src directory according to project structure. We will also copy the Boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:
html
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <br><br> <h3>Drag and Drop Files in the Window.</h3> <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html>
Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:
npm start
Using the HTML5 File API, users can directly work with the native files in the system OS environment. This is possible because the DOMβs File Interface provides an abstraction for the underlying native filesystem. Electron enhances the DOMβs File Interface by adding a path attribute to it. This path attribute exposes the absolute file path of the files on the filesystem. We will be making use of this functionality to get the absolute file path of a dragged-and-dropped file onto the Electron application. For more detailed Information, Refer this link.All the Instance events of the Drag-and-Drop Operation belong to the DragEvent Interface. This event is a DOM Event that represents a drag-and-drop operation from start to finish. This Interface also inherits properties from the MouseEvent and the global Event Interface. It has specific Instance Properties for data transfer, GlobalEventHandlers and Instance Events which we have used in our code. For more detailed Information, Refer this link.index.js: Add the following snippet in that file.
javascript
document.addEventListener('drop', (event) => { event.preventDefault(); event.stopPropagation(); for (const f of event.dataTransfer.files) { // Using the path attribute to get absolute file path console.log('File Path of dragged files: ', f.path) }}); document.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); }); document.addEventListener('dragenter', (event) => { console.log('File is in the Drop Space');}); document.addEventListener('dragleave', (event) => { console.log('File has left the Drop Space');});
A Detailed explanation of all the Instance Events and Properties of the HTML5 File API used in the code are explained below. All the Instance Events of DragEvent Interface will be fired upon the global document object and cannot be directly fired on a Specific DOM element.
event.dataTransfer This Instance Property is used to represent the data that is being transferred during a Drag and Drop Operation. In our case, the data being transferred is a file and hence we have used event.dataTransfer.files and fetched the absolute file path using the path attribute provided by Electron. We can also drag and drop multiple files at once. In case of the data being a text selection, we can simply use event.dataTransfer.setData(key, text) method when initiating a Drag operation. This method sets a unique key for the text data being transferred. To retrieve the text selection on the Drop Operation, we can simply use event.dataTransfer.getData(key) method. This method will return any data which was set using the unique key provided.
dragover: Event This event is fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds) such as another DOM element. The firing pattern for this event depends on the movement of the mouse pointer. By default, this event fires every 50 ms when the mouse pointer is not moving over a valid drop target else much faster between 5 ms and 1 ms approximately but this behaviour varies. The Event Handler Property for this event is ondragover. By default, a element or a text selection cannot be dropped in other DOM elements. To allow a drop, we must prevent the default handling of the element. Hence we have used the event.preventDefault() method for this very purpose. The default handling of an element is open as link in the browser on drop.
drop: Event This event is fired when an element or text selection is dropped on a valid drop target such as another DOM element. The Event Handler Property for this event is ondrop. We need to prevent the default handling of the element in this Event also as done for the dragover Event.
dragenter: Event This event is fired when a dragged element or text selection enters a valid drop target such as another DOM element. The Event Handler Property for this event is ondrageneter.
dragleave: Event This event is fired when a dragged element or text selection leaves a valid drop target such as another DOM element. The Event Handler Property for this event is ondragleave.
The dragStart, drag, dragend and dragexit Instance events will not be fired in this particular code example and hence have been excluded from the same. All of these Instance Events are fired on the Drag Target and in this case, drag Target does not exist in the application. The Drag Operation for files is initiated from outside the application from within the native filesystem dialog. All of the Instance events used in the above code are triggered on the Drop Target which lies within the application. Note: The event.stopPropagation() method prevents propagation of the same event from being called. Propagation means transferring up to the Parent DOM elements or transferring down to the Child DOM elements.Output:
saurabh1990aror
ElectronJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25567,
"s": 25539,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 26744,
"s": 25567,
"text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.There are several differences between a Drag-and-Drop Operation in traditional web applications and Electron. One of the major differences is that Electron applications work with the native filesystem in the OS environment. Hence we need to obtain the absolute file path for any files dragged onto the Electron application from the native file dialog on the userβs machine. Once we have obtained the file path, we can perform file operations using the NodeJS fs module or upload the file to a server. Electron makes use of the HTML5 File API to work with files in the native filesystem. This tutorial will demonstrate how to implement Drag-and-Drop functionality for native files in an Electron application.We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. "
},
{
"code": null,
"e": 26764,
"s": 26744,
"text": "Project Structure: "
},
{
"code": null,
"e": 26861,
"s": 26764,
"text": "Example: We will start by building the basic Electron Application by following the given steps. "
},
{
"code": null,
"e": 26954,
"s": 26861,
"text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command, "
},
{
"code": null,
"e": 26963,
"s": 26954,
"text": "npm init"
},
{
"code": null,
"e": 27050,
"s": 26963,
"text": "To generate the package.json file. Install Electron using npm if it is not installed. "
},
{
"code": null,
"e": 27078,
"s": 27050,
"text": "npm install electron --save"
},
{
"code": null,
"e": 27652,
"s": 27078,
"text": "This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Create the assets folder according to the project structure. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file. This image file will be dragged-and-dropped onto the BrowserWindow of the Electron application. package.json: "
},
{
"code": null,
"e": 27958,
"s": 27652,
"text": "{\n \"name\": \"electron-drag\",\n \"version\": \"1.0.0\",\n \"description\": \"File Drag and Drop in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}"
},
{
"code": null,
"e": 28244,
"s": 27958,
"text": "Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js: "
},
{
"code": null,
"e": 28255,
"s": 28244,
"text": "javascript"
},
{
"code": "const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your// app's specific main process code. You can also// put them in separate files and require them here.",
"e": 29520,
"s": 28255,
"text": null
},
{
"code": null,
"e": 29789,
"s": 29520,
"text": "Step 3: Create the index.html file and index.js file within the src directory according to project structure. We will also copy the Boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html: "
},
{
"code": null,
"e": 29794,
"s": 29789,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <br><br> <h3>Drag and Drop Files in the Window.</h3> <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>",
"e": 30552,
"s": 29794,
"text": null
},
{
"code": null,
"e": 30671,
"s": 30552,
"text": "Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command: "
},
{
"code": null,
"e": 30681,
"s": 30671,
"text": "npm start"
},
{
"code": null,
"e": 31736,
"s": 30683,
"text": "Using the HTML5 File API, users can directly work with the native files in the system OS environment. This is possible because the DOMβs File Interface provides an abstraction for the underlying native filesystem. Electron enhances the DOMβs File Interface by adding a path attribute to it. This path attribute exposes the absolute file path of the files on the filesystem. We will be making use of this functionality to get the absolute file path of a dragged-and-dropped file onto the Electron application. For more detailed Information, Refer this link.All the Instance events of the Drag-and-Drop Operation belong to the DragEvent Interface. This event is a DOM Event that represents a drag-and-drop operation from start to finish. This Interface also inherits properties from the MouseEvent and the global Event Interface. It has specific Instance Properties for data transfer, GlobalEventHandlers and Instance Events which we have used in our code. For more detailed Information, Refer this link.index.js: Add the following snippet in that file. "
},
{
"code": null,
"e": 31747,
"s": 31736,
"text": "javascript"
},
{
"code": "document.addEventListener('drop', (event) => { event.preventDefault(); event.stopPropagation(); for (const f of event.dataTransfer.files) { // Using the path attribute to get absolute file path console.log('File Path of dragged files: ', f.path) }}); document.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); }); document.addEventListener('dragenter', (event) => { console.log('File is in the Drop Space');}); document.addEventListener('dragleave', (event) => { console.log('File has left the Drop Space');});",
"e": 32329,
"s": 31747,
"text": null
},
{
"code": null,
"e": 32604,
"s": 32329,
"text": "A Detailed explanation of all the Instance Events and Properties of the HTML5 File API used in the code are explained below. All the Instance Events of DragEvent Interface will be fired upon the global document object and cannot be directly fired on a Specific DOM element. "
},
{
"code": null,
"e": 33364,
"s": 32604,
"text": "event.dataTransfer This Instance Property is used to represent the data that is being transferred during a Drag and Drop Operation. In our case, the data being transferred is a file and hence we have used event.dataTransfer.files and fetched the absolute file path using the path attribute provided by Electron. We can also drag and drop multiple files at once. In case of the data being a text selection, we can simply use event.dataTransfer.setData(key, text) method when initiating a Drag operation. This method sets a unique key for the text data being transferred. To retrieve the text selection on the Drop Operation, we can simply use event.dataTransfer.getData(key) method. This method will return any data which was set using the unique key provided."
},
{
"code": null,
"e": 34162,
"s": 33364,
"text": "dragover: Event This event is fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds) such as another DOM element. The firing pattern for this event depends on the movement of the mouse pointer. By default, this event fires every 50 ms when the mouse pointer is not moving over a valid drop target else much faster between 5 ms and 1 ms approximately but this behaviour varies. The Event Handler Property for this event is ondragover. By default, a element or a text selection cannot be dropped in other DOM elements. To allow a drop, we must prevent the default handling of the element. Hence we have used the event.preventDefault() method for this very purpose. The default handling of an element is open as link in the browser on drop."
},
{
"code": null,
"e": 34450,
"s": 34162,
"text": "drop: Event This event is fired when an element or text selection is dropped on a valid drop target such as another DOM element. The Event Handler Property for this event is ondrop. We need to prevent the default handling of the element in this Event also as done for the dragover Event."
},
{
"code": null,
"e": 34643,
"s": 34450,
"text": "dragenter: Event This event is fired when a dragged element or text selection enters a valid drop target such as another DOM element. The Event Handler Property for this event is ondrageneter."
},
{
"code": null,
"e": 34835,
"s": 34643,
"text": "dragleave: Event This event is fired when a dragged element or text selection leaves a valid drop target such as another DOM element. The Event Handler Property for this event is ondragleave."
},
{
"code": null,
"e": 35557,
"s": 34835,
"text": "The dragStart, drag, dragend and dragexit Instance events will not be fired in this particular code example and hence have been excluded from the same. All of these Instance Events are fired on the Drag Target and in this case, drag Target does not exist in the application. The Drag Operation for files is initiated from outside the application from within the native filesystem dialog. All of the Instance events used in the above code are triggered on the Drop Target which lies within the application. Note: The event.stopPropagation() method prevents propagation of the same event from being called. Propagation means transferring up to the Parent DOM elements or transferring down to the Child DOM elements.Output: "
},
{
"code": null,
"e": 35573,
"s": 35557,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 35584,
"s": 35573,
"text": "ElectronJS"
},
{
"code": null,
"e": 35595,
"s": 35584,
"text": "JavaScript"
},
{
"code": null,
"e": 35612,
"s": 35595,
"text": "Web Technologies"
},
{
"code": null,
"e": 35710,
"s": 35612,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35750,
"s": 35710,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35795,
"s": 35750,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35856,
"s": 35795,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35928,
"s": 35856,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 35980,
"s": 35928,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 36020,
"s": 35980,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 36053,
"s": 36020,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36098,
"s": 36053,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 36141,
"s": 36098,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTML | Window scrollBy() method - GeeksforGeeks
|
30 Jul, 2019
The window.scrollBy() method is used to scroll the document by given number of pixels.
Syntax:
window.scrollBy( xcoordinate, ycoordinate );
or
window.scrollBy(options);
Parameters: This method accepts two parameters as mentioned above and described below:
x-coordinate: It is the horizontal pixel value which indicates how much you want to scroll the document (in terms of px).
y-coordinate: It is the vertical pixel value which indicates how much you want to scroll the document (in terms of px).
Note: You can find these options in options in ScrollToOptions dictionary.
Example 1: Scroll horizontally
<!DOCTYPE html><html> <head> <title> HTML | DOM window scrollby() method </title> <style> body { width: 5000px; } a:focus { background-color: magenta; } button { position: fixed; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>HTML DOM Window.scrollBy() method</h2> <button onclick="scrollby()"> Scroll horizontally! </button> <br><br> <script> function scrollby() { window.scrollBy(100, 0); } </script></body> </html>
Output:
Example 2: Using options
<!DOCTYPE html><html> <head> <title> HTML | DOM Window scrollBy() method </title> <style> body { width: 5000px; height:5000px; } a:focus { background-color: magenta; } button { position: fixed; } </style></head> <body> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML DOM Window.scrollBy() method</h2> <div> <button onclick="scrollWin(0, 50)"> Scroll down </button> <br><br> <button onclick="scrollWin(0, -50)"> Scroll up </button> <br><br> <button onclick="scrollWin(50, 0)"> Scroll right </button> <br><br> <button onclick="scrollWin(-50, 0)"> Scroll left </button> </div> <script> function scrollWin(x, y) { window.scrollBy(x, y); } </script></body> </html>
Output:
Supported Browsers: The browser supported by HTML DOM Window scrollBy() method are listed below:
Google Chrome 45
Firefox
Opera 32
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 26226,
"s": 26139,
"text": "The window.scrollBy() method is used to scroll the document by given number of pixels."
},
{
"code": null,
"e": 26234,
"s": 26226,
"text": "Syntax:"
},
{
"code": null,
"e": 26279,
"s": 26234,
"text": "window.scrollBy( xcoordinate, ycoordinate );"
},
{
"code": null,
"e": 26282,
"s": 26279,
"text": "or"
},
{
"code": null,
"e": 26308,
"s": 26282,
"text": "window.scrollBy(options);"
},
{
"code": null,
"e": 26395,
"s": 26308,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26517,
"s": 26395,
"text": "x-coordinate: It is the horizontal pixel value which indicates how much you want to scroll the document (in terms of px)."
},
{
"code": null,
"e": 26637,
"s": 26517,
"text": "y-coordinate: It is the vertical pixel value which indicates how much you want to scroll the document (in terms of px)."
},
{
"code": null,
"e": 26712,
"s": 26637,
"text": "Note: You can find these options in options in ScrollToOptions dictionary."
},
{
"code": null,
"e": 26743,
"s": 26712,
"text": "Example 1: Scroll horizontally"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | DOM window scrollby() method </title> <style> body { width: 5000px; } a:focus { background-color: magenta; } button { position: fixed; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>HTML DOM Window.scrollBy() method</h2> <button onclick=\"scrollby()\"> Scroll horizontally! </button> <br><br> <script> function scrollby() { window.scrollBy(100, 0); } </script></body> </html>",
"e": 27373,
"s": 26743,
"text": null
},
{
"code": null,
"e": 27381,
"s": 27373,
"text": "Output:"
},
{
"code": null,
"e": 27406,
"s": 27381,
"text": "Example 2: Using options"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | DOM Window scrollBy() method </title> <style> body { width: 5000px; height:5000px; } a:focus { background-color: magenta; } button { position: fixed; } </style></head> <body> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML DOM Window.scrollBy() method</h2> <div> <button onclick=\"scrollWin(0, 50)\"> Scroll down </button> <br><br> <button onclick=\"scrollWin(0, -50)\"> Scroll up </button> <br><br> <button onclick=\"scrollWin(50, 0)\"> Scroll right </button> <br><br> <button onclick=\"scrollWin(-50, 0)\"> Scroll left </button> </div> <script> function scrollWin(x, y) { window.scrollBy(x, y); } </script></body> </html> ",
"e": 28449,
"s": 27406,
"text": null
},
{
"code": null,
"e": 28457,
"s": 28449,
"text": "Output:"
},
{
"code": null,
"e": 28554,
"s": 28457,
"text": "Supported Browsers: The browser supported by HTML DOM Window scrollBy() method are listed below:"
},
{
"code": null,
"e": 28571,
"s": 28554,
"text": "Google Chrome 45"
},
{
"code": null,
"e": 28579,
"s": 28571,
"text": "Firefox"
},
{
"code": null,
"e": 28588,
"s": 28579,
"text": "Opera 32"
},
{
"code": null,
"e": 28725,
"s": 28588,
"text": "Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28734,
"s": 28725,
"text": "HTML-DOM"
},
{
"code": null,
"e": 28739,
"s": 28734,
"text": "HTML"
},
{
"code": null,
"e": 28756,
"s": 28739,
"text": "Web Technologies"
},
{
"code": null,
"e": 28761,
"s": 28756,
"text": "HTML"
},
{
"code": null,
"e": 28859,
"s": 28761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28883,
"s": 28859,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28924,
"s": 28883,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 28961,
"s": 28924,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28990,
"s": 28961,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29010,
"s": 28990,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29050,
"s": 29010,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29083,
"s": 29050,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29128,
"s": 29083,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29171,
"s": 29128,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
ConcurrentSkipListSet in Java with Examples - GeeksforGeeks
|
11 Nov, 2020
The ConcurrentSkipListSet class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractSet class. It provides a scalable and concurrent version of NavigableSet in Java. The implementation of ConcurrentSkipListSet is based on ConcurrentSkipListMap. The elements in ConcurrentSkipListSet are sorted by default in their natural ordering or by a Comparator provided at set creation time, depending on which constructor is used.
Since it implements SortedSet<E> and NavigableSet<E>, it is similar to TreeSet with an added feature of being concurrent. Since it is a thread-safe, it can be used by multiple threads concurrently whereas TreeSet is not thread-safe.
Class Hierarchy:
Declaration:
public class ConcurrentSkipListSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable
Where E is the type of elements maintained by this collection
Some important points on ConcurrentSkipListSet:
It implements Serializable, Cloneable, Iterable<E>, Collection<E>, NavigableSet<E>, Set<E>, SortedSet<E> interfaces.
It does not allow null elements, because null arguments and return values cannot be reliably distinguished from the absence of elements.
Its implementation provides average log(n) time cost for contains, add, and remove operations and their variants.
It is thread-safe.
It should be preferred over implementing Set interface when concurrent modification of set is required.
Constructors:
1. ConcurrentSkipListSet(): This constructor is used to construct an empty set.
ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>();
2. ConcurrentSkipListSet(Collection<E> c): This constructor is used to construct a set with the elements of the Collection passed as the parameter.
ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>(Collection<E> c);
3. ConcurrentSkipListSet(Comparator<E> comparator): This constructor is used to construct a new, empty set that orders its elements according to the specified comparator.
ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>(Comparator<E> comparator);
4. ConcurrentSkipListSet(SortedSet<E> s): This constructor is used to construct a new set containing the same elements and using the same ordering as the specified sorted set.
ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>(SortedSet<E> s);
Example 1:
Java
// Java program to demonstrate ConcurrentSkipListSet import java.util.*;import java.util.concurrent.ConcurrentSkipListSet; class ConcurrentSkipListSetLastExample1 { public static void main(String[] args) { // Initializing the set using // ConcurrentSkipListSet() ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<Integer>(); // Adding elements to this set set.add(78); set.add(64); set.add(12); set.add(45); set.add(8); // Printing the ConcurrentSkipListSet System.out.println("ConcurrentSkipListSet: " + set); // Initializing the set using // ConcurrentSkipListSet(Collection) ConcurrentSkipListSet<Integer> set1 = new ConcurrentSkipListSet<Integer>(set); // Printing the ConcurrentSkipListSet1 System.out.println("ConcurrentSkipListSet1: " + set1); // Initializing the set using // ConcurrentSkipListSet() ConcurrentSkipListSet<String> set2 = new ConcurrentSkipListSet<>(); // Adding elements to this set set2.add("Apple"); set2.add("Lemon"); set2.add("Banana"); set2.add("Apple"); // creating an iterator Iterator<String> itr = set2.iterator(); System.out.print("Fruits Set: "); while (itr.hasNext()) { System.out.print(itr.next() + " "); } }}
Output:
ConcurrentSkipListSet: [8, 12, 45, 64, 78]
ConcurrentSkipListSet1: [8, 12, 45, 64, 78]
Fruits Set: Apple Banana Lemon
Example 2:
Java
// Java program to demonstrate ConcurrentSkipListSet import java.util.concurrent.ConcurrentSkipListSet; class ConcurrentSkipListSetLastExample1 { public static void main(String[] args) { // Initializing the set using ConcurrentSkipListSet() ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<Integer>(); // Adding elements to this set // using add() method set.add(78); set.add(64); set.add(12); set.add(45); set.add(8); // Printing the ConcurrentSkipListSet System.out.println("ConcurrentSkipListSet: " + set); // Printing the highest element of the set // using last() method System.out.println("The highest element of the set: " + set.last()); // Retrieving and removing first element of the set System.out.println("The first element of the set: " + set.pollFirst()); // Checks if 9 is present in the set // using contains() method if (set.contains(9)) System.out.println("9 is present in the set."); else System.out.println("9 is not present in the set."); // Printing the size of the set // using size() method System.out.println("Number of elements in the set = " + set.size()); }}
Output:
ConcurrentSkipListSet: [8, 12, 45, 64, 78]
The highest element of the set: 78
The first element of the set: 8
9 is not present in the set.
Number of elements in the set = 4
METHOD
DESCRIPTION
subSet(E fromElement, boolean
fromInclusive, E toElement, boolean toInclusive)
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
Ganeshchowdharysadanala
Java - util package
Java-Collections
Java-ConcurrentSkipListSet
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 25049,
"s": 25021,
"text": "\n11 Nov, 2020"
},
{
"code": null,
"e": 25525,
"s": 25049,
"text": "The ConcurrentSkipListSet class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractSet class. It provides a scalable and concurrent version of NavigableSet in Java. The implementation of ConcurrentSkipListSet is based on ConcurrentSkipListMap. The elements in ConcurrentSkipListSet are sorted by default in their natural ordering or by a Comparator provided at set creation time, depending on which constructor is used."
},
{
"code": null,
"e": 25758,
"s": 25525,
"text": "Since it implements SortedSet<E> and NavigableSet<E>, it is similar to TreeSet with an added feature of being concurrent. Since it is a thread-safe, it can be used by multiple threads concurrently whereas TreeSet is not thread-safe."
},
{
"code": null,
"e": 25776,
"s": 25758,
"text": "Class Hierarchy: "
},
{
"code": null,
"e": 25790,
"s": 25776,
"text": "Declaration: "
},
{
"code": null,
"e": 25979,
"s": 25790,
"text": "public class ConcurrentSkipListSet<E>\n extends AbstractSet<E>\n implements NavigableSet<E>, Cloneable, Serializable\n\nWhere E is the type of elements maintained by this collection\n"
},
{
"code": null,
"e": 26027,
"s": 25979,
"text": "Some important points on ConcurrentSkipListSet:"
},
{
"code": null,
"e": 26144,
"s": 26027,
"text": "It implements Serializable, Cloneable, Iterable<E>, Collection<E>, NavigableSet<E>, Set<E>, SortedSet<E> interfaces."
},
{
"code": null,
"e": 26281,
"s": 26144,
"text": "It does not allow null elements, because null arguments and return values cannot be reliably distinguished from the absence of elements."
},
{
"code": null,
"e": 26395,
"s": 26281,
"text": "Its implementation provides average log(n) time cost for contains, add, and remove operations and their variants."
},
{
"code": null,
"e": 26414,
"s": 26395,
"text": "It is thread-safe."
},
{
"code": null,
"e": 26518,
"s": 26414,
"text": "It should be preferred over implementing Set interface when concurrent modification of set is required."
},
{
"code": null,
"e": 26532,
"s": 26518,
"text": "Constructors:"
},
{
"code": null,
"e": 26612,
"s": 26532,
"text": "1. ConcurrentSkipListSet(): This constructor is used to construct an empty set."
},
{
"code": null,
"e": 26675,
"s": 26612,
"text": "ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>();"
},
{
"code": null,
"e": 26823,
"s": 26675,
"text": "2. ConcurrentSkipListSet(Collection<E> c): This constructor is used to construct a set with the elements of the Collection passed as the parameter."
},
{
"code": null,
"e": 26901,
"s": 26823,
"text": "ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>(Collection<E> c);"
},
{
"code": null,
"e": 27072,
"s": 26901,
"text": "3. ConcurrentSkipListSet(Comparator<E> comparator): This constructor is used to construct a new, empty set that orders its elements according to the specified comparator."
},
{
"code": null,
"e": 27159,
"s": 27072,
"text": "ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>(Comparator<E> comparator);"
},
{
"code": null,
"e": 27335,
"s": 27159,
"text": "4. ConcurrentSkipListSet(SortedSet<E> s): This constructor is used to construct a new set containing the same elements and using the same ordering as the specified sorted set."
},
{
"code": null,
"e": 27412,
"s": 27335,
"text": "ConcurrentSkipListSet<E> set = new ConcurrentSkipListSet<E>(SortedSet<E> s);"
},
{
"code": null,
"e": 27423,
"s": 27412,
"text": "Example 1:"
},
{
"code": null,
"e": 27428,
"s": 27423,
"text": "Java"
},
{
"code": "// Java program to demonstrate ConcurrentSkipListSet import java.util.*;import java.util.concurrent.ConcurrentSkipListSet; class ConcurrentSkipListSetLastExample1 { public static void main(String[] args) { // Initializing the set using // ConcurrentSkipListSet() ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<Integer>(); // Adding elements to this set set.add(78); set.add(64); set.add(12); set.add(45); set.add(8); // Printing the ConcurrentSkipListSet System.out.println(\"ConcurrentSkipListSet: \" + set); // Initializing the set using // ConcurrentSkipListSet(Collection) ConcurrentSkipListSet<Integer> set1 = new ConcurrentSkipListSet<Integer>(set); // Printing the ConcurrentSkipListSet1 System.out.println(\"ConcurrentSkipListSet1: \" + set1); // Initializing the set using // ConcurrentSkipListSet() ConcurrentSkipListSet<String> set2 = new ConcurrentSkipListSet<>(); // Adding elements to this set set2.add(\"Apple\"); set2.add(\"Lemon\"); set2.add(\"Banana\"); set2.add(\"Apple\"); // creating an iterator Iterator<String> itr = set2.iterator(); System.out.print(\"Fruits Set: \"); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } }}",
"e": 28890,
"s": 27428,
"text": null
},
{
"code": null,
"e": 28898,
"s": 28890,
"text": "Output:"
},
{
"code": null,
"e": 29017,
"s": 28898,
"text": "ConcurrentSkipListSet: [8, 12, 45, 64, 78]\nConcurrentSkipListSet1: [8, 12, 45, 64, 78]\nFruits Set: Apple Banana Lemon "
},
{
"code": null,
"e": 29031,
"s": 29017,
"text": " Example 2: "
},
{
"code": null,
"e": 29036,
"s": 29031,
"text": "Java"
},
{
"code": "// Java program to demonstrate ConcurrentSkipListSet import java.util.concurrent.ConcurrentSkipListSet; class ConcurrentSkipListSetLastExample1 { public static void main(String[] args) { // Initializing the set using ConcurrentSkipListSet() ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<Integer>(); // Adding elements to this set // using add() method set.add(78); set.add(64); set.add(12); set.add(45); set.add(8); // Printing the ConcurrentSkipListSet System.out.println(\"ConcurrentSkipListSet: \" + set); // Printing the highest element of the set // using last() method System.out.println(\"The highest element of the set: \" + set.last()); // Retrieving and removing first element of the set System.out.println(\"The first element of the set: \" + set.pollFirst()); // Checks if 9 is present in the set // using contains() method if (set.contains(9)) System.out.println(\"9 is present in the set.\"); else System.out.println(\"9 is not present in the set.\"); // Printing the size of the set // using size() method System.out.println(\"Number of elements in the set = \" + set.size()); }}",
"e": 30463,
"s": 29036,
"text": null
},
{
"code": null,
"e": 30471,
"s": 30463,
"text": "Output:"
},
{
"code": null,
"e": 30644,
"s": 30471,
"text": "ConcurrentSkipListSet: [8, 12, 45, 64, 78]\nThe highest element of the set: 78\nThe first element of the set: 8\n9 is not present in the set.\nNumber of elements in the set = 4"
},
{
"code": null,
"e": 30651,
"s": 30644,
"text": "METHOD"
},
{
"code": null,
"e": 30663,
"s": 30651,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 30695,
"s": 30663,
"text": " subSet(E fromElement, boolean "
},
{
"code": null,
"e": 30744,
"s": 30695,
"text": "fromInclusive, E toElement, boolean toInclusive)"
},
{
"code": null,
"e": 30751,
"s": 30744,
"text": "METHOD"
},
{
"code": null,
"e": 30763,
"s": 30751,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 30770,
"s": 30763,
"text": "METHOD"
},
{
"code": null,
"e": 30782,
"s": 30770,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 30789,
"s": 30782,
"text": "METHOD"
},
{
"code": null,
"e": 30801,
"s": 30789,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 30808,
"s": 30801,
"text": "METHOD"
},
{
"code": null,
"e": 30820,
"s": 30808,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 30827,
"s": 30820,
"text": "METHOD"
},
{
"code": null,
"e": 30839,
"s": 30827,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 30863,
"s": 30839,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 30883,
"s": 30863,
"text": "Java - util package"
},
{
"code": null,
"e": 30900,
"s": 30883,
"text": "Java-Collections"
},
{
"code": null,
"e": 30927,
"s": 30900,
"text": "Java-ConcurrentSkipListSet"
},
{
"code": null,
"e": 30942,
"s": 30927,
"text": "Java-Functions"
},
{
"code": null,
"e": 30947,
"s": 30942,
"text": "Java"
},
{
"code": null,
"e": 30952,
"s": 30947,
"text": "Java"
},
{
"code": null,
"e": 30969,
"s": 30952,
"text": "Java-Collections"
},
{
"code": null,
"e": 31067,
"s": 30969,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31082,
"s": 31067,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31126,
"s": 31082,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31148,
"s": 31126,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31199,
"s": 31148,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31235,
"s": 31199,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 31260,
"s": 31235,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31290,
"s": 31260,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31309,
"s": 31290,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31324,
"s": 31309,
"text": "Stream In Java"
}
] |
Convert PDF to Image using Python - GeeksforGeeks
|
21 Jan, 2021
Many tools are available on the internet for converting a PDF to an image. In this article, we are going to write code for converting pdf to image and make a handy application in python. Before writing the code we need to install the required module pdf2image and poppler.
pdf2image 1.14.0: This module converts a PDF to a PIL object. To install this module type the below command in the terminal.
pip install pdf2image
poppler: This module allows to read, render, or modify PDF documents. Windows users will have to build or download poppler for Windows. click here to download
You will then have to add the bin/ folder to PATH or use
poppler_path = rβC:\path\to\poppler-xx\binβ as an argument in convert_from_path.
Approach:
Import the pdf2image module
Store a PFD with convert_from_path()
Save image with save()
Below is the Implementation.
PDF File used:
Python
# import modulefrom pdf2image import convert_from_path # Store Pdf with convert_from_path functionimages = convert_from_path('example.pdf') for i in range(len(images)): # Save pages as images in the pdf images[i].save('page'+ str(i) +'.jpg', 'JPEG')
Output:
Letβs write code for Application Using Tkinter: This Script implements the above Implementation into a GUI.
Below is the Implementation.
Python3
from pdf2image import convert_from_pathfrom tkinter import *from tkinter import messagebox def pdf2img(): try: images = convert_from_path(str(e1.get())) for img in images: img.save('new_folder\output.jpg', 'JPEG') except : Result = "NO pdf found" messagebox.showinfo("Result", Result) else: Result = "success" messagebox.showinfo("Result", Result) master = Tk()Label(master, text="File Location").grid(row=0, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1) b = Button(master, text="Convert", command=pdf2img)b.grid(row=0, column=2,columnspan=2, rowspan=2,padx=5, pady=5) mainloop()
Output:
If there is no PDF file at your given location.
ashwinbeec16
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26147,
"s": 26119,
"text": "\n21 Jan, 2021"
},
{
"code": null,
"e": 26420,
"s": 26147,
"text": "Many tools are available on the internet for converting a PDF to an image. In this article, we are going to write code for converting pdf to image and make a handy application in python. Before writing the code we need to install the required module pdf2image and poppler."
},
{
"code": null,
"e": 26545,
"s": 26420,
"text": "pdf2image 1.14.0: This module converts a PDF to a PIL object. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 26567,
"s": 26545,
"text": "pip install pdf2image"
},
{
"code": null,
"e": 26726,
"s": 26567,
"text": "poppler: This module allows to read, render, or modify PDF documents. Windows users will have to build or download poppler for Windows. click here to download"
},
{
"code": null,
"e": 26784,
"s": 26726,
"text": " You will then have to add the bin/ folder to PATH or use"
},
{
"code": null,
"e": 26866,
"s": 26784,
"text": " poppler_path = rβC:\\path\\to\\poppler-xx\\binβ as an argument in convert_from_path."
},
{
"code": null,
"e": 26876,
"s": 26866,
"text": "Approach:"
},
{
"code": null,
"e": 26904,
"s": 26876,
"text": "Import the pdf2image module"
},
{
"code": null,
"e": 26941,
"s": 26904,
"text": "Store a PFD with convert_from_path()"
},
{
"code": null,
"e": 26964,
"s": 26941,
"text": "Save image with save()"
},
{
"code": null,
"e": 26993,
"s": 26964,
"text": "Below is the Implementation."
},
{
"code": null,
"e": 27008,
"s": 26993,
"text": "PDF File used:"
},
{
"code": null,
"e": 27015,
"s": 27008,
"text": "Python"
},
{
"code": "# import modulefrom pdf2image import convert_from_path # Store Pdf with convert_from_path functionimages = convert_from_path('example.pdf') for i in range(len(images)): # Save pages as images in the pdf images[i].save('page'+ str(i) +'.jpg', 'JPEG')",
"e": 27277,
"s": 27015,
"text": null
},
{
"code": null,
"e": 27288,
"s": 27280,
"text": "Output:"
},
{
"code": null,
"e": 27400,
"s": 27292,
"text": "Letβs write code for Application Using Tkinter: This Script implements the above Implementation into a GUI."
},
{
"code": null,
"e": 27431,
"s": 27402,
"text": "Below is the Implementation."
},
{
"code": null,
"e": 27441,
"s": 27433,
"text": "Python3"
},
{
"code": "from pdf2image import convert_from_pathfrom tkinter import *from tkinter import messagebox def pdf2img(): try: images = convert_from_path(str(e1.get())) for img in images: img.save('new_folder\\output.jpg', 'JPEG') except : Result = \"NO pdf found\" messagebox.showinfo(\"Result\", Result) else: Result = \"success\" messagebox.showinfo(\"Result\", Result) master = Tk()Label(master, text=\"File Location\").grid(row=0, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1) b = Button(master, text=\"Convert\", command=pdf2img)b.grid(row=0, column=2,columnspan=2, rowspan=2,padx=5, pady=5) mainloop()",
"e": 28097,
"s": 27441,
"text": null
},
{
"code": null,
"e": 28108,
"s": 28100,
"text": "Output:"
},
{
"code": null,
"e": 28160,
"s": 28112,
"text": "If there is no PDF file at your given location."
},
{
"code": null,
"e": 28177,
"s": 28164,
"text": "ashwinbeec16"
},
{
"code": null,
"e": 28192,
"s": 28177,
"text": "python-utility"
},
{
"code": null,
"e": 28199,
"s": 28192,
"text": "Python"
},
{
"code": null,
"e": 28297,
"s": 28199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28315,
"s": 28297,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28350,
"s": 28315,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28382,
"s": 28350,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28404,
"s": 28382,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28446,
"s": 28404,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28476,
"s": 28446,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28502,
"s": 28476,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28531,
"s": 28502,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28575,
"s": 28531,
"text": "Reading and Writing to text files in Python"
}
] |
p5.js | minute() function - GeeksforGeeks
|
08 Apr, 2019
The minute() function in p5.js is used to return the current minute in the system clock. The value of minute() function lies between 0 to 59.
Syntax:
minute()
Parameters: The function does not accept any parameter.
Return Value: This function returns an integer value which represents the minute time.
Below program illustrates the minute() function in p5.js:
Example: This example uses minute() function to return the current minute in the system clock.
function setup() { // Create Canvas of size 270*80 createCanvas(270, 80);} function draw() { // Set the background color background(220); // Initialize the parameter with // current minute let m = minute(); // Set the text font size textSize(16); // Set the text color fill(color('red')); // Display the result text("Current minute is : "+m, 50, 30);}
Output:
Reference: https://p5js.org/reference/#/p5/minute
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25497,
"s": 25469,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 25639,
"s": 25497,
"text": "The minute() function in p5.js is used to return the current minute in the system clock. The value of minute() function lies between 0 to 59."
},
{
"code": null,
"e": 25647,
"s": 25639,
"text": "Syntax:"
},
{
"code": null,
"e": 25656,
"s": 25647,
"text": "minute()"
},
{
"code": null,
"e": 25712,
"s": 25656,
"text": "Parameters: The function does not accept any parameter."
},
{
"code": null,
"e": 25799,
"s": 25712,
"text": "Return Value: This function returns an integer value which represents the minute time."
},
{
"code": null,
"e": 25857,
"s": 25799,
"text": "Below program illustrates the minute() function in p5.js:"
},
{
"code": null,
"e": 25952,
"s": 25857,
"text": "Example: This example uses minute() function to return the current minute in the system clock."
},
{
"code": "function setup() { // Create Canvas of size 270*80 createCanvas(270, 80);} function draw() { // Set the background color background(220); // Initialize the parameter with // current minute let m = minute(); // Set the text font size textSize(16); // Set the text color fill(color('red')); // Display the result text(\"Current minute is : \"+m, 50, 30);}",
"e": 26369,
"s": 25952,
"text": null
},
{
"code": null,
"e": 26377,
"s": 26369,
"text": "Output:"
},
{
"code": null,
"e": 26427,
"s": 26377,
"text": "Reference: https://p5js.org/reference/#/p5/minute"
},
{
"code": null,
"e": 26444,
"s": 26427,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 26455,
"s": 26444,
"text": "JavaScript"
},
{
"code": null,
"e": 26472,
"s": 26455,
"text": "Web Technologies"
},
{
"code": null,
"e": 26570,
"s": 26472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26610,
"s": 26570,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26655,
"s": 26610,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26716,
"s": 26655,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26788,
"s": 26716,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26840,
"s": 26788,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 26880,
"s": 26840,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26913,
"s": 26880,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26958,
"s": 26913,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27001,
"s": 26958,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Pandas Timestamp.to_pydatetime - GeeksforGeeks
|
27 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.to_pydatetime() function convert a Timestamp object to a native Python datetime object.
Syntax :Timestamp.to_pydatetime()
Parameters :
warn : boolean
Return : datetime object
Example #1: Use Timestamp.to_pydatetime() function to convert the given Timestamp to a native python datetime object.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_pydatetime() function to convert the given Timestamp to pythonβs datetime object.
# convert to datetimets.to_pydatetime()
Output :
As we can see in the output, the Timestamp.to_pydatetime() function has returned a native python datetime object constructed from the given Timestamp object.
Example #2: Use Timestamp.to_pydatetime() function to convert the given Timestamp to a native python datetime object.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_pydatetime() function to convert the given Timestamp to pythonβs datetime object.
# convert to datetimets.to_pydatetime()
Output :
As we can see in the output, the Timestamp.to_pydatetime() function has returned a native python datetime object constructed from the given Timestamp object.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25641,
"s": 25613,
"text": "\n27 Jan, 2019"
},
{
"code": null,
"e": 25855,
"s": 25641,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 25960,
"s": 25855,
"text": "Pandas Timestamp.to_pydatetime() function convert a Timestamp object to a native Python datetime object."
},
{
"code": null,
"e": 25994,
"s": 25960,
"text": "Syntax :Timestamp.to_pydatetime()"
},
{
"code": null,
"e": 26007,
"s": 25994,
"text": "Parameters :"
},
{
"code": null,
"e": 26022,
"s": 26007,
"text": "warn : boolean"
},
{
"code": null,
"e": 26047,
"s": 26022,
"text": "Return : datetime object"
},
{
"code": null,
"e": 26165,
"s": 26047,
"text": "Example #1: Use Timestamp.to_pydatetime() function to convert the given Timestamp to a native python datetime object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)",
"e": 26394,
"s": 26165,
"text": null
},
{
"code": null,
"e": 26403,
"s": 26394,
"text": "Output :"
},
{
"code": null,
"e": 26518,
"s": 26403,
"text": "Now we will use the Timestamp.to_pydatetime() function to convert the given Timestamp to pythonβs datetime object."
},
{
"code": "# convert to datetimets.to_pydatetime()",
"e": 26558,
"s": 26518,
"text": null
},
{
"code": null,
"e": 26567,
"s": 26558,
"text": "Output :"
},
{
"code": null,
"e": 26725,
"s": 26567,
"text": "As we can see in the output, the Timestamp.to_pydatetime() function has returned a native python datetime object constructed from the given Timestamp object."
},
{
"code": null,
"e": 26843,
"s": 26725,
"text": "Example #2: Use Timestamp.to_pydatetime() function to convert the given Timestamp to a native python datetime object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)",
"e": 27071,
"s": 26843,
"text": null
},
{
"code": null,
"e": 27080,
"s": 27071,
"text": "Output :"
},
{
"code": null,
"e": 27195,
"s": 27080,
"text": "Now we will use the Timestamp.to_pydatetime() function to convert the given Timestamp to pythonβs datetime object."
},
{
"code": "# convert to datetimets.to_pydatetime()",
"e": 27235,
"s": 27195,
"text": null
},
{
"code": null,
"e": 27244,
"s": 27235,
"text": "Output :"
},
{
"code": null,
"e": 27402,
"s": 27244,
"text": "As we can see in the output, the Timestamp.to_pydatetime() function has returned a native python datetime object constructed from the given Timestamp object."
},
{
"code": null,
"e": 27426,
"s": 27402,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 27440,
"s": 27426,
"text": "Python-pandas"
},
{
"code": null,
"e": 27447,
"s": 27440,
"text": "Python"
},
{
"code": null,
"e": 27545,
"s": 27447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27563,
"s": 27545,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27598,
"s": 27563,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27630,
"s": 27598,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27672,
"s": 27630,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27698,
"s": 27672,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27727,
"s": 27698,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27771,
"s": 27727,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27808,
"s": 27771,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27844,
"s": 27808,
"text": "Convert integer to string in Python"
}
] |
Python - Distance between collections of inputs - GeeksforGeeks
|
10 Jan, 2020
scipy.stats.cdist(array, axis=0) function calculates the distance between each pair of the two collections of inputs.
Parameters :array: Input array or object having the elements to calculate the distance between each pair of the two collections of inputs.axis: Axis along which to be computed. By default axis = 0
Returns : distance between each pair of the two collections of inputs.
Code #1 : 2D Array
from scipy.spatial.distance import cdista = [[1, 3, 27], [3, 6, 8]]arr1 = cdist(a, a) print("Value of cdist is :", arr1)
Output:
Value of cdist is : [[ 0. 19.33907961]
[19.33907961 0. ]]
Code #2 : 3D Array
from scipy.spatial.distance import cdist arr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print("Value of cdist is :", cdist(arr1, arr1))
Output:
Value of cdist is : [[ 0. 21.11871208 24.91987159 19.33907961]
[21.11871208 0. 5.38516481 2.82842712]
[24.91987159 5.38516481 0. 6.40312424]
[19.33907961 2.82842712 6.40312424 0. ]]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25909,
"s": 25881,
"text": "\n10 Jan, 2020"
},
{
"code": null,
"e": 26027,
"s": 25909,
"text": "scipy.stats.cdist(array, axis=0) function calculates the distance between each pair of the two collections of inputs."
},
{
"code": null,
"e": 26224,
"s": 26027,
"text": "Parameters :array: Input array or object having the elements to calculate the distance between each pair of the two collections of inputs.axis: Axis along which to be computed. By default axis = 0"
},
{
"code": null,
"e": 26295,
"s": 26224,
"text": "Returns : distance between each pair of the two collections of inputs."
},
{
"code": null,
"e": 26314,
"s": 26295,
"text": "Code #1 : 2D Array"
},
{
"code": "from scipy.spatial.distance import cdista = [[1, 3, 27], [3, 6, 8]]arr1 = cdist(a, a) print(\"Value of cdist is :\", arr1) ",
"e": 26438,
"s": 26314,
"text": null
},
{
"code": null,
"e": 26446,
"s": 26438,
"text": "Output:"
},
{
"code": null,
"e": 26522,
"s": 26446,
"text": "Value of cdist is : [[ 0. 19.33907961]\n [19.33907961 0. ]]\n"
},
{
"code": null,
"e": 26541,
"s": 26522,
"text": "Code #2 : 3D Array"
},
{
"code": "from scipy.spatial.distance import cdist arr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print(\"Value of cdist is :\", cdist(arr1, arr1)) ",
"e": 26720,
"s": 26541,
"text": null
},
{
"code": null,
"e": 26728,
"s": 26720,
"text": "Output:"
},
{
"code": null,
"e": 26954,
"s": 26728,
"text": "Value of cdist is : [[ 0. 21.11871208 24.91987159 19.33907961]\n [21.11871208 0. 5.38516481 2.82842712]\n [24.91987159 5.38516481 0. 6.40312424]\n [19.33907961 2.82842712 6.40312424 0. ]]\n"
},
{
"code": null,
"e": 26983,
"s": 26954,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 26996,
"s": 26983,
"text": "Python-scipy"
},
{
"code": null,
"e": 27003,
"s": 26996,
"text": "Python"
},
{
"code": null,
"e": 27101,
"s": 27003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27119,
"s": 27101,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27154,
"s": 27119,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27186,
"s": 27154,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27208,
"s": 27186,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27250,
"s": 27208,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27280,
"s": 27250,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27306,
"s": 27280,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27335,
"s": 27306,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27379,
"s": 27335,
"text": "Reading and Writing to text files in Python"
}
] |
Pyramid form (increasing then decreasing) consecutive array using reduce operations - GeeksforGeeks
|
28 Apr, 2021
We have N (where N > 2) stones of various heights laid out in a row. Task is to make a pyramid from given array of stones. In a pyramid, height of the stones start from 1, increase by 1, until it reaches some value x, then decreases by 1 until it reaches 1 again i.e. the stones should be 1, 2, 3, 4...x β 1, x, x β 1, x β 2 ... 1. All other stones not part of the pyramid should have a height 0. We cannot move any of the stones from their current position, however, by paying a fee of 1, we can reduce the heights of the stones. We wish to minimize the cost of building a pyramid. Output the minimum cost to build this pyramid.Examples:
Input : 1 2 3 4 2 1
Output : 4
The best pyramid that can be formed in this case is:
1 2 3 2 1 0
The cost is thus:
(4 - 2) + (2 - 1) + (1 - 0) = 4
Input : 1 5 2
Output : 4
We make a pyramid 1 2 1
Input : 1 2 1
Output : 0
We already have a pyramid, we do not need to do any
further construction.
By using simple logic, we can prove that the pyramid with the least cost of construction would be that of the maximum height. Also, two temples of same heights would cost the same to construct. This can be shown as follows: Assume the cost of demolishing all the stones to height 0 is x. Assume the cost of demolishing a temple of height h to height 0 is y. Then, if it is possible to construct a temple of height h from given stones, its cost would be x β y.By using this, we can simplify our approach to two main steps: 1. Identify the pyramid of maximum height that can be formed. 2. Calculate the cost of constructing such a pyramid.Step 2 can be completed in O(N) time complexity assuming we know where our pyramid is placed. Thus, our focus should be on decreasing the time complexity of step 1.Naive Approach For each position in the array, we can assume the pyramid starts at that point. We then find the cost of constructing a temple of maximum height from 1 onwards, until a higher height is not possible, that is, assume a pyramid of height 1 is the maximum, then assume 2 is maximum and so on. Out of each of these costs, we then choose the minimum. This approach uses a time complexity of O(N^3).Improved Approach For each position, assume it is the center of a temple. Move to the left and right of this point and attempt to find the maximum height of the temple. This can be done by setting the maximum of height of a temple at position i to be H(i) where H(i) is the height of the stone at that point. We then move to the left. If the height of the stone at this point is less than H(i) β 1, we set the maximum height to now be H(i β 1) + 1. In this way we identify the maximum height for each position. This approach uses a time complexity of O(N^2).Dynamic Programming Approach By modifying the above algorithm slightly, we can attempt to get an O(N) approach. Start at the left, and moving right, find the maximum possible height pyramid that can be created at that position. Assume that the part of the array to the right of that position is a mirror image of the left. If H(i) is the height of stone at position i, then maxHeight(i) = Minimum(H(i), i, maxHeight(i β 1)) This can be explained as follows: The maximum possible height cannot exceed H(i) as we can only decrease the height of stone, not increase. The maximum possible height cannot exceed i, as the pyramid has to start from a height 1. The maximum possible height cannot exceed the maximum possible height of the stone before it β 1, as the stones have to increase by 1 for each step.We calculate a similar value moving from right to left. We then take the minimum of these values for each position. Then by identifying the maximum, we can calculate the minimum cost of constructing a pyramid.
C++
Java
Python3
C#
Javascript
// Program to find minimum cost for pyramid// from given array#include <iostream>using namespace std; #define ull unsigned long long // Returns minimum cost to form a pyramidull minPyramidCost(ull arr[], ull N){ // Store the maximum possible pyramid height ull *left = new ull[N]; ull *right = new ull[N]; // Maximum height at start is 1 left[0] = min(arr[0], (ull)1); // For each position calculate maximum height for (int i = 1; i < N; ++i) left[i] = min(arr[i], min(left[i - 1] + 1, (ull)i + 1)); // Maximum height at end is 1 right[N - 1] = min(arr[N - 1], (ull)1); // For each position calculate maximum height for (int i = N - 2; i >= 0; --i) right[i] = min(arr[i], min(right[i + 1] + 1, N - i)); // Find minimum possible among calculated values ull tot[N]; for (int i = 0; i < N; ++i) tot[i] = min(right[i], left[i]); // Find maximum height of pyramid ull max_ind = 0; for (int i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid ull cost = 0; ull height = tot[max_ind]; // Calculate cost of left half for (int x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for (int x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost;} // Driver codeint main(){ ull arr[] = {1, 2, 3, 4, 2, 1}; ull N = sizeof(arr)/sizeof(arr[0]); cout << minPyramidCost(arr, N); return 0;}
// Java program to find minimum cost for// pyramid from given arrayimport java.util.*; class GFG{ // Returns minimum cost to form a pyramidstatic int minPyramidCost(int arr[], int N){ // Store the maximum possible pyramid height int left[] = new int[N]; int right[] = new int[N]; // Maximum height at start is 1 left[0] = Math.min(arr[0], 1); // For each position calculate maximum height for(int i = 1; i < N; ++i) left[i] = Math.min(arr[i], Math.min(left[i - 1] + 1, i + 1)); // Maximum height at end is 1 right[N - 1] = Math.min(arr[N - 1], 1); // For each position calculate maximum height for(int i = N - 2; i >= 0; --i) right[i] = Math.min(arr[i], Math.min(right[i + 1] + 1, N - i)); // Find minimum possible among // calculated values int tot[] = new int[N]; for(int i = 0; i < N; ++i) tot[i] = Math.min(right[i], left[i]); // Find maximum height of pyramid int max_ind = 0; for(int i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid int cost = 0; int height = tot[max_ind]; // Calculate cost of left half for(int x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for(int x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 2, 1 }; int N = arr.length; System.out.print(minPyramidCost(arr, N));}} // This code is contributed by chitranayal
# Program to find minimum cost for pyramid# from given array # Returns minimum cost to form a pyramiddef minPyramidCost(arr: list, N): # Store the maximum possible pyramid height left = [0] * N right = [0] * N # Maximum height at start is 1 left[0] = min(arr[0], 1) # For each position calculate maximum height for i in range(1, N): left[i] = min(arr[i], min(left[i - 1] + 1, i + 1)) # Maximum height at end is 1 right[N - 1] = min(arr[N - 1], 1) # For each position calculate maximum height for i in range(N - 2, -1, -1): right[i] = min(arr[i], min(right[i + 1] + 1, N - i)) # Find minimum possible among calculated values tot = [0] * N for i in range(N): tot[i] = min(right[i], left[i]) # Find maximum height of pyramid max_ind = 0 for i in range(N): if tot[i] > tot[max_ind]: max_ind = i # Calculate cost of this pyramid cost = 0 height = tot[max_ind] # Calculate cost of left half for x in range(max_ind, -1, -1): cost += arr[x] - height if height > 0: height -= 1 # Calculate cost of right half height = tot[max_ind] - 1 for x in range(max_ind + 1, N): cost += arr[x] - height if height > 0: height -= 1 return cost # Driver Codeif __name__ == "__main__": arr = [1, 2, 3, 4, 2, 1] N = len(arr) print(minPyramidCost(arr, N)) # This code is contributed by# sanjeev2552
// C# program to find minimum cost for// pyramid from given arrayusing System; public class GFG{ // Returns minimum cost to form a pyramidstatic int minPyramidCost(int[] arr, int N){ // Store the maximum possible pyramid height int[] left = new int[N]; int[] right = new int[N]; // Maximum height at start is 1 left[0] = Math.Min(arr[0], 1); // For each position calculate maximum height for(int i = 1; i < N; ++i) left[i] = Math.Min(arr[i], Math.Min(left[i - 1] + 1, i + 1)); // Maximum height at end is 1 right[N - 1] = Math.Min(arr[N - 1], 1); // For each position calculate maximum height for(int i = N - 2; i >= 0; --i) right[i] = Math.Min(arr[i], Math.Min(right[i + 1] + 1, N - i)); // Find minimum possible among // calculated values int[] tot = new int[N]; for(int i = 0; i < N; ++i) tot[i] = Math.Min(right[i], left[i]); // Find maximum height of pyramid int max_ind = 0; for(int i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid int cost = 0; int height = tot[max_ind]; // Calculate cost of left half for(int x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for(int x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost;} // Driver code static public void Main () { int[] arr = { 1, 2, 3, 4, 2, 1 }; int N = arr.Length; Console.WriteLine(minPyramidCost(arr, N)); }} // This code is contributed by avanitrachhadiya2155
<script>// Javascript program to find minimum cost for// pyramid from given array // Returns minimum cost to form a pyramidfunction minPyramidCost(arr,N){ // Store the maximum possible pyramid height let left = new Array(N); let right = new Array(N); // Maximum height at start is 1 left[0] = Math.min(arr[0], 1); // For each position calculate maximum height for(let i = 1; i < N; ++i) left[i] = Math.min(arr[i], Math.min(left[i - 1] + 1, i + 1)); // Maximum height at end is 1 right[N - 1] = Math.min(arr[N - 1], 1); // For each position calculate maximum height for(let i = N - 2; i >= 0; --i) right[i] = Math.min(arr[i], Math.min(right[i + 1] + 1, N - i)); // Find minimum possible among // calculated values let tot = new Array(N); for(let i = 0; i < N; ++i) tot[i] = Math.min(right[i], left[i]); // Find maximum height of pyramid let max_ind = 0; for(let i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid let cost = 0; let height = tot[max_ind]; // Calculate cost of left half for(let x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for(let x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost; } // Driver code let arr=[1, 2, 3, 4, 2, 1 ]; let N = arr.length; document.write(minPyramidCost(arr, N)); // This code is contributed by rag2127. </script>
Output:
4
This approach runs in O(N) time complexity.This article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sanjeev2552
ukasp
avanitrachhadiya2155
rag2127
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Binary Search Tree | DP-24
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Greedy approach vs Dynamic programming
Maximum sum such that no two elements are adjacent
Word Break Problem | DP-32
3 Different ways to print Fibonacci series in Java
Top 50 Dynamic Programming Coding Problems for Interviews
|
[
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 26582,
"s": 25941,
"text": "We have N (where N > 2) stones of various heights laid out in a row. Task is to make a pyramid from given array of stones. In a pyramid, height of the stones start from 1, increase by 1, until it reaches some value x, then decreases by 1 until it reaches 1 again i.e. the stones should be 1, 2, 3, 4...x β 1, x, x β 1, x β 2 ... 1. All other stones not part of the pyramid should have a height 0. We cannot move any of the stones from their current position, however, by paying a fee of 1, we can reduce the heights of the stones. We wish to minimize the cost of building a pyramid. Output the minimum cost to build this pyramid.Examples: "
},
{
"code": null,
"e": 26883,
"s": 26582,
"text": "Input : 1 2 3 4 2 1\nOutput : 4\nThe best pyramid that can be formed in this case is: \n1 2 3 2 1 0\nThe cost is thus:\n(4 - 2) + (2 - 1) + (1 - 0) = 4\n\nInput : 1 5 2\nOutput : 4\nWe make a pyramid 1 2 1\n\nInput : 1 2 1\nOutput : 0\nWe already have a pyramid, we do not need to do any \nfurther construction."
},
{
"code": null,
"e": 29664,
"s": 26883,
"text": "By using simple logic, we can prove that the pyramid with the least cost of construction would be that of the maximum height. Also, two temples of same heights would cost the same to construct. This can be shown as follows: Assume the cost of demolishing all the stones to height 0 is x. Assume the cost of demolishing a temple of height h to height 0 is y. Then, if it is possible to construct a temple of height h from given stones, its cost would be x β y.By using this, we can simplify our approach to two main steps: 1. Identify the pyramid of maximum height that can be formed. 2. Calculate the cost of constructing such a pyramid.Step 2 can be completed in O(N) time complexity assuming we know where our pyramid is placed. Thus, our focus should be on decreasing the time complexity of step 1.Naive Approach For each position in the array, we can assume the pyramid starts at that point. We then find the cost of constructing a temple of maximum height from 1 onwards, until a higher height is not possible, that is, assume a pyramid of height 1 is the maximum, then assume 2 is maximum and so on. Out of each of these costs, we then choose the minimum. This approach uses a time complexity of O(N^3).Improved Approach For each position, assume it is the center of a temple. Move to the left and right of this point and attempt to find the maximum height of the temple. This can be done by setting the maximum of height of a temple at position i to be H(i) where H(i) is the height of the stone at that point. We then move to the left. If the height of the stone at this point is less than H(i) β 1, we set the maximum height to now be H(i β 1) + 1. In this way we identify the maximum height for each position. This approach uses a time complexity of O(N^2).Dynamic Programming Approach By modifying the above algorithm slightly, we can attempt to get an O(N) approach. Start at the left, and moving right, find the maximum possible height pyramid that can be created at that position. Assume that the part of the array to the right of that position is a mirror image of the left. If H(i) is the height of stone at position i, then maxHeight(i) = Minimum(H(i), i, maxHeight(i β 1)) This can be explained as follows: The maximum possible height cannot exceed H(i) as we can only decrease the height of stone, not increase. The maximum possible height cannot exceed i, as the pyramid has to start from a height 1. The maximum possible height cannot exceed the maximum possible height of the stone before it β 1, as the stones have to increase by 1 for each step.We calculate a similar value moving from right to left. We then take the minimum of these values for each position. Then by identifying the maximum, we can calculate the minimum cost of constructing a pyramid. "
},
{
"code": null,
"e": 29668,
"s": 29664,
"text": "C++"
},
{
"code": null,
"e": 29673,
"s": 29668,
"text": "Java"
},
{
"code": null,
"e": 29681,
"s": 29673,
"text": "Python3"
},
{
"code": null,
"e": 29684,
"s": 29681,
"text": "C#"
},
{
"code": null,
"e": 29695,
"s": 29684,
"text": "Javascript"
},
{
"code": "// Program to find minimum cost for pyramid// from given array#include <iostream>using namespace std; #define ull unsigned long long // Returns minimum cost to form a pyramidull minPyramidCost(ull arr[], ull N){ // Store the maximum possible pyramid height ull *left = new ull[N]; ull *right = new ull[N]; // Maximum height at start is 1 left[0] = min(arr[0], (ull)1); // For each position calculate maximum height for (int i = 1; i < N; ++i) left[i] = min(arr[i], min(left[i - 1] + 1, (ull)i + 1)); // Maximum height at end is 1 right[N - 1] = min(arr[N - 1], (ull)1); // For each position calculate maximum height for (int i = N - 2; i >= 0; --i) right[i] = min(arr[i], min(right[i + 1] + 1, N - i)); // Find minimum possible among calculated values ull tot[N]; for (int i = 0; i < N; ++i) tot[i] = min(right[i], left[i]); // Find maximum height of pyramid ull max_ind = 0; for (int i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid ull cost = 0; ull height = tot[max_ind]; // Calculate cost of left half for (int x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for (int x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost;} // Driver codeint main(){ ull arr[] = {1, 2, 3, 4, 2, 1}; ull N = sizeof(arr)/sizeof(arr[0]); cout << minPyramidCost(arr, N); return 0;}",
"e": 31381,
"s": 29695,
"text": null
},
{
"code": "// Java program to find minimum cost for// pyramid from given arrayimport java.util.*; class GFG{ // Returns minimum cost to form a pyramidstatic int minPyramidCost(int arr[], int N){ // Store the maximum possible pyramid height int left[] = new int[N]; int right[] = new int[N]; // Maximum height at start is 1 left[0] = Math.min(arr[0], 1); // For each position calculate maximum height for(int i = 1; i < N; ++i) left[i] = Math.min(arr[i], Math.min(left[i - 1] + 1, i + 1)); // Maximum height at end is 1 right[N - 1] = Math.min(arr[N - 1], 1); // For each position calculate maximum height for(int i = N - 2; i >= 0; --i) right[i] = Math.min(arr[i], Math.min(right[i + 1] + 1, N - i)); // Find minimum possible among // calculated values int tot[] = new int[N]; for(int i = 0; i < N; ++i) tot[i] = Math.min(right[i], left[i]); // Find maximum height of pyramid int max_ind = 0; for(int i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid int cost = 0; int height = tot[max_ind]; // Calculate cost of left half for(int x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for(int x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 2, 1 }; int N = arr.length; System.out.print(minPyramidCost(arr, N));}} // This code is contributed by chitranayal ",
"e": 33317,
"s": 31381,
"text": null
},
{
"code": "# Program to find minimum cost for pyramid# from given array # Returns minimum cost to form a pyramiddef minPyramidCost(arr: list, N): # Store the maximum possible pyramid height left = [0] * N right = [0] * N # Maximum height at start is 1 left[0] = min(arr[0], 1) # For each position calculate maximum height for i in range(1, N): left[i] = min(arr[i], min(left[i - 1] + 1, i + 1)) # Maximum height at end is 1 right[N - 1] = min(arr[N - 1], 1) # For each position calculate maximum height for i in range(N - 2, -1, -1): right[i] = min(arr[i], min(right[i + 1] + 1, N - i)) # Find minimum possible among calculated values tot = [0] * N for i in range(N): tot[i] = min(right[i], left[i]) # Find maximum height of pyramid max_ind = 0 for i in range(N): if tot[i] > tot[max_ind]: max_ind = i # Calculate cost of this pyramid cost = 0 height = tot[max_ind] # Calculate cost of left half for x in range(max_ind, -1, -1): cost += arr[x] - height if height > 0: height -= 1 # Calculate cost of right half height = tot[max_ind] - 1 for x in range(max_ind + 1, N): cost += arr[x] - height if height > 0: height -= 1 return cost # Driver Codeif __name__ == \"__main__\": arr = [1, 2, 3, 4, 2, 1] N = len(arr) print(minPyramidCost(arr, N)) # This code is contributed by# sanjeev2552",
"e": 34811,
"s": 33317,
"text": null
},
{
"code": "// C# program to find minimum cost for// pyramid from given arrayusing System; public class GFG{ // Returns minimum cost to form a pyramidstatic int minPyramidCost(int[] arr, int N){ // Store the maximum possible pyramid height int[] left = new int[N]; int[] right = new int[N]; // Maximum height at start is 1 left[0] = Math.Min(arr[0], 1); // For each position calculate maximum height for(int i = 1; i < N; ++i) left[i] = Math.Min(arr[i], Math.Min(left[i - 1] + 1, i + 1)); // Maximum height at end is 1 right[N - 1] = Math.Min(arr[N - 1], 1); // For each position calculate maximum height for(int i = N - 2; i >= 0; --i) right[i] = Math.Min(arr[i], Math.Min(right[i + 1] + 1, N - i)); // Find minimum possible among // calculated values int[] tot = new int[N]; for(int i = 0; i < N; ++i) tot[i] = Math.Min(right[i], left[i]); // Find maximum height of pyramid int max_ind = 0; for(int i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid int cost = 0; int height = tot[max_ind]; // Calculate cost of left half for(int x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for(int x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost;} // Driver code static public void Main () { int[] arr = { 1, 2, 3, 4, 2, 1 }; int N = arr.Length; Console.WriteLine(minPyramidCost(arr, N)); }} // This code is contributed by avanitrachhadiya2155",
"e": 36797,
"s": 34811,
"text": null
},
{
"code": "<script>// Javascript program to find minimum cost for// pyramid from given array // Returns minimum cost to form a pyramidfunction minPyramidCost(arr,N){ // Store the maximum possible pyramid height let left = new Array(N); let right = new Array(N); // Maximum height at start is 1 left[0] = Math.min(arr[0], 1); // For each position calculate maximum height for(let i = 1; i < N; ++i) left[i] = Math.min(arr[i], Math.min(left[i - 1] + 1, i + 1)); // Maximum height at end is 1 right[N - 1] = Math.min(arr[N - 1], 1); // For each position calculate maximum height for(let i = N - 2; i >= 0; --i) right[i] = Math.min(arr[i], Math.min(right[i + 1] + 1, N - i)); // Find minimum possible among // calculated values let tot = new Array(N); for(let i = 0; i < N; ++i) tot[i] = Math.min(right[i], left[i]); // Find maximum height of pyramid let max_ind = 0; for(let i = 0; i < N; ++i) if (tot[i] > tot[max_ind]) max_ind = i; // Calculate cost of this pyramid let cost = 0; let height = tot[max_ind]; // Calculate cost of left half for(let x = max_ind; x >= 0; --x) { cost += arr[x] - height; if (height > 0) --height; } // Calculate cost of right half height = tot[max_ind] - 1; for(let x = max_ind + 1; x < N; ++x) { cost += arr[x] - height; if (height > 0) --height; } return cost; } // Driver code let arr=[1, 2, 3, 4, 2, 1 ]; let N = arr.length; document.write(minPyramidCost(arr, N)); // This code is contributed by rag2127. </script>",
"e": 38696,
"s": 36797,
"text": null
},
{
"code": null,
"e": 38706,
"s": 38696,
"text": "Output: "
},
{
"code": null,
"e": 38708,
"s": 38706,
"text": "4"
},
{
"code": null,
"e": 39173,
"s": 38708,
"text": "This approach runs in O(N) time complexity.This article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39185,
"s": 39173,
"text": "sanjeev2552"
},
{
"code": null,
"e": 39191,
"s": 39185,
"text": "ukasp"
},
{
"code": null,
"e": 39212,
"s": 39191,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 39220,
"s": 39212,
"text": "rag2127"
},
{
"code": null,
"e": 39240,
"s": 39220,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39260,
"s": 39240,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39358,
"s": 39260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39401,
"s": 39358,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 39461,
"s": 39401,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 39496,
"s": 39461,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 39517,
"s": 39496,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 39573,
"s": 39517,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 39612,
"s": 39573,
"text": "Greedy approach vs Dynamic programming"
},
{
"code": null,
"e": 39663,
"s": 39612,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 39690,
"s": 39663,
"text": "Word Break Problem | DP-32"
},
{
"code": null,
"e": 39741,
"s": 39690,
"text": "3 Different ways to print Fibonacci series in Java"
}
] |
How to create a responsive scrollbox in CSS ? - GeeksforGeeks
|
22 Dec, 2020
The purpose of this article is to create a responsive scrollbar in HTML page structure using CSS.
In CSS, responsive scroll box is an interaction technique which contains text, images, or any other elements. They can be scrolled in preset directions, which allows users to scroll if the contents are larger for the box. Scroll boxes are often used when you donβt want to take up plenty of space with your content. By creating a scroll box, you provide more contents to fit into smaller space.
Approach: To create a responsive scroll box, add a <div> tag and then proceed to create the scroll box. All you need to do is to choose the height and width of the scroll box (make sure that the height of your box is short enough so that you have an overflow of the text, allowing box to scroll down. Add overflow: auto to create a scrolling effect.
Now, you have formatted the text box, you are ready to add content. Format the content of the text box, just like you would do on your HTML page. Once you have added all content, close your <div> tag. You have created a scroll box and your page will instantly look more systematic.
Example:
HTML
<!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1"> <style> table { border-collapse: collapse; border-spacing: 0; width: 100%; border: 0px solid #ddd; } th, td { text-align: left; padding: 8px; } /* width */ ::-webkit-scrollbar { width: 10px; } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #888; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #555; } .scroll { display: block; border: 0px solid red; padding: 5px; margin-top: 5px; width: 100%; height: 100px; overflow-y: scroll; } </style></head> <body> <div class="scroll"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> </div></body> </html>
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
HTML5
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 25011,
"s": 24983,
"text": "\n22 Dec, 2020"
},
{
"code": null,
"e": 25109,
"s": 25011,
"text": "The purpose of this article is to create a responsive scrollbar in HTML page structure using CSS."
},
{
"code": null,
"e": 25504,
"s": 25109,
"text": "In CSS, responsive scroll box is an interaction technique which contains text, images, or any other elements. They can be scrolled in preset directions, which allows users to scroll if the contents are larger for the box. Scroll boxes are often used when you donβt want to take up plenty of space with your content. By creating a scroll box, you provide more contents to fit into smaller space."
},
{
"code": null,
"e": 25856,
"s": 25504,
"text": "Approach: To create a responsive scroll box, add a <div> tag and then proceed to create the scroll box. All you need to do is to choose the height and width of the scroll box (make sure that the height of your box is short enough so that you have an overflow of the text, allowing box to scroll down. Add overflow: auto to create a scrolling effect. "
},
{
"code": null,
"e": 26139,
"s": 25856,
"text": "Now, you have formatted the text box, you are ready to add content. Format the content of the text box, just like you would do on your HTML page. Once you have added all content, close your <div> tag. You have created a scroll box and your page will instantly look more systematic. "
},
{
"code": null,
"e": 26148,
"s": 26139,
"text": "Example:"
},
{
"code": null,
"e": 26153,
"s": 26148,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <style> table { border-collapse: collapse; border-spacing: 0; width: 100%; border: 0px solid #ddd; } th, td { text-align: left; padding: 8px; } /* width */ ::-webkit-scrollbar { width: 10px; } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #888; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #555; } .scroll { display: block; border: 0px solid red; padding: 5px; margin-top: 5px; width: 100%; height: 100px; overflow-y: scroll; } </style></head> <body> <div class=\"scroll\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> </div></body> </html>",
"e": 28029,
"s": 26153,
"text": null
},
{
"code": null,
"e": 28166,
"s": 28029,
"text": "Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28175,
"s": 28166,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28185,
"s": 28175,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28191,
"s": 28185,
"text": "HTML5"
},
{
"code": null,
"e": 28198,
"s": 28191,
"text": "Picked"
},
{
"code": null,
"e": 28202,
"s": 28198,
"text": "CSS"
},
{
"code": null,
"e": 28207,
"s": 28202,
"text": "HTML"
},
{
"code": null,
"e": 28224,
"s": 28207,
"text": "Web Technologies"
},
{
"code": null,
"e": 28251,
"s": 28224,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28256,
"s": 28251,
"text": "HTML"
},
{
"code": null,
"e": 28354,
"s": 28256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28363,
"s": 28354,
"text": "Comments"
},
{
"code": null,
"e": 28376,
"s": 28363,
"text": "Old Comments"
},
{
"code": null,
"e": 28413,
"s": 28376,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28442,
"s": 28413,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28481,
"s": 28442,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28523,
"s": 28481,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28558,
"s": 28523,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28618,
"s": 28558,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28679,
"s": 28618,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28732,
"s": 28679,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 28782,
"s": 28732,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Storage of integer and character values in C
|
We have used the integer and character variables many times in our program. Here we will see how they are stored in the memory.
In C the character values are also stored as integers. In the following code, we shall put 270 into a character type data. So the binary equivalent of 270 is 100001110, but takes only first 8-bits from right. So the result will be (00001110), that is 14. Then stores the value into variable a. It also gives warning for overflow.
In the next variable y, we are trying to store negative number say -130. The negative number will be stored as 2βs complemented method. So the binary of 130 is (10000010). The 2βs complemented value is 01111101 + 1 = 01111110. Here also the right most 8-bits are taken. So the result will be (01111110) = 126
#include <stdio.h>
int main() {
char x = 270;
char y = -130;
printf("The value of x is: %d\n", x);
printf("The value of y is: %d", y);
}
The value of x is: 14
The value of y is: 126
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "We have used the integer and character variables many times in our program. Here we will see how they are stored in the memory."
},
{
"code": null,
"e": 1520,
"s": 1190,
"text": "In C the character values are also stored as integers. In the following code, we shall put 270 into a character type data. So the binary equivalent of 270 is 100001110, but takes only first 8-bits from right. So the result will be (00001110), that is 14. Then stores the value into variable a. It also gives warning for overflow."
},
{
"code": null,
"e": 1829,
"s": 1520,
"text": "In the next variable y, we are trying to store negative number say -130. The negative number will be stored as 2βs complemented method. So the binary of 130 is (10000010). The 2βs complemented value is 01111101 + 1 = 01111110. Here also the right most 8-bits are taken. So the result will be (01111110) = 126"
},
{
"code": null,
"e": 1978,
"s": 1829,
"text": "#include <stdio.h>\nint main() {\n char x = 270;\n char y = -130;\n printf(\"The value of x is: %d\\n\", x);\n printf(\"The value of y is: %d\", y);\n}"
},
{
"code": null,
"e": 2023,
"s": 1978,
"text": "The value of x is: 14\nThe value of y is: 126"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.