title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to remove all non-alphanumeric characters from a string in Java
|
11 Jul, 2020
Given a string str, the task is to remove all non-alphanumeric characters from it and print the modified it. Examples:
Input: @!Geeks-for’Geeks,123 Output: GeeksforGeeks123 Explanation: at symbol(@), exclamation point(!), dash(-), apostrophes(‘), and commas(, ) are removed.
Input: Geeks_for$ Geeks?{}[] Output: GeeksforGeeks Explanation: underscore(_), dollar sign($), white space, question mark(?), curly braces({}), and square bracket([]) are removed.
Input: GeeksforGeeks123 Output: GeeksforGeeks123 Explanation: No need to remove any character, because the given string doesn’t have any non-alphanumeric character.
Method 1: Using ASCII valuesSince the alphanumeric characters lie in the ASCII value range of [65, 90] for uppercase alphabets, [97, 122] for lowercase alphabets, and [48, 57] for digits. Hence traverse the string character by character and fetch the ASCII value of each character. If the ASCII value is not in the above three ranges, then the character is a non-alphanumeric character. Therefore skip such characters and add the rest in another string and print it.
Method 2: Using String.replaceAll() Non-alphanumeric characters comprise of all the characters except alphabets and numbers. It can be punctuation characters like exclamation mark(!), at symbol(@), commas(, ), question mark(?), colon(:), dash(-) etc and special characters like dollar sign($), equal symbol(=), plus sign(+), apostrophes(‘).
The approach is to use the String.replaceAll method to replace all the non-alphanumeric characters with an empty string.
Below is the implementation of the above approach:
Java
// Java program to remove non-alphanumeric// characters from a stringclass GFG { // Function to remove non-alphanumeric // characters from string public static String removeNonAlphanumeric(String str) { // replace the given string // with empty string // except the pattern "[^a-zA-Z0-9]" str = str.replaceAll( "[^a-zA-Z0-9]", ""); // return string return str; } // Driver Code public static void main(String args[]) { // Test Case 1: String str1 = "@!Geeks-for'Geeks, 123"; System.out.println( removeNonAlphanumeric(str1)); // Test Case 2: String str2 = "Geeks_for$ Geeks?{}[]"; System.out.println( removeNonAlphanumeric(str2)); // Test Case 3: String str3 = "GeeksforGeeks123"; System.out.println( removeNonAlphanumeric(str3)); }}
GeeksforGeeks123
GeeksforGeeks
GeeksforGeeks123
Method 3: Using Regular ExpressionAnother approach involved using of regular expression. The string can be easily filtered using the ReGex [^a-zA-Z0-9 ].
ASCII
java-regular-expression
Java-String-Programs
Java Programs
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Jul, 2020"
},
{
"code": null,
"e": 173,
"s": 53,
"text": "Given a string str, the task is to remove all non-alphanumeric characters from it and print the modified it. Examples: "
},
{
"code": null,
"e": 329,
"s": 173,
"text": "Input: @!Geeks-for’Geeks,123 Output: GeeksforGeeks123 Explanation: at symbol(@), exclamation point(!), dash(-), apostrophes(‘), and commas(, ) are removed."
},
{
"code": null,
"e": 509,
"s": 329,
"text": "Input: Geeks_for$ Geeks?{}[] Output: GeeksforGeeks Explanation: underscore(_), dollar sign($), white space, question mark(?), curly braces({}), and square bracket([]) are removed."
},
{
"code": null,
"e": 674,
"s": 509,
"text": "Input: GeeksforGeeks123 Output: GeeksforGeeks123 Explanation: No need to remove any character, because the given string doesn’t have any non-alphanumeric character."
},
{
"code": null,
"e": 1141,
"s": 674,
"text": "Method 1: Using ASCII valuesSince the alphanumeric characters lie in the ASCII value range of [65, 90] for uppercase alphabets, [97, 122] for lowercase alphabets, and [48, 57] for digits. Hence traverse the string character by character and fetch the ASCII value of each character. If the ASCII value is not in the above three ranges, then the character is a non-alphanumeric character. Therefore skip such characters and add the rest in another string and print it."
},
{
"code": null,
"e": 1484,
"s": 1141,
"text": " Method 2: Using String.replaceAll() Non-alphanumeric characters comprise of all the characters except alphabets and numbers. It can be punctuation characters like exclamation mark(!), at symbol(@), commas(, ), question mark(?), colon(:), dash(-) etc and special characters like dollar sign($), equal symbol(=), plus sign(+), apostrophes(‘). "
},
{
"code": null,
"e": 1605,
"s": 1484,
"text": "The approach is to use the String.replaceAll method to replace all the non-alphanumeric characters with an empty string."
},
{
"code": null,
"e": 1657,
"s": 1605,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1662,
"s": 1657,
"text": "Java"
},
{
"code": "// Java program to remove non-alphanumeric// characters from a stringclass GFG { // Function to remove non-alphanumeric // characters from string public static String removeNonAlphanumeric(String str) { // replace the given string // with empty string // except the pattern \"[^a-zA-Z0-9]\" str = str.replaceAll( \"[^a-zA-Z0-9]\", \"\"); // return string return str; } // Driver Code public static void main(String args[]) { // Test Case 1: String str1 = \"@!Geeks-for'Geeks, 123\"; System.out.println( removeNonAlphanumeric(str1)); // Test Case 2: String str2 = \"Geeks_for$ Geeks?{}[]\"; System.out.println( removeNonAlphanumeric(str2)); // Test Case 3: String str3 = \"GeeksforGeeks123\"; System.out.println( removeNonAlphanumeric(str3)); }}",
"e": 2610,
"s": 1662,
"text": null
},
{
"code": null,
"e": 2659,
"s": 2610,
"text": "GeeksforGeeks123\nGeeksforGeeks\nGeeksforGeeks123\n"
},
{
"code": null,
"e": 2814,
"s": 2659,
"text": "Method 3: Using Regular ExpressionAnother approach involved using of regular expression. The string can be easily filtered using the ReGex [^a-zA-Z0-9 ]. "
},
{
"code": null,
"e": 2820,
"s": 2814,
"text": "ASCII"
},
{
"code": null,
"e": 2844,
"s": 2820,
"text": "java-regular-expression"
},
{
"code": null,
"e": 2865,
"s": 2844,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 2879,
"s": 2865,
"text": "Java Programs"
},
{
"code": null,
"e": 2898,
"s": 2879,
"text": "School Programming"
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Strings"
},
{
"code": null,
"e": 2914,
"s": 2906,
"text": "Strings"
}
] |
Teradata - Secondary Index
|
A table can contain only one primary index. More often, you will come across scenarios where the table contains other columns, using which the data is frequently accessed. Teradata will perform full table scan for those queries. Secondary indexes resolve this issue.
Secondary indexes are an alternate path to access the data. There are some differences between the primary index and the secondary index.
Secondary index is not involved in data distribution.
Secondary index is not involved in data distribution.
Secondary index values are stored in sub tables. These tables are built in all AMPs.
Secondary index values are stored in sub tables. These tables are built in all AMPs.
Secondary indexes are optional.
Secondary indexes are optional.
They can be created during table creation or after a table is created.
They can be created during table creation or after a table is created.
They occupy additional space since they build sub-table and they also require maintenance since the sub-tables need to be updated for each new row.
They occupy additional space since they build sub-table and they also require maintenance since the sub-tables need to be updated for each new row.
There are two types of secondary indexes −
Unique Secondary Index (USI)
Non-Unique Secondary Index (NUSI)
A Unique Secondary Index allows only unique values for the columns defined as USI. Accessing the row by USI is a two amp operation.
The following example creates USI on EmployeeNo column of employee table.
CREATE UNIQUE INDEX(EmployeeNo) on employee;
A Non-Unique Secondary Index allows duplicate values for the columns defined as NUSI. Accessing the row by NUSI is all-amp operation.
The following example creates NUSI on FirstName column of employee table.
CREATE INDEX(FirstName) on Employee;
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2897,
"s": 2630,
"text": "A table can contain only one primary index. More often, you will come across scenarios where the table contains other columns, using which the data is frequently accessed. Teradata will perform full table scan for those queries. Secondary indexes resolve this issue."
},
{
"code": null,
"e": 3035,
"s": 2897,
"text": "Secondary indexes are an alternate path to access the data. There are some differences between the primary index and the secondary index."
},
{
"code": null,
"e": 3089,
"s": 3035,
"text": "Secondary index is not involved in data distribution."
},
{
"code": null,
"e": 3143,
"s": 3089,
"text": "Secondary index is not involved in data distribution."
},
{
"code": null,
"e": 3228,
"s": 3143,
"text": "Secondary index values are stored in sub tables. These tables are built in all AMPs."
},
{
"code": null,
"e": 3313,
"s": 3228,
"text": "Secondary index values are stored in sub tables. These tables are built in all AMPs."
},
{
"code": null,
"e": 3345,
"s": 3313,
"text": "Secondary indexes are optional."
},
{
"code": null,
"e": 3377,
"s": 3345,
"text": "Secondary indexes are optional."
},
{
"code": null,
"e": 3448,
"s": 3377,
"text": "They can be created during table creation or after a table is created."
},
{
"code": null,
"e": 3519,
"s": 3448,
"text": "They can be created during table creation or after a table is created."
},
{
"code": null,
"e": 3667,
"s": 3519,
"text": "They occupy additional space since they build sub-table and they also require maintenance since the sub-tables need to be updated for each new row."
},
{
"code": null,
"e": 3815,
"s": 3667,
"text": "They occupy additional space since they build sub-table and they also require maintenance since the sub-tables need to be updated for each new row."
},
{
"code": null,
"e": 3858,
"s": 3815,
"text": "There are two types of secondary indexes −"
},
{
"code": null,
"e": 3887,
"s": 3858,
"text": "Unique Secondary Index (USI)"
},
{
"code": null,
"e": 3921,
"s": 3887,
"text": "Non-Unique Secondary Index (NUSI)"
},
{
"code": null,
"e": 4053,
"s": 3921,
"text": "A Unique Secondary Index allows only unique values for the columns defined as USI. Accessing the row by USI is a two amp operation."
},
{
"code": null,
"e": 4127,
"s": 4053,
"text": "The following example creates USI on EmployeeNo column of employee table."
},
{
"code": null,
"e": 4173,
"s": 4127,
"text": "CREATE UNIQUE INDEX(EmployeeNo) on employee;\n"
},
{
"code": null,
"e": 4307,
"s": 4173,
"text": "A Non-Unique Secondary Index allows duplicate values for the columns defined as NUSI. Accessing the row by NUSI is all-amp operation."
},
{
"code": null,
"e": 4381,
"s": 4307,
"text": "The following example creates NUSI on FirstName column of employee table."
},
{
"code": null,
"e": 4419,
"s": 4381,
"text": "CREATE INDEX(FirstName) on Employee;\n"
},
{
"code": null,
"e": 4426,
"s": 4419,
"text": " Print"
},
{
"code": null,
"e": 4437,
"s": 4426,
"text": " Add Notes"
}
] |
KeyValuePair in C#
|
The KeyValuePair class stores a pair of values in a single list with C#.
Set KeyValuePair and add elements −
var myList = new List<KeyValuePair<string, int>>();
// adding elements
myList.Add(new KeyValuePair<string, int>("Laptop", 20));
myList.Add(new KeyValuePair<string, int>("Desktop", 40));
myList.Add(new KeyValuePair<string, int>("Tablet", 60));
Here is the code to learn how to work with KeyValuePair and display the keys and values −
Using System;
using System.Collections.Generic;
class Program {
static void Main() {
var myList = new List<KeyValuePair<string, int>>();
// adding elements
myList.Add(new KeyValuePair<string, int>("Laptop", 20));
myList.Add(new KeyValuePair<string, int>("Desktop", 40));
myList.Add(new KeyValuePair<string, int>("Tablet", 60));
foreach (var val in myList) {
Console.WriteLine(val);
}
}
}
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "The KeyValuePair class stores a pair of values in a single list with C#."
},
{
"code": null,
"e": 1171,
"s": 1135,
"text": "Set KeyValuePair and add elements −"
},
{
"code": null,
"e": 1415,
"s": 1171,
"text": "var myList = new List<KeyValuePair<string, int>>();\n\n// adding elements\nmyList.Add(new KeyValuePair<string, int>(\"Laptop\", 20));\nmyList.Add(new KeyValuePair<string, int>(\"Desktop\", 40));\nmyList.Add(new KeyValuePair<string, int>(\"Tablet\", 60));"
},
{
"code": null,
"e": 1505,
"s": 1415,
"text": "Here is the code to learn how to work with KeyValuePair and display the keys and values −"
},
{
"code": null,
"e": 1950,
"s": 1505,
"text": "Using System;\nusing System.Collections.Generic;\nclass Program {\n static void Main() {\n var myList = new List<KeyValuePair<string, int>>();\n // adding elements\n myList.Add(new KeyValuePair<string, int>(\"Laptop\", 20));\n myList.Add(new KeyValuePair<string, int>(\"Desktop\", 40));\n myList.Add(new KeyValuePair<string, int>(\"Tablet\", 60));\n foreach (var val in myList) {\n Console.WriteLine(val);\n }\n }\n}"
}
] |
Program to check if an Array is Palindrome or not using STL in C++
|
Given an array arr[n] of n integers, the task is to find whether array is a palindrome or not. We have to do the stated task using STL in C++.
In C++ there is a feature of STL(Standard Template Library), it is a set of C++ template classes which are used to provide the data structures and several functions such as stacks, queues, lists, etc. To use these one must have knowledge of template classes.
Palindrome is a sequence which is read the same from the front or rear of the sequence. Some simple examples of a palindrome are − MADAM, RACECAR, etc. An array would be a palindrome like in the given example below −
So, the task is simple to find out whether the array is a palindrome or not using STL in C++ and print “its a palindrome” if it is a palindrome else “its not a palindrome” if it is not a palindrome.
Input
arr[] = {1, 2, 3, 5, 3, 2, 1}
Output
its a palindrome
Input
arr[] = {1, 2, 3, 4, 5}
Output
its not a palindrome
Set flag = 0 by default in the starting.
Set flag = 0 by default in the starting.
Loop the array i from 0 till size n/2
Loop the array i from 0 till size n/2
For every i check if arr[i]! = arr[n-i-1] then set the flag = 1 and break
For every i check if arr[i]! = arr[n-i-1] then set the flag = 1 and break
After the loop has ended, If flag is 1 the print “its a palindrome” else print “its not a palindrome”.
After the loop has ended, If flag is 1 the print “its a palindrome” else print “its not a palindrome”.
Start 1→ declare function to check if an array is palindrome or not
void check_palindrome(int arr[], int size)
declare int flag = 0
Declare int arr_2[size]
Call memcpy(arr_2, arr, size * sizeof(int))
Call reverse(arr, arr + size)
Loop For int i = 0 and i < size and i++
IF (arr[i] != arr_2[i])
Set flag = 1
Break
End
IF (flag == 0)
Print its a palindrome
End
Else
Print its not a palindrome
End
Step 2→ In main()
Declare int arr[] = { 2,3,4,3,2 }
Declare int size = sizeof(arr) / sizeof(arr[0])
Call check_palindrome(arr, size)
Live Demo
#include <bits/stdc++.h>
using namespace std;
void check_palindrome(int arr[], int size){
int flag = 0;
int arr_2[size];
memcpy(arr_2, arr, size * sizeof(int));
reverse(arr, arr + size);
for (int i = 0; i < size; i++)
if (arr[i] != arr_2[i]){
flag = 1;
break;
}
if (flag == 0)
cout << "its a palindrome\n";
else
cout << "its not a palindrome\n";
}
int main(){
int arr[] = { 2,3,4,3,2 };
int size = sizeof(arr) / sizeof(arr[0]);
check_palindrome(arr, size);
return 0;
}
If run the above code it will generate the following output −
its a palindrome
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "Given an array arr[n] of n integers, the task is to find whether array is a palindrome or not. We have to do the stated task using STL in C++."
},
{
"code": null,
"e": 1464,
"s": 1205,
"text": "In C++ there is a feature of STL(Standard Template Library), it is a set of C++ template classes which are used to provide the data structures and several functions such as stacks, queues, lists, etc. To use these one must have knowledge of template classes."
},
{
"code": null,
"e": 1681,
"s": 1464,
"text": "Palindrome is a sequence which is read the same from the front or rear of the sequence. Some simple examples of a palindrome are − MADAM, RACECAR, etc. An array would be a palindrome like in the given example below −"
},
{
"code": null,
"e": 1880,
"s": 1681,
"text": "So, the task is simple to find out whether the array is a palindrome or not using STL in C++ and print “its a palindrome” if it is a palindrome else “its not a palindrome” if it is not a palindrome."
},
{
"code": null,
"e": 1886,
"s": 1880,
"text": "Input"
},
{
"code": null,
"e": 1916,
"s": 1886,
"text": "arr[] = {1, 2, 3, 5, 3, 2, 1}"
},
{
"code": null,
"e": 1923,
"s": 1916,
"text": "Output"
},
{
"code": null,
"e": 1940,
"s": 1923,
"text": "its a palindrome"
},
{
"code": null,
"e": 1946,
"s": 1940,
"text": "Input"
},
{
"code": null,
"e": 1970,
"s": 1946,
"text": "arr[] = {1, 2, 3, 4, 5}"
},
{
"code": null,
"e": 1977,
"s": 1970,
"text": "Output"
},
{
"code": null,
"e": 1998,
"s": 1977,
"text": "its not a palindrome"
},
{
"code": null,
"e": 2039,
"s": 1998,
"text": "Set flag = 0 by default in the starting."
},
{
"code": null,
"e": 2080,
"s": 2039,
"text": "Set flag = 0 by default in the starting."
},
{
"code": null,
"e": 2118,
"s": 2080,
"text": "Loop the array i from 0 till size n/2"
},
{
"code": null,
"e": 2156,
"s": 2118,
"text": "Loop the array i from 0 till size n/2"
},
{
"code": null,
"e": 2230,
"s": 2156,
"text": "For every i check if arr[i]! = arr[n-i-1] then set the flag = 1 and break"
},
{
"code": null,
"e": 2304,
"s": 2230,
"text": "For every i check if arr[i]! = arr[n-i-1] then set the flag = 1 and break"
},
{
"code": null,
"e": 2407,
"s": 2304,
"text": "After the loop has ended, If flag is 1 the print “its a palindrome” else print “its not a palindrome”."
},
{
"code": null,
"e": 2510,
"s": 2407,
"text": "After the loop has ended, If flag is 1 the print “its a palindrome” else print “its not a palindrome”."
},
{
"code": null,
"e": 3182,
"s": 2510,
"text": "Start 1→ declare function to check if an array is palindrome or not\n void check_palindrome(int arr[], int size)\n declare int flag = 0\n Declare int arr_2[size]\n Call memcpy(arr_2, arr, size * sizeof(int))\n Call reverse(arr, arr + size)\n Loop For int i = 0 and i < size and i++\n IF (arr[i] != arr_2[i])\n Set flag = 1\n Break\n End\n IF (flag == 0)\n Print its a palindrome\n End\n Else\n Print its not a palindrome\n End\nStep 2→ In main()\n Declare int arr[] = { 2,3,4,3,2 }\n Declare int size = sizeof(arr) / sizeof(arr[0])\n Call check_palindrome(arr, size)"
},
{
"code": null,
"e": 3193,
"s": 3182,
"text": " Live Demo"
},
{
"code": null,
"e": 3749,
"s": 3193,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid check_palindrome(int arr[], int size){\n int flag = 0;\n int arr_2[size];\n memcpy(arr_2, arr, size * sizeof(int));\n reverse(arr, arr + size);\n for (int i = 0; i < size; i++)\n if (arr[i] != arr_2[i]){\n flag = 1;\n break;\n }\n if (flag == 0)\n cout << \"its a palindrome\\n\";\n else\n cout << \"its not a palindrome\\n\";\n}\nint main(){\n int arr[] = { 2,3,4,3,2 };\n int size = sizeof(arr) / sizeof(arr[0]);\n check_palindrome(arr, size);\n return 0;\n}"
},
{
"code": null,
"e": 3811,
"s": 3749,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 3828,
"s": 3811,
"text": "its a palindrome"
}
] |
HTML | <thead> valign Attribute - GeeksforGeeks
|
25 Feb, 2022
The HTML thead valign Attribute is used to specify the vertical alignment of content inside the thead Element.
Syntax:
<thead valign="top | middle | bottom | baseline">
Attribute values:
top: It sets the content to top-align.
middle: It sets the content to middle-align.
bottom: It sets the content to bottom-align.
baseline: It sets the content to baseline. The baseline is the line where most of the characters sit. It has a default value.
Note : The HTML
Example:
<!DOCTYPE html><html> <head> <title>HTML <thead> valign Attribute </title> <style> h1 { color: green; } thead { color: blue; } table, tbody, td { border: 1px solid black; border-collapse: collapse; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> HTML thead valign Attribute</h2> <table> <!-- thead tag starts from here --> <thead align="char" valign="bottom" char="M"> <tr> <th>Name</th> <th>User Id</th> </tr> </thead> <!-- thead tag ends here --> <tbody> <tr> <td>Ram</td> <td>@ram_b</td> </tr> <tr> <td>Shashank</td> <td>@shashankla</td> </tr> </tbody> </table> </center></body> </html>
Output:
Supported Browsers: The browsers supported by HTML <thead> valign Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Form validation using HTML and JavaScript
How to Insert Form Data into Database using PHP ?
How to set input type date in dd-mm-yyyy format using HTML ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Express.js express.Router() Function
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 31678,
"s": 31650,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 31789,
"s": 31678,
"text": "The HTML thead valign Attribute is used to specify the vertical alignment of content inside the thead Element."
},
{
"code": null,
"e": 31797,
"s": 31789,
"text": "Syntax:"
},
{
"code": null,
"e": 31847,
"s": 31797,
"text": "<thead valign=\"top | middle | bottom | baseline\">"
},
{
"code": null,
"e": 31865,
"s": 31847,
"text": "Attribute values:"
},
{
"code": null,
"e": 31904,
"s": 31865,
"text": "top: It sets the content to top-align."
},
{
"code": null,
"e": 31949,
"s": 31904,
"text": "middle: It sets the content to middle-align."
},
{
"code": null,
"e": 31994,
"s": 31949,
"text": "bottom: It sets the content to bottom-align."
},
{
"code": null,
"e": 32120,
"s": 31994,
"text": "baseline: It sets the content to baseline. The baseline is the line where most of the characters sit. It has a default value."
},
{
"code": null,
"e": 32136,
"s": 32120,
"text": "Note : The HTML"
},
{
"code": null,
"e": 32145,
"s": 32136,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML <thead> valign Attribute </title> <style> h1 { color: green; } thead { color: blue; } table, tbody, td { border: 1px solid black; border-collapse: collapse; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> HTML thead valign Attribute</h2> <table> <!-- thead tag starts from here --> <thead align=\"char\" valign=\"bottom\" char=\"M\"> <tr> <th>Name</th> <th>User Id</th> </tr> </thead> <!-- thead tag ends here --> <tbody> <tr> <td>Ram</td> <td>@ram_b</td> </tr> <tr> <td>Shashank</td> <td>@shashankla</td> </tr> </tbody> </table> </center></body> </html>",
"e": 33246,
"s": 32145,
"text": null
},
{
"code": null,
"e": 33254,
"s": 33246,
"text": "Output:"
},
{
"code": null,
"e": 33348,
"s": 33254,
"text": "Supported Browsers: The browsers supported by HTML <thead> valign Attribute are listed below:"
},
{
"code": null,
"e": 33362,
"s": 33348,
"text": "Google Chrome"
},
{
"code": null,
"e": 33380,
"s": 33362,
"text": "Internet Explorer"
},
{
"code": null,
"e": 33388,
"s": 33380,
"text": "Firefox"
},
{
"code": null,
"e": 33401,
"s": 33388,
"text": "Apple Safari"
},
{
"code": null,
"e": 33407,
"s": 33401,
"text": "Opera"
},
{
"code": null,
"e": 33544,
"s": 33407,
"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": 33564,
"s": 33544,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 33578,
"s": 33564,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 33594,
"s": 33578,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 33599,
"s": 33594,
"text": "HTML"
},
{
"code": null,
"e": 33616,
"s": 33599,
"text": "Web Technologies"
},
{
"code": null,
"e": 33621,
"s": 33616,
"text": "HTML"
},
{
"code": null,
"e": 33719,
"s": 33621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33728,
"s": 33719,
"text": "Comments"
},
{
"code": null,
"e": 33741,
"s": 33728,
"text": "Old Comments"
},
{
"code": null,
"e": 33803,
"s": 33741,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33853,
"s": 33803,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 33895,
"s": 33853,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 33945,
"s": 33895,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 34006,
"s": 33945,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 34039,
"s": 34006,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34101,
"s": 34039,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34144,
"s": 34101,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 34181,
"s": 34144,
"text": "Express.js express.Router() Function"
}
] |
Data Visualization: How to choose the right chart [Part 2] | by XuanKhanh Nguyen | Towards Data Science
|
This is the second installment in a two-part series on Data Visualization. If you haven’t read Part 1 of this series, I recommend checking that out!
In part 1 of this series, we walked through the first three data visualization functions: relationship, data over time, and ranking plot. In case you need a quick refresher:
Relationship: We use a relationship method to display a connection or correlation between two or more variables. We often use scatter charts or heat maps to show the relationship method.
Data over time: This visualization method shows data over the period to find trends or changes over time. A line chart or an area chart is often used to represent data over a continuous time span.
Ranking: A visualization method displays the relative order of data values. Bar charts are often used to present data points or compare metric values across different subgroups of our data.
For the second part, we’ll discuss the last two data visualization functions: distribution and comparison.
15. Histogram16. Density Curve with Histogram17. Density Plot18. Box Plot19. Strip Plot20. Violin Plot21. Population Pyramid
22. Bubble Chart23. Bullet Chart24. Pie Chart25. Net Pie Chart26. Donut Chart27. TreeMap28. Diverging Bar29. Choropleth Map30. Bubble Map
Disclaimer: I grouped the chart by the purpose of data visualization, but it isn’t perfect. For example, the scatter plots and bubble charts are useful for quickly identifying relationships between numeric variables. However, unlike the scatter plot, each point on the bubble chart is assigned a label or category. Buble charts can also be useful for comparison between data points. Additionally, time can be shown either by having it as a variable on one axis or by animating the data variables changing over time. So bubble charts can be useful for relationships, data over time, and comparison. For those reasons, I consider this as a guide for selecting a chart based on the purpose of analysis or communication needs.
Distribution charts are used to show how variables are distributed over time, helping identify outliers and trends.
When evaluating a distribution, we want to find out the existence (or absence) of patterns and their evolution over time.
A histogram is a vertical bar chart that depicts the distribution of a set of data. Each bar in a histogram represents the tabulated frequency at each interval/bin.
Note:
Histograms plot quantitative data with ranges of the data grouped into bins or intervals, while bar charts plot categorical data.
Bar graphs have space between the columns, while histograms do not.
The histogram shows the distribution of variables, plotting quantitative data, and identifying the frequency of something occurring within a bucketed range of values. In other words, histograms help gives an estimate as to where values are concentrated, what the extremes are, and whether there are any gaps or unusual values. They are also useful for giving a rough view of the probability distribution.
If we are considering just one variable instead, the best visualization to use is the histogram. Since histogram allows us to group continuous data into bins, it provides a good representation of where observations are concentrated. If considering two variables, we use a scatter chart as described previously.
Python Implementation
Here, we want to present the distribution of happiness scores.
plt.hist(happy['Score'], edgecolor = 'black')
A histogram can also be used to compare the data distribution to a theoretical model, such as a normal distribution. This requires using a density scale for the vertical axis.
sns.distplot(happy['Score'], hist=True, kde=True, hist_kws={'edgecolor':'black'}, kde_kws={'linewidth': 4})
Density plots (aka Kernel Density Plots or Density Trace Graph) are used to observe a variable's distribution in a dataset.
This chart is a smoothed version of the histogram and is used in the same concept. It uses a kernel density estimate to show the variable's probability density function, allowing for smoother distributions by smoothing out the noise. Thus, the plots are smooth across bins and are not affected by the number of bins created, creating a more defined distribution shape. The peaks of a density plot help display where values are concentrated over the interval. (see more)
An advantage density plots have over histograms is that they’re better at determining the distribution shape because they’re not affected by the number of bins used (each bar used in a typical histogram).
Density plots are used to study the distribution of one or a few variables. Checking our variables' distribution one by one is probably the first task we should do once getting a new dataset. It delivers a good quantity of information. Several distribution shapes exist; here is an illustration of the six most common ones.
Here, we want to visualize the probability density of the engine displacement in liters (displ)
We use kdeplot function for visualizing the probability density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can plot a single graph for multiple samples, which helps in more efficient data visualization.
# simple density plotsns.kdeplot(car['displ'], shade=True)
The density plot also allows us to compare the distribution of a few variables. However, we should not compare more than three or four since it would make the figure cluttered and unreadable.
cty Record miles per gallon (mpg) for city driving. Here, we want to make a comparison between two class: compact and suv
for class_ in ['compact', 'suv', 'midsize']: # extract the data x = car[car['class'] == class_]['cty'] # plot the data using seaborn sns.kdeplot(x, shade=True, label = '{} '.format(class_))
A box plot or whisker plot summarizes a set of data measured on an interval scale. This type of graph shows the shape of the distribution, its central value, and its variability.
The box plot shows data is distributed based on a five-number statistical summary. A small “box” indicates that most of the information falls within a consistent range, while a larger box displays the data is more widely distributed.
The line that divides the box into two parts represents the median of the data. For example, the median equals 5, meaning the same number of data points below and above 5.
The ends of the box show the upper (Q3) and lower (Q1) quartiles. If the third quartile equals 10, 75% of the observation is lower than 10.
The difference between Q1 and Q3 is called the interquartile range (IQR)
The extreme line shows Q3+1.5xIQR to Q1–1.5xIQR (the highest and lowest value excluding outliers).
Dots (or other markers) beyond the extreme line shows potential outliers.
We use box plots in descriptive data analysis, indicating whether a distribution is skewed and potential unusual observations (outliers) in the data set.
Box plots are also very useful when large numbers of observations are involved and when two or more data sets are being compared.
One drawback of boxplots is that they emphasize the tails of a distribution, which are the least specific data set points. They also hide many of the details of the distribution.
Here, we want to present the distribution of vehicle classes.
plot1 = ax.boxplot(vects, notch=False, vert=True, meanline=True,showmeans=True, patch_artist=True)
A strip plot is a scatter plot where one of the variables is categorical. The strip plot is an alternative to a histogram or a density plot. It is typically used for small data sets (histograms and density plots are usually preferred for larger data sets).
A strip plot can be drawn on its own. Still, it is also a good complement to a box or violin plot in cases we want to show all observations along with some representation of the underlying distribution.
Boxplot is a fantastic way to study distributions. However, some types of distribution can be hidden under the same box. Thus, plotting strip charts and boxplots side-by-side can be useful to display every observation over your boxplot, to be sure not to miss an interesting pattern.
jitter=True helps spread out overlapping points so that all the points don’t fall in single vertical lines above the species
ax = sns.boxplot(car['class'], car['hwy'],boxprops=dict(alpha=0.75))ax = sns.stripplot(car['class'], car['hwy'], jitter=True, edgecolor="gray")
Sometimes the median and mean aren’t enough to understand a dataset. This is where the violin plot comes in. A violin plot is a hybrid of a box plot and a density plot rotated and placed on each side. It is used to visualize the distribution of the data and its probability density.
The “violin” shape of a violin plot comes from the data’s density plot. We turn that density plot sideways and put it on both sides of the box plot, mirroring each other. Each side of a violin is a density estimation to show the distribution shape of the data. Reading the violin shape is exactly how we read a density plot: Wider sections of the violin plot represent a higher probability that members of the population will take on the given value; the skinnier sections represent a lower probability.
Box plots are well explained in many statistics courses, while violin plots are rarely mentioned. One downside of violin plots is that it is not familiar to many readers, we should consider who is our target readers while using violin plots.
Here, we want to compare the distribution of mile per gallon for highway driving across vehicle classes.
sns.violinplot(car['class'], car['hwy'], scale='width', inner='quartile')
Population pyramids are ideal for detecting changes or differences in population patterns. Population pyramids are important graphs for visualizing how populations are composed when looking at groups divided by age and sex.
It is a pair of back-to-back histograms (for each sex) that displays a population's distribution in all age groups and both sexes. The x-axis is used to plot population numbers, and the y-axis lists all age groups. The shape of a population pyramid can be used to interpret a population. For instance, a pyramid with an extensive base and a narrow top section suggests a community with high fertility and death rates. A pyramid with a wider top half and a narrower base would tell an aging population with low fertility rates.
Population pyramids can also be used to speculate a population’s future development. This makes the population pyramids useful for fields such as Ecology, Sociology, and Economics.
Assume we want to show the age-sex distribution of a given population. It a graphic profile of the population’s residents. Sex is shown on the left/right sides, age on the y-axis, and the number of people on the x-axis.
ax[0].barh(range(0, len(df)), df['Male'], align='center', color='#4c85ff')ax[0].set(title='Males')ax[1].barh(range(0, len(df)), df['Female'], align='center', color='#ff68b3')ax[1].set(title='Females')
When analyzing our data, we might be interested in comparing data sets to understand differences or similarities between data points or time periods. I grouped the charts that are most used to compare one or more datasets.
Comparison questions ask how different values or attributes within the data compare to each other.
Note:
Bar charts can be listed under comparison groups since we can compare different groups during the same time period using horizontal for the vertical bar charts.
Tables help you compare exact values to one another. Column and bar charts showcase comparisons across different categories, while line charts excel at showing trends over time.
A bubble chart displays multiple bubbles (circles) in a two-dimensional plot. It is a generalization of the scatter plot, replacing the dots with bubbles.
Like a scatter plot, bubble charts use a cartesian coordinate system to plot points along a grid where the x-axis and y-axis are separate variables. However, unlike a scatter plot, each point is assigned a label or category (either displayed alongside or on a legend). Each plotted point then represents a third variable by the area of its bubble. We can use color to distinguish between categories or used to describe an additional data variable. Time can be shown either by having it as a variable on one axis or by animating the data variables changing over time.
We can use a bubble chart to depict and show relationships between numeric variables. However, marker size as a dimension allows for the comparison between three variables rather than just two. In a single bubble chart, we can make three different pairwise comparisons (X vs. Y, Y vs. Z, X vs. Z) and an overall three-way comparison. It would require multiple two-variable scatter plots to gain the same number of insights; even then, inferring a three-way relationship between data points will not be as direct as in a bubble chart.
Too many bubbles can make the chart hard to read, so bubble charts have a limited data size capacity. This can be somewhat remedied by interactivity: clicking or hovering over bubbles to display hidden information, having an option to reorganize or filter out grouped categories.
px.scatter(happy, x="GDP", y="Score", animation_frame="Year", animation_group="Country", size="Rank", color="Country", hover_name="Country", trendline= "ols")
Bullet charts are used typically to display performance data; they are similar to bar charts but are accompanied by extra visual elements to pack in more context. Originally, Bullet Graphs were developed by Stephen Few as an alternative to dashboard gauges and meters. This is because they often displayed insufficient information, were less space-efficient, and were cluttered with “chartjunk.”
The main bar's length encodes the primary data value in the middle of the chart, known as the feature measure. The line marker that runs perpendicular to the graph's orientation is known as the comparative measure and is used as a target marker to compare against the feature measure value. So if the main bar has passed the relative measure position, we know we hit the goal.
The segmented colored bars behind the feature measure display the qualitative range scores. Each color shade (the three shades of grey in the example above) assigns a performance range rating, for example, low, average, and excellent. When using a bullet chart, we often keep the maximum number of ranges to five.
fig = ff.create_bullet( data, titles='label', subtitles='sublabel', markers='point', measures='performance', ranges='range', orientation='h', measure_colors=['#1e747c', '#7ac7bf'], range_colors=['#F5E1DA', '#F1F1F1'] )
Pie charts are a classic way to show the composition of groups. A pie chart is a circular graph divided into slices. The larger a slice is the more significant portion of the total quantity it represents.
However, it is not generally advisable to use because the area of the pie portions can sometimes become misleading. So, while using pie charts, it is highly recommended to explicitly write down the percentage or numbers for each pie portion.
Pie charts are best suited to depict sections of a whole: the proportional distribution of the data. However, the significant downsides to pie charts are:
Unsuitable for extensive data: as the number of values shown increases, each segment/slice's size becomes smaller and harder to read.
Not great for making accurate comparisons between groups of pie charts.
Cant display the proportion distribution over time.
Assume we want to display a spending habit of a particular customer.
labels = 'Food', 'Housing', 'Saving', 'Gas', 'Insurance', 'Car'spend = [800, 2000, 500, 200, 300, 250]p = plt.pie(spend, # Value labels=labels, # Labels for each sections explode=(0.07, 0, 0, 0, 0, 0), # To slice the perticuler section colors=colors, # Color of each section autopct='%1.1f%%', # Show data in persentage for with 1 decimal point startangle=130, # Start angle of first section shadow=True # Showing shadow of pie chart )
A nested pie chart goes one step further and split every pie chart's outer level into smaller groups. In the inner circle, we treat each number as belonging to its group. In the outer circle, we plot them as members of their original groups.
We first generate a dataframe to work on. In the inner circle, we treat each number as belonging to its group. In the outer circle, we plot them as members of their original groups.
The effect of the donut shape is achieved by setting a width to the pie’s wedges through the wedgeprops argument. For example, we can pass in wedgeprops = dict(linewidth=5) to set the width of the wedge border lines equal to 0.5
# get the datasize = 0.3labels = 'Food', 'Housing', 'Saving', 'Gas', 'Insurance', 'Car'spend = [800, 2000, 500, 200, 300, 250]vals = np.array([[300., 500.], [1800., 200.], [500., 0.],[200., 0.], [150., 150.],[150., 50]])in_labels = 'At Home','Out', 'Rent','Utilities','Saving','', 'Gas','','Car','Health','Tires','Mai# outer levelax.pie(vals.sum(axis=1), # plot the total [60., 32.] = 92 radius=1, # Radius to increase or decrease the size of pie chart labels=labels, # Labels for each sections colors=outer_colors, # Color of each section wedgeprops=dict(linewidth=5,width=size, edgecolor='w') # Add edges to each portion/slice of the pie )# inner levelpatches, texts = ax.pie(vals.flatten(), # using flatten we plot 60, 32 separetly radius=1-size, labels=in_labels, labeldistance=0.8, colors=inner_colors, wedgeprops=dict(linewidth=3,width=size, edgecolor='w'))
A donut chart is essentially a pie chart with an area of the center cut out, making it look like a donut. As donut charts are hollowed out, there is no central point to attract your attention. Where do your eyes go instead?
If we are like most people, our eyes travel around the circumference and judge each piece according to its length. Therefore, we can also think of a donut chart as a stacked bar graph curled around on itself.
Pie charts and donut charts are commonly used to visualize election and census results, revenue by product or division, recycling data, survey responses, budget breakdowns, educational statistics, spending plans, or population segmentation.
As we discussed above, one drawback of pie charts is that it is not useful for making accurate comparisons between groups of pie charts. Since the readers focus on the slices' proportional areas to one another and the chart as a whole, it is tricky to see the differences between slices, especially when comparing multiple pie charts together.
A donut chart resolves this problem because readers tend to focus more on reading the arcs' length instead of comparing the proportions between slices.
trace = go.Pie(labels=labels, values=spend, marker=dict(colors=colors), hole=0.3)
A treemap chart is similar to a pie chart, and it does better work without misleading each group's contributions. Treemap chart allows us to split the whole into hierarchies and then show an internal breakdown of each of these hierarchies. At their simplest, they display shapes in sizes appropriate to their value, so bigger rectangles represent higher values.
We often use treemaps for sales data. They capture relative sizes of data categories, allowing for a quick, high-level summary of the similarities and anomalies within one category and between multiple categories.
Treemap charts are not suitable when our data is not divisible into categories and sub-categories.
Moreover, when we’re encoding data with area and intensity of color, our eyes aren’t great a detecting relatively minor differences in either of these dimensions. If our data is such that our audience needs to make precise comparisons between categories, it’s even more cumbersome when the categories aren’t aligned to a common baseline. We should never make our audience do more work than necessary to understand a graph!
Python allows us to create these charts quickly, as it will calculate each rectangle's size and plot it in a way that fits. We can also combine our treemap with the Matplotlib library’s ability to scale colors against variables to make good looking and easy to understand plots with Python.
Here, we want to display the value counted for each type of car.
Make sure you install squarify!
import squarify# plot the data using squarifysquarify.plot(sizes=label_value.values(), label=labels, color=colors, alpha=0.6)
A diverging bar chart is a bar chart with marks for some dimension members pointing up or right, and the marks for other dimension members point in the opposite direction (down or left, respectively).
Note:
The marks flowing down or left does not necessarily represent negative values.
The divergent line can represent zero, but it can also separate the marks for two-dimension members.
We use diverging bars to see how the items vary based on a single metric and visualize the order and amount of this variance. If our primary objective is to compare each dimension member's trend, a divergent bar chart is a good option.
The drawback to using diverging bar charts is that it’s not easy to compare the values across dimension members with a grouped bar chart.
# plot using horizontal lines and make it look like a column by changing the linewidthax.hlines(y=health.index, xmin=0 , xmax=health['x_plot'], color=colors, linewidth=5)
A choropleth map is a type of thematic map. A set of pre-defined areas is colored or patterned in proportion to a statistical variable representing an aggregate summary of a geographic characteristic within each region. Typically the color scale will be darker for large values and lighter for small values.
We use a choropleth map to visualize how a measurement varies across a geographic area, or it shows the level of variability within a region. For example, we can use a choropleth map to show the percentage of unemployed people by region, with darker color indicating that more people are unemployed.
Note:
A large region doesn’t mean the colored statistic is of more importance than a smaller regional area. The larger area’s statistic may be related to the people in the area rather than the area itself — so we should beware of size distorting our interpretation.
world_map_1 = go.Figure(data=[happiness_rank], layout=layout)
A bubble map uses circles of different sizes to represent a numeric value on a territory. It displays one bubble per geographic coordinate or one bubble per region.
We often use bubble maps for a dataset with:
a list of geographic coordinates (longitude and latitude), and a numeric variable is controlling the size of the bubble.
a list of regions with attributed values and known boundaries. In this case, the bubble map will replace the usual choropleth map.
Note: Bubble map allows avoiding the bias caused by different regional areas in choropleth maps. (large regions tend to have more weight during the observation).
fig = px.scatter_geo( df_today, # provide the Pandas data frame locations='countryCode', # indicate locations color='continent', hover_name='country', # what to display when the mouse hovering on the bubble size='cases', # how large the bubble is projection='equirectangular', title=f'World COVID-19 Cases for {today}')
My note just covered all of what I consider to be the necessities for data visualization. Data visualization isn’t going away anytime soon, so it’s essential to build a foundation of analysis and storytelling, and exploration that you can carry with regardless of the tools or software you end up using. It takes months, sometimes years, to master a skill, so don’t stop learning! If you want to dig deeper into this particular topic, here are some excellent places to start.
Histograms and Density Plots in Python
Histograms and Density Plots in Python
2. The Next Level of Data Visualization in Python
3. A step-by-step guide for creating advanced Python data visualizations with Seaborn / Matplotlib
4. Matplotlib Cheat Sheet
|
[
{
"code": null,
"e": 321,
"s": 172,
"text": "This is the second installment in a two-part series on Data Visualization. If you haven’t read Part 1 of this series, I recommend checking that out!"
},
{
"code": null,
"e": 495,
"s": 321,
"text": "In part 1 of this series, we walked through the first three data visualization functions: relationship, data over time, and ranking plot. In case you need a quick refresher:"
},
{
"code": null,
"e": 682,
"s": 495,
"text": "Relationship: We use a relationship method to display a connection or correlation between two or more variables. We often use scatter charts or heat maps to show the relationship method."
},
{
"code": null,
"e": 879,
"s": 682,
"text": "Data over time: This visualization method shows data over the period to find trends or changes over time. A line chart or an area chart is often used to represent data over a continuous time span."
},
{
"code": null,
"e": 1069,
"s": 879,
"text": "Ranking: A visualization method displays the relative order of data values. Bar charts are often used to present data points or compare metric values across different subgroups of our data."
},
{
"code": null,
"e": 1176,
"s": 1069,
"text": "For the second part, we’ll discuss the last two data visualization functions: distribution and comparison."
},
{
"code": null,
"e": 1301,
"s": 1176,
"text": "15. Histogram16. Density Curve with Histogram17. Density Plot18. Box Plot19. Strip Plot20. Violin Plot21. Population Pyramid"
},
{
"code": null,
"e": 1439,
"s": 1301,
"text": "22. Bubble Chart23. Bullet Chart24. Pie Chart25. Net Pie Chart26. Donut Chart27. TreeMap28. Diverging Bar29. Choropleth Map30. Bubble Map"
},
{
"code": null,
"e": 2162,
"s": 1439,
"text": "Disclaimer: I grouped the chart by the purpose of data visualization, but it isn’t perfect. For example, the scatter plots and bubble charts are useful for quickly identifying relationships between numeric variables. However, unlike the scatter plot, each point on the bubble chart is assigned a label or category. Buble charts can also be useful for comparison between data points. Additionally, time can be shown either by having it as a variable on one axis or by animating the data variables changing over time. So bubble charts can be useful for relationships, data over time, and comparison. For those reasons, I consider this as a guide for selecting a chart based on the purpose of analysis or communication needs."
},
{
"code": null,
"e": 2278,
"s": 2162,
"text": "Distribution charts are used to show how variables are distributed over time, helping identify outliers and trends."
},
{
"code": null,
"e": 2400,
"s": 2278,
"text": "When evaluating a distribution, we want to find out the existence (or absence) of patterns and their evolution over time."
},
{
"code": null,
"e": 2565,
"s": 2400,
"text": "A histogram is a vertical bar chart that depicts the distribution of a set of data. Each bar in a histogram represents the tabulated frequency at each interval/bin."
},
{
"code": null,
"e": 2571,
"s": 2565,
"text": "Note:"
},
{
"code": null,
"e": 2701,
"s": 2571,
"text": "Histograms plot quantitative data with ranges of the data grouped into bins or intervals, while bar charts plot categorical data."
},
{
"code": null,
"e": 2769,
"s": 2701,
"text": "Bar graphs have space between the columns, while histograms do not."
},
{
"code": null,
"e": 3174,
"s": 2769,
"text": "The histogram shows the distribution of variables, plotting quantitative data, and identifying the frequency of something occurring within a bucketed range of values. In other words, histograms help gives an estimate as to where values are concentrated, what the extremes are, and whether there are any gaps or unusual values. They are also useful for giving a rough view of the probability distribution."
},
{
"code": null,
"e": 3485,
"s": 3174,
"text": "If we are considering just one variable instead, the best visualization to use is the histogram. Since histogram allows us to group continuous data into bins, it provides a good representation of where observations are concentrated. If considering two variables, we use a scatter chart as described previously."
},
{
"code": null,
"e": 3507,
"s": 3485,
"text": "Python Implementation"
},
{
"code": null,
"e": 3570,
"s": 3507,
"text": "Here, we want to present the distribution of happiness scores."
},
{
"code": null,
"e": 3616,
"s": 3570,
"text": "plt.hist(happy['Score'], edgecolor = 'black')"
},
{
"code": null,
"e": 3792,
"s": 3616,
"text": "A histogram can also be used to compare the data distribution to a theoretical model, such as a normal distribution. This requires using a density scale for the vertical axis."
},
{
"code": null,
"e": 3925,
"s": 3792,
"text": "sns.distplot(happy['Score'], hist=True, kde=True, hist_kws={'edgecolor':'black'}, kde_kws={'linewidth': 4})"
},
{
"code": null,
"e": 4049,
"s": 3925,
"text": "Density plots (aka Kernel Density Plots or Density Trace Graph) are used to observe a variable's distribution in a dataset."
},
{
"code": null,
"e": 4519,
"s": 4049,
"text": "This chart is a smoothed version of the histogram and is used in the same concept. It uses a kernel density estimate to show the variable's probability density function, allowing for smoother distributions by smoothing out the noise. Thus, the plots are smooth across bins and are not affected by the number of bins created, creating a more defined distribution shape. The peaks of a density plot help display where values are concentrated over the interval. (see more)"
},
{
"code": null,
"e": 4724,
"s": 4519,
"text": "An advantage density plots have over histograms is that they’re better at determining the distribution shape because they’re not affected by the number of bins used (each bar used in a typical histogram)."
},
{
"code": null,
"e": 5048,
"s": 4724,
"text": "Density plots are used to study the distribution of one or a few variables. Checking our variables' distribution one by one is probably the first task we should do once getting a new dataset. It delivers a good quantity of information. Several distribution shapes exist; here is an illustration of the six most common ones."
},
{
"code": null,
"e": 5144,
"s": 5048,
"text": "Here, we want to visualize the probability density of the engine displacement in liters (displ)"
},
{
"code": null,
"e": 5414,
"s": 5144,
"text": "We use kdeplot function for visualizing the probability density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can plot a single graph for multiple samples, which helps in more efficient data visualization."
},
{
"code": null,
"e": 5473,
"s": 5414,
"text": "# simple density plotsns.kdeplot(car['displ'], shade=True)"
},
{
"code": null,
"e": 5665,
"s": 5473,
"text": "The density plot also allows us to compare the distribution of a few variables. However, we should not compare more than three or four since it would make the figure cluttered and unreadable."
},
{
"code": null,
"e": 5787,
"s": 5665,
"text": "cty Record miles per gallon (mpg) for city driving. Here, we want to make a comparison between two class: compact and suv"
},
{
"code": null,
"e": 5989,
"s": 5787,
"text": "for class_ in ['compact', 'suv', 'midsize']: # extract the data x = car[car['class'] == class_]['cty'] # plot the data using seaborn sns.kdeplot(x, shade=True, label = '{} '.format(class_))"
},
{
"code": null,
"e": 6168,
"s": 5989,
"text": "A box plot or whisker plot summarizes a set of data measured on an interval scale. This type of graph shows the shape of the distribution, its central value, and its variability."
},
{
"code": null,
"e": 6402,
"s": 6168,
"text": "The box plot shows data is distributed based on a five-number statistical summary. A small “box” indicates that most of the information falls within a consistent range, while a larger box displays the data is more widely distributed."
},
{
"code": null,
"e": 6574,
"s": 6402,
"text": "The line that divides the box into two parts represents the median of the data. For example, the median equals 5, meaning the same number of data points below and above 5."
},
{
"code": null,
"e": 6714,
"s": 6574,
"text": "The ends of the box show the upper (Q3) and lower (Q1) quartiles. If the third quartile equals 10, 75% of the observation is lower than 10."
},
{
"code": null,
"e": 6787,
"s": 6714,
"text": "The difference between Q1 and Q3 is called the interquartile range (IQR)"
},
{
"code": null,
"e": 6886,
"s": 6787,
"text": "The extreme line shows Q3+1.5xIQR to Q1–1.5xIQR (the highest and lowest value excluding outliers)."
},
{
"code": null,
"e": 6960,
"s": 6886,
"text": "Dots (or other markers) beyond the extreme line shows potential outliers."
},
{
"code": null,
"e": 7114,
"s": 6960,
"text": "We use box plots in descriptive data analysis, indicating whether a distribution is skewed and potential unusual observations (outliers) in the data set."
},
{
"code": null,
"e": 7244,
"s": 7114,
"text": "Box plots are also very useful when large numbers of observations are involved and when two or more data sets are being compared."
},
{
"code": null,
"e": 7423,
"s": 7244,
"text": "One drawback of boxplots is that they emphasize the tails of a distribution, which are the least specific data set points. They also hide many of the details of the distribution."
},
{
"code": null,
"e": 7485,
"s": 7423,
"text": "Here, we want to present the distribution of vehicle classes."
},
{
"code": null,
"e": 7593,
"s": 7485,
"text": "plot1 = ax.boxplot(vects, notch=False, vert=True, meanline=True,showmeans=True, patch_artist=True)"
},
{
"code": null,
"e": 7850,
"s": 7593,
"text": "A strip plot is a scatter plot where one of the variables is categorical. The strip plot is an alternative to a histogram or a density plot. It is typically used for small data sets (histograms and density plots are usually preferred for larger data sets)."
},
{
"code": null,
"e": 8053,
"s": 7850,
"text": "A strip plot can be drawn on its own. Still, it is also a good complement to a box or violin plot in cases we want to show all observations along with some representation of the underlying distribution."
},
{
"code": null,
"e": 8337,
"s": 8053,
"text": "Boxplot is a fantastic way to study distributions. However, some types of distribution can be hidden under the same box. Thus, plotting strip charts and boxplots side-by-side can be useful to display every observation over your boxplot, to be sure not to miss an interesting pattern."
},
{
"code": null,
"e": 8462,
"s": 8337,
"text": "jitter=True helps spread out overlapping points so that all the points don’t fall in single vertical lines above the species"
},
{
"code": null,
"e": 8606,
"s": 8462,
"text": "ax = sns.boxplot(car['class'], car['hwy'],boxprops=dict(alpha=0.75))ax = sns.stripplot(car['class'], car['hwy'], jitter=True, edgecolor=\"gray\")"
},
{
"code": null,
"e": 8889,
"s": 8606,
"text": "Sometimes the median and mean aren’t enough to understand a dataset. This is where the violin plot comes in. A violin plot is a hybrid of a box plot and a density plot rotated and placed on each side. It is used to visualize the distribution of the data and its probability density."
},
{
"code": null,
"e": 9393,
"s": 8889,
"text": "The “violin” shape of a violin plot comes from the data’s density plot. We turn that density plot sideways and put it on both sides of the box plot, mirroring each other. Each side of a violin is a density estimation to show the distribution shape of the data. Reading the violin shape is exactly how we read a density plot: Wider sections of the violin plot represent a higher probability that members of the population will take on the given value; the skinnier sections represent a lower probability."
},
{
"code": null,
"e": 9635,
"s": 9393,
"text": "Box plots are well explained in many statistics courses, while violin plots are rarely mentioned. One downside of violin plots is that it is not familiar to many readers, we should consider who is our target readers while using violin plots."
},
{
"code": null,
"e": 9740,
"s": 9635,
"text": "Here, we want to compare the distribution of mile per gallon for highway driving across vehicle classes."
},
{
"code": null,
"e": 9828,
"s": 9740,
"text": "sns.violinplot(car['class'], car['hwy'], scale='width', inner='quartile')"
},
{
"code": null,
"e": 10052,
"s": 9828,
"text": "Population pyramids are ideal for detecting changes or differences in population patterns. Population pyramids are important graphs for visualizing how populations are composed when looking at groups divided by age and sex."
},
{
"code": null,
"e": 10579,
"s": 10052,
"text": "It is a pair of back-to-back histograms (for each sex) that displays a population's distribution in all age groups and both sexes. The x-axis is used to plot population numbers, and the y-axis lists all age groups. The shape of a population pyramid can be used to interpret a population. For instance, a pyramid with an extensive base and a narrow top section suggests a community with high fertility and death rates. A pyramid with a wider top half and a narrower base would tell an aging population with low fertility rates."
},
{
"code": null,
"e": 10760,
"s": 10579,
"text": "Population pyramids can also be used to speculate a population’s future development. This makes the population pyramids useful for fields such as Ecology, Sociology, and Economics."
},
{
"code": null,
"e": 10980,
"s": 10760,
"text": "Assume we want to show the age-sex distribution of a given population. It a graphic profile of the population’s residents. Sex is shown on the left/right sides, age on the y-axis, and the number of people on the x-axis."
},
{
"code": null,
"e": 11181,
"s": 10980,
"text": "ax[0].barh(range(0, len(df)), df['Male'], align='center', color='#4c85ff')ax[0].set(title='Males')ax[1].barh(range(0, len(df)), df['Female'], align='center', color='#ff68b3')ax[1].set(title='Females')"
},
{
"code": null,
"e": 11404,
"s": 11181,
"text": "When analyzing our data, we might be interested in comparing data sets to understand differences or similarities between data points or time periods. I grouped the charts that are most used to compare one or more datasets."
},
{
"code": null,
"e": 11503,
"s": 11404,
"text": "Comparison questions ask how different values or attributes within the data compare to each other."
},
{
"code": null,
"e": 11509,
"s": 11503,
"text": "Note:"
},
{
"code": null,
"e": 11670,
"s": 11509,
"text": "Bar charts can be listed under comparison groups since we can compare different groups during the same time period using horizontal for the vertical bar charts."
},
{
"code": null,
"e": 11848,
"s": 11670,
"text": "Tables help you compare exact values to one another. Column and bar charts showcase comparisons across different categories, while line charts excel at showing trends over time."
},
{
"code": null,
"e": 12003,
"s": 11848,
"text": "A bubble chart displays multiple bubbles (circles) in a two-dimensional plot. It is a generalization of the scatter plot, replacing the dots with bubbles."
},
{
"code": null,
"e": 12570,
"s": 12003,
"text": "Like a scatter plot, bubble charts use a cartesian coordinate system to plot points along a grid where the x-axis and y-axis are separate variables. However, unlike a scatter plot, each point is assigned a label or category (either displayed alongside or on a legend). Each plotted point then represents a third variable by the area of its bubble. We can use color to distinguish between categories or used to describe an additional data variable. Time can be shown either by having it as a variable on one axis or by animating the data variables changing over time."
},
{
"code": null,
"e": 13104,
"s": 12570,
"text": "We can use a bubble chart to depict and show relationships between numeric variables. However, marker size as a dimension allows for the comparison between three variables rather than just two. In a single bubble chart, we can make three different pairwise comparisons (X vs. Y, Y vs. Z, X vs. Z) and an overall three-way comparison. It would require multiple two-variable scatter plots to gain the same number of insights; even then, inferring a three-way relationship between data points will not be as direct as in a bubble chart."
},
{
"code": null,
"e": 13384,
"s": 13104,
"text": "Too many bubbles can make the chart hard to read, so bubble charts have a limited data size capacity. This can be somewhat remedied by interactivity: clicking or hovering over bubbles to display hidden information, having an option to reorganize or filter out grouped categories."
},
{
"code": null,
"e": 13573,
"s": 13384,
"text": "px.scatter(happy, x=\"GDP\", y=\"Score\", animation_frame=\"Year\", animation_group=\"Country\", size=\"Rank\", color=\"Country\", hover_name=\"Country\", trendline= \"ols\")"
},
{
"code": null,
"e": 13969,
"s": 13573,
"text": "Bullet charts are used typically to display performance data; they are similar to bar charts but are accompanied by extra visual elements to pack in more context. Originally, Bullet Graphs were developed by Stephen Few as an alternative to dashboard gauges and meters. This is because they often displayed insufficient information, were less space-efficient, and were cluttered with “chartjunk.”"
},
{
"code": null,
"e": 14346,
"s": 13969,
"text": "The main bar's length encodes the primary data value in the middle of the chart, known as the feature measure. The line marker that runs perpendicular to the graph's orientation is known as the comparative measure and is used as a target marker to compare against the feature measure value. So if the main bar has passed the relative measure position, we know we hit the goal."
},
{
"code": null,
"e": 14660,
"s": 14346,
"text": "The segmented colored bars behind the feature measure display the qualitative range scores. Each color shade (the three shades of grey in the example above) assigns a performance range rating, for example, low, average, and excellent. When using a bullet chart, we often keep the maximum number of ranges to five."
},
{
"code": null,
"e": 14893,
"s": 14660,
"text": "fig = ff.create_bullet( data, titles='label', subtitles='sublabel', markers='point', measures='performance', ranges='range', orientation='h', measure_colors=['#1e747c', '#7ac7bf'], range_colors=['#F5E1DA', '#F1F1F1'] )"
},
{
"code": null,
"e": 15098,
"s": 14893,
"text": "Pie charts are a classic way to show the composition of groups. A pie chart is a circular graph divided into slices. The larger a slice is the more significant portion of the total quantity it represents."
},
{
"code": null,
"e": 15340,
"s": 15098,
"text": "However, it is not generally advisable to use because the area of the pie portions can sometimes become misleading. So, while using pie charts, it is highly recommended to explicitly write down the percentage or numbers for each pie portion."
},
{
"code": null,
"e": 15495,
"s": 15340,
"text": "Pie charts are best suited to depict sections of a whole: the proportional distribution of the data. However, the significant downsides to pie charts are:"
},
{
"code": null,
"e": 15629,
"s": 15495,
"text": "Unsuitable for extensive data: as the number of values shown increases, each segment/slice's size becomes smaller and harder to read."
},
{
"code": null,
"e": 15701,
"s": 15629,
"text": "Not great for making accurate comparisons between groups of pie charts."
},
{
"code": null,
"e": 15753,
"s": 15701,
"text": "Cant display the proportion distribution over time."
},
{
"code": null,
"e": 15822,
"s": 15753,
"text": "Assume we want to display a spending habit of a particular customer."
},
{
"code": null,
"e": 16334,
"s": 15822,
"text": "labels = 'Food', 'Housing', 'Saving', 'Gas', 'Insurance', 'Car'spend = [800, 2000, 500, 200, 300, 250]p = plt.pie(spend, # Value labels=labels, # Labels for each sections explode=(0.07, 0, 0, 0, 0, 0), # To slice the perticuler section colors=colors, # Color of each section autopct='%1.1f%%', # Show data in persentage for with 1 decimal point startangle=130, # Start angle of first section shadow=True # Showing shadow of pie chart )"
},
{
"code": null,
"e": 16576,
"s": 16334,
"text": "A nested pie chart goes one step further and split every pie chart's outer level into smaller groups. In the inner circle, we treat each number as belonging to its group. In the outer circle, we plot them as members of their original groups."
},
{
"code": null,
"e": 16758,
"s": 16576,
"text": "We first generate a dataframe to work on. In the inner circle, we treat each number as belonging to its group. In the outer circle, we plot them as members of their original groups."
},
{
"code": null,
"e": 16987,
"s": 16758,
"text": "The effect of the donut shape is achieved by setting a width to the pie’s wedges through the wedgeprops argument. For example, we can pass in wedgeprops = dict(linewidth=5) to set the width of the wedge border lines equal to 0.5"
},
{
"code": null,
"e": 17911,
"s": 16987,
"text": "# get the datasize = 0.3labels = 'Food', 'Housing', 'Saving', 'Gas', 'Insurance', 'Car'spend = [800, 2000, 500, 200, 300, 250]vals = np.array([[300., 500.], [1800., 200.], [500., 0.],[200., 0.], [150., 150.],[150., 50]])in_labels = 'At Home','Out', 'Rent','Utilities','Saving','', 'Gas','','Car','Health','Tires','Mai# outer levelax.pie(vals.sum(axis=1), # plot the total [60., 32.] = 92 radius=1, # Radius to increase or decrease the size of pie chart labels=labels, # Labels for each sections colors=outer_colors, # Color of each section wedgeprops=dict(linewidth=5,width=size, edgecolor='w') # Add edges to each portion/slice of the pie )# inner levelpatches, texts = ax.pie(vals.flatten(), # using flatten we plot 60, 32 separetly radius=1-size, labels=in_labels, labeldistance=0.8, colors=inner_colors, wedgeprops=dict(linewidth=3,width=size, edgecolor='w'))"
},
{
"code": null,
"e": 18135,
"s": 17911,
"text": "A donut chart is essentially a pie chart with an area of the center cut out, making it look like a donut. As donut charts are hollowed out, there is no central point to attract your attention. Where do your eyes go instead?"
},
{
"code": null,
"e": 18344,
"s": 18135,
"text": "If we are like most people, our eyes travel around the circumference and judge each piece according to its length. Therefore, we can also think of a donut chart as a stacked bar graph curled around on itself."
},
{
"code": null,
"e": 18585,
"s": 18344,
"text": "Pie charts and donut charts are commonly used to visualize election and census results, revenue by product or division, recycling data, survey responses, budget breakdowns, educational statistics, spending plans, or population segmentation."
},
{
"code": null,
"e": 18929,
"s": 18585,
"text": "As we discussed above, one drawback of pie charts is that it is not useful for making accurate comparisons between groups of pie charts. Since the readers focus on the slices' proportional areas to one another and the chart as a whole, it is tricky to see the differences between slices, especially when comparing multiple pie charts together."
},
{
"code": null,
"e": 19081,
"s": 18929,
"text": "A donut chart resolves this problem because readers tend to focus more on reading the arcs' length instead of comparing the proportions between slices."
},
{
"code": null,
"e": 19205,
"s": 19081,
"text": "trace = go.Pie(labels=labels, values=spend, marker=dict(colors=colors), hole=0.3)"
},
{
"code": null,
"e": 19567,
"s": 19205,
"text": "A treemap chart is similar to a pie chart, and it does better work without misleading each group's contributions. Treemap chart allows us to split the whole into hierarchies and then show an internal breakdown of each of these hierarchies. At their simplest, they display shapes in sizes appropriate to their value, so bigger rectangles represent higher values."
},
{
"code": null,
"e": 19781,
"s": 19567,
"text": "We often use treemaps for sales data. They capture relative sizes of data categories, allowing for a quick, high-level summary of the similarities and anomalies within one category and between multiple categories."
},
{
"code": null,
"e": 19880,
"s": 19781,
"text": "Treemap charts are not suitable when our data is not divisible into categories and sub-categories."
},
{
"code": null,
"e": 20303,
"s": 19880,
"text": "Moreover, when we’re encoding data with area and intensity of color, our eyes aren’t great a detecting relatively minor differences in either of these dimensions. If our data is such that our audience needs to make precise comparisons between categories, it’s even more cumbersome when the categories aren’t aligned to a common baseline. We should never make our audience do more work than necessary to understand a graph!"
},
{
"code": null,
"e": 20594,
"s": 20303,
"text": "Python allows us to create these charts quickly, as it will calculate each rectangle's size and plot it in a way that fits. We can also combine our treemap with the Matplotlib library’s ability to scale colors against variables to make good looking and easy to understand plots with Python."
},
{
"code": null,
"e": 20659,
"s": 20594,
"text": "Here, we want to display the value counted for each type of car."
},
{
"code": null,
"e": 20691,
"s": 20659,
"text": "Make sure you install squarify!"
},
{
"code": null,
"e": 20817,
"s": 20691,
"text": "import squarify# plot the data using squarifysquarify.plot(sizes=label_value.values(), label=labels, color=colors, alpha=0.6)"
},
{
"code": null,
"e": 21018,
"s": 20817,
"text": "A diverging bar chart is a bar chart with marks for some dimension members pointing up or right, and the marks for other dimension members point in the opposite direction (down or left, respectively)."
},
{
"code": null,
"e": 21024,
"s": 21018,
"text": "Note:"
},
{
"code": null,
"e": 21103,
"s": 21024,
"text": "The marks flowing down or left does not necessarily represent negative values."
},
{
"code": null,
"e": 21204,
"s": 21103,
"text": "The divergent line can represent zero, but it can also separate the marks for two-dimension members."
},
{
"code": null,
"e": 21440,
"s": 21204,
"text": "We use diverging bars to see how the items vary based on a single metric and visualize the order and amount of this variance. If our primary objective is to compare each dimension member's trend, a divergent bar chart is a good option."
},
{
"code": null,
"e": 21578,
"s": 21440,
"text": "The drawback to using diverging bar charts is that it’s not easy to compare the values across dimension members with a grouped bar chart."
},
{
"code": null,
"e": 21750,
"s": 21578,
"text": "# plot using horizontal lines and make it look like a column by changing the linewidthax.hlines(y=health.index, xmin=0 , xmax=health['x_plot'], color=colors, linewidth=5)"
},
{
"code": null,
"e": 22058,
"s": 21750,
"text": "A choropleth map is a type of thematic map. A set of pre-defined areas is colored or patterned in proportion to a statistical variable representing an aggregate summary of a geographic characteristic within each region. Typically the color scale will be darker for large values and lighter for small values."
},
{
"code": null,
"e": 22358,
"s": 22058,
"text": "We use a choropleth map to visualize how a measurement varies across a geographic area, or it shows the level of variability within a region. For example, we can use a choropleth map to show the percentage of unemployed people by region, with darker color indicating that more people are unemployed."
},
{
"code": null,
"e": 22364,
"s": 22358,
"text": "Note:"
},
{
"code": null,
"e": 22624,
"s": 22364,
"text": "A large region doesn’t mean the colored statistic is of more importance than a smaller regional area. The larger area’s statistic may be related to the people in the area rather than the area itself — so we should beware of size distorting our interpretation."
},
{
"code": null,
"e": 22686,
"s": 22624,
"text": "world_map_1 = go.Figure(data=[happiness_rank], layout=layout)"
},
{
"code": null,
"e": 22851,
"s": 22686,
"text": "A bubble map uses circles of different sizes to represent a numeric value on a territory. It displays one bubble per geographic coordinate or one bubble per region."
},
{
"code": null,
"e": 22896,
"s": 22851,
"text": "We often use bubble maps for a dataset with:"
},
{
"code": null,
"e": 23017,
"s": 22896,
"text": "a list of geographic coordinates (longitude and latitude), and a numeric variable is controlling the size of the bubble."
},
{
"code": null,
"e": 23148,
"s": 23017,
"text": "a list of regions with attributed values and known boundaries. In this case, the bubble map will replace the usual choropleth map."
},
{
"code": null,
"e": 23310,
"s": 23148,
"text": "Note: Bubble map allows avoiding the bias caused by different regional areas in choropleth maps. (large regions tend to have more weight during the observation)."
},
{
"code": null,
"e": 23651,
"s": 23310,
"text": "fig = px.scatter_geo( df_today, # provide the Pandas data frame locations='countryCode', # indicate locations color='continent', hover_name='country', # what to display when the mouse hovering on the bubble size='cases', # how large the bubble is projection='equirectangular', title=f'World COVID-19 Cases for {today}')"
},
{
"code": null,
"e": 24127,
"s": 23651,
"text": "My note just covered all of what I consider to be the necessities for data visualization. Data visualization isn’t going away anytime soon, so it’s essential to build a foundation of analysis and storytelling, and exploration that you can carry with regardless of the tools or software you end up using. It takes months, sometimes years, to master a skill, so don’t stop learning! If you want to dig deeper into this particular topic, here are some excellent places to start."
},
{
"code": null,
"e": 24166,
"s": 24127,
"text": "Histograms and Density Plots in Python"
},
{
"code": null,
"e": 24205,
"s": 24166,
"text": "Histograms and Density Plots in Python"
},
{
"code": null,
"e": 24255,
"s": 24205,
"text": "2. The Next Level of Data Visualization in Python"
},
{
"code": null,
"e": 24354,
"s": 24255,
"text": "3. A step-by-step guide for creating advanced Python data visualizations with Seaborn / Matplotlib"
}
] |
Can selenium handle Windows based pop up?
|
Selenium can handle Windows based pop up. There may be scenarios where a web page opens more than one window after performing some actions on it. The child windows that get opened may be a pop up containing some information or advertisement.
Selenium uses the getWindowHandles () and getWindowHandle () methods to work with child windows. The getWindowHandles () method contains all the window handle ids of the opened windows. The window id handles are held in the form of Set data structure [containing data type as String].
The getWindowHandle () method is used to store the window handle id of the present active window. As we know, getWindowHandles () method is used to store all the opened window handle ids. To iterate through all the handles, iterator () and next () methods are used.
Since getWindowHandles () stores the window ids in the form of Set data structure, we have to import java.util.Set in our code. Also, for using the iterator () method, we have to import java.util.Iterator and import java.util.List.
Finally to switch to a particular window, switchTo.().window() method is used. The handle id of the window where we want to switch is passed as an argument to that method.
The steps to be followed to implement the above concept −
After the application is launched, let us first store all the window handle ids in a Set data structure with the help of getWindowHandles () method.
After the application is launched, let us first store all the window handle ids in a Set data structure with the help of getWindowHandles () method.
We shall iterate through all the window handle ids with the help of iterator () and next () methods.
We shall iterate through all the window handle ids with the help of iterator () and next () methods.
Let us then grab the current window handle id with the help of getWindowHandle () method.
Let us then grab the current window handle id with the help of getWindowHandle () method.
Then switch to that window with switchTo.().window() method.
Then switch to that window with switchTo.().window() method.
Code Implementation.
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 java.util.Set;
import java.util.Iterator;
public class HandleWindows {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://secure.indeed.com/account/login";
driver.get(url);
//implicit wait
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// store all window handles
Set<String> a = driver.getWindowHandles();
// iterate through handles
Iterator<String> it = a.iterator();
String chlwnd = it.next();
String pwnd = it.next();
// switch to child window
driver.switchTo().window(chlwnd);
System.out.println("Page title "+ driver.getTitle());
// switch to parent window
driver.switchTo().window(pwnd);
System.out.println("Page title "+ driver.getTitle());
driver.quit();
|
[
{
"code": null,
"e": 1304,
"s": 1062,
"text": "Selenium can handle Windows based pop up. There may be scenarios where a web page opens more than one window after performing some actions on it. The child windows that get opened may be a pop up containing some information or advertisement."
},
{
"code": null,
"e": 1589,
"s": 1304,
"text": "Selenium uses the getWindowHandles () and getWindowHandle () methods to work with child windows. The getWindowHandles () method contains all the window handle ids of the opened windows. The window id handles are held in the form of Set data structure [containing data type as String]."
},
{
"code": null,
"e": 1855,
"s": 1589,
"text": "The getWindowHandle () method is used to store the window handle id of the present active window. As we know, getWindowHandles () method is used to store all the opened window handle ids. To iterate through all the handles, iterator () and next () methods are used."
},
{
"code": null,
"e": 2087,
"s": 1855,
"text": "Since getWindowHandles () stores the window ids in the form of Set data structure, we have to import java.util.Set in our code. Also, for using the iterator () method, we have to import java.util.Iterator and import java.util.List."
},
{
"code": null,
"e": 2259,
"s": 2087,
"text": "Finally to switch to a particular window, switchTo.().window() method is used. The handle id of the window where we want to switch is passed as an argument to that method."
},
{
"code": null,
"e": 2317,
"s": 2259,
"text": "The steps to be followed to implement the above concept −"
},
{
"code": null,
"e": 2466,
"s": 2317,
"text": "After the application is launched, let us first store all the window handle ids in a Set data structure with the help of getWindowHandles () method."
},
{
"code": null,
"e": 2615,
"s": 2466,
"text": "After the application is launched, let us first store all the window handle ids in a Set data structure with the help of getWindowHandles () method."
},
{
"code": null,
"e": 2716,
"s": 2615,
"text": "We shall iterate through all the window handle ids with the help of iterator () and next () methods."
},
{
"code": null,
"e": 2817,
"s": 2716,
"text": "We shall iterate through all the window handle ids with the help of iterator () and next () methods."
},
{
"code": null,
"e": 2907,
"s": 2817,
"text": "Let us then grab the current window handle id with the help of getWindowHandle () method."
},
{
"code": null,
"e": 2997,
"s": 2907,
"text": "Let us then grab the current window handle id with the help of getWindowHandle () method."
},
{
"code": null,
"e": 3058,
"s": 2997,
"text": "Then switch to that window with switchTo.().window() method."
},
{
"code": null,
"e": 3119,
"s": 3058,
"text": "Then switch to that window with switchTo.().window() method."
},
{
"code": null,
"e": 3140,
"s": 3119,
"text": "Code Implementation."
},
{
"code": null,
"e": 4316,
"s": 3140,
"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 java.util.Set;\nimport java.util.Iterator;\npublic class HandleWindows {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://secure.indeed.com/account/login\";\n driver.get(url);\n //implicit wait\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // store all window handles\n Set<String> a = driver.getWindowHandles();\n // iterate through handles\n Iterator<String> it = a.iterator();\n String chlwnd = it.next();\n String pwnd = it.next();\n // switch to child window\n driver.switchTo().window(chlwnd);\n System.out.println(\"Page title \"+ driver.getTitle());\n // switch to parent window\n driver.switchTo().window(pwnd);\n System.out.println(\"Page title \"+ driver.getTitle());\n driver.quit();"
}
] |
Printing HELLO with turtle module - GeeksforGeeks
|
06 Oct, 2020
Turtle is a Python Module which allows us to draw a various geometrical illustration by just importing it in Python and using the inbuilt function of the turtle Module. We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Turtle is a beginner-friendly way to learn python by running some basic commands and viewing the turtle do it graphically. It is like a drawing board that allows you to draw over it. The turtle module can be used in both object-oriented and procedure-oriented ways.
Turtle methods used are as follows:
position()– This function is used to get the coordinates/position of the turtle pointer. No parameter is required here as this function is not used for giving input but is used to output the position of turtle in the console window.
Note: To know more about turtle click here. Example:
python3
# Python program to# demonstrate basics of turtle # Importing and making a turtle object# with background color as whiteimport turtle frame = turtle.Screen().bgcolor("White")draw = turtle.Turtle()draw.left(90)draw.forward(100)draw.right(90)draw.forward(100)
Output:
After having learned the basics of turtle, let’s write the code for printing ‘HELLO’. Below is the implementation.
python3
# Python program to# demonstrate printing HELLO# using turtle # Here frame is initialized with# background colour as "White"import turtleframe = turtle.Screen().bgcolor("White")draw = turtle.Turtle() # The colour, width and speed of the pen is initializeddraw.color("Green")draw.width(3)draw.speed(10) # Now lets get started with actual code# printing letter Hdraw.left(90)draw.forward(70)draw.penup()draw.goto(0, 35)draw.pendown()draw.right(90)draw.forward(30)draw.penup()draw.goto(30, 70)draw.pendown()draw.right(90)draw.forward(70) # printing letter Edraw.penup()draw.goto(40, 0)draw.pendown()draw.right(180)draw.forward(70)draw.right(90)draw.forward(35)draw.penup()draw.goto(40, 35)draw.pendown()draw.forward(35)draw.penup()draw.goto(40, 0)draw.pendown()draw.forward(35) # printing letter Ldraw.penup()draw.goto(90, 70)draw.pendown()draw.right(90)draw.forward(70)draw.left(90)draw.forward(35) # printing letter Ldraw.penup()draw.goto(135, 70)draw.pendown()draw.right(90)draw.forward(70)draw.left(90)draw.forward(35) # printing letter Odraw.penup()draw.goto(210, 70)draw.pendown()for i in range(25): draw.right(15) draw.forward(10)
Output:
pulkitagarwal03pulkit
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n06 Oct, 2020"
},
{
"code": null,
"e": 24750,
"s": 24212,
"text": "Turtle is a Python Module which allows us to draw a various geometrical illustration by just importing it in Python and using the inbuilt function of the turtle Module. We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Turtle is a beginner-friendly way to learn python by running some basic commands and viewing the turtle do it graphically. It is like a drawing board that allows you to draw over it. The turtle module can be used in both object-oriented and procedure-oriented ways. "
},
{
"code": null,
"e": 24787,
"s": 24750,
"text": "Turtle methods used are as follows: "
},
{
"code": null,
"e": 25023,
"s": 24789,
"text": "position()– This function is used to get the coordinates/position of the turtle pointer. No parameter is required here as this function is not used for giving input but is used to output the position of turtle in the console window. "
},
{
"code": null,
"e": 25079,
"s": 25025,
"text": "Note: To know more about turtle click here. Example: "
},
{
"code": null,
"e": 25087,
"s": 25079,
"text": "python3"
},
{
"code": "# Python program to# demonstrate basics of turtle # Importing and making a turtle object# with background color as whiteimport turtle frame = turtle.Screen().bgcolor(\"White\")draw = turtle.Turtle()draw.left(90)draw.forward(100)draw.right(90)draw.forward(100)",
"e": 25345,
"s": 25087,
"text": null
},
{
"code": null,
"e": 25355,
"s": 25345,
"text": "Output: "
},
{
"code": null,
"e": 25471,
"s": 25355,
"text": "After having learned the basics of turtle, let’s write the code for printing ‘HELLO’. Below is the implementation. "
},
{
"code": null,
"e": 25479,
"s": 25471,
"text": "python3"
},
{
"code": "# Python program to# demonstrate printing HELLO# using turtle # Here frame is initialized with# background colour as \"White\"import turtleframe = turtle.Screen().bgcolor(\"White\")draw = turtle.Turtle() # The colour, width and speed of the pen is initializeddraw.color(\"Green\")draw.width(3)draw.speed(10) # Now lets get started with actual code# printing letter Hdraw.left(90)draw.forward(70)draw.penup()draw.goto(0, 35)draw.pendown()draw.right(90)draw.forward(30)draw.penup()draw.goto(30, 70)draw.pendown()draw.right(90)draw.forward(70) # printing letter Edraw.penup()draw.goto(40, 0)draw.pendown()draw.right(180)draw.forward(70)draw.right(90)draw.forward(35)draw.penup()draw.goto(40, 35)draw.pendown()draw.forward(35)draw.penup()draw.goto(40, 0)draw.pendown()draw.forward(35) # printing letter Ldraw.penup()draw.goto(90, 70)draw.pendown()draw.right(90)draw.forward(70)draw.left(90)draw.forward(35) # printing letter Ldraw.penup()draw.goto(135, 70)draw.pendown()draw.right(90)draw.forward(70)draw.left(90)draw.forward(35) # printing letter Odraw.penup()draw.goto(210, 70)draw.pendown()for i in range(25): draw.right(15) draw.forward(10)",
"e": 26620,
"s": 25479,
"text": null
},
{
"code": null,
"e": 26630,
"s": 26620,
"text": "Output: "
},
{
"code": null,
"e": 26654,
"s": 26632,
"text": "pulkitagarwal03pulkit"
},
{
"code": null,
"e": 26661,
"s": 26654,
"text": "Python"
},
{
"code": null,
"e": 26759,
"s": 26661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26768,
"s": 26759,
"text": "Comments"
},
{
"code": null,
"e": 26781,
"s": 26768,
"text": "Old Comments"
},
{
"code": null,
"e": 26802,
"s": 26781,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26834,
"s": 26802,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26857,
"s": 26834,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26879,
"s": 26857,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26906,
"s": 26879,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26922,
"s": 26906,
"text": "Deque in Python"
},
{
"code": null,
"e": 26964,
"s": 26922,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27020,
"s": 26964,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27065,
"s": 27020,
"text": "Python - Ways to remove duplicates from list"
}
] |
Shortest path in an unweighted graph - GeeksforGeeks
|
09 Nov, 2021
Given an unweighted graph, a source, and a destination, we need to find the shortest path from source to destination in the graph in the most optimal way.
unweighted graph of 8 vertices
Input: source vertex = 0 and destination vertex is = 7.
Output: Shortest path length is:2
Path is::
0 3 7
Input: source vertex is = 2 and destination vertex is = 6.
Output: Shortest path length is:5
Path is::
2 1 0 3 4 6
One solution is to solve in O(VE) time using Bellman–Ford. If there are no negative weight cycles, then we can solve in O(E + VLogV) time using Dijkstra’s algorithm. Since the graph is unweighted, we can solve this problem in O(V + E) time. The idea is to use a modified version of Breadth-first search in which we keep storing the predecessor of a given vertex while doing the breadth-first search. We first initialize an array dist[0, 1, ...., v-1] such that dist[i] stores the distance of vertex i from the source vertex and array pred[0, 1, ....., v-1] such that pred[i] represents the immediate predecessor of the vertex i in the breadth-first search starting from the source. Now we get the length of the path from source to any other vertex in O(1) time from array d, and for printing the path from source to any vertex we can use array p and that will take O(V) time in worst case as V is the size of array P. So most of the time of the algorithm is spent in doing the Breadth-first search from a given source which we know takes O(V+E) time. Thus the time complexity of our algorithm is O(V+E). Take the following unweighted graph as an example:Following is the complete algorithm for finding the shortest path:
C++
Java
Python3
C#
// CPP code for printing shortest path between// two vertices of unweighted graph#include <bits/stdc++.h>using namespace std; // utility function to form edge between two vertices// source and destvoid add_edge(vector<int> adj[], int src, int dest){ adj[src].push_back(dest); adj[dest].push_back(src);} // a modified version of BFS that stores predecessor// of each vertex in array p// and its distance from source in array dbool BFS(vector<int> adj[], int src, int dest, int v, int pred[], int dist[]){ // a queue to maintain queue of vertices whose // adjacency list is to be scanned as per normal // DFS algorithm list<int> queue; // boolean array visited[] which stores the // information whether ith vertex is reached // at least once in the Breadth first search bool visited[v]; // initially all vertices are unvisited // so v[i] for all i is false // and as no path is yet constructed // dist[i] for all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = INT_MAX; pred[i] = -1; } // now source is first to be visited and // distance from source to itself should be 0 visited[src] = true; dist[src] = 0; queue.push_back(src); // standard BFS algorithm while (!queue.empty()) { int u = queue.front(); queue.pop_front(); for (int i = 0; i < adj[u].size(); i++) { if (visited[adj[u][i]] == false) { visited[adj[u][i]] = true; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.push_back(adj[u][i]); // We stop BFS when we find // destination. if (adj[u][i] == dest) return true; } } } return false;} // utility function to print the shortest distance// between source vertex and destination vertexvoid printShortestDistance(vector<int> adj[], int s, int dest, int v){ // predecessor[i] array stores predecessor of // i and distance array stores distance of i // from s int pred[v], dist[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { cout << "Given source and destination" << " are not connected"; return; } // vector path stores the shortest path vector<int> path; int crawl = dest; path.push_back(crawl); while (pred[crawl] != -1) { path.push_back(pred[crawl]); crawl = pred[crawl]; } // distance from source is in distance array cout << "Shortest path length is : " << dist[dest]; // printing path from source to destination cout << "\nPath is::\n"; for (int i = path.size() - 1; i >= 0; i--) cout << path[i] << " ";} // Driver program to test above functionsint main(){ // no. of vertices int v = 8; // array of vectors is used to store the graph // in the form of an adjacency list vector<int> adj[v]; // Creating graph given in the above diagram. // add_edge function takes adjacency list, source // and destination vertex as argument and forms // an edge between them. add_edge(adj, 0, 1); add_edge(adj, 0, 3); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 3, 7); add_edge(adj, 4, 5); add_edge(adj, 4, 6); add_edge(adj, 4, 7); add_edge(adj, 5, 6); add_edge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v); return 0;}
// Java program to find shortest path in an undirected// graphimport java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList; public class pathUnweighted { // Driver Program public static void main(String args[]) { // No of vertices int v = 8; // Adjacency list for storing which vertices are connected ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(v); for (int i = 0; i < v; i++) { adj.add(new ArrayList<Integer>()); } // Creating graph given in the above diagram. // add_edge function takes adjacency list, source // and destination vertex as argument and forms // an edge between them. addEdge(adj, 0, 1); addEdge(adj, 0, 3); addEdge(adj, 1, 2); addEdge(adj, 3, 4); addEdge(adj, 3, 7); addEdge(adj, 4, 5); addEdge(adj, 4, 6); addEdge(adj, 4, 7); addEdge(adj, 5, 6); addEdge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v); } // function to form edge between two vertices // source and dest private static void addEdge(ArrayList<ArrayList<Integer>> adj, int i, int j) { adj.get(i).add(j); adj.get(j).add(i); } // function to print the shortest distance and path // between source vertex and destination vertex private static void printShortestDistance( ArrayList<ArrayList<Integer>> adj, int s, int dest, int v) { // predecessor[i] array stores predecessor of // i and distance array stores distance of i // from s int pred[] = new int[v]; int dist[] = new int[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { System.out.println("Given source and destination" + "are not connected"); return; } // LinkedList to store path LinkedList<Integer> path = new LinkedList<Integer>(); int crawl = dest; path.add(crawl); while (pred[crawl] != -1) { path.add(pred[crawl]); crawl = pred[crawl]; } // Print distance System.out.println("Shortest path length is: " + dist[dest]); // Print path System.out.println("Path is ::"); for (int i = path.size() - 1; i >= 0; i--) { System.out.print(path.get(i) + " "); } } // a modified version of BFS that stores predecessor // of each vertex in array pred // and its distance from source in array dist private static boolean BFS(ArrayList<ArrayList<Integer>> adj, int src, int dest, int v, int pred[], int dist[]) { // a queue to maintain queue of vertices whose // adjacency list is to be scanned as per normal // BFS algorithm using LinkedList of Integer type LinkedList<Integer> queue = new LinkedList<Integer>(); // boolean array visited[] which stores the // information whether ith vertex is reached // at least once in the Breadth first search boolean visited[] = new boolean[v]; // initially all vertices are unvisited // so v[i] for all i is false // and as no path is yet constructed // dist[i] for all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = Integer.MAX_VALUE; pred[i] = -1; } // now source is first to be visited and // distance from source to itself should be 0 visited[src] = true; dist[src] = 0; queue.add(src); // bfs Algorithm while (!queue.isEmpty()) { int u = queue.remove(); for (int i = 0; i < adj.get(u).size(); i++) { if (visited[adj.get(u).get(i)] == false) { visited[adj.get(u).get(i)] = true; dist[adj.get(u).get(i)] = dist[u] + 1; pred[adj.get(u).get(i)] = u; queue.add(adj.get(u).get(i)); // stopping condition (when we find // our destination) if (adj.get(u).get(i) == dest) return true; } } } return false; }}// This code is contributed by Sahil Vaid
# Python3 code for printing shortest path between# two vertices of unweighted graph # utility function to form edge between two vertices# source and destdef add_edge(adj, src, dest): adj[src].append(dest); adj[dest].append(src); # a modified version of BFS that stores predecessor# of each vertex in array p# and its distance from source in array ddef BFS(adj, src, dest, v, pred, dist): # a queue to maintain queue of vertices whose # adjacency list is to be scanned as per normal # DFS algorithm queue = [] # boolean array visited[] which stores the # information whether ith vertex is reached # at least once in the Breadth first search visited = [False for i in range(v)]; # initially all vertices are unvisited # so v[i] for all i is false # and as no path is yet constructed # dist[i] for all i set to infinity for i in range(v): dist[i] = 1000000 pred[i] = -1; # now source is first to be visited and # distance from source to itself should be 0 visited[src] = True; dist[src] = 0; queue.append(src); # standard BFS algorithm while (len(queue) != 0): u = queue[0]; queue.pop(0); for i in range(len(adj[u])): if (visited[adj[u][i]] == False): visited[adj[u][i]] = True; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.append(adj[u][i]); # We stop BFS when we find # destination. if (adj[u][i] == dest): return True; return False; # utility function to print the shortest distance# between source vertex and destination vertexdef printShortestDistance(adj, s, dest, v): # predecessor[i] array stores predecessor of # i and distance array stores distance of i # from s pred=[0 for i in range(v)] dist=[0 for i in range(v)]; if (BFS(adj, s, dest, v, pred, dist) == False): print("Given source and destination are not connected") # vector path stores the shortest path path = [] crawl = dest; crawl = dest; path.append(crawl); while (pred[crawl] != -1): path.append(pred[crawl]); crawl = pred[crawl]; # distance from source is in distance array print("Shortest path length is : " + str(dist[dest]), end = '') # printing path from source to destination print("\nPath is : : ") for i in range(len(path)-1, -1, -1): print(path[i], end=' ') # Driver program to test above functionsif __name__=='__main__': # no. of vertices v = 8; # array of vectors is used to store the graph # in the form of an adjacency list adj = [[] for i in range(v)]; # Creating graph given in the above diagram. # add_edge function takes adjacency list, source # and destination vertex as argument and forms # an edge between them. add_edge(adj, 0, 1); add_edge(adj, 0, 3); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 3, 7); add_edge(adj, 4, 5); add_edge(adj, 4, 6); add_edge(adj, 4, 7); add_edge(adj, 5, 6); add_edge(adj, 6, 7); source = 0 dest = 7; printShortestDistance(adj, source, dest, v); # This code is contributed by rutvik_56
// C# program to find shortest// path in an undirected graphusing System;using System.Collections.Generic;class pathUnweighted{ // Driver codepublic static void Main(String []args){ // No of vertices int v = 8; // Adjacency list for storing // which vertices are connected List<List<int>> adj = new List<List<int>>(v); for (int i = 0; i < v; i++) { adj.Add(new List<int>()); } // Creating graph given in the // above diagram. add_edge // function takes adjacency list, // source and destination vertex // as argument and forms an edge // between them. addEdge(adj, 0, 1); addEdge(adj, 0, 3); addEdge(adj, 1, 2); addEdge(adj, 3, 4); addEdge(adj, 3, 7); addEdge(adj, 4, 5); addEdge(adj, 4, 6); addEdge(adj, 4, 7); addEdge(adj, 5, 6); addEdge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v);} // function to form edge between// two vertices source and destprivate static void addEdge(List<List<int>> adj, int i, int j){ adj[i].Add(j); adj[j].Add(i);} // function to print the shortest// distance and path between source// vertex and destination vertexprivate static void printShortestDistance(List<List<int>> adj, int s, int dest, int v){ // predecessor[i] array stores // predecessor of i and distance // array stores distance of i // from s int []pred = new int[v]; int []dist = new int[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { Console.WriteLine("Given source and destination" + "are not connected"); return; } // List to store path List<int> path = new List<int>(); int crawl = dest; path.Add(crawl); while (pred[crawl] != -1) { path.Add(pred[crawl]); crawl = pred[crawl]; } // Print distance Console.WriteLine("Shortest path length is: " + dist[dest]); // Print path Console.WriteLine("Path is ::"); for (int i = path.Count - 1; i >= 0; i--) { Console.Write(path[i] + " "); }} // a modified version of BFS that// stores predecessor of each vertex// in array pred and its distance// from source in array distprivate static bool BFS(List<List<int>> adj, int src, int dest, int v, int []pred, int []dist){ // a queue to maintain queue of // vertices whose adjacency list // is to be scanned as per normal // BFS algorithm using List of int type List<int> queue = new List<int>(); // bool array visited[] which // stores the information whether // ith vertex is reached at least // once in the Breadth first search bool []visited = new bool[v]; // initially all vertices are // unvisited so v[i] for all i // is false and as no path is // yet constructed dist[i] for // all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = int.MaxValue; pred[i] = -1; } // now source is first to be // visited and distance from // source to itself should be 0 visited[src] = true; dist[src] = 0; queue.Add(src); // bfs Algorithm while (queue.Count != 0) { int u = queue[0]; queue.RemoveAt(0); for (int i = 0; i < adj[u].Count; i++) { if (visited[adj[u][i]] == false) { visited[adj[u][i]] = true; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.Add(adj[u][i]); // stopping condition (when we // find our destination) if (adj[u][i] == dest) return true; } } } return false;}} // This code is contributed by Rajput-Ji
Shortest path length is : 2
Path is::
0 3 7
Time Complexity : O(V + E) Auxiliary Space: O(V)
svision
Rajput-Ji
rutvik_56
uttamsingh
BFS
cpp-queue
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Check whether a given graph is Bipartite or not
Iterative Depth First Traversal of Graph
m Coloring Problem | Backtracking-5
Kahn's algorithm for Topological Sorting
Best First Search (Informed Search)
Hamiltonian Cycle | Backtracking-6
Longest Path in a Directed Acyclic Graph
Connected Components in an undirected graph
|
[
{
"code": null,
"e": 24551,
"s": 24523,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 24707,
"s": 24551,
"text": "Given an unweighted graph, a source, and a destination, we need to find the shortest path from source to destination in the graph in the most optimal way. "
},
{
"code": null,
"e": 24739,
"s": 24707,
"text": "unweighted graph of 8 vertices "
},
{
"code": null,
"e": 24993,
"s": 24739,
"text": "Input: source vertex = 0 and destination vertex is = 7.\nOutput: Shortest path length is:2\n Path is::\n 0 3 7\n\nInput: source vertex is = 2 and destination vertex is = 6.\nOutput: Shortest path length is:5\n Path is::\n 2 1 0 3 4 6"
},
{
"code": null,
"e": 26215,
"s": 24993,
"text": "One solution is to solve in O(VE) time using Bellman–Ford. If there are no negative weight cycles, then we can solve in O(E + VLogV) time using Dijkstra’s algorithm. Since the graph is unweighted, we can solve this problem in O(V + E) time. The idea is to use a modified version of Breadth-first search in which we keep storing the predecessor of a given vertex while doing the breadth-first search. We first initialize an array dist[0, 1, ...., v-1] such that dist[i] stores the distance of vertex i from the source vertex and array pred[0, 1, ....., v-1] such that pred[i] represents the immediate predecessor of the vertex i in the breadth-first search starting from the source. Now we get the length of the path from source to any other vertex in O(1) time from array d, and for printing the path from source to any vertex we can use array p and that will take O(V) time in worst case as V is the size of array P. So most of the time of the algorithm is spent in doing the Breadth-first search from a given source which we know takes O(V+E) time. Thus the time complexity of our algorithm is O(V+E). Take the following unweighted graph as an example:Following is the complete algorithm for finding the shortest path: "
},
{
"code": null,
"e": 26219,
"s": 26215,
"text": "C++"
},
{
"code": null,
"e": 26224,
"s": 26219,
"text": "Java"
},
{
"code": null,
"e": 26232,
"s": 26224,
"text": "Python3"
},
{
"code": null,
"e": 26235,
"s": 26232,
"text": "C#"
},
{
"code": "// CPP code for printing shortest path between// two vertices of unweighted graph#include <bits/stdc++.h>using namespace std; // utility function to form edge between two vertices// source and destvoid add_edge(vector<int> adj[], int src, int dest){ adj[src].push_back(dest); adj[dest].push_back(src);} // a modified version of BFS that stores predecessor// of each vertex in array p// and its distance from source in array dbool BFS(vector<int> adj[], int src, int dest, int v, int pred[], int dist[]){ // a queue to maintain queue of vertices whose // adjacency list is to be scanned as per normal // DFS algorithm list<int> queue; // boolean array visited[] which stores the // information whether ith vertex is reached // at least once in the Breadth first search bool visited[v]; // initially all vertices are unvisited // so v[i] for all i is false // and as no path is yet constructed // dist[i] for all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = INT_MAX; pred[i] = -1; } // now source is first to be visited and // distance from source to itself should be 0 visited[src] = true; dist[src] = 0; queue.push_back(src); // standard BFS algorithm while (!queue.empty()) { int u = queue.front(); queue.pop_front(); for (int i = 0; i < adj[u].size(); i++) { if (visited[adj[u][i]] == false) { visited[adj[u][i]] = true; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.push_back(adj[u][i]); // We stop BFS when we find // destination. if (adj[u][i] == dest) return true; } } } return false;} // utility function to print the shortest distance// between source vertex and destination vertexvoid printShortestDistance(vector<int> adj[], int s, int dest, int v){ // predecessor[i] array stores predecessor of // i and distance array stores distance of i // from s int pred[v], dist[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { cout << \"Given source and destination\" << \" are not connected\"; return; } // vector path stores the shortest path vector<int> path; int crawl = dest; path.push_back(crawl); while (pred[crawl] != -1) { path.push_back(pred[crawl]); crawl = pred[crawl]; } // distance from source is in distance array cout << \"Shortest path length is : \" << dist[dest]; // printing path from source to destination cout << \"\\nPath is::\\n\"; for (int i = path.size() - 1; i >= 0; i--) cout << path[i] << \" \";} // Driver program to test above functionsint main(){ // no. of vertices int v = 8; // array of vectors is used to store the graph // in the form of an adjacency list vector<int> adj[v]; // Creating graph given in the above diagram. // add_edge function takes adjacency list, source // and destination vertex as argument and forms // an edge between them. add_edge(adj, 0, 1); add_edge(adj, 0, 3); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 3, 7); add_edge(adj, 4, 5); add_edge(adj, 4, 6); add_edge(adj, 4, 7); add_edge(adj, 5, 6); add_edge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v); return 0;}",
"e": 29734,
"s": 26235,
"text": null
},
{
"code": "// Java program to find shortest path in an undirected// graphimport java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList; public class pathUnweighted { // Driver Program public static void main(String args[]) { // No of vertices int v = 8; // Adjacency list for storing which vertices are connected ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(v); for (int i = 0; i < v; i++) { adj.add(new ArrayList<Integer>()); } // Creating graph given in the above diagram. // add_edge function takes adjacency list, source // and destination vertex as argument and forms // an edge between them. addEdge(adj, 0, 1); addEdge(adj, 0, 3); addEdge(adj, 1, 2); addEdge(adj, 3, 4); addEdge(adj, 3, 7); addEdge(adj, 4, 5); addEdge(adj, 4, 6); addEdge(adj, 4, 7); addEdge(adj, 5, 6); addEdge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v); } // function to form edge between two vertices // source and dest private static void addEdge(ArrayList<ArrayList<Integer>> adj, int i, int j) { adj.get(i).add(j); adj.get(j).add(i); } // function to print the shortest distance and path // between source vertex and destination vertex private static void printShortestDistance( ArrayList<ArrayList<Integer>> adj, int s, int dest, int v) { // predecessor[i] array stores predecessor of // i and distance array stores distance of i // from s int pred[] = new int[v]; int dist[] = new int[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { System.out.println(\"Given source and destination\" + \"are not connected\"); return; } // LinkedList to store path LinkedList<Integer> path = new LinkedList<Integer>(); int crawl = dest; path.add(crawl); while (pred[crawl] != -1) { path.add(pred[crawl]); crawl = pred[crawl]; } // Print distance System.out.println(\"Shortest path length is: \" + dist[dest]); // Print path System.out.println(\"Path is ::\"); for (int i = path.size() - 1; i >= 0; i--) { System.out.print(path.get(i) + \" \"); } } // a modified version of BFS that stores predecessor // of each vertex in array pred // and its distance from source in array dist private static boolean BFS(ArrayList<ArrayList<Integer>> adj, int src, int dest, int v, int pred[], int dist[]) { // a queue to maintain queue of vertices whose // adjacency list is to be scanned as per normal // BFS algorithm using LinkedList of Integer type LinkedList<Integer> queue = new LinkedList<Integer>(); // boolean array visited[] which stores the // information whether ith vertex is reached // at least once in the Breadth first search boolean visited[] = new boolean[v]; // initially all vertices are unvisited // so v[i] for all i is false // and as no path is yet constructed // dist[i] for all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = Integer.MAX_VALUE; pred[i] = -1; } // now source is first to be visited and // distance from source to itself should be 0 visited[src] = true; dist[src] = 0; queue.add(src); // bfs Algorithm while (!queue.isEmpty()) { int u = queue.remove(); for (int i = 0; i < adj.get(u).size(); i++) { if (visited[adj.get(u).get(i)] == false) { visited[adj.get(u).get(i)] = true; dist[adj.get(u).get(i)] = dist[u] + 1; pred[adj.get(u).get(i)] = u; queue.add(adj.get(u).get(i)); // stopping condition (when we find // our destination) if (adj.get(u).get(i) == dest) return true; } } } return false; }}// This code is contributed by Sahil Vaid",
"e": 34166,
"s": 29734,
"text": null
},
{
"code": "# Python3 code for printing shortest path between# two vertices of unweighted graph # utility function to form edge between two vertices# source and destdef add_edge(adj, src, dest): adj[src].append(dest); adj[dest].append(src); # a modified version of BFS that stores predecessor# of each vertex in array p# and its distance from source in array ddef BFS(adj, src, dest, v, pred, dist): # a queue to maintain queue of vertices whose # adjacency list is to be scanned as per normal # DFS algorithm queue = [] # boolean array visited[] which stores the # information whether ith vertex is reached # at least once in the Breadth first search visited = [False for i in range(v)]; # initially all vertices are unvisited # so v[i] for all i is false # and as no path is yet constructed # dist[i] for all i set to infinity for i in range(v): dist[i] = 1000000 pred[i] = -1; # now source is first to be visited and # distance from source to itself should be 0 visited[src] = True; dist[src] = 0; queue.append(src); # standard BFS algorithm while (len(queue) != 0): u = queue[0]; queue.pop(0); for i in range(len(adj[u])): if (visited[adj[u][i]] == False): visited[adj[u][i]] = True; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.append(adj[u][i]); # We stop BFS when we find # destination. if (adj[u][i] == dest): return True; return False; # utility function to print the shortest distance# between source vertex and destination vertexdef printShortestDistance(adj, s, dest, v): # predecessor[i] array stores predecessor of # i and distance array stores distance of i # from s pred=[0 for i in range(v)] dist=[0 for i in range(v)]; if (BFS(adj, s, dest, v, pred, dist) == False): print(\"Given source and destination are not connected\") # vector path stores the shortest path path = [] crawl = dest; crawl = dest; path.append(crawl); while (pred[crawl] != -1): path.append(pred[crawl]); crawl = pred[crawl]; # distance from source is in distance array print(\"Shortest path length is : \" + str(dist[dest]), end = '') # printing path from source to destination print(\"\\nPath is : : \") for i in range(len(path)-1, -1, -1): print(path[i], end=' ') # Driver program to test above functionsif __name__=='__main__': # no. of vertices v = 8; # array of vectors is used to store the graph # in the form of an adjacency list adj = [[] for i in range(v)]; # Creating graph given in the above diagram. # add_edge function takes adjacency list, source # and destination vertex as argument and forms # an edge between them. add_edge(adj, 0, 1); add_edge(adj, 0, 3); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 3, 7); add_edge(adj, 4, 5); add_edge(adj, 4, 6); add_edge(adj, 4, 7); add_edge(adj, 5, 6); add_edge(adj, 6, 7); source = 0 dest = 7; printShortestDistance(adj, source, dest, v); # This code is contributed by rutvik_56",
"e": 37460,
"s": 34166,
"text": null
},
{
"code": "// C# program to find shortest// path in an undirected graphusing System;using System.Collections.Generic;class pathUnweighted{ // Driver codepublic static void Main(String []args){ // No of vertices int v = 8; // Adjacency list for storing // which vertices are connected List<List<int>> adj = new List<List<int>>(v); for (int i = 0; i < v; i++) { adj.Add(new List<int>()); } // Creating graph given in the // above diagram. add_edge // function takes adjacency list, // source and destination vertex // as argument and forms an edge // between them. addEdge(adj, 0, 1); addEdge(adj, 0, 3); addEdge(adj, 1, 2); addEdge(adj, 3, 4); addEdge(adj, 3, 7); addEdge(adj, 4, 5); addEdge(adj, 4, 6); addEdge(adj, 4, 7); addEdge(adj, 5, 6); addEdge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v);} // function to form edge between// two vertices source and destprivate static void addEdge(List<List<int>> adj, int i, int j){ adj[i].Add(j); adj[j].Add(i);} // function to print the shortest// distance and path between source// vertex and destination vertexprivate static void printShortestDistance(List<List<int>> adj, int s, int dest, int v){ // predecessor[i] array stores // predecessor of i and distance // array stores distance of i // from s int []pred = new int[v]; int []dist = new int[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { Console.WriteLine(\"Given source and destination\" + \"are not connected\"); return; } // List to store path List<int> path = new List<int>(); int crawl = dest; path.Add(crawl); while (pred[crawl] != -1) { path.Add(pred[crawl]); crawl = pred[crawl]; } // Print distance Console.WriteLine(\"Shortest path length is: \" + dist[dest]); // Print path Console.WriteLine(\"Path is ::\"); for (int i = path.Count - 1; i >= 0; i--) { Console.Write(path[i] + \" \"); }} // a modified version of BFS that// stores predecessor of each vertex// in array pred and its distance// from source in array distprivate static bool BFS(List<List<int>> adj, int src, int dest, int v, int []pred, int []dist){ // a queue to maintain queue of // vertices whose adjacency list // is to be scanned as per normal // BFS algorithm using List of int type List<int> queue = new List<int>(); // bool array visited[] which // stores the information whether // ith vertex is reached at least // once in the Breadth first search bool []visited = new bool[v]; // initially all vertices are // unvisited so v[i] for all i // is false and as no path is // yet constructed dist[i] for // all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = int.MaxValue; pred[i] = -1; } // now source is first to be // visited and distance from // source to itself should be 0 visited[src] = true; dist[src] = 0; queue.Add(src); // bfs Algorithm while (queue.Count != 0) { int u = queue[0]; queue.RemoveAt(0); for (int i = 0; i < adj[u].Count; i++) { if (visited[adj[u][i]] == false) { visited[adj[u][i]] = true; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.Add(adj[u][i]); // stopping condition (when we // find our destination) if (adj[u][i] == dest) return true; } } } return false;}} // This code is contributed by Rajput-Ji",
"e": 41103,
"s": 37460,
"text": null
},
{
"code": null,
"e": 41147,
"s": 41103,
"text": "Shortest path length is : 2\nPath is::\n0 3 7"
},
{
"code": null,
"e": 41199,
"s": 41149,
"text": "Time Complexity : O(V + E) Auxiliary Space: O(V) "
},
{
"code": null,
"e": 41207,
"s": 41199,
"text": "svision"
},
{
"code": null,
"e": 41217,
"s": 41207,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 41227,
"s": 41217,
"text": "rutvik_56"
},
{
"code": null,
"e": 41238,
"s": 41227,
"text": "uttamsingh"
},
{
"code": null,
"e": 41242,
"s": 41238,
"text": "BFS"
},
{
"code": null,
"e": 41252,
"s": 41242,
"text": "cpp-queue"
},
{
"code": null,
"e": 41258,
"s": 41252,
"text": "Graph"
},
{
"code": null,
"e": 41264,
"s": 41258,
"text": "Graph"
},
{
"code": null,
"e": 41268,
"s": 41264,
"text": "BFS"
},
{
"code": null,
"e": 41366,
"s": 41268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41375,
"s": 41366,
"text": "Comments"
},
{
"code": null,
"e": 41388,
"s": 41375,
"text": "Old Comments"
},
{
"code": null,
"e": 41438,
"s": 41388,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 41486,
"s": 41438,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 41534,
"s": 41486,
"text": "Check whether a given graph is Bipartite or not"
},
{
"code": null,
"e": 41575,
"s": 41534,
"text": "Iterative Depth First Traversal of Graph"
},
{
"code": null,
"e": 41611,
"s": 41575,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 41652,
"s": 41611,
"text": "Kahn's algorithm for Topological Sorting"
},
{
"code": null,
"e": 41688,
"s": 41652,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 41723,
"s": 41688,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 41764,
"s": 41723,
"text": "Longest Path in a Directed Acyclic Graph"
}
] |
Difference Between for loop and Enhanced for loop in Java - GeeksforGeeks
|
10 Feb, 2022
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice.
Syntax:
for( initializationsection ; conditional check ; increment/decrement section)
{
// Code to be executed
}
Curly braces in for loop is optional without curly braces in for-loop we can take only one statement under for-loop which should not be a declarative statement and if we write declarative statement there then we will get compile-time error.
Example
Java
// Java Program to illustrate the use of// for loop // Importing all input output classesimport java.io.*;// Importing all classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // 1st for-loop // Iteration ocer 5 elements using for loop for (int i = 1; i <= 5; i++) { // Print statement System.out.println("GFG!"); } // 2nd for-loop // Declaring and initialization a variable // so we will get compile time error for (int i = 1; i <= 1; i++) int x = 0; }}
Output:
Case 1: Absence of second for-loop
GFG
GFG
GFG
GFG
GFG
Case 2: Presence of second for-loop
prog.java:28: error: variable declaration not allowed here
int x=0;
^
1 error
Output explanation:
In the Initialization section, This part will be executed only once in the loop life cycle. Here we can declare and initialize a local variable for loop. Here we can declare any number of variables but should have the same type by mistake if we are trying to declare a different data type then we will get a compile–time error. In this section, we can take any valid java statement including ‘System.out.println()’.
During the condition check, we can take any valid java expression that should be of type boolean. This part is optional and if we are not taking anything then the compiler will always place a true value here.
In the Increment/Decrement section, we can either increment or decrement we can the initialized value. In this section we can take any valid java statement including ‘System.out.println()’ and this section is also optional.
Enhanced for loop(for-each loop)
This for-loop was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing array or collections. This loop also makes the code more readable and reduces the chance of bugs in the code.
Syntax:
for(data-type variable : array | collection)
{
// Code to be executed
}
Example:
Java
// Java Program to show usage of for-each loop // Importing all classes from// java.util package// Importing all input output classesimport java.io.*;import java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing the integer array // Custom integer entries in an array int[] array = { 1, 2, 3, 4, 5, 6 }; // Accessing the element of array // using for-each loop for (int a : array) { // Print all elements of an array System.out.println(a); } }}
1
2
3
4
5
6
After visualizing both the programs we landed upon some conclusive differences which are depicted in tabular format to get a clear understanding hand in hand.
In a normal for-loop, we can increase the counter as per our wish by using
i=i+x( where x is any constant x=1,2,3...)
Example: Printing element in a 1D array
int[ ] x={1,2,3};
for(int i=0;i<x.length;i++)
{
System.out.println(x[i]);
}
Example: Printing element in a 1D array using for-each loop
int[ ] x={1,2,3};
for(int a : x)
{
System.out.println(a);
}
Example: Printing element in a 2D array using for loop
int[ ][ ] x={{1,2,3},{4,5,6}};
for(int i=0;i<x.length;i++) {
for(int j=0; j<x[i].length;j++) {
System.out.println(x[i][j]);
}
}
Example: Printing element in a 2D array using for-each loop
int[ ][ ] x={{1,2,3},{4,5,6}} ;
for(int[ ] x1 :x){
for(int x2 : x1) {
System.out.println(x2);
}
}
saurabh1990aror
surinderdawra388
sagar0719kumar
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 24802,
"s": 24774,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 25025,
"s": 24802,
"text": "Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice."
},
{
"code": null,
"e": 25033,
"s": 25025,
"text": "Syntax:"
},
{
"code": null,
"e": 25149,
"s": 25033,
"text": "for( initializationsection ; conditional check ; increment/decrement section)\n {\n // Code to be executed\n }"
},
{
"code": null,
"e": 25390,
"s": 25149,
"text": "Curly braces in for loop is optional without curly braces in for-loop we can take only one statement under for-loop which should not be a declarative statement and if we write declarative statement there then we will get compile-time error."
},
{
"code": null,
"e": 25398,
"s": 25390,
"text": "Example"
},
{
"code": null,
"e": 25403,
"s": 25398,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of// for loop // Importing all input output classesimport java.io.*;// Importing all classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // 1st for-loop // Iteration ocer 5 elements using for loop for (int i = 1; i <= 5; i++) { // Print statement System.out.println(\"GFG!\"); } // 2nd for-loop // Declaring and initialization a variable // so we will get compile time error for (int i = 1; i <= 1; i++) int x = 0; }}",
"e": 26045,
"s": 25403,
"text": null
},
{
"code": null,
"e": 26056,
"s": 26045,
"text": " Output: "
},
{
"code": null,
"e": 26092,
"s": 26056,
"text": "Case 1: Absence of second for-loop "
},
{
"code": null,
"e": 26113,
"s": 26092,
"text": "GFG\nGFG\nGFG\nGFG\nGFG "
},
{
"code": null,
"e": 26150,
"s": 26113,
"text": "Case 2: Presence of second for-loop "
},
{
"code": null,
"e": 26251,
"s": 26150,
"text": "prog.java:28: error: variable declaration not allowed here\n int x=0;\n ^\n1 error "
},
{
"code": null,
"e": 26273,
"s": 26251,
"text": "Output explanation: "
},
{
"code": null,
"e": 26689,
"s": 26273,
"text": "In the Initialization section, This part will be executed only once in the loop life cycle. Here we can declare and initialize a local variable for loop. Here we can declare any number of variables but should have the same type by mistake if we are trying to declare a different data type then we will get a compile–time error. In this section, we can take any valid java statement including ‘System.out.println()’."
},
{
"code": null,
"e": 26898,
"s": 26689,
"text": "During the condition check, we can take any valid java expression that should be of type boolean. This part is optional and if we are not taking anything then the compiler will always place a true value here."
},
{
"code": null,
"e": 27122,
"s": 26898,
"text": "In the Increment/Decrement section, we can either increment or decrement we can the initialized value. In this section we can take any valid java statement including ‘System.out.println()’ and this section is also optional."
},
{
"code": null,
"e": 27155,
"s": 27122,
"text": "Enhanced for loop(for-each loop)"
},
{
"code": null,
"e": 27524,
"s": 27155,
"text": "This for-loop was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing array or collections. This loop also makes the code more readable and reduces the chance of bugs in the code."
},
{
"code": null,
"e": 27532,
"s": 27524,
"text": "Syntax:"
},
{
"code": null,
"e": 27613,
"s": 27532,
"text": "for(data-type variable : array | collection)\n {\n // Code to be executed\n } "
},
{
"code": null,
"e": 27623,
"s": 27613,
"text": "Example: "
},
{
"code": null,
"e": 27628,
"s": 27623,
"text": "Java"
},
{
"code": "// Java Program to show usage of for-each loop // Importing all classes from// java.util package// Importing all input output classesimport java.io.*;import java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing the integer array // Custom integer entries in an array int[] array = { 1, 2, 3, 4, 5, 6 }; // Accessing the element of array // using for-each loop for (int a : array) { // Print all elements of an array System.out.println(a); } }}",
"e": 28230,
"s": 27628,
"text": null
},
{
"code": null,
"e": 28242,
"s": 28230,
"text": "1\n2\n3\n4\n5\n6"
},
{
"code": null,
"e": 28403,
"s": 28242,
"text": " After visualizing both the programs we landed upon some conclusive differences which are depicted in tabular format to get a clear understanding hand in hand. "
},
{
"code": null,
"e": 28478,
"s": 28403,
"text": "In a normal for-loop, we can increase the counter as per our wish by using"
},
{
"code": null,
"e": 28522,
"s": 28478,
"text": " i=i+x( where x is any constant x=1,2,3...)"
},
{
"code": null,
"e": 28563,
"s": 28522,
"text": "Example: Printing element in a 1D array "
},
{
"code": null,
"e": 28581,
"s": 28563,
"text": "int[ ] x={1,2,3};"
},
{
"code": null,
"e": 28609,
"s": 28581,
"text": "for(int i=0;i<x.length;i++)"
},
{
"code": null,
"e": 28611,
"s": 28609,
"text": "{"
},
{
"code": null,
"e": 28640,
"s": 28611,
"text": " System.out.println(x[i]);"
},
{
"code": null,
"e": 28642,
"s": 28640,
"text": "}"
},
{
"code": null,
"e": 28703,
"s": 28642,
"text": "Example: Printing element in a 1D array using for-each loop "
},
{
"code": null,
"e": 28721,
"s": 28703,
"text": "int[ ] x={1,2,3};"
},
{
"code": null,
"e": 28737,
"s": 28721,
"text": "for(int a : x)"
},
{
"code": null,
"e": 28739,
"s": 28737,
"text": "{"
},
{
"code": null,
"e": 28764,
"s": 28739,
"text": " System.out.println(a);"
},
{
"code": null,
"e": 28766,
"s": 28764,
"text": "}"
},
{
"code": null,
"e": 28821,
"s": 28766,
"text": "Example: Printing element in a 2D array using for loop"
},
{
"code": null,
"e": 28852,
"s": 28821,
"text": "int[ ][ ] x={{1,2,3},{4,5,6}};"
},
{
"code": null,
"e": 28882,
"s": 28852,
"text": "for(int i=0;i<x.length;i++) {"
},
{
"code": null,
"e": 28916,
"s": 28882,
"text": "for(int j=0; j<x[i].length;j++) {"
},
{
"code": null,
"e": 28945,
"s": 28916,
"text": "System.out.println(x[i][j]);"
},
{
"code": null,
"e": 28947,
"s": 28945,
"text": "}"
},
{
"code": null,
"e": 28949,
"s": 28947,
"text": "}"
},
{
"code": null,
"e": 29009,
"s": 28949,
"text": "Example: Printing element in a 2D array using for-each loop"
},
{
"code": null,
"e": 29041,
"s": 29009,
"text": "int[ ][ ] x={{1,2,3},{4,5,6}} ;"
},
{
"code": null,
"e": 29060,
"s": 29041,
"text": "for(int[ ] x1 :x){"
},
{
"code": null,
"e": 29079,
"s": 29060,
"text": "for(int x2 : x1) {"
},
{
"code": null,
"e": 29103,
"s": 29079,
"text": "System.out.println(x2);"
},
{
"code": null,
"e": 29105,
"s": 29103,
"text": "}"
},
{
"code": null,
"e": 29107,
"s": 29105,
"text": "}"
},
{
"code": null,
"e": 29125,
"s": 29109,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29142,
"s": 29125,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29157,
"s": 29142,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 29164,
"s": 29157,
"text": "Picked"
},
{
"code": null,
"e": 29188,
"s": 29164,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29207,
"s": 29188,
"text": "Difference Between"
},
{
"code": null,
"e": 29212,
"s": 29207,
"text": "Java"
},
{
"code": null,
"e": 29231,
"s": 29212,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29236,
"s": 29231,
"text": "Java"
},
{
"code": null,
"e": 29334,
"s": 29236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29343,
"s": 29334,
"text": "Comments"
},
{
"code": null,
"e": 29356,
"s": 29343,
"text": "Old Comments"
},
{
"code": null,
"e": 29417,
"s": 29356,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29485,
"s": 29417,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 29540,
"s": 29485,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 29598,
"s": 29540,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 29672,
"s": 29598,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 29687,
"s": 29672,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29731,
"s": 29687,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 29753,
"s": 29731,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 29778,
"s": 29753,
"text": "Reverse a string in Java"
}
] |
Bet you didn’t know this about Airflow! | by Jyoti Dhiman | Towards Data Science
|
We are living in the Airflow era. Almost all of us started our scheduling journey with cronjobs and the transition to a workflow scheduler like Airflow has given us better handling with complex inter-dependent pipelines, UI based scheduling, retry mechanism, alerts & what not! AWS also recently announced managed airflow workflows. These are truly exciting times and today, Airflow has really changed the scheduling landscape, with scheduling configuration as a code.
Let’s dig deeper.
Now, coming to a use case where I really dug down in airflow capabilities. For the below use case, all the references to task are for airflow tasks.
The above DAG consists of the following operations:
Start an AWS EMR cluster: EMR is an AWS based big data environment. To understand the use case we don’t need to deep dive into how AWS EMR works. But if you want to, you can read more about it here. Airflow task_id for this operation: EMR_start_cluster
Submit an ETL job: This is done by adding a step to the EMR, basically submitting a spark job on the cluster. This is just the job submission part, and will always be successful if the task is able to submit the job successfully to the cluster. This is done using EMRAddStepOperator.Airflow task_id for this operation: promo_etl/user_etl
Wait for the ETL job to complete: This is the actual indicator of the status of the job submitted by the upstream ETL task(in the context of the above DAG). Using EMRStepSensor tasks, we wait for the submitted job to complete and the state of this task indicates whether the job is in the running/successful or failed state.Airflow task_id for this operation: promo_etl_sensor/user_etl_sensor
Load partitions: Task for adding partitions to the deliver table of the pipeline.Airflow task_id for this operation: load_user_partitions/load_promo_partitions
Terminate the EMR cluster: Once all the tasks have completed, shut down the EMR.
So, in a nutshell, one task is submitting the spark job to the cluster and its downstream sensor task is polling the state of the upstream task to get job status. Since the pipeline includes EMR, this might be a little different from the scenario in a running cluster where you can submit the spark job directly from airflow using spark-submit and BashOperator and single task indicates job state.
Now, coming to the catch. Here, my user_etl pipeline was dependent on the previous DAG run of the same. That is, with an hourly schedule, the job for 2020–12–25 12:00 will use deliverables of the previous DAG run, i.e. 2020–12–25 11:00. So, in case the 2020–12–25 11:00 run has failed, user_etl task for 2020–12–25 12:00 DAG run should not run.
I didn’t want to handle this in code or via markers and was looking to take care of the same in the DAG itself. Additionally, I also wanted to add a retry mechanism to the user_etl pipeline, so in case user_etl_sensor fails, retry user_etl(which is an upstream task).
What did I want? For a DAG run, if user_etl_sensor fails, user_etl is submitted again to the cluster n times as a retry mechanism and if it still fails, then in the next DAG run, user_etl job is not submitted to the cluster.
For these “inter-dependent” task use cases, I could not simply use airflow parameters mentioned below, directly.
Add retry on user_etl_sensor: It would have retried user_etl_sensor task on failure but its upstream task(user_etl) is the one that is actually submitting the job to the cluster, not the sensor. Using retry would have been useless here.
Add depends_on_past=True on user_etl_sensor: This airflow parameter, if set on a task, doesn’t run the task in the current DAG run if the previous run of the task has failed. But, in this case, it won’t run user_etl_sensor if the previous run has failed but user_etl would have already submitted the job in the current DAG run by then, so it won’t really matter.
As a retry mechanism, I thought if I can clear the state of the upstream task(user_etl), on user_etl_sensor failure, I might be able to submit the job to the cluster n times and that’s what I implemented withon_retry_callback on the user_etl_sensor task with 2 retries and programmatically cleared the state of the user_etl task on sensor failure.
So now, user_etl_sensor fails > goes into retry state > function mentioned as on_retry_callback is called > function clears the state of user_etl > job gets submitted to the cluster again > sensor goes into running state again.
Now, coming to controlling the next scheduled run of user_step if the previous run of the user_etl_sensor has failed even after retries. I thought of programmatically mark user_etl to failed(in the same DAG run) if user_etl_sensor fails.
By doing so, I can use depends_on_past=True on user_etl and the task won’t be triggered in the next DAG run because user_etl is marked failed on the previous run. It’ll behave like only one task is controlling the submission of the job and the running state of the job and that’s what I did, using on_failure_callback.
retry_upstream_task function is passed as on_retry_callback:
mark_upstream_failed function is passed as on_failure_callback:
These callbacks can be added on user_etl_sensor as shown below:
user_etl_sensor = EMRStepSensor( task_id='user_etl_sensor', dag=dag, on_failure_callback=mark_upstream_failed, on_retry_callback=retry_upstream_task, params={'mark_failed': ['user_etl'], 'to_retry': ['user_etl']})
Pretty cool, isn’t it? That’s how I explored the configuration as code. This “Pythonic” task state control can be applied to any airflow sensor operator which inherits BaseSensorOperator not just dealing with EMR based jobs or basically any use case of working with interdependent tasks.
This user_etl pipeline in my case was a Delta Lake based pipeline and if the next scheduled run has “run” with the previous run failed, it might have caused data inconsistencies. I really like the flexibility airflow allowed me to convert my logic to code and actually achieve it.
In the callbacks, I looped over all the tasks to get the task object to make changes in its state i.e. marking the task as failed or clearing the task for the retry functionality. I am researching more to get the task object directly from task_id, instead of looping over, will edit the post if I find a better way to do it.
Ciao from my DAG, which, Airflow says, is fresh as a Daisy :)
|
[
{
"code": null,
"e": 641,
"s": 172,
"text": "We are living in the Airflow era. Almost all of us started our scheduling journey with cronjobs and the transition to a workflow scheduler like Airflow has given us better handling with complex inter-dependent pipelines, UI based scheduling, retry mechanism, alerts & what not! AWS also recently announced managed airflow workflows. These are truly exciting times and today, Airflow has really changed the scheduling landscape, with scheduling configuration as a code."
},
{
"code": null,
"e": 659,
"s": 641,
"text": "Let’s dig deeper."
},
{
"code": null,
"e": 808,
"s": 659,
"text": "Now, coming to a use case where I really dug down in airflow capabilities. For the below use case, all the references to task are for airflow tasks."
},
{
"code": null,
"e": 860,
"s": 808,
"text": "The above DAG consists of the following operations:"
},
{
"code": null,
"e": 1113,
"s": 860,
"text": "Start an AWS EMR cluster: EMR is an AWS based big data environment. To understand the use case we don’t need to deep dive into how AWS EMR works. But if you want to, you can read more about it here. Airflow task_id for this operation: EMR_start_cluster"
},
{
"code": null,
"e": 1451,
"s": 1113,
"text": "Submit an ETL job: This is done by adding a step to the EMR, basically submitting a spark job on the cluster. This is just the job submission part, and will always be successful if the task is able to submit the job successfully to the cluster. This is done using EMRAddStepOperator.Airflow task_id for this operation: promo_etl/user_etl"
},
{
"code": null,
"e": 1844,
"s": 1451,
"text": "Wait for the ETL job to complete: This is the actual indicator of the status of the job submitted by the upstream ETL task(in the context of the above DAG). Using EMRStepSensor tasks, we wait for the submitted job to complete and the state of this task indicates whether the job is in the running/successful or failed state.Airflow task_id for this operation: promo_etl_sensor/user_etl_sensor"
},
{
"code": null,
"e": 2004,
"s": 1844,
"text": "Load partitions: Task for adding partitions to the deliver table of the pipeline.Airflow task_id for this operation: load_user_partitions/load_promo_partitions"
},
{
"code": null,
"e": 2085,
"s": 2004,
"text": "Terminate the EMR cluster: Once all the tasks have completed, shut down the EMR."
},
{
"code": null,
"e": 2483,
"s": 2085,
"text": "So, in a nutshell, one task is submitting the spark job to the cluster and its downstream sensor task is polling the state of the upstream task to get job status. Since the pipeline includes EMR, this might be a little different from the scenario in a running cluster where you can submit the spark job directly from airflow using spark-submit and BashOperator and single task indicates job state."
},
{
"code": null,
"e": 2828,
"s": 2483,
"text": "Now, coming to the catch. Here, my user_etl pipeline was dependent on the previous DAG run of the same. That is, with an hourly schedule, the job for 2020–12–25 12:00 will use deliverables of the previous DAG run, i.e. 2020–12–25 11:00. So, in case the 2020–12–25 11:00 run has failed, user_etl task for 2020–12–25 12:00 DAG run should not run."
},
{
"code": null,
"e": 3096,
"s": 2828,
"text": "I didn’t want to handle this in code or via markers and was looking to take care of the same in the DAG itself. Additionally, I also wanted to add a retry mechanism to the user_etl pipeline, so in case user_etl_sensor fails, retry user_etl(which is an upstream task)."
},
{
"code": null,
"e": 3321,
"s": 3096,
"text": "What did I want? For a DAG run, if user_etl_sensor fails, user_etl is submitted again to the cluster n times as a retry mechanism and if it still fails, then in the next DAG run, user_etl job is not submitted to the cluster."
},
{
"code": null,
"e": 3434,
"s": 3321,
"text": "For these “inter-dependent” task use cases, I could not simply use airflow parameters mentioned below, directly."
},
{
"code": null,
"e": 3671,
"s": 3434,
"text": "Add retry on user_etl_sensor: It would have retried user_etl_sensor task on failure but its upstream task(user_etl) is the one that is actually submitting the job to the cluster, not the sensor. Using retry would have been useless here."
},
{
"code": null,
"e": 4034,
"s": 3671,
"text": "Add depends_on_past=True on user_etl_sensor: This airflow parameter, if set on a task, doesn’t run the task in the current DAG run if the previous run of the task has failed. But, in this case, it won’t run user_etl_sensor if the previous run has failed but user_etl would have already submitted the job in the current DAG run by then, so it won’t really matter."
},
{
"code": null,
"e": 4382,
"s": 4034,
"text": "As a retry mechanism, I thought if I can clear the state of the upstream task(user_etl), on user_etl_sensor failure, I might be able to submit the job to the cluster n times and that’s what I implemented withon_retry_callback on the user_etl_sensor task with 2 retries and programmatically cleared the state of the user_etl task on sensor failure."
},
{
"code": null,
"e": 4610,
"s": 4382,
"text": "So now, user_etl_sensor fails > goes into retry state > function mentioned as on_retry_callback is called > function clears the state of user_etl > job gets submitted to the cluster again > sensor goes into running state again."
},
{
"code": null,
"e": 4848,
"s": 4610,
"text": "Now, coming to controlling the next scheduled run of user_step if the previous run of the user_etl_sensor has failed even after retries. I thought of programmatically mark user_etl to failed(in the same DAG run) if user_etl_sensor fails."
},
{
"code": null,
"e": 5167,
"s": 4848,
"text": "By doing so, I can use depends_on_past=True on user_etl and the task won’t be triggered in the next DAG run because user_etl is marked failed on the previous run. It’ll behave like only one task is controlling the submission of the job and the running state of the job and that’s what I did, using on_failure_callback."
},
{
"code": null,
"e": 5228,
"s": 5167,
"text": "retry_upstream_task function is passed as on_retry_callback:"
},
{
"code": null,
"e": 5292,
"s": 5228,
"text": "mark_upstream_failed function is passed as on_failure_callback:"
},
{
"code": null,
"e": 5356,
"s": 5292,
"text": "These callbacks can be added on user_etl_sensor as shown below:"
},
{
"code": null,
"e": 5585,
"s": 5356,
"text": "user_etl_sensor = EMRStepSensor( task_id='user_etl_sensor', dag=dag, on_failure_callback=mark_upstream_failed, on_retry_callback=retry_upstream_task, params={'mark_failed': ['user_etl'], 'to_retry': ['user_etl']})"
},
{
"code": null,
"e": 5873,
"s": 5585,
"text": "Pretty cool, isn’t it? That’s how I explored the configuration as code. This “Pythonic” task state control can be applied to any airflow sensor operator which inherits BaseSensorOperator not just dealing with EMR based jobs or basically any use case of working with interdependent tasks."
},
{
"code": null,
"e": 6154,
"s": 5873,
"text": "This user_etl pipeline in my case was a Delta Lake based pipeline and if the next scheduled run has “run” with the previous run failed, it might have caused data inconsistencies. I really like the flexibility airflow allowed me to convert my logic to code and actually achieve it."
},
{
"code": null,
"e": 6479,
"s": 6154,
"text": "In the callbacks, I looped over all the tasks to get the task object to make changes in its state i.e. marking the task as failed or clearing the task for the retry functionality. I am researching more to get the task object directly from task_id, instead of looping over, will edit the post if I find a better way to do it."
}
] |
Solving A Data Science Challenge - The Visual Way | by Sepehr Sisakht | Towards Data Science
|
For the visual learners
In this post I will show you some cool geospatial visualizations using Folium, including time variant mapping, and superimposing data binning on a Foium map in order to gain a deeper understanding of your geospatial data. This post could be used as a guide for exploratory analysis of geospatial data.
The main question that I tried to answer here was “What is the most ideal location for a retailer in a city?” I have made a few assumptions to give this question some context but it is in fact not far from an actual study done for a client.
Lets say the retailer is actually a warehouse of some sortWe have bunch of GPS data points across the city which are the destinations that our fleet of vehicles visit daily
Lets say the retailer is actually a warehouse of some sort
We have bunch of GPS data points across the city which are the destinations that our fleet of vehicles visit daily
As I mentioned, we have bunch of GPS data points across the city. Her’s a snapshot
To make this more interesting I have gone ahead and found a data set listing all the neighborhoods of Calgary, i.e, the city :). We will use this data to gather some information about the most common venues in each neighborhood which will help us to group them into a bunch of clusters. Our hypothesis is that a neighborhood with more constructions or furniture store would be more suitable for a warehouse compared to a neighborhood with more coffee shops or parks which suggests it’s a residential area.
OK, enough with boring stuff. Below is how you make a pretty heat map of our GPS data. Tada...
# Add a column with ones, then calculate sum and generate the heatsliceDF[‘count’] = 1 # create map of Calgary using latitude and longitude valuesbase_heatmap = folium.Map(location=[calgLat, calgLng], zoom_start=10)# Just adding a marker for funfolium.Marker((lat,lng), popup=”label”).add_to(base_heatmap)HeatMap(data=sliceDF[[‘Lat’, ‘Lng’, ‘count’]].groupby([‘Lat’, ‘Lng’]).sum().reset_index().values.tolist(), radius=8, max_zoom=4).add_to(base_heatmap)# If you want to save the map base_heatmap.save(outfile= “truckheatMap.html”)# To show the map in jupyterbase_heatmap
The heat map above doesn’t actually show an accurate picture because we are combining all the data points regardless of time. To get a better picture of where our fleet is spending most of its time we need to somehow incorporate time into this. The pretty animated header of this post is one way to do this. Looking at the fleet moving across the city can reveal they regions in which they are spending more time. So lets generate that animation using the cool Folium...
# Creating list of hours that we need to slice by to generate the time variant mapdf_hour_list = []for hour in sliceDF.Hour.sort_values().unique(): df_hour_list.append(sliceDF.loc[sliceDF.Hour == hour, ['Lat', 'Lng', 'count']].groupby(['Lat', 'Lng']).sum().reset_index().values.tolist())base_heattimemap = folium.Map(location=[latitude, longitude], zoom_start=11)HeatMapWithTime(df_hour_list, radius=8, gradient={0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 1: 'red'}, min_opacity=0.8, max_opacity=1, use_local_extrema=True).add_to(base_heattimemap)base_heattimemap
Now, that’s all fine and dandy, but it’s not a way to quantify this. We still need to visually chase the points and guess what regions are denser than others at the end. What if we could have a density based plot that uses a grid and shows us a relative density per each cell? OK, you got it.
# Used a def so that if you wish to add interactivity you can do that easily later on.def plot(min_hour,max_hour,n): #boundaries of the main rectangle upper_right = [51.1741,-113.8925] lower_left = [50.8672,-114.2715] # Creating a grid of nxn from the given cordinate corners grid = get_geojson_grid(upper_right, lower_left , n) # Holds number of points that fall in each cell & time window if provided counts_array = [] # Adding the total number of visits to each cell for box in grid: # get the corners for each cell upper_right = box["properties"]["upper_right"] lower_left = box["properties"]["lower_left"]# check to make sure it's in the box and between the time window if time window is given mask = ((sliceDF.Lat <= upper_right[1]) & (sliceDF.Lat >= lower_left[1]) & (sliceDF.Lng <= upper_right[0]) & (sliceDF.Lng >= lower_left[0]) & (sliceDF.Hour >= min_hour) & (sliceDF.Hour <= max_hour))# Number of points that fall in the cell and meet the condition counts_array.append(len(sliceDF[mask]))# creating a base map m = folium.Map(zoom_start = 10, location=[latitude, longitude])# Add GeoJson to map for i, geo_json in enumerate(grid): relativeCount = counts_array[i]*100/4345 color = plt.cm.YlGn(relativeCount) color = mpl.colors.to_hex(color) gj = folium.GeoJson(geo_json, style_function=lambda feature, color=color: { 'fillColor': color, 'color':"gray", 'weight': 0.5, 'dashArray': '6,6', 'fillOpacity': 0.8, }) m.add_child(gj) colormap = branca.colormap.linear.YlGn_09.scale(0, 1) colormap = colormap.to_step(index=[0, 0.3, 0.6, 0.8 , 1]) colormap.caption = 'Relative density of fleet activity per cell' colormap.add_to(m)return m# limiting time window for our data to 8 am - 5 pm and also grid is 20 x 20 plot(8,17,20)
The second part of this post is aiming to show you how to use Foursquare APIs to get some geospatial information about different neighborhoods, group neighborhoods in clusters and eventually combine the results to reach to our conclusion.
I have worked quite a bit with Google’s APIs and later on was introduce to Foursquare when I started digging data science and can be awesome. So for those of you who are not familiar with Foursquare I highly recommend checking it out. It’s worth it.
The community data was shown above. For now we ignore the labels the author has used and assume we don’t have them. Our aim is to cluster those neighborhoods ourselves and find a suitable area for our retail shop (warehouse). For this, we use Foursquare explore API but feel free to check the list of all their APIs might come handy in your projects.
By now, you should know how to plot pretty maps, so lets make one from the community data using the original labels just to see what’s going on.
Next we attempt to get n number of most common venues for each neighborhood and we will feed that into our k-means clustering code to group the neighborhoods in clusters.
To get a list of common venues for a neighborhoods using explore Foursquare API you would do something like below.
# Using Foursquare's explore API get 10 most common venues around # the latitude, longitude provided within 500 m radius. # You'll get the CLIENT_ID, CLIENT_SECRET and VERSION after signing up for Foursquare.(Pay attention to API call limits.)url = "https://api.foursquare.com/v2/venues/explore?client_id={}&client_secret={}&v={}&ll={},{}&radius=500&limit=10".format(CLIENT_ID,CLIENT_SECRET,VERSION,neighborhood_lat,neighborhood_lng)# results come back in format of JSON results = requests.get(url).json()results
We can extend this to all the neighborhoods. The data frame below shows a few rows of the results.
Why? Because we have strings as labels for each neighborhood and need a way to digitizing them so that we can use them in our classification algorithm. “One hot encoding” basically parses your labels and assigns dummy values to each as well as creates new columns per each label and using 1 or 0 to determine weather that row of table has that feature or not. So, for instance, Spruce Cliff has cafe, but may not have a gym and so on. The snippet below shows how to “one hot encode” your results:
# one hot encodingcalgary_onehot = pd.get_dummies(calgary_venues[['Venue Category']], prefix="", prefix_sep="")# add neighborhood column back to dataframecalgary_onehot['Neighbourhood'] = calgary_venues['Neighborhood']# move neighborhood column to the first columnfixed_columns = [calgary_onehot.columns[-1]] + list(calgary_onehot.columns[:-1])calgary_onehot = calgary_onehot[fixed_columns]print("calgary_onehot shape is " , calgary_onehot.shape)calgary_onehot.head()
The resulting table is something like this:
For gaining a better insight on the nature of each neighborhood, we can group these result and fined the most common venues per neighborhood. We can then attempt to label each neighborhood, so for instance, a neighborhood with more coffee shops and grocery stores is most likely a residential area while a neighborhood with more construction zones or factories might be an industrial neighborhood.
We will create a pandas dataframe from the results and include 10 most common venues for each neighborhood.
num_top_venues = 10indicators = ['st', 'nd', 'rd']def return_most_common_venues(row, num_top_venues): row_categories = row.iloc[1:] row_categories_sorted = row_categories.sort_values(ascending=False) return row_categories_sorted.index.values[0:num_top_venues]# create columns according to number of top venuescolumns = ['Neighborhood']for ind in np.arange(num_top_venues): try: columns.append('{}{} Most Common Venue'.format(ind+1, indicators[ind])) except: columns.append('{}th Most Common Venue'.format(ind+1))# create a new dataframeneighborhoods_venues_sorted = pd.DataFrame(columns=columns)neighborhoods_venues_sorted['Neighborhood'] = calgary_grouped['Neighbourhood']neighborhoods_venues_sorted.rename(columns={'Neighborhood':"NAME"},inplace=True)for ind in np.arange(calgary_grouped.shape[0]): neighborhoods_venues_sorted.iloc[ind, 1:] = return_most_common_venues(calgary_grouped.iloc[ind, :], num_top_venues)neighborhoods_venues_sorted.head()
and the result is something like this:
Now we are at a point to cluster our neighborhoods based on the one hot encoded data frame we have. In this case I used kmeans-clustering from Sklearn package and to be able to compare the results later on with the original cluster labels in our community data I chose to use n=4 as the number of clusters.
# set number of clusterskclusters = 4calgary_grouped_clustering = calgary_grouped.drop('Neighbourhood', 1)# run k-means clusteringkmeans = KMeans(n_clusters=kclusters, random_state=0).fit(calgary_grouped_clustering)# check cluster labels generated for each row in the dataframeneighborhoods_venues_sorted['labels'] = kmeans.labels_neighborhoods_venues_sorted.head()
Let’s merge our results with the original dataframe which includes the geolocations and make a pretty plot with some selectors so we can filter through the clusters and see what’s going on.
The graph:
The code to achieve this:
calgary_merged['labels'] = calgary_merged['labels'].astype(int)map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11)# set color scheme for the clustersx = np.arange(kclusters)ys = [i + x + (i*x)**2 for i in range(kclusters)]colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))rainbow = [colors.rgb2hex(i) for i in colors_array]for cluster in range(0,kclusters): group = folium.FeatureGroup(name='<span style=\\"color: {0};\\">{1}</span>'.format(rainbow[cluster-1],cluster)) for lat, lon, poi, label in zip(calgary_merged['latitude'], calgary_merged['longitude'], calgary_merged['CLASS_CODE'], calgary_merged['labels']): if int(label) == cluster: label = folium.Popup('ORIG. '+ str(poi) + 'Cluster ' + str(cluster), parse_html=True) folium.CircleMarker( (lat, lon), radius=5, popup=label, color=rainbow[cluster-1], fill=True, fill_color=rainbow[cluster-1], fill_opacity=0.7).add_to(group) group.add_to(map_clusters)folium.map.LayerControl('topright', collapsed=False).add_to(map_clusters)map_clusters.save(outfile= "map_clusters.html")map_clusters
OK, all that is fine and dandy so what? The whole point of this study was to compare the clusters with the labels and try to identify a suitable location close to the center of minimum distance for a retail store or rather a warehouse.
So lets group by our cluster labels and the original labels and have a look at the confusion matrix. Keep in mind the original labels are not necessarily the true labels and are merely subjective labels made by the author of data set. So this should give us some ideas as to how similar are the distributions of our labels compared to the original ones and nothing more.
The final result of our finding is shown below. The red circle is enclosing the center of medium distance (Median Center) as well as two of the neighborhoods which were determined to be most likely under development or industrial (the most common venues were construction, big retain stores)
GPS data from the fleet and the city community data were used to support this finding and form a basis for this conclusion. Keep in mind I was trying to show you how you can quickly and without digging too much in details find an approximate solution for a problem of this nature.
Finding the median center using the actual routing data is much more complex and perhaps a next step towards modeling and finding a more precise answer would be to use relative weights for each point.
|
[
{
"code": null,
"e": 195,
"s": 171,
"text": "For the visual learners"
},
{
"code": null,
"e": 497,
"s": 195,
"text": "In this post I will show you some cool geospatial visualizations using Folium, including time variant mapping, and superimposing data binning on a Foium map in order to gain a deeper understanding of your geospatial data. This post could be used as a guide for exploratory analysis of geospatial data."
},
{
"code": null,
"e": 738,
"s": 497,
"text": "The main question that I tried to answer here was “What is the most ideal location for a retailer in a city?” I have made a few assumptions to give this question some context but it is in fact not far from an actual study done for a client."
},
{
"code": null,
"e": 911,
"s": 738,
"text": "Lets say the retailer is actually a warehouse of some sortWe have bunch of GPS data points across the city which are the destinations that our fleet of vehicles visit daily"
},
{
"code": null,
"e": 970,
"s": 911,
"text": "Lets say the retailer is actually a warehouse of some sort"
},
{
"code": null,
"e": 1085,
"s": 970,
"text": "We have bunch of GPS data points across the city which are the destinations that our fleet of vehicles visit daily"
},
{
"code": null,
"e": 1168,
"s": 1085,
"text": "As I mentioned, we have bunch of GPS data points across the city. Her’s a snapshot"
},
{
"code": null,
"e": 1674,
"s": 1168,
"text": "To make this more interesting I have gone ahead and found a data set listing all the neighborhoods of Calgary, i.e, the city :). We will use this data to gather some information about the most common venues in each neighborhood which will help us to group them into a bunch of clusters. Our hypothesis is that a neighborhood with more constructions or furniture store would be more suitable for a warehouse compared to a neighborhood with more coffee shops or parks which suggests it’s a residential area."
},
{
"code": null,
"e": 1769,
"s": 1674,
"text": "OK, enough with boring stuff. Below is how you make a pretty heat map of our GPS data. Tada..."
},
{
"code": null,
"e": 2341,
"s": 1769,
"text": "# Add a column with ones, then calculate sum and generate the heatsliceDF[‘count’] = 1 # create map of Calgary using latitude and longitude valuesbase_heatmap = folium.Map(location=[calgLat, calgLng], zoom_start=10)# Just adding a marker for funfolium.Marker((lat,lng), popup=”label”).add_to(base_heatmap)HeatMap(data=sliceDF[[‘Lat’, ‘Lng’, ‘count’]].groupby([‘Lat’, ‘Lng’]).sum().reset_index().values.tolist(), radius=8, max_zoom=4).add_to(base_heatmap)# If you want to save the map base_heatmap.save(outfile= “truckheatMap.html”)# To show the map in jupyterbase_heatmap"
},
{
"code": null,
"e": 2812,
"s": 2341,
"text": "The heat map above doesn’t actually show an accurate picture because we are combining all the data points regardless of time. To get a better picture of where our fleet is spending most of its time we need to somehow incorporate time into this. The pretty animated header of this post is one way to do this. Looking at the fleet moving across the city can reveal they regions in which they are spending more time. So lets generate that animation using the cool Folium..."
},
{
"code": null,
"e": 3377,
"s": 2812,
"text": "# Creating list of hours that we need to slice by to generate the time variant mapdf_hour_list = []for hour in sliceDF.Hour.sort_values().unique(): df_hour_list.append(sliceDF.loc[sliceDF.Hour == hour, ['Lat', 'Lng', 'count']].groupby(['Lat', 'Lng']).sum().reset_index().values.tolist())base_heattimemap = folium.Map(location=[latitude, longitude], zoom_start=11)HeatMapWithTime(df_hour_list, radius=8, gradient={0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 1: 'red'}, min_opacity=0.8, max_opacity=1, use_local_extrema=True).add_to(base_heattimemap)base_heattimemap"
},
{
"code": null,
"e": 3670,
"s": 3377,
"text": "Now, that’s all fine and dandy, but it’s not a way to quantify this. We still need to visually chase the points and guess what regions are denser than others at the end. What if we could have a density based plot that uses a grid and shows us a relative density per each cell? OK, you got it."
},
{
"code": null,
"e": 5686,
"s": 3670,
"text": "# Used a def so that if you wish to add interactivity you can do that easily later on.def plot(min_hour,max_hour,n): #boundaries of the main rectangle upper_right = [51.1741,-113.8925] lower_left = [50.8672,-114.2715] # Creating a grid of nxn from the given cordinate corners grid = get_geojson_grid(upper_right, lower_left , n) # Holds number of points that fall in each cell & time window if provided counts_array = [] # Adding the total number of visits to each cell for box in grid: # get the corners for each cell upper_right = box[\"properties\"][\"upper_right\"] lower_left = box[\"properties\"][\"lower_left\"]# check to make sure it's in the box and between the time window if time window is given mask = ((sliceDF.Lat <= upper_right[1]) & (sliceDF.Lat >= lower_left[1]) & (sliceDF.Lng <= upper_right[0]) & (sliceDF.Lng >= lower_left[0]) & (sliceDF.Hour >= min_hour) & (sliceDF.Hour <= max_hour))# Number of points that fall in the cell and meet the condition counts_array.append(len(sliceDF[mask]))# creating a base map m = folium.Map(zoom_start = 10, location=[latitude, longitude])# Add GeoJson to map for i, geo_json in enumerate(grid): relativeCount = counts_array[i]*100/4345 color = plt.cm.YlGn(relativeCount) color = mpl.colors.to_hex(color) gj = folium.GeoJson(geo_json, style_function=lambda feature, color=color: { 'fillColor': color, 'color':\"gray\", 'weight': 0.5, 'dashArray': '6,6', 'fillOpacity': 0.8, }) m.add_child(gj) colormap = branca.colormap.linear.YlGn_09.scale(0, 1) colormap = colormap.to_step(index=[0, 0.3, 0.6, 0.8 , 1]) colormap.caption = 'Relative density of fleet activity per cell' colormap.add_to(m)return m# limiting time window for our data to 8 am - 5 pm and also grid is 20 x 20 plot(8,17,20)"
},
{
"code": null,
"e": 5925,
"s": 5686,
"text": "The second part of this post is aiming to show you how to use Foursquare APIs to get some geospatial information about different neighborhoods, group neighborhoods in clusters and eventually combine the results to reach to our conclusion."
},
{
"code": null,
"e": 6175,
"s": 5925,
"text": "I have worked quite a bit with Google’s APIs and later on was introduce to Foursquare when I started digging data science and can be awesome. So for those of you who are not familiar with Foursquare I highly recommend checking it out. It’s worth it."
},
{
"code": null,
"e": 6526,
"s": 6175,
"text": "The community data was shown above. For now we ignore the labels the author has used and assume we don’t have them. Our aim is to cluster those neighborhoods ourselves and find a suitable area for our retail shop (warehouse). For this, we use Foursquare explore API but feel free to check the list of all their APIs might come handy in your projects."
},
{
"code": null,
"e": 6671,
"s": 6526,
"text": "By now, you should know how to plot pretty maps, so lets make one from the community data using the original labels just to see what’s going on."
},
{
"code": null,
"e": 6842,
"s": 6671,
"text": "Next we attempt to get n number of most common venues for each neighborhood and we will feed that into our k-means clustering code to group the neighborhoods in clusters."
},
{
"code": null,
"e": 6957,
"s": 6842,
"text": "To get a list of common venues for a neighborhoods using explore Foursquare API you would do something like below."
},
{
"code": null,
"e": 7470,
"s": 6957,
"text": "# Using Foursquare's explore API get 10 most common venues around # the latitude, longitude provided within 500 m radius. # You'll get the CLIENT_ID, CLIENT_SECRET and VERSION after signing up for Foursquare.(Pay attention to API call limits.)url = \"https://api.foursquare.com/v2/venues/explore?client_id={}&client_secret={}&v={}&ll={},{}&radius=500&limit=10\".format(CLIENT_ID,CLIENT_SECRET,VERSION,neighborhood_lat,neighborhood_lng)# results come back in format of JSON results = requests.get(url).json()results"
},
{
"code": null,
"e": 7569,
"s": 7470,
"text": "We can extend this to all the neighborhoods. The data frame below shows a few rows of the results."
},
{
"code": null,
"e": 8066,
"s": 7569,
"text": "Why? Because we have strings as labels for each neighborhood and need a way to digitizing them so that we can use them in our classification algorithm. “One hot encoding” basically parses your labels and assigns dummy values to each as well as creates new columns per each label and using 1 or 0 to determine weather that row of table has that feature or not. So, for instance, Spruce Cliff has cafe, but may not have a gym and so on. The snippet below shows how to “one hot encode” your results:"
},
{
"code": null,
"e": 8534,
"s": 8066,
"text": "# one hot encodingcalgary_onehot = pd.get_dummies(calgary_venues[['Venue Category']], prefix=\"\", prefix_sep=\"\")# add neighborhood column back to dataframecalgary_onehot['Neighbourhood'] = calgary_venues['Neighborhood']# move neighborhood column to the first columnfixed_columns = [calgary_onehot.columns[-1]] + list(calgary_onehot.columns[:-1])calgary_onehot = calgary_onehot[fixed_columns]print(\"calgary_onehot shape is \" , calgary_onehot.shape)calgary_onehot.head()"
},
{
"code": null,
"e": 8578,
"s": 8534,
"text": "The resulting table is something like this:"
},
{
"code": null,
"e": 8976,
"s": 8578,
"text": "For gaining a better insight on the nature of each neighborhood, we can group these result and fined the most common venues per neighborhood. We can then attempt to label each neighborhood, so for instance, a neighborhood with more coffee shops and grocery stores is most likely a residential area while a neighborhood with more construction zones or factories might be an industrial neighborhood."
},
{
"code": null,
"e": 9084,
"s": 8976,
"text": "We will create a pandas dataframe from the results and include 10 most common venues for each neighborhood."
},
{
"code": null,
"e": 10067,
"s": 9084,
"text": "num_top_venues = 10indicators = ['st', 'nd', 'rd']def return_most_common_venues(row, num_top_venues): row_categories = row.iloc[1:] row_categories_sorted = row_categories.sort_values(ascending=False) return row_categories_sorted.index.values[0:num_top_venues]# create columns according to number of top venuescolumns = ['Neighborhood']for ind in np.arange(num_top_venues): try: columns.append('{}{} Most Common Venue'.format(ind+1, indicators[ind])) except: columns.append('{}th Most Common Venue'.format(ind+1))# create a new dataframeneighborhoods_venues_sorted = pd.DataFrame(columns=columns)neighborhoods_venues_sorted['Neighborhood'] = calgary_grouped['Neighbourhood']neighborhoods_venues_sorted.rename(columns={'Neighborhood':\"NAME\"},inplace=True)for ind in np.arange(calgary_grouped.shape[0]): neighborhoods_venues_sorted.iloc[ind, 1:] = return_most_common_venues(calgary_grouped.iloc[ind, :], num_top_venues)neighborhoods_venues_sorted.head()"
},
{
"code": null,
"e": 10106,
"s": 10067,
"text": "and the result is something like this:"
},
{
"code": null,
"e": 10413,
"s": 10106,
"text": "Now we are at a point to cluster our neighborhoods based on the one hot encoded data frame we have. In this case I used kmeans-clustering from Sklearn package and to be able to compare the results later on with the original cluster labels in our community data I chose to use n=4 as the number of clusters."
},
{
"code": null,
"e": 10779,
"s": 10413,
"text": "# set number of clusterskclusters = 4calgary_grouped_clustering = calgary_grouped.drop('Neighbourhood', 1)# run k-means clusteringkmeans = KMeans(n_clusters=kclusters, random_state=0).fit(calgary_grouped_clustering)# check cluster labels generated for each row in the dataframeneighborhoods_venues_sorted['labels'] = kmeans.labels_neighborhoods_venues_sorted.head()"
},
{
"code": null,
"e": 10969,
"s": 10779,
"text": "Let’s merge our results with the original dataframe which includes the geolocations and make a pretty plot with some selectors so we can filter through the clusters and see what’s going on."
},
{
"code": null,
"e": 10980,
"s": 10969,
"text": "The graph:"
},
{
"code": null,
"e": 11006,
"s": 10980,
"text": "The code to achieve this:"
},
{
"code": null,
"e": 12218,
"s": 11006,
"text": "calgary_merged['labels'] = calgary_merged['labels'].astype(int)map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11)# set color scheme for the clustersx = np.arange(kclusters)ys = [i + x + (i*x)**2 for i in range(kclusters)]colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))rainbow = [colors.rgb2hex(i) for i in colors_array]for cluster in range(0,kclusters): group = folium.FeatureGroup(name='<span style=\\\\\"color: {0};\\\\\">{1}</span>'.format(rainbow[cluster-1],cluster)) for lat, lon, poi, label in zip(calgary_merged['latitude'], calgary_merged['longitude'], calgary_merged['CLASS_CODE'], calgary_merged['labels']): if int(label) == cluster: label = folium.Popup('ORIG. '+ str(poi) + 'Cluster ' + str(cluster), parse_html=True) folium.CircleMarker( (lat, lon), radius=5, popup=label, color=rainbow[cluster-1], fill=True, fill_color=rainbow[cluster-1], fill_opacity=0.7).add_to(group) group.add_to(map_clusters)folium.map.LayerControl('topright', collapsed=False).add_to(map_clusters)map_clusters.save(outfile= \"map_clusters.html\")map_clusters"
},
{
"code": null,
"e": 12454,
"s": 12218,
"text": "OK, all that is fine and dandy so what? The whole point of this study was to compare the clusters with the labels and try to identify a suitable location close to the center of minimum distance for a retail store or rather a warehouse."
},
{
"code": null,
"e": 12825,
"s": 12454,
"text": "So lets group by our cluster labels and the original labels and have a look at the confusion matrix. Keep in mind the original labels are not necessarily the true labels and are merely subjective labels made by the author of data set. So this should give us some ideas as to how similar are the distributions of our labels compared to the original ones and nothing more."
},
{
"code": null,
"e": 13117,
"s": 12825,
"text": "The final result of our finding is shown below. The red circle is enclosing the center of medium distance (Median Center) as well as two of the neighborhoods which were determined to be most likely under development or industrial (the most common venues were construction, big retain stores)"
},
{
"code": null,
"e": 13398,
"s": 13117,
"text": "GPS data from the fleet and the city community data were used to support this finding and form a basis for this conclusion. Keep in mind I was trying to show you how you can quickly and without digging too much in details find an approximate solution for a problem of this nature."
}
] |
How to create and apply CSS to JavaScript Alert box?
|
The standard alert box in JavaScript does not provide the option to apply CSS. To style your alert box, you need to create a custom one first. The custom alert box will be created using jQuery and styles will be applied to CSS.
You can try to run the following code to learn how to create and apply CSS to alert box −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function functionAlert(msg, myYes) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #F3F5F6;
color: #000000;
border: 1px solid #aaa;
position: fixed;
width: 300px;
height: 100px;
left: 40%;
top: 40%;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #FFFFFF;
display: inline-block;
border-radius: 12px;
border: 4px solid #aaa;
padding: 5px;
text-align: center;
width: 60px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message">This is a warning message.</div><br>
<button class="yes">OK</button>
</div>
<input type="button" value="Click Me" onclick="functionAlert();" />
</body>
</html>
|
[
{
"code": null,
"e": 1291,
"s": 1062,
"text": " The standard alert box in JavaScript does not provide the option to apply CSS. To style your alert box, you need to create a custom one first. The custom alert box will be created using jQuery and styles will be applied to CSS."
},
{
"code": null,
"e": 1381,
"s": 1291,
"text": "You can try to run the following code to learn how to create and apply CSS to alert box −"
},
{
"code": null,
"e": 1391,
"s": 1381,
"text": "Live Demo"
},
{
"code": null,
"e": 2906,
"s": 1391,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n function functionAlert(msg, myYes) {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes\").unbind().click(function() {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm {\n display: none;\n background-color: #F3F5F6;\n color: #000000;\n border: 1px solid #aaa;\n position: fixed;\n width: 300px;\n height: 100px;\n left: 40%;\n top: 40%;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #FFFFFF;\n display: inline-block;\n border-radius: 12px;\n border: 4px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 60px;\n cursor: pointer;\n }\n #confirm .message {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id=\"confirm\">\n <div class=\"message\">This is a warning message.</div><br>\n <button class=\"yes\">OK</button>\n </div>\n <input type=\"button\" value=\"Click Me\" onclick=\"functionAlert();\" />\n </body>\n </html>"
}
] |
user defined exceptions in Java - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
User-defined exceptions in Java are used to handle the application-specific error conditions. Here application-specific error conditions are bound to a specific application those are not generic for all the applications.
The guys implemented the Java API, provide us extreme Exception handling mechanism which was generic for all the Java-based applications. In the previous tutorials, we have discussed what is Exceptions and top 10 Exceptions in Java. Now we are going to discuss the importance of user-defined exceptions.
The best scenario, when we talk about the user defined exceptions are banking domain applications. In any banking application, the major modules are deposits and withdrawals. When performing a withdrawal from a bank account, it is required to validate the minimum balance in the account. To validate this requirement Java didn’t provide any specific exception class. Hence to handle this requirement, a user-defined exception MinimumAccountBalance may be created.
The user defined exceptions are generated using the throw statement and handle them as normal exceptions.
If necessary, we can write our own user defined exceptions and throw and handle them. We can create the user defined exceptions by extending the Exception class.
class MinimumAccountBalance extends Exception{
}
import java.util.Scanner;
class MinimumAccountBalance extends Exception {
String message;
public MinimumAccountBalance(String message) {
this.message = message;
}
@Override
public String toString() {
return message;
}
}
public class UserDefinedException {
static double current_balance = 100;
public static void main(String[] args) throws MinimumAccountBalance {
Scanner s = new Scanner(System.in);
System.out.println("Enter amount to withdrawal");
int n = s.nextInt();
try {
if (current_balance < n) {
throw new MinimumAccountBalance("Insufficient funds ! your Current balance is " + current_balance);
} else {
System.out.println("Please Take The Money : " + n);
}
} catch (MinimumAccountBalance mab) {
mab.printStackTrace();
}
}
}
Output:
Case I:
Enter amount to withdrawal
200
Insufficient funds ! your Current balance is 100.0
Case II:
Enter amount to withdrawal
90
Please Take The Money : 90
Happy Learning 🙂
User defined sorting with Java 8 Comparator
What is Exception in Java
How do we Handle Exception in Java
Top 10 Exceptions in Java
Checked and Unchecked Exceptions in Java
Catching Multiple Exceptions in Java 7
Writing data to a file in Java
Try with Resources Example in Java
Advantages of Exception Handling
String sorting in Java
Java Program to Find the GCD of Two Numbers
Exception Chaining and Debugging Example
Java Program to Find the characters count in String
Factory Method Pattern in Java
How to Rotate an Array to Left direction based on user input ?
User defined sorting with Java 8 Comparator
What is Exception in Java
How do we Handle Exception in Java
Top 10 Exceptions in Java
Checked and Unchecked Exceptions in Java
Catching Multiple Exceptions in Java 7
Writing data to a file in Java
Try with Resources Example in Java
Advantages of Exception Handling
String sorting in Java
Java Program to Find the GCD of Two Numbers
Exception Chaining and Debugging Example
Java Program to Find the characters count in String
Factory Method Pattern in Java
How to Rotate an Array to Left direction based on user input ?
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 619,
"s": 398,
"text": "User-defined exceptions in Java are used to handle the application-specific error conditions. Here application-specific error conditions are bound to a specific application those are not generic for all the applications."
},
{
"code": null,
"e": 923,
"s": 619,
"text": "The guys implemented the Java API, provide us extreme Exception handling mechanism which was generic for all the Java-based applications. In the previous tutorials, we have discussed what is Exceptions and top 10 Exceptions in Java. Now we are going to discuss the importance of user-defined exceptions."
},
{
"code": null,
"e": 1387,
"s": 923,
"text": "The best scenario, when we talk about the user defined exceptions are banking domain applications. In any banking application, the major modules are deposits and withdrawals. When performing a withdrawal from a bank account, it is required to validate the minimum balance in the account. To validate this requirement Java didn’t provide any specific exception class. Hence to handle this requirement, a user-defined exception MinimumAccountBalance may be created."
},
{
"code": null,
"e": 1493,
"s": 1387,
"text": "The user defined exceptions are generated using the throw statement and handle them as normal exceptions."
},
{
"code": null,
"e": 1655,
"s": 1493,
"text": "If necessary, we can write our own user defined exceptions and throw and handle them. We can create the user defined exceptions by extending the Exception class."
},
{
"code": null,
"e": 1705,
"s": 1655,
"text": "class MinimumAccountBalance extends Exception{\n\n}"
},
{
"code": null,
"e": 2629,
"s": 1707,
"text": "import java.util.Scanner;\n\nclass MinimumAccountBalance extends Exception {\n\n String message;\n\n public MinimumAccountBalance(String message) {\n this.message = message;\n }\n\n @Override\n public String toString() {\n return message;\n }\n}\n\npublic class UserDefinedException {\n\n static double current_balance = 100;\n\n public static void main(String[] args) throws MinimumAccountBalance {\n Scanner s = new Scanner(System.in);\n System.out.println(\"Enter amount to withdrawal\");\n int n = s.nextInt();\n try {\n if (current_balance < n) {\n throw new MinimumAccountBalance(\"Insufficient funds ! your Current balance is \" + current_balance);\n } else {\n System.out.println(\"Please Take The Money : \" + n);\n }\n\n } catch (MinimumAccountBalance mab) {\n mab.printStackTrace();\n }\n }\n\n}"
},
{
"code": null,
"e": 2637,
"s": 2629,
"text": "Output:"
},
{
"code": null,
"e": 2796,
"s": 2637,
"text": "Case I:\n\nEnter amount to withdrawal\n200\nInsufficient funds ! your Current balance is 100.0\n\nCase II:\n\nEnter amount to withdrawal\n90\nPlease Take The Money : 90"
},
{
"code": null,
"e": 2813,
"s": 2796,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3379,
"s": 2813,
"text": "\nUser defined sorting with Java 8 Comparator\nWhat is Exception in Java\nHow do we Handle Exception in Java\nTop 10 Exceptions in Java\nChecked and Unchecked Exceptions in Java\nCatching Multiple Exceptions in Java 7\nWriting data to a file in Java\nTry with Resources Example in Java\nAdvantages of Exception Handling\nString sorting in Java\nJava Program to Find the GCD of Two Numbers\nException Chaining and Debugging Example\nJava Program to Find the characters count in String\nFactory Method Pattern in Java\nHow to Rotate an Array to Left direction based on user input ?\n"
},
{
"code": null,
"e": 3423,
"s": 3379,
"text": "User defined sorting with Java 8 Comparator"
},
{
"code": null,
"e": 3449,
"s": 3423,
"text": "What is Exception in Java"
},
{
"code": null,
"e": 3484,
"s": 3449,
"text": "How do we Handle Exception in Java"
},
{
"code": null,
"e": 3510,
"s": 3484,
"text": "Top 10 Exceptions in Java"
},
{
"code": null,
"e": 3551,
"s": 3510,
"text": "Checked and Unchecked Exceptions in Java"
},
{
"code": null,
"e": 3590,
"s": 3551,
"text": "Catching Multiple Exceptions in Java 7"
},
{
"code": null,
"e": 3621,
"s": 3590,
"text": "Writing data to a file in Java"
},
{
"code": null,
"e": 3656,
"s": 3621,
"text": "Try with Resources Example in Java"
},
{
"code": null,
"e": 3689,
"s": 3656,
"text": "Advantages of Exception Handling"
},
{
"code": null,
"e": 3712,
"s": 3689,
"text": "String sorting in Java"
},
{
"code": null,
"e": 3756,
"s": 3712,
"text": "Java Program to Find the GCD of Two Numbers"
},
{
"code": null,
"e": 3797,
"s": 3756,
"text": "Exception Chaining and Debugging Example"
},
{
"code": null,
"e": 3849,
"s": 3797,
"text": "Java Program to Find the characters count in String"
},
{
"code": null,
"e": 3880,
"s": 3849,
"text": "Factory Method Pattern in Java"
},
{
"code": null,
"e": 3943,
"s": 3880,
"text": "How to Rotate an Array to Left direction based on user input ?"
},
{
"code": null,
"e": 3949,
"s": 3947,
"text": "Δ"
},
{
"code": null,
"e": 3973,
"s": 3949,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 4001,
"s": 3973,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 4030,
"s": 4001,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 4065,
"s": 4030,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 4092,
"s": 4065,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 4119,
"s": 4092,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 4148,
"s": 4119,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 4174,
"s": 4148,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 4200,
"s": 4174,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 4236,
"s": 4200,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 4270,
"s": 4236,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 4296,
"s": 4270,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 4321,
"s": 4296,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 4355,
"s": 4321,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 4390,
"s": 4355,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 4414,
"s": 4390,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 4443,
"s": 4414,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 4475,
"s": 4443,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 4508,
"s": 4475,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 4533,
"s": 4508,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 4550,
"s": 4533,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 4578,
"s": 4550,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 4609,
"s": 4578,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 4641,
"s": 4609,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 4661,
"s": 4641,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 4681,
"s": 4661,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 4705,
"s": 4681,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 4735,
"s": 4705,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 4767,
"s": 4735,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 4803,
"s": 4767,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 4847,
"s": 4803,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 4879,
"s": 4847,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 4920,
"s": 4879,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 4957,
"s": 4920,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4997,
"s": 4957,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 5026,
"s": 4997,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 5058,
"s": 5026,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 5078,
"s": 5058,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 5100,
"s": 5078,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 5130,
"s": 5100,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 5181,
"s": 5130,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 5217,
"s": 5181,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 5249,
"s": 5217,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 5284,
"s": 5249,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 5307,
"s": 5284,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 5354,
"s": 5307,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 5379,
"s": 5354,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 5423,
"s": 5379,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
Bootstrap .btn-primary class
|
The .btn-primary class provides extra visual weight and identifies the primary action in a set of buttons:
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta name = "viewport" content = "width=device-width, initial-scale=1">
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<button type = "button" class = "btn btn-primary">Primary Button</button>
</body>
</html>
|
[
{
"code": null,
"e": 1169,
"s": 1062,
"text": "The .btn-primary class provides extra visual weight and identifies the primary action in a set of buttons:"
},
{
"code": null,
"e": 1179,
"s": 1169,
"text": "Live Demo"
},
{
"code": null,
"e": 1764,
"s": 1179,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale=1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <button type = \"button\" class = \"btn btn-primary\">Primary Button</button>\n </body>\n</html>"
}
] |
CelebA Attribute Prediction and Clustering with Keras | by Luca Anzalone | Towards Data Science
|
In this article, we talk about facial attribute prediction. We will examine the dataset and point out its weaknesses. Furthermore, we will build and train a deep model and finally discuss the overall results.
Facial Attribute prediction is a Computer Vision (CV) task about deducing the set of attributes belonging to a face. Example attributes are the color of hair, hairstyle, age, gender, etc.
In general, facial attribute prediction is a challenging task: it involves face localization first, and then attribute prediction. Moreover, faces are inherently difficult to analyze due to their complex appearance. The appearance of a face can be altered, being even more complex, by face variations. The most common form of face variations are the following:
Occlusions: hairstyle, makeup, glasses (especially sunglasses), hats and other kind of objects can hide meaningful pixels needed by the model to detect a face and its attributes. In case of extreme occlusion, a model may not be able to localize a face at all!
Illumination: extreme lightning or extreme shadowing can make the work of a detection algorithm much harder (if not impossible), like occlusions do.
Expression: emotions can alter the way a face normally appear. If a detection system has never seen faces subject to emotions during training, it can fail to detect them correctly.
Pose: high-degree rotations in terms of roll (x-axis), yaw (z-axis) e pitch (y-axis) can eventually alter both the appearance of a face, and hide its facial features.
Thus, it’s very important that a convolutional model is trained on difficult exemplars of faces in order to generalize well to faces captured in the wild (faces captured under any kind of conditions).
Facial attribute prediction is not only an academic challenge, but also a way to improve existing applications. For example, a photo app can detect the “smiling” attribute in order to decide which is the best photo among a given sequence.
A nice, wide, and diversified dataset to work with is the CelebA dataset. It is a large-scale face attributes dataset with more than 200K celebrity images, covering a large amount of variations, each with 40 attribute annotations.
So, the first thing to do is to download the dataset. It can be found here or on Kaggle, by executing the following code in the terminal:
# install kaggle first: $> pip install kaggle# set your Kaggle API key:os.environ['KAGGLE_USERNAME'] = "YOUR_USERNAME" os.environ['KAGGLE_KEY'] = "YOUR_API_KEY"# then download: $> kaggle datasets download -d jessicali9530/celeba-dataset
After downloading and unzipping it, we can load it in our Python environment or Jupyter Notebook. For this, I’ve prepared the CelebA class that does all the boring work, loading the dataset into a nice Pandas DataFrame:
Now, its a piece of cake to load the dataset (I assume that its path is celeba-dataset\) and eventually select a subset of the facial attributes. In the example code, we drop three features.
# load the dataset with 37 out of 40 features:celeba = CelebA(drop_features=[ 'Attractive', 'Pale_Skin', 'Blurry',])
After that, we can show some random samples to understand the structure of the celeba dataframe.
# shows five random samplesceleba.attributes.sample(5)
Now we know that every example is associated to a vector of binary labels, where each attribute can be 0 or 1. Therefore, can be very useful to know how much faces an attribute belong to (I omit this but each image of the dataset depicts a single face). By counting the times a 1 occurs for a certain attribute, it is possible to compute its absolute frequency (or even relative frequency by dividing by the total number of samples).
Here, we can clearly observe a data imbalance problem. The frequency of the facial attributes vary a lot, rather than being roughly equal to each other. There are rare attributes (Bald, Mustache, Double_Chin, etc) with a frequency below 10%, and a couple of very common attributes (No_Beard, Young) with a frequency above 70%.
This exhibit another issue: the dataset is biased with respect to young and beardless people.
When the data is imbalanced, the model can easily overfit the datapoints. In this case, it can learn to always output a 1 for every common attributes, and always output a 0 for the rare attributes: the model finds out that this strategy (predicting 0s and 1s) is good (which is not true, because it doesn’t learn patterns). Following this fashion, the model’s output predictions will look like [1, 0, ..., 0, 1] vectors, all the same for every image.
If that happen, the resulting model is quite dumb: it will only waste computational resources, because it can be replaced by simple code (e.g. random guess, or a constant value).
The good news is that the problem can be mitigated by using a proper loss function (further details in the next section).
Finally, the above image shows some images taken from CelebA:
The model we are going to build is heavily based on the MobileNetV2 architecture, basically is the same model but without the top classification layers (MobileNetV2 is built to output 1000 class probabilities).
First, the model takes one image (3 channels, 224×224 in size) at a time as input, and outputs a vector of probabilities of size n (typically, the size vary according to how much attributes you want to detect). The i-th element of the vector is a real number between 0 (attribute i is not present) and 1 (attribute i is present).
Note that the output vector can contain more than one non-zero elements, meaning that more than one attribute can belong to a face.
To define the model architecture we have to load the MobileNetV2 architecture without its top layers, set the input size to be 224×224, and add the new top layers. The following code implements all the needed operations:
Then to create the model and display its summary (layers, number of parameters, ...), run the following code:
model = build_model(num_features=celeba.num_features)model.summary()
As you can see, creating the model is simple. Here, we will review the newly added top layers:
GlobalAveragePooling2D: uses a kernel big as the last convolutional layers’ kernel to produce 1×1 feature maps. So, if the last convolutional layers outputs n feature maps, each of them wide w and tall h, the global average pooling layer will apply a kernel (w, h) to each feature map to obtain n confidence scores. When the kernel is big as the feature map, the result is a scalar or, equivalently, a 1×1 feature map. Doing so, allows to reduce the number of Fully-Connected (Dense) layers (usually, being at least 2 — thanks to GlobalAveragePooling only one is necessary), thus, reducing the number of parameters, training time, and speed-up inference. The GlobalAveragePooling layer was one of the key innovation of the GoogleLeNet model.
Note that without the GlobalAveragePooling layer, a Flatten layer is necessary. Flattening (w, h, n) feature maps results in a layer with w×h×n units, instead of n resulting from the application of global average pooling (the number of parameter is, thus, considerably less).
Dense: after that, we use a dense layer with 1536 units ReLU-activated, to perform nonlinear combinations of the confidence scores (this increases the model capacity as well its discriminative ability).
BatchNormalization: the model is based on a very deep architecture with hundreds of layers. In order to speed-up training and to reduce the chances for the gradient to vanish or explode, we apply Batch Normalization that normalizes, scales, and shifts the inputs right before applying an activation function. Batch normalization does this by learning four additional parameters. In some cases, batch normalization has regularizing effects.
Dropout: randomly deactivates units during training, according to a probability p. In this way, a neuron (unit) is less depended on its neighbor units. This forces the model to generalize better. In addition, dropout can be seen as a simple and efficient (but approximated) method to train an ensemble of many neural networks: at each iteration, different neurons are deactivated resulting in a different network. When training ends, the resulting network performs roughly as averaging all the different networks obtained during training time.
Dense: this is the output layer of the network. Here we use sigmoid as activation function because it allows to have classes (attributes) that are not mutually exclusive (with a softmax layer only one output element can be 1), and more importantly, to directly estimate the probability for each attribute.
Finally, the model is pretty simple to create and is even small: it has only 4.3M parameters, being lightweight and fast, making it also suitable for mobile and web applications.
Sometimes, training a neural network to solve a certain task given a dataset, can be seen as trying to make the network fit the true underlying probability distribution that generates the dataset and the real-world data (the dataset is only a part of the whole data). Usually, the true probability distribution is unknown and can only be partially estimated thanks to the use of a dataset during training.
The amount of training data impacts directly the generalization capability of the network we are trying to train. Briefly, the generalization error drops as the amount of training data increases.
The sad news is that, usually, the training data cannot capture the entire probability distribution, because there could be no examples that cover a particular case of the distribution.
Actually, what we can do is to slightly “edit” the training data in order to intentionally introduce some variations (e.g. rotations, shifts, ...) — we assume that the real-world data could have such variations.
The practice of Data Augmentation is an effective way to increase the size of the training set. Augmenting the training examples allow the network to “see” more diversified, but still representative, datapoints during training.
The following code defines a set of augmentations for the training-set: rotation, shift, shear, flip, and zoom.
Note that both the validation-set and test-set must not be augmented.
Then we define a couple of data generators: one for training data, and the other for validation data.
When we deal with big datasets that doesn’t fit into memory, we have to find a way to load only the data actually needed.
A data generator is capable of loading the required amount of data (a minibatch of images) directly from the source folder, convert them into training data (fed to the model) and training targets (a vector of attributes — the supervision signal).
For my experiments, I usually set the batch_size = 80. In general a value between 64 and 128 should work well. Usually you want to increase/decrease the batch size according to computational resources and model’s performances.
At this point we select the adadelta optimizer (adam optimizer is fine too, but it seems to perform slightly worse) with default values: like adam, adadelta is an optimizer that requires little tuning because it is capable of automatically adapting the learning rate (slowing down when things go wrong, or moving faster towards promising directions).
The next step, is to chose the loss function: responsible of monitoring the model’s performance and guiding the optimization process.
I find out that a good loss function for attribute prediction task, is a function able to discriminate the single elements of the attribute vector rather than considering the whole vector as a single object. I mean that the loss must understand that the vector [0, 1, 1, 0] is a lot different from this vector [1, 0, 0, 1](the loss should be high); what is meaningful is the amount of 1s and 0s, and the exact location of the single elements within the input vector.
Loss functions like Mean Absolute Error (MAE), Mean Square Error (MSE) or Root Mean Square Error (RMSE) are not capable of doing this kind of distinction: intuitively, they just count the 1s over a vector, and average on them, consequently loosing information about position.
Instead, loss functions like binary cross-entropy and cosine proximity are the ideal choice. Empirically, the latter seems to perform slightly better.
The last step, is to choose our target performance measure. In this case, we care about maximizing the binary accuracy of the model’s predictions.
Finally, we can compile our model:
model.compile(loss='cosine_proximity', optimizer='adadelta', metrics='binary_accuracy')
Before training the model is useful to define one or more callbacks. Pretty handy one, are: ModelCheckpoint and EarlyStopping.
ModelCheckpoint: when training requires a lot of time to achieve a good result, often many iterations (or a few costly one) are required. In this case, it is better to save a copy of the best performing model only when an epoch that improves the metrics ends.
EarlyStopping: sometimes, during training we can notice that the generalization gap (i.e. the difference between training and validation error) starts to increase, instead of decreasing. This is a symptom of overfitting that can be solved in many ways (reducing model capacity, increasing training data, data augmentation, regularization, dropout, etc). Often, a practical and efficient solution is to stop training when the generalization gap is getting worse.
Actually, I’ve used only the ModelCheckpoint callback because there was no need to use early stopping. Anyway, if you want to play around by changing the model architecture, hyperparameters, loss and optimizer, the use of early stopping is suggested.
The following code will start training, collecting fitting info into the history variable that provides two learning curve: one for loss, and another for accuracy; which can be both plotted.
Usually, I set num_epochs to be between 10 and 20. Note that the model reaches more or less 89% of accuracy in the first two epochs. But requires longer training to stuck at about 91% (well, at least this is the maximum accuracy I’ve got).
Note: each epoch took around 40 minutes to complete (on Google Colab GPU).
To evaluate the model on the test partition of the dataset, we have to set the test data generator, and let the model make a prediction for each test-data:
The test accuracy I’ve got is about 90.95%. In particular, each facial attribute is detected with the following accuracy:
Once we have a working model, we can do stuff like clustering. For this task, the goal of clustering is to group images into clusters where each cluster share the largest possible amount of facial attributes among the images it contains.
In other words, we want to group images whose faces have similar attributes, like having a blonde girls cluster, guys with hats and eyeglasses, etc.
For example, if we want to cluster the following ten attributes:
'Wearing_Lipstick''Smiling''No_Beard' 'Heavy_Makeup''Bald''Male' 'Young''Eyeglasses''Blond_Hair''Wearing_Hat'
we may end up with these clusters:
Here, we can see that each cluster captures one or more facial attributes among the ones that we chosen.
Note: the above clusters are obtained by running standard clustering algorithms like K-Means, on the model’s predictions.
To have a better understanding of the attributes that the cluster have captured, we can summarize it and observe the cluster’s summary, instead.
A cluster can be summarized by extracting its “distinctive features”. Such a thing can be done by computing the principal components describing the cluster (e.g. using PCA). In this case we have clusters of faces, so we can try to compute an eigenface for each cluster, and see what it looks like...
Surprisingly, a cluster’s eigenface is able to summarize the entire cluster by producing a synthetic face (not belonging to the cluster) whose facial attributes are the one captured by the cluster.
In this way, we can see at a glance what are the prominent facial attributes of a set of images, grouped into the same cluster.
In conclusion, well engineered and general applicable models like MobileNetV2 (or Inception and Resnet models), make possible to build effective task-specific models.
It is always a good practice to analyze the dataset and observe some of its sample, in order to understand its structure, data, and eventual flaws.
Attribute prediction is a task that can improve many existing applications and fields (e.g. security, photography, etc).
I omitted the code about the clustering because is a bit long and convoluted. Anyway, you can find all the code at this repository.
I recommend experiment with the Jupyter notebook version of the code.
Hope you enjoyed it, and Thanks for reading it!
Anzalone, Luca, et al. “Transfer Learning for Facial Attributes Prediction and Clustering.” International Conference on Smart City and Informatization. Springer, Singapore, 2019.
Liu, Ziwei, et al. “Deep learning face attributes in the wild.” Proceedings of the IEEE international conference on computer vision. 2015.
MIT 6.S191: Introduction to Deep Learning
Goodfellow, Ian, Yoshua Bengio, and Aaron Courville. Deep learning. MIT press, 2016.
Szegedy, Christian, et al. “Going deeper with convolutions.” Proceedings of the IEEE conference on computer vision and pattern recognition. 2015.
|
[
{
"code": null,
"e": 380,
"s": 171,
"text": "In this article, we talk about facial attribute prediction. We will examine the dataset and point out its weaknesses. Furthermore, we will build and train a deep model and finally discuss the overall results."
},
{
"code": null,
"e": 568,
"s": 380,
"text": "Facial Attribute prediction is a Computer Vision (CV) task about deducing the set of attributes belonging to a face. Example attributes are the color of hair, hairstyle, age, gender, etc."
},
{
"code": null,
"e": 929,
"s": 568,
"text": "In general, facial attribute prediction is a challenging task: it involves face localization first, and then attribute prediction. Moreover, faces are inherently difficult to analyze due to their complex appearance. The appearance of a face can be altered, being even more complex, by face variations. The most common form of face variations are the following:"
},
{
"code": null,
"e": 1189,
"s": 929,
"text": "Occlusions: hairstyle, makeup, glasses (especially sunglasses), hats and other kind of objects can hide meaningful pixels needed by the model to detect a face and its attributes. In case of extreme occlusion, a model may not be able to localize a face at all!"
},
{
"code": null,
"e": 1338,
"s": 1189,
"text": "Illumination: extreme lightning or extreme shadowing can make the work of a detection algorithm much harder (if not impossible), like occlusions do."
},
{
"code": null,
"e": 1519,
"s": 1338,
"text": "Expression: emotions can alter the way a face normally appear. If a detection system has never seen faces subject to emotions during training, it can fail to detect them correctly."
},
{
"code": null,
"e": 1686,
"s": 1519,
"text": "Pose: high-degree rotations in terms of roll (x-axis), yaw (z-axis) e pitch (y-axis) can eventually alter both the appearance of a face, and hide its facial features."
},
{
"code": null,
"e": 1887,
"s": 1686,
"text": "Thus, it’s very important that a convolutional model is trained on difficult exemplars of faces in order to generalize well to faces captured in the wild (faces captured under any kind of conditions)."
},
{
"code": null,
"e": 2126,
"s": 1887,
"text": "Facial attribute prediction is not only an academic challenge, but also a way to improve existing applications. For example, a photo app can detect the “smiling” attribute in order to decide which is the best photo among a given sequence."
},
{
"code": null,
"e": 2357,
"s": 2126,
"text": "A nice, wide, and diversified dataset to work with is the CelebA dataset. It is a large-scale face attributes dataset with more than 200K celebrity images, covering a large amount of variations, each with 40 attribute annotations."
},
{
"code": null,
"e": 2495,
"s": 2357,
"text": "So, the first thing to do is to download the dataset. It can be found here or on Kaggle, by executing the following code in the terminal:"
},
{
"code": null,
"e": 2754,
"s": 2495,
"text": "# install kaggle first: $> pip install kaggle# set your Kaggle API key:os.environ['KAGGLE_USERNAME'] = \"YOUR_USERNAME\" os.environ['KAGGLE_KEY'] = \"YOUR_API_KEY\"# then download: $> kaggle datasets download -d jessicali9530/celeba-dataset"
},
{
"code": null,
"e": 2974,
"s": 2754,
"text": "After downloading and unzipping it, we can load it in our Python environment or Jupyter Notebook. For this, I’ve prepared the CelebA class that does all the boring work, loading the dataset into a nice Pandas DataFrame:"
},
{
"code": null,
"e": 3165,
"s": 2974,
"text": "Now, its a piece of cake to load the dataset (I assume that its path is celeba-dataset\\) and eventually select a subset of the facial attributes. In the example code, we drop three features."
},
{
"code": null,
"e": 3291,
"s": 3165,
"text": "# load the dataset with 37 out of 40 features:celeba = CelebA(drop_features=[ 'Attractive', 'Pale_Skin', 'Blurry',])"
},
{
"code": null,
"e": 3388,
"s": 3291,
"text": "After that, we can show some random samples to understand the structure of the celeba dataframe."
},
{
"code": null,
"e": 3443,
"s": 3388,
"text": "# shows five random samplesceleba.attributes.sample(5)"
},
{
"code": null,
"e": 3877,
"s": 3443,
"text": "Now we know that every example is associated to a vector of binary labels, where each attribute can be 0 or 1. Therefore, can be very useful to know how much faces an attribute belong to (I omit this but each image of the dataset depicts a single face). By counting the times a 1 occurs for a certain attribute, it is possible to compute its absolute frequency (or even relative frequency by dividing by the total number of samples)."
},
{
"code": null,
"e": 4204,
"s": 3877,
"text": "Here, we can clearly observe a data imbalance problem. The frequency of the facial attributes vary a lot, rather than being roughly equal to each other. There are rare attributes (Bald, Mustache, Double_Chin, etc) with a frequency below 10%, and a couple of very common attributes (No_Beard, Young) with a frequency above 70%."
},
{
"code": null,
"e": 4298,
"s": 4204,
"text": "This exhibit another issue: the dataset is biased with respect to young and beardless people."
},
{
"code": null,
"e": 4749,
"s": 4298,
"text": "When the data is imbalanced, the model can easily overfit the datapoints. In this case, it can learn to always output a 1 for every common attributes, and always output a 0 for the rare attributes: the model finds out that this strategy (predicting 0s and 1s) is good (which is not true, because it doesn’t learn patterns). Following this fashion, the model’s output predictions will look like [1, 0, ..., 0, 1] vectors, all the same for every image."
},
{
"code": null,
"e": 4928,
"s": 4749,
"text": "If that happen, the resulting model is quite dumb: it will only waste computational resources, because it can be replaced by simple code (e.g. random guess, or a constant value)."
},
{
"code": null,
"e": 5050,
"s": 4928,
"text": "The good news is that the problem can be mitigated by using a proper loss function (further details in the next section)."
},
{
"code": null,
"e": 5112,
"s": 5050,
"text": "Finally, the above image shows some images taken from CelebA:"
},
{
"code": null,
"e": 5323,
"s": 5112,
"text": "The model we are going to build is heavily based on the MobileNetV2 architecture, basically is the same model but without the top classification layers (MobileNetV2 is built to output 1000 class probabilities)."
},
{
"code": null,
"e": 5653,
"s": 5323,
"text": "First, the model takes one image (3 channels, 224×224 in size) at a time as input, and outputs a vector of probabilities of size n (typically, the size vary according to how much attributes you want to detect). The i-th element of the vector is a real number between 0 (attribute i is not present) and 1 (attribute i is present)."
},
{
"code": null,
"e": 5785,
"s": 5653,
"text": "Note that the output vector can contain more than one non-zero elements, meaning that more than one attribute can belong to a face."
},
{
"code": null,
"e": 6006,
"s": 5785,
"text": "To define the model architecture we have to load the MobileNetV2 architecture without its top layers, set the input size to be 224×224, and add the new top layers. The following code implements all the needed operations:"
},
{
"code": null,
"e": 6116,
"s": 6006,
"text": "Then to create the model and display its summary (layers, number of parameters, ...), run the following code:"
},
{
"code": null,
"e": 6185,
"s": 6116,
"text": "model = build_model(num_features=celeba.num_features)model.summary()"
},
{
"code": null,
"e": 6280,
"s": 6185,
"text": "As you can see, creating the model is simple. Here, we will review the newly added top layers:"
},
{
"code": null,
"e": 7022,
"s": 6280,
"text": "GlobalAveragePooling2D: uses a kernel big as the last convolutional layers’ kernel to produce 1×1 feature maps. So, if the last convolutional layers outputs n feature maps, each of them wide w and tall h, the global average pooling layer will apply a kernel (w, h) to each feature map to obtain n confidence scores. When the kernel is big as the feature map, the result is a scalar or, equivalently, a 1×1 feature map. Doing so, allows to reduce the number of Fully-Connected (Dense) layers (usually, being at least 2 — thanks to GlobalAveragePooling only one is necessary), thus, reducing the number of parameters, training time, and speed-up inference. The GlobalAveragePooling layer was one of the key innovation of the GoogleLeNet model."
},
{
"code": null,
"e": 7298,
"s": 7022,
"text": "Note that without the GlobalAveragePooling layer, a Flatten layer is necessary. Flattening (w, h, n) feature maps results in a layer with w×h×n units, instead of n resulting from the application of global average pooling (the number of parameter is, thus, considerably less)."
},
{
"code": null,
"e": 7501,
"s": 7298,
"text": "Dense: after that, we use a dense layer with 1536 units ReLU-activated, to perform nonlinear combinations of the confidence scores (this increases the model capacity as well its discriminative ability)."
},
{
"code": null,
"e": 7941,
"s": 7501,
"text": "BatchNormalization: the model is based on a very deep architecture with hundreds of layers. In order to speed-up training and to reduce the chances for the gradient to vanish or explode, we apply Batch Normalization that normalizes, scales, and shifts the inputs right before applying an activation function. Batch normalization does this by learning four additional parameters. In some cases, batch normalization has regularizing effects."
},
{
"code": null,
"e": 8485,
"s": 7941,
"text": "Dropout: randomly deactivates units during training, according to a probability p. In this way, a neuron (unit) is less depended on its neighbor units. This forces the model to generalize better. In addition, dropout can be seen as a simple and efficient (but approximated) method to train an ensemble of many neural networks: at each iteration, different neurons are deactivated resulting in a different network. When training ends, the resulting network performs roughly as averaging all the different networks obtained during training time."
},
{
"code": null,
"e": 8791,
"s": 8485,
"text": "Dense: this is the output layer of the network. Here we use sigmoid as activation function because it allows to have classes (attributes) that are not mutually exclusive (with a softmax layer only one output element can be 1), and more importantly, to directly estimate the probability for each attribute."
},
{
"code": null,
"e": 8970,
"s": 8791,
"text": "Finally, the model is pretty simple to create and is even small: it has only 4.3M parameters, being lightweight and fast, making it also suitable for mobile and web applications."
},
{
"code": null,
"e": 9376,
"s": 8970,
"text": "Sometimes, training a neural network to solve a certain task given a dataset, can be seen as trying to make the network fit the true underlying probability distribution that generates the dataset and the real-world data (the dataset is only a part of the whole data). Usually, the true probability distribution is unknown and can only be partially estimated thanks to the use of a dataset during training."
},
{
"code": null,
"e": 9572,
"s": 9376,
"text": "The amount of training data impacts directly the generalization capability of the network we are trying to train. Briefly, the generalization error drops as the amount of training data increases."
},
{
"code": null,
"e": 9758,
"s": 9572,
"text": "The sad news is that, usually, the training data cannot capture the entire probability distribution, because there could be no examples that cover a particular case of the distribution."
},
{
"code": null,
"e": 9970,
"s": 9758,
"text": "Actually, what we can do is to slightly “edit” the training data in order to intentionally introduce some variations (e.g. rotations, shifts, ...) — we assume that the real-world data could have such variations."
},
{
"code": null,
"e": 10198,
"s": 9970,
"text": "The practice of Data Augmentation is an effective way to increase the size of the training set. Augmenting the training examples allow the network to “see” more diversified, but still representative, datapoints during training."
},
{
"code": null,
"e": 10310,
"s": 10198,
"text": "The following code defines a set of augmentations for the training-set: rotation, shift, shear, flip, and zoom."
},
{
"code": null,
"e": 10380,
"s": 10310,
"text": "Note that both the validation-set and test-set must not be augmented."
},
{
"code": null,
"e": 10482,
"s": 10380,
"text": "Then we define a couple of data generators: one for training data, and the other for validation data."
},
{
"code": null,
"e": 10604,
"s": 10482,
"text": "When we deal with big datasets that doesn’t fit into memory, we have to find a way to load only the data actually needed."
},
{
"code": null,
"e": 10851,
"s": 10604,
"text": "A data generator is capable of loading the required amount of data (a minibatch of images) directly from the source folder, convert them into training data (fed to the model) and training targets (a vector of attributes — the supervision signal)."
},
{
"code": null,
"e": 11078,
"s": 10851,
"text": "For my experiments, I usually set the batch_size = 80. In general a value between 64 and 128 should work well. Usually you want to increase/decrease the batch size according to computational resources and model’s performances."
},
{
"code": null,
"e": 11429,
"s": 11078,
"text": "At this point we select the adadelta optimizer (adam optimizer is fine too, but it seems to perform slightly worse) with default values: like adam, adadelta is an optimizer that requires little tuning because it is capable of automatically adapting the learning rate (slowing down when things go wrong, or moving faster towards promising directions)."
},
{
"code": null,
"e": 11563,
"s": 11429,
"text": "The next step, is to chose the loss function: responsible of monitoring the model’s performance and guiding the optimization process."
},
{
"code": null,
"e": 12030,
"s": 11563,
"text": "I find out that a good loss function for attribute prediction task, is a function able to discriminate the single elements of the attribute vector rather than considering the whole vector as a single object. I mean that the loss must understand that the vector [0, 1, 1, 0] is a lot different from this vector [1, 0, 0, 1](the loss should be high); what is meaningful is the amount of 1s and 0s, and the exact location of the single elements within the input vector."
},
{
"code": null,
"e": 12306,
"s": 12030,
"text": "Loss functions like Mean Absolute Error (MAE), Mean Square Error (MSE) or Root Mean Square Error (RMSE) are not capable of doing this kind of distinction: intuitively, they just count the 1s over a vector, and average on them, consequently loosing information about position."
},
{
"code": null,
"e": 12457,
"s": 12306,
"text": "Instead, loss functions like binary cross-entropy and cosine proximity are the ideal choice. Empirically, the latter seems to perform slightly better."
},
{
"code": null,
"e": 12604,
"s": 12457,
"text": "The last step, is to choose our target performance measure. In this case, we care about maximizing the binary accuracy of the model’s predictions."
},
{
"code": null,
"e": 12639,
"s": 12604,
"text": "Finally, we can compile our model:"
},
{
"code": null,
"e": 12753,
"s": 12639,
"text": "model.compile(loss='cosine_proximity', optimizer='adadelta', metrics='binary_accuracy')"
},
{
"code": null,
"e": 12880,
"s": 12753,
"text": "Before training the model is useful to define one or more callbacks. Pretty handy one, are: ModelCheckpoint and EarlyStopping."
},
{
"code": null,
"e": 13140,
"s": 12880,
"text": "ModelCheckpoint: when training requires a lot of time to achieve a good result, often many iterations (or a few costly one) are required. In this case, it is better to save a copy of the best performing model only when an epoch that improves the metrics ends."
},
{
"code": null,
"e": 13602,
"s": 13140,
"text": "EarlyStopping: sometimes, during training we can notice that the generalization gap (i.e. the difference between training and validation error) starts to increase, instead of decreasing. This is a symptom of overfitting that can be solved in many ways (reducing model capacity, increasing training data, data augmentation, regularization, dropout, etc). Often, a practical and efficient solution is to stop training when the generalization gap is getting worse."
},
{
"code": null,
"e": 13853,
"s": 13602,
"text": "Actually, I’ve used only the ModelCheckpoint callback because there was no need to use early stopping. Anyway, if you want to play around by changing the model architecture, hyperparameters, loss and optimizer, the use of early stopping is suggested."
},
{
"code": null,
"e": 14044,
"s": 13853,
"text": "The following code will start training, collecting fitting info into the history variable that provides two learning curve: one for loss, and another for accuracy; which can be both plotted."
},
{
"code": null,
"e": 14284,
"s": 14044,
"text": "Usually, I set num_epochs to be between 10 and 20. Note that the model reaches more or less 89% of accuracy in the first two epochs. But requires longer training to stuck at about 91% (well, at least this is the maximum accuracy I’ve got)."
},
{
"code": null,
"e": 14359,
"s": 14284,
"text": "Note: each epoch took around 40 minutes to complete (on Google Colab GPU)."
},
{
"code": null,
"e": 14515,
"s": 14359,
"text": "To evaluate the model on the test partition of the dataset, we have to set the test data generator, and let the model make a prediction for each test-data:"
},
{
"code": null,
"e": 14637,
"s": 14515,
"text": "The test accuracy I’ve got is about 90.95%. In particular, each facial attribute is detected with the following accuracy:"
},
{
"code": null,
"e": 14875,
"s": 14637,
"text": "Once we have a working model, we can do stuff like clustering. For this task, the goal of clustering is to group images into clusters where each cluster share the largest possible amount of facial attributes among the images it contains."
},
{
"code": null,
"e": 15024,
"s": 14875,
"text": "In other words, we want to group images whose faces have similar attributes, like having a blonde girls cluster, guys with hats and eyeglasses, etc."
},
{
"code": null,
"e": 15089,
"s": 15024,
"text": "For example, if we want to cluster the following ten attributes:"
},
{
"code": null,
"e": 15221,
"s": 15089,
"text": "'Wearing_Lipstick''Smiling''No_Beard' 'Heavy_Makeup''Bald''Male' 'Young''Eyeglasses''Blond_Hair''Wearing_Hat'"
},
{
"code": null,
"e": 15256,
"s": 15221,
"text": "we may end up with these clusters:"
},
{
"code": null,
"e": 15361,
"s": 15256,
"text": "Here, we can see that each cluster captures one or more facial attributes among the ones that we chosen."
},
{
"code": null,
"e": 15483,
"s": 15361,
"text": "Note: the above clusters are obtained by running standard clustering algorithms like K-Means, on the model’s predictions."
},
{
"code": null,
"e": 15628,
"s": 15483,
"text": "To have a better understanding of the attributes that the cluster have captured, we can summarize it and observe the cluster’s summary, instead."
},
{
"code": null,
"e": 15928,
"s": 15628,
"text": "A cluster can be summarized by extracting its “distinctive features”. Such a thing can be done by computing the principal components describing the cluster (e.g. using PCA). In this case we have clusters of faces, so we can try to compute an eigenface for each cluster, and see what it looks like..."
},
{
"code": null,
"e": 16126,
"s": 15928,
"text": "Surprisingly, a cluster’s eigenface is able to summarize the entire cluster by producing a synthetic face (not belonging to the cluster) whose facial attributes are the one captured by the cluster."
},
{
"code": null,
"e": 16254,
"s": 16126,
"text": "In this way, we can see at a glance what are the prominent facial attributes of a set of images, grouped into the same cluster."
},
{
"code": null,
"e": 16421,
"s": 16254,
"text": "In conclusion, well engineered and general applicable models like MobileNetV2 (or Inception and Resnet models), make possible to build effective task-specific models."
},
{
"code": null,
"e": 16569,
"s": 16421,
"text": "It is always a good practice to analyze the dataset and observe some of its sample, in order to understand its structure, data, and eventual flaws."
},
{
"code": null,
"e": 16690,
"s": 16569,
"text": "Attribute prediction is a task that can improve many existing applications and fields (e.g. security, photography, etc)."
},
{
"code": null,
"e": 16822,
"s": 16690,
"text": "I omitted the code about the clustering because is a bit long and convoluted. Anyway, you can find all the code at this repository."
},
{
"code": null,
"e": 16892,
"s": 16822,
"text": "I recommend experiment with the Jupyter notebook version of the code."
},
{
"code": null,
"e": 16940,
"s": 16892,
"text": "Hope you enjoyed it, and Thanks for reading it!"
},
{
"code": null,
"e": 17119,
"s": 16940,
"text": "Anzalone, Luca, et al. “Transfer Learning for Facial Attributes Prediction and Clustering.” International Conference on Smart City and Informatization. Springer, Singapore, 2019."
},
{
"code": null,
"e": 17258,
"s": 17119,
"text": "Liu, Ziwei, et al. “Deep learning face attributes in the wild.” Proceedings of the IEEE international conference on computer vision. 2015."
},
{
"code": null,
"e": 17300,
"s": 17258,
"text": "MIT 6.S191: Introduction to Deep Learning"
},
{
"code": null,
"e": 17385,
"s": 17300,
"text": "Goodfellow, Ian, Yoshua Bengio, and Aaron Courville. Deep learning. MIT press, 2016."
}
] |
Tug of War Algorithm
|
In this problem a set of integers are given, we have to break them into two parts, such that the difference of the sum of two subsets is minimum as possible. So our target is to divide two groups of nearly equal strength to participate in the Tug of war game.
If the size of subset n is even, it must be divided into n/2, but for the odd value of n, then the size of one subset must be (n-1)/2, and size of another subset must be (n+1)/2.
Input:
A set of different weights.
{23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4}
Output:
The left and right subset to distribute the weights to make the difference minimum.
Left: {45, -34, 12, 98, -1}
Right: {23, 0, -99, 4, 189, 4}
tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos)
Input − Set of given weights, number of weights, current list, number of selected items, the difference between two subset sum, the sum of all items, total in the subset, position of the selected element.
Output − Solution set for selected for left and right subsets.
Begin
if pos = n, then //when all elements are taken
return
if (n/2-select) > (n - pos), then
return
tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1)
select := select + 1
total := total + weight[pos]
curr[pos] := true //when item at pos is taken
if select = n/2, then
if difference of (sum/2 and total) < diff, then
diff := difference of (sum/2 and total)
for i := 0 to n, do
sol[i] := curr[i]
done
else
tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1)
curr[pos] := false //remove current element if not properly done
End
#include <iostream>
#include<cmath>
using namespace std;
void tugOfWar(int* weight, int n, bool curr[], int select, bool sol[], int &diff, int sum, int total, int pos) {
if (pos == n) //when the pos is covered all weights
return;
if ((n/2 - select) > (n - pos)) //left elements must be bigger than required result
return;
tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1);
select++;
total += weight[pos];
curr[pos] = true; //add current element to the solution
if (select == n/2) { //when solution is formed
if (abs(sum/2 - total) < diff) { //check whether it is better solution or not
diff = abs(sum/2 - total);
for (int i = 0; i<n; i++)
sol[i] = curr[i];
}
} else {
tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1);
}
curr[pos] = false; //when not properly done, remove current element
}
void findSolution(int *arr, int n) {
bool* curr = new bool[n];
bool* soln = new bool[n];
int diff = INT_MAX; //set minimum difference to infinity initially
int sum = 0;
for (int i=0; i<n; i++) {
sum += arr[i]; //find the sum of all elements
curr[i] = soln[i] = false; //make all elements as false
}
tugOfWar(arr, n, curr, 0, soln, diff, sum, 0, 0);
cout << "Left: ";
for (int i=0; i<n; i++)
if (soln[i] == true)
cout << arr[i] << " ";
cout << endl << "Right: ";
for (int i=0; i<n; i++)
if (soln[i] == false)
cout << arr[i] << " ";
}
int main() {
int weight[] = {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4};
int n = 11;
findSolution(weight, n);
}
Left: 45 -34 12 98 -1
Right: 23 0 -99 4 189 4
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "In this problem a set of integers are given, we have to break them into two parts, such that the difference of the sum of two subsets is minimum as possible. So our target is to divide two groups of nearly equal strength to participate in the Tug of war game."
},
{
"code": null,
"e": 1501,
"s": 1322,
"text": "If the size of subset n is even, it must be divided into n/2, but for the odd value of n, then the size of one subset must be (n-1)/2, and size of another subset must be (n+1)/2."
},
{
"code": null,
"e": 1732,
"s": 1501,
"text": "Input:\nA set of different weights.\n{23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4}\nOutput:\nThe left and right subset to distribute the weights to make the difference minimum.\nLeft: {45, -34, 12, 98, -1}\nRight: {23, 0, -99, 4, 189, 4}"
},
{
"code": null,
"e": 1794,
"s": 1732,
"text": "tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos)"
},
{
"code": null,
"e": 1999,
"s": 1794,
"text": "Input − Set of given weights, number of weights, current list, number of selected items, the difference between two subset sum, the sum of all items, total in the subset, position of the selected element."
},
{
"code": null,
"e": 2062,
"s": 1999,
"text": "Output − Solution set for selected for left and right subsets."
},
{
"code": null,
"e": 2717,
"s": 2062,
"text": "Begin\n if pos = n, then //when all elements are taken\n return\n if (n/2-select) > (n - pos), then\n return\n tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1)\n select := select + 1\n total := total + weight[pos]\n curr[pos] := true //when item at pos is taken\n\n if select = n/2, then\n if difference of (sum/2 and total) < diff, then\n diff := difference of (sum/2 and total)\n for i := 0 to n, do\n sol[i] := curr[i]\n done\n else\n tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1)\n curr[pos] := false //remove current element if not properly done\nEnd"
},
{
"code": null,
"e": 4418,
"s": 2717,
"text": "#include <iostream>\n#include<cmath>\nusing namespace std;\n\nvoid tugOfWar(int* weight, int n, bool curr[], int select, bool sol[], int &diff, int sum, int total, int pos) {\n if (pos == n) //when the pos is covered all weights\n return;\n if ((n/2 - select) > (n - pos)) //left elements must be bigger than required result\n return;\n tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1);\n\n select++;\n total += weight[pos];\n curr[pos] = true; //add current element to the solution\n\n if (select == n/2) { //when solution is formed\n if (abs(sum/2 - total) < diff) { //check whether it is better solution or not\n diff = abs(sum/2 - total);\n for (int i = 0; i<n; i++)\n sol[i] = curr[i];\n }\n } else {\n tugOfWar(weight, n, curr, select, sol, diff, sum, total, pos+1);\n }\n curr[pos] = false; //when not properly done, remove current element\n}\n\nvoid findSolution(int *arr, int n) {\n bool* curr = new bool[n];\n bool* soln = new bool[n];\n int diff = INT_MAX; //set minimum difference to infinity initially\n int sum = 0;\n\n for (int i=0; i<n; i++) {\n sum += arr[i]; //find the sum of all elements\n curr[i] = soln[i] = false; //make all elements as false\n }\n\n tugOfWar(arr, n, curr, 0, soln, diff, sum, 0, 0);\n cout << \"Left: \";\n\n for (int i=0; i<n; i++)\n if (soln[i] == true)\n cout << arr[i] << \" \";\n cout << endl << \"Right: \";\n\n for (int i=0; i<n; i++)\n if (soln[i] == false)\n cout << arr[i] << \" \";\n}\n\nint main() {\n int weight[] = {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4};\n int n = 11;\n findSolution(weight, n);\n}"
},
{
"code": null,
"e": 4464,
"s": 4418,
"text": "Left: 45 -34 12 98 -1\nRight: 23 0 -99 4 189 4"
}
] |
Slideio: a new python library for reading medical images. | by Stanislav Melnikov | Towards Data Science
|
This is an introduction to a new python library for the reading of medical images. More detailed information can be found on the project WEB site: www.slideio.com. The source code is available on a GitLab repository: https://gitlab.com/bioslide/slideio.
Medical images — images produced by bio-scanners, microscopes, etc. are different from normal images. One of the important differences is their size. Such images can be very large. Currently, slides with sizes of many gigabytes are not so rare. Another difference is the number of dimensions. Many bio-image formats support 3 and 4 dimensions (volumes and time series). Additionally to the conventional dimensions, some formats introduce scanner specific dimensions like focal distance, rotation (for data recorded from various angles), phase index, etc.
It is not possible to encode a multi-gigapixel image with conventional compression methods. Such image codecs like jpeg or png require saving of the whole image to the computer memory to show it on the screen or even to read a small region of the image. Bio-formats solve the problems using tiling approach and zoom pyramids. It allows reading of an arbitrary region of an image at an arbitrary scale with minimal memory and computational resources. A zoom pyramid is a set of image copies at different scales.
Slideio library is designed to read medical images using their internal structure to make the process as performant as possible. Slideio is not the first library that provides such functionality. In my practice in image analysis, I used a lot of different libraries. But so far, I did not find any library that can serve all my requirements for image analysis. So I decided to create my own, which should aggregate my experience in this area.
The library has a driver architecture. Each driver supports one or more image formats. The first version of the slideio provides 4 drivers:
CZI — driver for the reading of Zeiss CZI images.
SVS — driver for the reading of Aperio SVS images.
AFI — driver for the reading of Aperion fluorescent images.
GDAL — driver for the reading of generic formats like jpeg, png, tiff, etc. It uses a popular c++ image library GDAL.
Slideio library has a simple object structure:
Image drivers create Slide objects. Slide object represents a single image file (or a folder, depending on the image format). A Slide object contains at least one Scene object which is a continuous raster region (2D image, volume, time-series, etc). Some image formats support a single scene like a single tissue scan. Some formats allow storing in a file multiple tissue regions. All layers of a 2D Scene have the same pixel size and resolution. If a scene is a 3D volume, all slices of the volume have the same size and resolution. The same is true for time series.
Following code snippet shows how to open a slide with “SVS” image driver:
Slideio library provides image information on different levels. Slide object has a property “raw_metadata” which exposes an unmodified text information extracted from the image. Content of the text is specific to the file format. In the case of the Aperio SVS slide, it is a string extracted from the “Image Information” tiff tag. In the case of the Zeiss CZI file, it is an XML document with complete file metadata. Here is a code snippet for retrieving of the metadata from an Aperio SVS file:
Here is an output produced by the code sample:
['Aperio Image Library vFS90 01\r\n20320x19545 [0,100 19919x19445] (240x240) JPEG/RGB Q=70', 'AppMag = 20', 'StripeWidth = 2032', 'ScanScope ID = SS1598', 'Filename = 24496', 'Date = 11/09/11', 'Time = 18:51:40', 'Time Zone = GMT+09:00', 'User = e8ddb309-efc1-4a6b-b9b0-7c555f9fa0ef', 'MPP = 0.4962', 'Left = 23.939867', 'Top = 19.531540', 'LineCameraSkew = 0.000320', 'LineAreaXOffset = 0.060417', 'LineAreaYOffset = 0.011084', 'Focus Offset = -0.000500', 'DSR ID = ap6101-dsr', 'ImageID = 24496', 'Exposure Time = 109', 'Exposure Scale = 0.000001', 'DisplayColor = 0', 'OriginalWidth = 20320', 'OriginalHeight = 19545', 'ICC Profile = ScanScope v1']
A Scene is the main object for accessing of raster data. It exposes the following information:
compression: type of data compression;
magnification: scanner magnification;
name: scene name;
num_t_frames: number of time frames in the time series;
num_z_slices: number of slices in the volume;
rect: coordinates and dimensions of the scene rectangle;
resolution: the resolution of the scene in-plane (a tuple);
t_resolution, z_resolution: resolutions of the scene in time and z-direction;
num_channels: number of channels in the scene;
channel_data_type: data type of an image channel (byte, 16 bit, etc.);
channel_name: name of an image channel.
The following code snippet retrieves scene name, rectangle, and resolution.
It produces the following output:
('Image', (0, 0, 19919, 19445), 3, (4.961999999999999e-07, 4.961999999999999e-07))
The image has a width of 19919 pixels and a height of 19445 pixels. Each pixel is 0.4962 mkm in both x and y directions. The image has 3 channels. The meaning of a channel in bio images depends on image format. For the bright field images, it is just red, green, and blue colors. Such images have 3 8-bit channels. Channel properties are accessible through methods get_chanel_data_type and get_channel_name.
uint8uint8uint8
Method read_block retrieves pixel values of continuous regions. Execution of the method without parameters retrieves the whole scene in the original size. Normally it is not possible to read the whole image at the original scale because of the large size. In this case, the program can retrieve a region of the image, down-scale it to the acceptable size, or retrieve a down-scaled region. A code snippet bellow. retrieves the whole image and scales it to 500 pixels width picture. Note, zero in place of the picture height indicates that it has to be automatically calculated to keep the same scale in x and y directions.
The code snippet below reads a rectangle region from the image and down-scales it to a 500 pixels width picture.
It is possible to read a single channel or a subset of channels:
Additional tuple-parameters slices and frames allow reading of volumes and time series:
(1000, 1000, 27)
The slideio library can be installed with pip:
pip install slideio
Currently, only Linux and Windows builds are supported.
Slideio is a python module for the reading of medical images. It allows reading of whole slides as well as any region of a slide. Large slides can be effectively scaled to a smaller size. The module uses internal zoom pyramids of images to make the scaling process as fast as possible. Slideio supports 2D slides as well as 3D data sets and time series.
The library delivers raster as numpy array and compatible with many popular image analysis libraries such as opencv.
Currently, it supports reading of Aperio SVS and AFI files, Zeiss CZI files and generic formats. Soon coming drivers for the following formats:
PerkinElmer images
Leica SCN images
DICOM datasets
Leica lif images
and more ...
Thank you for reading. Any comments or suggestions would be highly appreciated.
|
[
{
"code": null,
"e": 425,
"s": 171,
"text": "This is an introduction to a new python library for the reading of medical images. More detailed information can be found on the project WEB site: www.slideio.com. The source code is available on a GitLab repository: https://gitlab.com/bioslide/slideio."
},
{
"code": null,
"e": 980,
"s": 425,
"text": "Medical images — images produced by bio-scanners, microscopes, etc. are different from normal images. One of the important differences is their size. Such images can be very large. Currently, slides with sizes of many gigabytes are not so rare. Another difference is the number of dimensions. Many bio-image formats support 3 and 4 dimensions (volumes and time series). Additionally to the conventional dimensions, some formats introduce scanner specific dimensions like focal distance, rotation (for data recorded from various angles), phase index, etc."
},
{
"code": null,
"e": 1491,
"s": 980,
"text": "It is not possible to encode a multi-gigapixel image with conventional compression methods. Such image codecs like jpeg or png require saving of the whole image to the computer memory to show it on the screen or even to read a small region of the image. Bio-formats solve the problems using tiling approach and zoom pyramids. It allows reading of an arbitrary region of an image at an arbitrary scale with minimal memory and computational resources. A zoom pyramid is a set of image copies at different scales."
},
{
"code": null,
"e": 1934,
"s": 1491,
"text": "Slideio library is designed to read medical images using their internal structure to make the process as performant as possible. Slideio is not the first library that provides such functionality. In my practice in image analysis, I used a lot of different libraries. But so far, I did not find any library that can serve all my requirements for image analysis. So I decided to create my own, which should aggregate my experience in this area."
},
{
"code": null,
"e": 2074,
"s": 1934,
"text": "The library has a driver architecture. Each driver supports one or more image formats. The first version of the slideio provides 4 drivers:"
},
{
"code": null,
"e": 2124,
"s": 2074,
"text": "CZI — driver for the reading of Zeiss CZI images."
},
{
"code": null,
"e": 2175,
"s": 2124,
"text": "SVS — driver for the reading of Aperio SVS images."
},
{
"code": null,
"e": 2235,
"s": 2175,
"text": "AFI — driver for the reading of Aperion fluorescent images."
},
{
"code": null,
"e": 2353,
"s": 2235,
"text": "GDAL — driver for the reading of generic formats like jpeg, png, tiff, etc. It uses a popular c++ image library GDAL."
},
{
"code": null,
"e": 2400,
"s": 2353,
"text": "Slideio library has a simple object structure:"
},
{
"code": null,
"e": 2968,
"s": 2400,
"text": "Image drivers create Slide objects. Slide object represents a single image file (or a folder, depending on the image format). A Slide object contains at least one Scene object which is a continuous raster region (2D image, volume, time-series, etc). Some image formats support a single scene like a single tissue scan. Some formats allow storing in a file multiple tissue regions. All layers of a 2D Scene have the same pixel size and resolution. If a scene is a 3D volume, all slices of the volume have the same size and resolution. The same is true for time series."
},
{
"code": null,
"e": 3042,
"s": 2968,
"text": "Following code snippet shows how to open a slide with “SVS” image driver:"
},
{
"code": null,
"e": 3538,
"s": 3042,
"text": "Slideio library provides image information on different levels. Slide object has a property “raw_metadata” which exposes an unmodified text information extracted from the image. Content of the text is specific to the file format. In the case of the Aperio SVS slide, it is a string extracted from the “Image Information” tiff tag. In the case of the Zeiss CZI file, it is an XML document with complete file metadata. Here is a code snippet for retrieving of the metadata from an Aperio SVS file:"
},
{
"code": null,
"e": 3585,
"s": 3538,
"text": "Here is an output produced by the code sample:"
},
{
"code": null,
"e": 4237,
"s": 3585,
"text": "['Aperio Image Library vFS90 01\\r\\n20320x19545 [0,100 19919x19445] (240x240) JPEG/RGB Q=70', 'AppMag = 20', 'StripeWidth = 2032', 'ScanScope ID = SS1598', 'Filename = 24496', 'Date = 11/09/11', 'Time = 18:51:40', 'Time Zone = GMT+09:00', 'User = e8ddb309-efc1-4a6b-b9b0-7c555f9fa0ef', 'MPP = 0.4962', 'Left = 23.939867', 'Top = 19.531540', 'LineCameraSkew = 0.000320', 'LineAreaXOffset = 0.060417', 'LineAreaYOffset = 0.011084', 'Focus Offset = -0.000500', 'DSR ID = ap6101-dsr', 'ImageID = 24496', 'Exposure Time = 109', 'Exposure Scale = 0.000001', 'DisplayColor = 0', 'OriginalWidth = 20320', 'OriginalHeight = 19545', 'ICC Profile = ScanScope v1']"
},
{
"code": null,
"e": 4332,
"s": 4237,
"text": "A Scene is the main object for accessing of raster data. It exposes the following information:"
},
{
"code": null,
"e": 4371,
"s": 4332,
"text": "compression: type of data compression;"
},
{
"code": null,
"e": 4409,
"s": 4371,
"text": "magnification: scanner magnification;"
},
{
"code": null,
"e": 4427,
"s": 4409,
"text": "name: scene name;"
},
{
"code": null,
"e": 4483,
"s": 4427,
"text": "num_t_frames: number of time frames in the time series;"
},
{
"code": null,
"e": 4529,
"s": 4483,
"text": "num_z_slices: number of slices in the volume;"
},
{
"code": null,
"e": 4586,
"s": 4529,
"text": "rect: coordinates and dimensions of the scene rectangle;"
},
{
"code": null,
"e": 4646,
"s": 4586,
"text": "resolution: the resolution of the scene in-plane (a tuple);"
},
{
"code": null,
"e": 4724,
"s": 4646,
"text": "t_resolution, z_resolution: resolutions of the scene in time and z-direction;"
},
{
"code": null,
"e": 4771,
"s": 4724,
"text": "num_channels: number of channels in the scene;"
},
{
"code": null,
"e": 4842,
"s": 4771,
"text": "channel_data_type: data type of an image channel (byte, 16 bit, etc.);"
},
{
"code": null,
"e": 4882,
"s": 4842,
"text": "channel_name: name of an image channel."
},
{
"code": null,
"e": 4958,
"s": 4882,
"text": "The following code snippet retrieves scene name, rectangle, and resolution."
},
{
"code": null,
"e": 4992,
"s": 4958,
"text": "It produces the following output:"
},
{
"code": null,
"e": 5075,
"s": 4992,
"text": "('Image', (0, 0, 19919, 19445), 3, (4.961999999999999e-07, 4.961999999999999e-07))"
},
{
"code": null,
"e": 5483,
"s": 5075,
"text": "The image has a width of 19919 pixels and a height of 19445 pixels. Each pixel is 0.4962 mkm in both x and y directions. The image has 3 channels. The meaning of a channel in bio images depends on image format. For the bright field images, it is just red, green, and blue colors. Such images have 3 8-bit channels. Channel properties are accessible through methods get_chanel_data_type and get_channel_name."
},
{
"code": null,
"e": 5499,
"s": 5483,
"text": "uint8uint8uint8"
},
{
"code": null,
"e": 6122,
"s": 5499,
"text": "Method read_block retrieves pixel values of continuous regions. Execution of the method without parameters retrieves the whole scene in the original size. Normally it is not possible to read the whole image at the original scale because of the large size. In this case, the program can retrieve a region of the image, down-scale it to the acceptable size, or retrieve a down-scaled region. A code snippet bellow. retrieves the whole image and scales it to 500 pixels width picture. Note, zero in place of the picture height indicates that it has to be automatically calculated to keep the same scale in x and y directions."
},
{
"code": null,
"e": 6235,
"s": 6122,
"text": "The code snippet below reads a rectangle region from the image and down-scales it to a 500 pixels width picture."
},
{
"code": null,
"e": 6300,
"s": 6235,
"text": "It is possible to read a single channel or a subset of channels:"
},
{
"code": null,
"e": 6388,
"s": 6300,
"text": "Additional tuple-parameters slices and frames allow reading of volumes and time series:"
},
{
"code": null,
"e": 6405,
"s": 6388,
"text": "(1000, 1000, 27)"
},
{
"code": null,
"e": 6452,
"s": 6405,
"text": "The slideio library can be installed with pip:"
},
{
"code": null,
"e": 6472,
"s": 6452,
"text": "pip install slideio"
},
{
"code": null,
"e": 6528,
"s": 6472,
"text": "Currently, only Linux and Windows builds are supported."
},
{
"code": null,
"e": 6882,
"s": 6528,
"text": "Slideio is a python module for the reading of medical images. It allows reading of whole slides as well as any region of a slide. Large slides can be effectively scaled to a smaller size. The module uses internal zoom pyramids of images to make the scaling process as fast as possible. Slideio supports 2D slides as well as 3D data sets and time series."
},
{
"code": null,
"e": 6999,
"s": 6882,
"text": "The library delivers raster as numpy array and compatible with many popular image analysis libraries such as opencv."
},
{
"code": null,
"e": 7143,
"s": 6999,
"text": "Currently, it supports reading of Aperio SVS and AFI files, Zeiss CZI files and generic formats. Soon coming drivers for the following formats:"
},
{
"code": null,
"e": 7162,
"s": 7143,
"text": "PerkinElmer images"
},
{
"code": null,
"e": 7179,
"s": 7162,
"text": "Leica SCN images"
},
{
"code": null,
"e": 7194,
"s": 7179,
"text": "DICOM datasets"
},
{
"code": null,
"e": 7211,
"s": 7194,
"text": "Leica lif images"
},
{
"code": null,
"e": 7224,
"s": 7211,
"text": "and more ..."
}
] |
How can we convert a JSON array to a list using Jackson in Java?
|
A Jackson is a Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. A Jackson API is faster than other API, needs less memory area and is good for the large objects. We can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.
import java.util.*;
import com.fasterxml.jackson.databind.*;
public class JSONArrayToListTest1 {
public static void main(String args[]) {
String jsonStr = "[\"INDIA\", \"AUSTRALIA\", \"ENGLAND\", \"SOUTH AFRICA\", \"WEST INDIES\"]";
ObjectMapper objectMapper = new ObjectMapper();
try {
List<String> countries = objectMapper.readValue(jsonStr, List.class);
System.out.println("The countries are:\n " + countries);
} catch(Exception e) {
e.printStackTrace();
}
}
}
The countries are:
[INDIA, AUSTRALIA, ENGLAND, SOUTH AFRICA, WEST INDIES]
|
[
{
"code": null,
"e": 1471,
"s": 1062,
"text": "A Jackson is a Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. A Jackson API is faster than other API, needs less memory area and is good for the large objects. We can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument."
},
{
"code": null,
"e": 1998,
"s": 1471,
"text": "import java.util.*;\nimport com.fasterxml.jackson.databind.*;\npublic class JSONArrayToListTest1 {\n public static void main(String args[]) {\n String jsonStr = \"[\\\"INDIA\\\", \\\"AUSTRALIA\\\", \\\"ENGLAND\\\", \\\"SOUTH AFRICA\\\", \\\"WEST INDIES\\\"]\";\n ObjectMapper objectMapper = new ObjectMapper();\n try {\n List<String> countries = objectMapper.readValue(jsonStr, List.class);\n System.out.println(\"The countries are:\\n \" + countries);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2072,
"s": 1998,
"text": "The countries are:\n[INDIA, AUSTRALIA, ENGLAND, SOUTH AFRICA, WEST INDIES]"
}
] |
What are Python function attributes?
|
Everything in Python is an object, and almost everything has attributes and methods. In python, functions too are objects. So they have attributes like other objects. All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code. We can also assign new attributes to them, as well as retrieve the values of those attributes.
For handling attributes, Python provides us with “getattr” and “setattr”, a function that takes three arguments. There is no difference between “setattr” and using the dot-notation on the left side of the = assignment operator:
The given code can be written as follows to assign and retrieve attributes.
def foo():
pass
setattr(foo, 'age', 23 )
setattr(foo, 'name', 'John Doe' )
print(getattr(foo, 'age'))
foo.gender ='male'
print(foo.gender)
print(foo.name)
print(foo.age)
C:/Users/TutorialsPoint1/~.py
23
male
John Doe
23
|
[
{
"code": null,
"e": 1439,
"s": 1062,
"text": "Everything in Python is an object, and almost everything has attributes and methods. In python, functions too are objects. So they have attributes like other objects. All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code. We can also assign new attributes to them, as well as retrieve the values of those attributes."
},
{
"code": null,
"e": 1667,
"s": 1439,
"text": "For handling attributes, Python provides us with “getattr” and “setattr”, a function that takes three arguments. There is no difference between “setattr” and using the dot-notation on the left side of the = assignment operator:"
},
{
"code": null,
"e": 1743,
"s": 1667,
"text": "The given code can be written as follows to assign and retrieve attributes."
},
{
"code": null,
"e": 1917,
"s": 1743,
"text": "def foo():\n pass\nsetattr(foo, 'age', 23 )\nsetattr(foo, 'name', 'John Doe' )\nprint(getattr(foo, 'age'))\nfoo.gender ='male'\nprint(foo.gender)\nprint(foo.name)\nprint(foo.age)"
},
{
"code": null,
"e": 1967,
"s": 1917,
"text": "C:/Users/TutorialsPoint1/~.py\n23\nmale\nJohn Doe\n23"
}
] |
C++ Program to Implement the linear congruential generator for Pseudo Random Number Generation
|
The linear congruential generator is a very simple example of a random number generator. It is one of the oldest and best-known pseudorandom number generator algorithms. The function which is used in this method −
Xn+1=(aXn + C) mod m
where X is the sequence of pseudorandom values, and
m,0<m— the “modulus"
a,0<a<m — the "multiplier"
c,0<c<m — the "increment"
X0, 0<x0<m — the "seed" or "start value"
are integer constants that specify the generator.
A benefit of this method is is that with appropriate choice of parameters, the period is known and long.
Begin
Declare class mRND
Create a function Seed(number)
Assign a variable _seed=number
Create a constructor mRND
Declare _seed(0), a(0), c(0), m(2147483648)
Create a function rnd()
Return
_seed = (a * _seed + c) mod m
Declare a, c, m, _seed
Done
Declare an another subclass MS_RND inheriting from base class mRND
Create a constructor
Read the variables a, c
Create a function rnd()
return mRND::rnd() right shift 16
Done
Declare an another subclass BSD_RND inheriting from base class mRND
Create a constructor
Read the variables a, c
Create a function rnd()
return mRND::rnd()
Done
For x=0 to 6
Print MS_RAND
For x=0 to 6
Print BSD_RAND
Done
End
#include <iostream>
using namespace std;
class mRND {
public:
void seed(unsigned int s) {
_seed= s;
}
protected:
mRND() :
_seed(0), a(0), c(0), m(2147483648) { }
int rnd() {
return (_seed = (a * _seed + c) % m);
}
int a, c;
unsigned int m, _seed;
};
class MS_RND: public mRND {
public:
MS_RND() {
a = 214013;
c = 2531011;
}
int rnd() {
return mRND::rnd() >> 16;
}
};
class BSD_RND: public mRND {
public:
BSD_RND() {
a = 1016404597;
c = 12345;
}
int rnd() {
return mRND::rnd();
}
};
int main(int argc, char* argv[]) {
BSD_RND bsd_rnd;
MS_RND ms_rnd;
cout << "MS RAND:" << endl << "-----------" << endl;
for (int x = 0; x < 6; x++)
cout << ms_rnd.rnd() << endl;
cout << endl << "BSD RAND:" << endl << "-------------" << endl;
for (int x = 0; x < 6; x++)
cout << bsd_rnd.rnd() << endl;
return 0;
}
MS RAND:
-------
38
7719
21238
2437
8855
11797
BSD RAND:
--------
12345
1915290694
1005338679
629284700
741596485
1834373826
|
[
{
"code": null,
"e": 1276,
"s": 1062,
"text": "The linear congruential generator is a very simple example of a random number generator. It is one of the oldest and best-known pseudorandom number generator algorithms. The function which is used in this method −"
},
{
"code": null,
"e": 1297,
"s": 1276,
"text": "Xn+1=(aXn + C) mod m"
},
{
"code": null,
"e": 1349,
"s": 1297,
"text": "where X is the sequence of pseudorandom values, and"
},
{
"code": null,
"e": 1464,
"s": 1349,
"text": "m,0<m— the “modulus\"\na,0<a<m — the \"multiplier\"\nc,0<c<m — the \"increment\"\nX0, 0<x0<m — the \"seed\" or \"start value\""
},
{
"code": null,
"e": 1514,
"s": 1464,
"text": "are integer constants that specify the generator."
},
{
"code": null,
"e": 1619,
"s": 1514,
"text": "A benefit of this method is is that with appropriate choice of parameters, the period is known and long."
},
{
"code": null,
"e": 2388,
"s": 1619,
"text": "Begin\n Declare class mRND\n Create a function Seed(number)\n Assign a variable _seed=number\n Create a constructor mRND\n Declare _seed(0), a(0), c(0), m(2147483648)\n Create a function rnd()\n Return\n _seed = (a * _seed + c) mod m\n Declare a, c, m, _seed\n Done\n Declare an another subclass MS_RND inheriting from base class mRND\n Create a constructor\n Read the variables a, c\n Create a function rnd()\n return mRND::rnd() right shift 16\n Done\n Declare an another subclass BSD_RND inheriting from base class mRND\n Create a constructor\n Read the variables a, c\n Create a function rnd()\n return mRND::rnd()\n Done\n For x=0 to 6\n Print MS_RAND\n For x=0 to 6\n Print BSD_RAND\n Done\nEnd"
},
{
"code": null,
"e": 3327,
"s": 2388,
"text": "#include <iostream>\nusing namespace std;\nclass mRND {\n public:\n void seed(unsigned int s) {\n _seed= s;\n }\n protected:\n mRND() :\n _seed(0), a(0), c(0), m(2147483648) { }\n int rnd() {\n return (_seed = (a * _seed + c) % m);\n }\n int a, c;\n unsigned int m, _seed;\n};\nclass MS_RND: public mRND {\n public:\n MS_RND() {\n a = 214013;\n c = 2531011;\n }\n int rnd() {\n return mRND::rnd() >> 16;\n }\n};\nclass BSD_RND: public mRND {\n public:\n BSD_RND() {\n a = 1016404597;\n c = 12345;\n }\n int rnd() {\n return mRND::rnd();\n }\n};\nint main(int argc, char* argv[]) {\n BSD_RND bsd_rnd;\n MS_RND ms_rnd;\n cout << \"MS RAND:\" << endl << \"-----------\" << endl;\n for (int x = 0; x < 6; x++)\n cout << ms_rnd.rnd() << endl;\n cout << endl << \"BSD RAND:\" << endl << \"-------------\" << endl;\n for (int x = 0; x < 6; x++)\n cout << bsd_rnd.rnd() << endl;\n return 0;\n}"
},
{
"code": null,
"e": 3452,
"s": 3327,
"text": "MS RAND:\n-------\n38\n7719\n21238\n2437\n8855\n11797\nBSD RAND:\n--------\n12345\n1915290694\n1005338679\n629284700\n741596485\n1834373826"
}
] |
Get Nth Column of Matrix in Python
|
When it is required to get the ‘n’th column of a matrix, the ‘any’ method can be used.
Below is a demonstration of the same −
Live Demo
my_list = [[34, 67, 89], [16, 27, 86], [48, 30, 0]]
print("The list is : ")
print(my_list)
N = 1
print("The value of N has been initialized to -")
print(N)
elem = 30
my_result = any(sub[N] == elem for sub in my_list)
print("Does the element exist in a particular column ? ")
print(my_result)
The list is :
[[34, 67, 89], [16, 27, 86], [48, 30, 0]]
The value of N has been initialized to -
1
Does the element exist in a particular column ?
True
A list of list is defined, and is displayed on the console.
A list of list is defined, and is displayed on the console.
The value of N is initialized.
The value of N is initialized.
This is displayed on the console.
This is displayed on the console.
An elem variable is assigned an integer value.
An elem variable is assigned an integer value.
The any method is used to see if any element in the list matches the elem variable previously defined.
The any method is used to see if any element in the list matches the elem variable previously defined.
The results are stored in a variable.
The results are stored in a variable.
This is displayed as output on the console.
This is displayed as output on the console.
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "When it is required to get the ‘n’th column of a matrix, the ‘any’ method can be used."
},
{
"code": null,
"e": 1188,
"s": 1149,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1199,
"s": 1188,
"text": " Live Demo"
},
{
"code": null,
"e": 1495,
"s": 1199,
"text": "my_list = [[34, 67, 89], [16, 27, 86], [48, 30, 0]]\n\nprint(\"The list is : \")\nprint(my_list)\n\nN = 1\nprint(\"The value of N has been initialized to -\")\nprint(N)\nelem = 30\n\nmy_result = any(sub[N] == elem for sub in my_list)\n\nprint(\"Does the element exist in a particular column ? \")\nprint(my_result)"
},
{
"code": null,
"e": 1647,
"s": 1495,
"text": "The list is :\n[[34, 67, 89], [16, 27, 86], [48, 30, 0]]\nThe value of N has been initialized to -\n1\nDoes the element exist in a particular column ?\nTrue"
},
{
"code": null,
"e": 1707,
"s": 1647,
"text": "A list of list is defined, and is displayed on the console."
},
{
"code": null,
"e": 1767,
"s": 1707,
"text": "A list of list is defined, and is displayed on the console."
},
{
"code": null,
"e": 1798,
"s": 1767,
"text": "The value of N is initialized."
},
{
"code": null,
"e": 1829,
"s": 1798,
"text": "The value of N is initialized."
},
{
"code": null,
"e": 1863,
"s": 1829,
"text": "This is displayed on the console."
},
{
"code": null,
"e": 1897,
"s": 1863,
"text": "This is displayed on the console."
},
{
"code": null,
"e": 1944,
"s": 1897,
"text": "An elem variable is assigned an integer value."
},
{
"code": null,
"e": 1991,
"s": 1944,
"text": "An elem variable is assigned an integer value."
},
{
"code": null,
"e": 2094,
"s": 1991,
"text": "The any method is used to see if any element in the list matches the elem variable previously defined."
},
{
"code": null,
"e": 2197,
"s": 2094,
"text": "The any method is used to see if any element in the list matches the elem variable previously defined."
},
{
"code": null,
"e": 2235,
"s": 2197,
"text": "The results are stored in a variable."
},
{
"code": null,
"e": 2273,
"s": 2235,
"text": "The results are stored in a variable."
},
{
"code": null,
"e": 2317,
"s": 2273,
"text": "This is displayed as output on the console."
},
{
"code": null,
"e": 2361,
"s": 2317,
"text": "This is displayed as output on the console."
}
] |
CUDA error 59: Device-side assert triggered | by Perez Ogayo | Towards Data Science
|
If you happen to run into this error, you know how frustrating it can be. The most frustrating part, for me, was the lack of a clear, step-by-step solution to this problem. This could be caused by the fact that PyTorch is still relatively new.
A little backstory ...
I was working on the Stanford car dataset as part of a hackathon born out of my participation in Udacity Pytorch Challenge when I encountered this problem. It took me quite a while to fix it, and this was worsened by the fact that I was using Kaggle Kernels which presented its own challenges with regards to GPU.
What is the Error?
This error occurs due to the following two reasons:
Inconsistency between the number of labels/classes and the number of output unitsThe input of the loss function may be incorrect.
Inconsistency between the number of labels/classes and the number of output units
The input of the loss function may be incorrect.
Let’s unpack these reasons and their solutions below:
Reason 1: Inconsistency between number of labels and number of output units
When defining the final fully connected layer of my model, instead of putting 196(total number of classes for the Stanford car dataset) as the number of output units, I put 195.
The error is usually identified in the line where you do the backpropagation. Your loss function will be comparing the output from your model and the label of that observation in your dataset. Just in case you are confused between labels and output, see how I define them below:
Label: This is the tags associated with an observation. When working on a classification problem, the label is the class. For example, in the classic dog vs cat problem, the labels are cat and dog.
Output: This is the predicted ‘label’ from your model. You give your model a set of features from an observation and it gives out a prediction called output in the PyTorch ecosystem. Think of it as a predicted label.
In my case, some of the labels will have a value 195 which is beyond the range of output for my model whose greatest possible value is 194(Start counting from zero). This causes the error to be triggered.
How can you fix it?
Make sure the number of output units match the number of your classes
That would be changing my classifier to be as follows:
classifier = nn.Sequential(nn.Linear(2048, 700), nn.ReLU(), nn.Dropout(p = 0.2), nn.Linear(700 , 300), nn.ReLU(), nn.Dropout(p = 0.2), nn.Linear(300 ,196), #changed this from 195 to 196 nn.LogSoftmax(dim = 1))model.fc = classifier
This is how you get the number of classes in your dataset programmatically:
#.classes returns a list of the classes in your dataset, usually #numbered from 0 to number_of_classes-1len(dataset.classes)#Calling len() function on the list will return the number of classes in your dataset
Reason 2: Wrong input for the loss function
Loss functions have different ranges for the possible inputs that they can accept. If you choose an incompatible activation function for your output layer this error will be triggered. For example, BCELoss requires its input to be between 0 and 1. If the input(output from your model) is beyond the acceptable range for that particular loss function, the error gets triggered.
Recap on activation loss functions
Activation functions are the mathematical equations that determine the output of your neural network. The purpose of the activation function is to introduce non-linearity into the output of a model thus making a model capable to learn and perform more complex tasks. They, in turn, determine how accurate your network gets to be.
Loss functions are the equations that compute the error that is used to learn by means of backpropagation.
For a detailed explanation of loss functions and how they work, please check out this article and the Pytorch documentation. Find information about activation function here.
How can you fix it?
Make sure your output layer returns values in the range of the loss function(criterion) that you chose. This implies using the appropriate activation function(Sigmoid, Softmax, LogSoftmax) in your final output layer.
Example of problematic code
model = nn.Linear()input = torch.randn(128, 2)output = model(input)criterion=nn.BCELoss()torch.empty(128).random_(2)loss=criterion(output, target)
The code above will trigger runtime error 59 if we are using GPU. You can fix it by passing your output through sigmoid function or using BCEWithLogitsLoss().
Fix 1: Passing the results through Sigmoid function
model = nn.Linear() #The sigmoid funtion can also be applied here as model=nn.Sigmoid(nn.Linear())input = torch.randn(128, 2)output = model(input)criterion=nn.BCELoss()target=torch.empty(128).random_(2)loss=criterion(nn.Sigmoid(output), target)
Fix 2: Using BCEWithLogitsLoss() instead
model = nn.Linear()input = torch.randn(128, 2)output = model(input)criterion=nn.BCEWithLogitsLoss() #changed fromBCELosstarget = torch.empty(128).random_(2)loss=criterion(output, target)
Working on Kaggle? Here’s why even after following the above steps, you are still struggling
Once that error is triggered, you cannot continue using your GPU. Even after changing the problematic line and reloading the entire kernel, you will still get the error presented in different forms. The form depends on which line is the first one to attempt to use the GPU. Look at the image below for an idea.
The reason why this is happening even though you have fixed the bug in your code is that once the runtime error 59 is triggered, you are blocked from using the GPU entirely during the same GPU session that the error was triggered in.
How can you fix it?
Stop your current kernel session and start a new one.
To do this, follow the steps below:
From your Kernel, click the ‘K’ on the top left. It automatically takes you to your kernelsYou will see a list of your kernels, having edit option and additional stop for the ones currently running.Click stop kernelOpen your Kernel afresh, every variable will be reset and you will have a brand new GPU session
From your Kernel, click the ‘K’ on the top left. It automatically takes you to your kernels
You will see a list of your kernels, having edit option and additional stop for the ones currently running.
Click stop kernel
Open your Kernel afresh, every variable will be reset and you will have a brand new GPU session
Extra tip
The error messages you get when running into this error may not be very descriptive. To make sure you get the complete and useful stack trace, have this at the very beginning of your code and run it before anything else:
CUDA_LAUNCH_BLOCKING="1"
References
[1]Thread, GPU goes away after an error occurs #1010(2018), Pytorch Github Issues pages
[2] Lernapprat, Debugging CUDA device-side assert in PyTorch (2018), https://lernapparat.de/
I hope this article helped you. Feel free to leave your comments on any aspect of this tutorial in the response section below.
|
[
{
"code": null,
"e": 416,
"s": 172,
"text": "If you happen to run into this error, you know how frustrating it can be. The most frustrating part, for me, was the lack of a clear, step-by-step solution to this problem. This could be caused by the fact that PyTorch is still relatively new."
},
{
"code": null,
"e": 439,
"s": 416,
"text": "A little backstory ..."
},
{
"code": null,
"e": 753,
"s": 439,
"text": "I was working on the Stanford car dataset as part of a hackathon born out of my participation in Udacity Pytorch Challenge when I encountered this problem. It took me quite a while to fix it, and this was worsened by the fact that I was using Kaggle Kernels which presented its own challenges with regards to GPU."
},
{
"code": null,
"e": 772,
"s": 753,
"text": "What is the Error?"
},
{
"code": null,
"e": 824,
"s": 772,
"text": "This error occurs due to the following two reasons:"
},
{
"code": null,
"e": 954,
"s": 824,
"text": "Inconsistency between the number of labels/classes and the number of output unitsThe input of the loss function may be incorrect."
},
{
"code": null,
"e": 1036,
"s": 954,
"text": "Inconsistency between the number of labels/classes and the number of output units"
},
{
"code": null,
"e": 1085,
"s": 1036,
"text": "The input of the loss function may be incorrect."
},
{
"code": null,
"e": 1139,
"s": 1085,
"text": "Let’s unpack these reasons and their solutions below:"
},
{
"code": null,
"e": 1215,
"s": 1139,
"text": "Reason 1: Inconsistency between number of labels and number of output units"
},
{
"code": null,
"e": 1393,
"s": 1215,
"text": "When defining the final fully connected layer of my model, instead of putting 196(total number of classes for the Stanford car dataset) as the number of output units, I put 195."
},
{
"code": null,
"e": 1672,
"s": 1393,
"text": "The error is usually identified in the line where you do the backpropagation. Your loss function will be comparing the output from your model and the label of that observation in your dataset. Just in case you are confused between labels and output, see how I define them below:"
},
{
"code": null,
"e": 1870,
"s": 1672,
"text": "Label: This is the tags associated with an observation. When working on a classification problem, the label is the class. For example, in the classic dog vs cat problem, the labels are cat and dog."
},
{
"code": null,
"e": 2087,
"s": 1870,
"text": "Output: This is the predicted ‘label’ from your model. You give your model a set of features from an observation and it gives out a prediction called output in the PyTorch ecosystem. Think of it as a predicted label."
},
{
"code": null,
"e": 2292,
"s": 2087,
"text": "In my case, some of the labels will have a value 195 which is beyond the range of output for my model whose greatest possible value is 194(Start counting from zero). This causes the error to be triggered."
},
{
"code": null,
"e": 2312,
"s": 2292,
"text": "How can you fix it?"
},
{
"code": null,
"e": 2382,
"s": 2312,
"text": "Make sure the number of output units match the number of your classes"
},
{
"code": null,
"e": 2437,
"s": 2382,
"text": "That would be changing my classifier to be as follows:"
},
{
"code": null,
"e": 2668,
"s": 2437,
"text": "classifier = nn.Sequential(nn.Linear(2048, 700), nn.ReLU(), nn.Dropout(p = 0.2), nn.Linear(700 , 300), nn.ReLU(), nn.Dropout(p = 0.2), nn.Linear(300 ,196), #changed this from 195 to 196 nn.LogSoftmax(dim = 1))model.fc = classifier"
},
{
"code": null,
"e": 2744,
"s": 2668,
"text": "This is how you get the number of classes in your dataset programmatically:"
},
{
"code": null,
"e": 2954,
"s": 2744,
"text": "#.classes returns a list of the classes in your dataset, usually #numbered from 0 to number_of_classes-1len(dataset.classes)#Calling len() function on the list will return the number of classes in your dataset"
},
{
"code": null,
"e": 2998,
"s": 2954,
"text": "Reason 2: Wrong input for the loss function"
},
{
"code": null,
"e": 3375,
"s": 2998,
"text": "Loss functions have different ranges for the possible inputs that they can accept. If you choose an incompatible activation function for your output layer this error will be triggered. For example, BCELoss requires its input to be between 0 and 1. If the input(output from your model) is beyond the acceptable range for that particular loss function, the error gets triggered."
},
{
"code": null,
"e": 3410,
"s": 3375,
"text": "Recap on activation loss functions"
},
{
"code": null,
"e": 3740,
"s": 3410,
"text": "Activation functions are the mathematical equations that determine the output of your neural network. The purpose of the activation function is to introduce non-linearity into the output of a model thus making a model capable to learn and perform more complex tasks. They, in turn, determine how accurate your network gets to be."
},
{
"code": null,
"e": 3847,
"s": 3740,
"text": "Loss functions are the equations that compute the error that is used to learn by means of backpropagation."
},
{
"code": null,
"e": 4021,
"s": 3847,
"text": "For a detailed explanation of loss functions and how they work, please check out this article and the Pytorch documentation. Find information about activation function here."
},
{
"code": null,
"e": 4041,
"s": 4021,
"text": "How can you fix it?"
},
{
"code": null,
"e": 4258,
"s": 4041,
"text": "Make sure your output layer returns values in the range of the loss function(criterion) that you chose. This implies using the appropriate activation function(Sigmoid, Softmax, LogSoftmax) in your final output layer."
},
{
"code": null,
"e": 4286,
"s": 4258,
"text": "Example of problematic code"
},
{
"code": null,
"e": 4433,
"s": 4286,
"text": "model = nn.Linear()input = torch.randn(128, 2)output = model(input)criterion=nn.BCELoss()torch.empty(128).random_(2)loss=criterion(output, target)"
},
{
"code": null,
"e": 4592,
"s": 4433,
"text": "The code above will trigger runtime error 59 if we are using GPU. You can fix it by passing your output through sigmoid function or using BCEWithLogitsLoss()."
},
{
"code": null,
"e": 4644,
"s": 4592,
"text": "Fix 1: Passing the results through Sigmoid function"
},
{
"code": null,
"e": 4890,
"s": 4644,
"text": "model = nn.Linear() #The sigmoid funtion can also be applied here as model=nn.Sigmoid(nn.Linear())input = torch.randn(128, 2)output = model(input)criterion=nn.BCELoss()target=torch.empty(128).random_(2)loss=criterion(nn.Sigmoid(output), target)"
},
{
"code": null,
"e": 4931,
"s": 4890,
"text": "Fix 2: Using BCEWithLogitsLoss() instead"
},
{
"code": null,
"e": 5118,
"s": 4931,
"text": "model = nn.Linear()input = torch.randn(128, 2)output = model(input)criterion=nn.BCEWithLogitsLoss() #changed fromBCELosstarget = torch.empty(128).random_(2)loss=criterion(output, target)"
},
{
"code": null,
"e": 5211,
"s": 5118,
"text": "Working on Kaggle? Here’s why even after following the above steps, you are still struggling"
},
{
"code": null,
"e": 5522,
"s": 5211,
"text": "Once that error is triggered, you cannot continue using your GPU. Even after changing the problematic line and reloading the entire kernel, you will still get the error presented in different forms. The form depends on which line is the first one to attempt to use the GPU. Look at the image below for an idea."
},
{
"code": null,
"e": 5756,
"s": 5522,
"text": "The reason why this is happening even though you have fixed the bug in your code is that once the runtime error 59 is triggered, you are blocked from using the GPU entirely during the same GPU session that the error was triggered in."
},
{
"code": null,
"e": 5776,
"s": 5756,
"text": "How can you fix it?"
},
{
"code": null,
"e": 5830,
"s": 5776,
"text": "Stop your current kernel session and start a new one."
},
{
"code": null,
"e": 5866,
"s": 5830,
"text": "To do this, follow the steps below:"
},
{
"code": null,
"e": 6177,
"s": 5866,
"text": "From your Kernel, click the ‘K’ on the top left. It automatically takes you to your kernelsYou will see a list of your kernels, having edit option and additional stop for the ones currently running.Click stop kernelOpen your Kernel afresh, every variable will be reset and you will have a brand new GPU session"
},
{
"code": null,
"e": 6269,
"s": 6177,
"text": "From your Kernel, click the ‘K’ on the top left. It automatically takes you to your kernels"
},
{
"code": null,
"e": 6377,
"s": 6269,
"text": "You will see a list of your kernels, having edit option and additional stop for the ones currently running."
},
{
"code": null,
"e": 6395,
"s": 6377,
"text": "Click stop kernel"
},
{
"code": null,
"e": 6491,
"s": 6395,
"text": "Open your Kernel afresh, every variable will be reset and you will have a brand new GPU session"
},
{
"code": null,
"e": 6501,
"s": 6491,
"text": "Extra tip"
},
{
"code": null,
"e": 6722,
"s": 6501,
"text": "The error messages you get when running into this error may not be very descriptive. To make sure you get the complete and useful stack trace, have this at the very beginning of your code and run it before anything else:"
},
{
"code": null,
"e": 6747,
"s": 6722,
"text": "CUDA_LAUNCH_BLOCKING=\"1\""
},
{
"code": null,
"e": 6758,
"s": 6747,
"text": "References"
},
{
"code": null,
"e": 6846,
"s": 6758,
"text": "[1]Thread, GPU goes away after an error occurs #1010(2018), Pytorch Github Issues pages"
},
{
"code": null,
"e": 6939,
"s": 6846,
"text": "[2] Lernapprat, Debugging CUDA device-side assert in PyTorch (2018), https://lernapparat.de/"
}
] |
Common Operations on Fuzzy Set with Example and Code - GeeksforGeeks
|
08 Mar, 2022
What is Fuzzy Set ?
Fuzzy refers to something that is unclear or vague . Hence, Fuzzy Set is a Set where every key is associated with value, which is between 0 to 1 based on the certainty .This value is often called as degree of membership. Fuzzy Set is denoted with a Tilde Sign on top of the normal Set notation.
Operations on Fuzzy Set with Code :
1. Union :
Consider 2 Fuzzy Sets denoted by A and B, then let’s consider Y be the Union of them, then for every member of A and B, Y will be:
degree_of_membership(Y)= max(degree_of_membership(A), degree_of_membership(B))
EXAMPLE :
Python3
# Example to Demonstrate the# Union of Two Fuzzy SetsA = dict()B = dict()Y = dict() A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}B = {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5} print('The First Fuzzy Set is :', A)print('The Second Fuzzy Set is :', B) for A_key, B_key in zip(A, B): A_value = A[A_key] B_value = B[B_key] if A_value > B_value: Y[A_key] = A_value else: Y[B_key] = B_value print('Fuzzy Set Union is :', Y)
The First Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}
The Second Fuzzy Set is : {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}
Fuzzy Set Union is : {'a': 0.9, 'b': 0.9, 'c': 0.6, 'd': 0.6}
2. Intersection :
Consider 2 Fuzzy Sets denoted by A and B, then let’s consider Y be the Intersection of them, then for every member of A and B, Y will be:
degree_of_membership(Y)= min(degree_of_membership(A), degree_of_membership(B))
EXAMPLE :
Python3
# Example to Demonstrate# Intersection of Two Fuzzy SetsA = dict()B = dict()Y = dict() A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}B = {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5} print('The First Fuzzy Set is :', A)print('The Second Fuzzy Set is :', B) for A_key, B_key in zip(A, B): A_value = A[A_key] B_value = B[B_key] if A_value < B_value: Y[A_key] = A_value else: Y[B_key] = B_valueprint('Fuzzy Set Intersection is :', Y)
The First Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}
The Second Fuzzy Set is : {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}
Fuzzy Set Intersection is : {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd': 0.5}
3. Complement :
Consider a Fuzzy Sets denoted by A , then let’s consider Y be the Complement of it, then for every member of A , Y will be:
degree_of_membership(Y)= 1 - degree_of_membership(A)
EXAMPLE :
Python3
# Example to Demonstrate the# Difference Between Two Fuzzy SetsA = dict()Y = dict() A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6} print('The Fuzzy Set is :', A) for A_key in A: Y[A_key]= 1-A[A_key] print('Fuzzy Set Complement is :', Y)
The Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}
Fuzzy Set Complement is : {'a': 0.8, 'b': 0.7, 'c': 0.4, 'd': 0.4}
4. Difference : Consider 2 Fuzzy Sets denoted by A and B, then let’s consider Y be the Intersection of them, then for every member of A and B, Y will be:
degree_of_membership(Y)= min(degree_of_membership(A), 1- degree_of_membership(B))
EXAMPLE :
Python3
# Example to Demonstrate the# Difference Between Two Fuzzy SetsA = dict()B = dict()Y = dict() A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}B = {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5} print('The First Fuzzy Set is :', A)print('The Second Fuzzy Set is :', B) for A_key, B_key in zip(A, B): A_value = A[A_key] B_value = B[B_key] B_value = 1 - B_value if A_value < B_value: Y[A_key] = A_value else: Y[B_key] = B_value print('Fuzzy Set Difference is :', Y)
Output
The First Fuzzy Set is : {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}
The Second Fuzzy Set is : {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5}
Fuzzy Set Difference is : {"a": 0.1, "b": 0.1, "c": 0.6, "d": 0.5}
Class Fuzzy Sets
Python3
class FzSets: def __init__(self): self.A = dict() self.B = dict() self.complement_A = dict() self.complement_B = dict() self.union_AB = dict() self.intersection_AB = dict() self.differenceAB = dict() self.differenceBA = dict() self.change_union = False self.change_intersection = False self.change_complement = False def __init__(self,A,nA,B,nB): self.A = A self.B = B self.Aname = nA self.Bname = nB self.complement_A = dict() self.complement_B = dict() self.union_AB = dict() self.intersection_AB = dict() self.differenceAB = dict() self.differenceBA = dict() self.change_union = False self.change_intersection = False self.change_complement = False def unionOp(self): if self.change_union: print('Result of UNION operation :',self.union_AB) else: #unionSet = set(self.A.keys()).union(self.B.keys()) sa = set(self.A.keys()) sb = set(self.B.keys()) intersectionSet = set(self.A.keys()).intersection(self.B.keys()) for i in intersectionSet: self.union_AB[i] = max(self.A[i],self.B[i]) for i in sa-intersectionSet: self.union_AB[i] = self.A[i] for i in sb-intersectionSet: self.union_AB[i] = self.B[i] print('Result of UNION operation :',self.union_AB) def intersectionOp(self): if self.change_intersection: print('Result of INTERSECTION operation :\n\t\t',self.intersection_AB) else: #unionSet = set(self.A.keys()).union(self.B.keys()) sa = set(self.A.keys()) sb = set(self.B.keys()) intersectionSet = set(self.A.keys()).intersection(self.B.keys()) for i in intersectionSet: self.intersection_AB[i] = min(self.A[i],self.B[i]) for i in sa-intersectionSet: self.intersection_AB[i] = 0.0 for i in sb-intersectionSet: self.intersection_AB[i] = 0.0 print('Result of INTERSECTION operation :\n\t\t',self.intersection_AB) self.change_intersection = True def complementOp(self): if self.change_complement: print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_A) print('Result of COMPLEMENT on ',self.Bname,' operation :',self.complement_B) else: for i in self.A: self.complement_A[i] = 1 - A[i] for i in self.B: self.complement_B[i] = 1 - B[i] print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_A) print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_B) self.change_complement = True def __oneMinustwo(self,L,R): minus_d = dict() Rcomp = dict() for i in R: Rcomp[i] = 1 - R[i] sa = set(L.keys()) sb = set(R.keys()) intersectionSet = sa.intersection(sb) # min( A , complement(B) ) # l - r OR a - b for i in intersectionSet: minus_d[i] = min(L[i],Rcomp[i]) for i in sa-intersectionSet: minus_d[i] = 0.0 for i in sb-intersectionSet: minus_d[i] = 0.0 return minus_d def AminusB(self): self.differenceAB = self.__oneMinustwo(self.A,self.B) print('Result of DIFFERENCE ',self.Aname,' | ',self.Bname,' operation :\n\t\t',self.differenceAB) def BminusA(self): self.differenceBA = self.__oneMinustwo(self.B,self.A) print('Result of DIFFERENCE ',self.Bname,' | ',self.Aname,' operation :\n\t\t',self.differenceBA) def change_Setz(self,A,B): self.A = A self.B = B print('\nSet ',self.Aname,' :',self.A) print('Set ',self.Bname,' :',self.B,end='') self.change_union = True self.change_intersection = True self.change_complement = True print('\t\t\t Cache Reset') def displaySets(self): print('\nSet ',self.Aname,' :',self.A) print('Set ',self.Bname,' :' ,self.B)
lonelionlancer
simranarora5sos
fuzzy-logic
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Python String | replace()
Python | Get unique values from a list
sum() function in Python
|
[
{
"code": null,
"e": 24702,
"s": 24674,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 24722,
"s": 24702,
"text": "What is Fuzzy Set ?"
},
{
"code": null,
"e": 25017,
"s": 24722,
"text": "Fuzzy refers to something that is unclear or vague . Hence, Fuzzy Set is a Set where every key is associated with value, which is between 0 to 1 based on the certainty .This value is often called as degree of membership. Fuzzy Set is denoted with a Tilde Sign on top of the normal Set notation."
},
{
"code": null,
"e": 25053,
"s": 25017,
"text": "Operations on Fuzzy Set with Code :"
},
{
"code": null,
"e": 25064,
"s": 25053,
"text": "1. Union :"
},
{
"code": null,
"e": 25198,
"s": 25064,
"text": "Consider 2 Fuzzy Sets denoted by A and B, then let’s consider Y be the Union of them, then for every member of A and B, Y will be:"
},
{
"code": null,
"e": 25279,
"s": 25198,
"text": " degree_of_membership(Y)= max(degree_of_membership(A), degree_of_membership(B)) "
},
{
"code": null,
"e": 25290,
"s": 25279,
"text": "EXAMPLE : "
},
{
"code": null,
"e": 25298,
"s": 25290,
"text": "Python3"
},
{
"code": "# Example to Demonstrate the# Union of Two Fuzzy SetsA = dict()B = dict()Y = dict() A = {\"a\": 0.2, \"b\": 0.3, \"c\": 0.6, \"d\": 0.6}B = {\"a\": 0.9, \"b\": 0.9, \"c\": 0.4, \"d\": 0.5} print('The First Fuzzy Set is :', A)print('The Second Fuzzy Set is :', B) for A_key, B_key in zip(A, B): A_value = A[A_key] B_value = B[B_key] if A_value > B_value: Y[A_key] = A_value else: Y[B_key] = B_value print('Fuzzy Set Union is :', Y)",
"e": 25749,
"s": 25298,
"text": null
},
{
"code": null,
"e": 25944,
"s": 25749,
"text": "The First Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}\nThe Second Fuzzy Set is : {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}\nFuzzy Set Union is : {'a': 0.9, 'b': 0.9, 'c': 0.6, 'd': 0.6}"
},
{
"code": null,
"e": 25962,
"s": 25944,
"text": "2. Intersection :"
},
{
"code": null,
"e": 26103,
"s": 25962,
"text": "Consider 2 Fuzzy Sets denoted by A and B, then let’s consider Y be the Intersection of them, then for every member of A and B, Y will be:"
},
{
"code": null,
"e": 26183,
"s": 26103,
"text": "degree_of_membership(Y)= min(degree_of_membership(A), degree_of_membership(B)) "
},
{
"code": null,
"e": 26194,
"s": 26183,
"text": "EXAMPLE : "
},
{
"code": null,
"e": 26202,
"s": 26194,
"text": "Python3"
},
{
"code": "# Example to Demonstrate# Intersection of Two Fuzzy SetsA = dict()B = dict()Y = dict() A = {\"a\": 0.2, \"b\": 0.3, \"c\": 0.6, \"d\": 0.6}B = {\"a\": 0.9, \"b\": 0.9, \"c\": 0.4, \"d\": 0.5} print('The First Fuzzy Set is :', A)print('The Second Fuzzy Set is :', B) for A_key, B_key in zip(A, B): A_value = A[A_key] B_value = B[B_key] if A_value < B_value: Y[A_key] = A_value else: Y[B_key] = B_valueprint('Fuzzy Set Intersection is :', Y)",
"e": 26654,
"s": 26202,
"text": null
},
{
"code": null,
"e": 26856,
"s": 26654,
"text": "The First Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}\nThe Second Fuzzy Set is : {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}\nFuzzy Set Intersection is : {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd': 0.5}"
},
{
"code": null,
"e": 26872,
"s": 26856,
"text": "3. Complement :"
},
{
"code": null,
"e": 26999,
"s": 26872,
"text": "Consider a Fuzzy Sets denoted by A , then let’s consider Y be the Complement of it, then for every member of A , Y will be:"
},
{
"code": null,
"e": 27052,
"s": 26999,
"text": "degree_of_membership(Y)= 1 - degree_of_membership(A)"
},
{
"code": null,
"e": 27062,
"s": 27052,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 27070,
"s": 27062,
"text": "Python3"
},
{
"code": "# Example to Demonstrate the# Difference Between Two Fuzzy SetsA = dict()Y = dict() A = {\"a\": 0.2, \"b\": 0.3, \"c\": 0.6, \"d\": 0.6} print('The Fuzzy Set is :', A) for A_key in A: Y[A_key]= 1-A[A_key] print('Fuzzy Set Complement is :', Y)",
"e": 27316,
"s": 27070,
"text": null
},
{
"code": null,
"e": 27443,
"s": 27316,
"text": "The Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}\nFuzzy Set Complement is : {'a': 0.8, 'b': 0.7, 'c': 0.4, 'd': 0.4}"
},
{
"code": null,
"e": 27601,
"s": 27443,
"text": "4. Difference : Consider 2 Fuzzy Sets denoted by A and B, then let’s consider Y be the Intersection of them, then for every member of A and B, Y will be:"
},
{
"code": null,
"e": 27684,
"s": 27601,
"text": "degree_of_membership(Y)= min(degree_of_membership(A), 1- degree_of_membership(B)) "
},
{
"code": null,
"e": 27694,
"s": 27684,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 27702,
"s": 27694,
"text": "Python3"
},
{
"code": "# Example to Demonstrate the# Difference Between Two Fuzzy SetsA = dict()B = dict()Y = dict() A = {\"a\": 0.2, \"b\": 0.3, \"c\": 0.6, \"d\": 0.6}B = {\"a\": 0.9, \"b\": 0.9, \"c\": 0.4, \"d\": 0.5} print('The First Fuzzy Set is :', A)print('The Second Fuzzy Set is :', B) for A_key, B_key in zip(A, B): A_value = A[A_key] B_value = B[B_key] B_value = 1 - B_value if A_value < B_value: Y[A_key] = A_value else: Y[B_key] = B_value print('Fuzzy Set Difference is :', Y)",
"e": 28193,
"s": 27702,
"text": null
},
{
"code": null,
"e": 28201,
"s": 28193,
"text": "Output "
},
{
"code": null,
"e": 28401,
"s": 28201,
"text": "The First Fuzzy Set is : {\"a\": 0.2, \"b\": 0.3, \"c\": 0.6, \"d\": 0.6}\nThe Second Fuzzy Set is : {\"a\": 0.9, \"b\": 0.9, \"c\": 0.4, \"d\": 0.5}\nFuzzy Set Difference is : {\"a\": 0.1, \"b\": 0.1, \"c\": 0.6, \"d\": 0.5}"
},
{
"code": null,
"e": 28418,
"s": 28401,
"text": "Class Fuzzy Sets"
},
{
"code": null,
"e": 28426,
"s": 28418,
"text": "Python3"
},
{
"code": "class FzSets: def __init__(self): self.A = dict() self.B = dict() self.complement_A = dict() self.complement_B = dict() self.union_AB = dict() self.intersection_AB = dict() self.differenceAB = dict() self.differenceBA = dict() self.change_union = False self.change_intersection = False self.change_complement = False def __init__(self,A,nA,B,nB): self.A = A self.B = B self.Aname = nA self.Bname = nB self.complement_A = dict() self.complement_B = dict() self.union_AB = dict() self.intersection_AB = dict() self.differenceAB = dict() self.differenceBA = dict() self.change_union = False self.change_intersection = False self.change_complement = False def unionOp(self): if self.change_union: print('Result of UNION operation :',self.union_AB) else: #unionSet = set(self.A.keys()).union(self.B.keys()) sa = set(self.A.keys()) sb = set(self.B.keys()) intersectionSet = set(self.A.keys()).intersection(self.B.keys()) for i in intersectionSet: self.union_AB[i] = max(self.A[i],self.B[i]) for i in sa-intersectionSet: self.union_AB[i] = self.A[i] for i in sb-intersectionSet: self.union_AB[i] = self.B[i] print('Result of UNION operation :',self.union_AB) def intersectionOp(self): if self.change_intersection: print('Result of INTERSECTION operation :\\n\\t\\t',self.intersection_AB) else: #unionSet = set(self.A.keys()).union(self.B.keys()) sa = set(self.A.keys()) sb = set(self.B.keys()) intersectionSet = set(self.A.keys()).intersection(self.B.keys()) for i in intersectionSet: self.intersection_AB[i] = min(self.A[i],self.B[i]) for i in sa-intersectionSet: self.intersection_AB[i] = 0.0 for i in sb-intersectionSet: self.intersection_AB[i] = 0.0 print('Result of INTERSECTION operation :\\n\\t\\t',self.intersection_AB) self.change_intersection = True def complementOp(self): if self.change_complement: print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_A) print('Result of COMPLEMENT on ',self.Bname,' operation :',self.complement_B) else: for i in self.A: self.complement_A[i] = 1 - A[i] for i in self.B: self.complement_B[i] = 1 - B[i] print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_A) print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_B) self.change_complement = True def __oneMinustwo(self,L,R): minus_d = dict() Rcomp = dict() for i in R: Rcomp[i] = 1 - R[i] sa = set(L.keys()) sb = set(R.keys()) intersectionSet = sa.intersection(sb) # min( A , complement(B) ) # l - r OR a - b for i in intersectionSet: minus_d[i] = min(L[i],Rcomp[i]) for i in sa-intersectionSet: minus_d[i] = 0.0 for i in sb-intersectionSet: minus_d[i] = 0.0 return minus_d def AminusB(self): self.differenceAB = self.__oneMinustwo(self.A,self.B) print('Result of DIFFERENCE ',self.Aname,' | ',self.Bname,' operation :\\n\\t\\t',self.differenceAB) def BminusA(self): self.differenceBA = self.__oneMinustwo(self.B,self.A) print('Result of DIFFERENCE ',self.Bname,' | ',self.Aname,' operation :\\n\\t\\t',self.differenceBA) def change_Setz(self,A,B): self.A = A self.B = B print('\\nSet ',self.Aname,' :',self.A) print('Set ',self.Bname,' :',self.B,end='') self.change_union = True self.change_intersection = True self.change_complement = True print('\\t\\t\\t Cache Reset') def displaySets(self): print('\\nSet ',self.Aname,' :',self.A) print('Set ',self.Bname,' :' ,self.B)",
"e": 32206,
"s": 28426,
"text": null
},
{
"code": null,
"e": 32221,
"s": 32206,
"text": "lonelionlancer"
},
{
"code": null,
"e": 32237,
"s": 32221,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32249,
"s": 32237,
"text": "fuzzy-logic"
},
{
"code": null,
"e": 32256,
"s": 32249,
"text": "Python"
},
{
"code": null,
"e": 32354,
"s": 32256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32363,
"s": 32354,
"text": "Comments"
},
{
"code": null,
"e": 32376,
"s": 32363,
"text": "Old Comments"
},
{
"code": null,
"e": 32408,
"s": 32376,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32430,
"s": 32408,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 32472,
"s": 32430,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 32493,
"s": 32472,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 32530,
"s": 32493,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 32559,
"s": 32530,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 32615,
"s": 32559,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 32641,
"s": 32615,
"text": "Python String | replace()"
},
{
"code": null,
"e": 32680,
"s": 32641,
"text": "Python | Get unique values from a list"
}
] |
How to calculate the nth root of a number in JavaScript?
|
To calculate the end root of a number, use Math.abs() method. Here, we’re using the Match.pow method also. You can try to run the following code to calculate the square root of numbers in JavaScript −
Live Demo
<html>
<head>
<title>Calculate root</title>
</head>
<body>
<script>
function displayRoot(x, num) {
val = num % 2;
if((val == 1) || x < 0)
x = -x;
var a, num;
a = Math.pow(x, 1 / num);
num = Math.pow(a, num);
if(Math.abs(x - num) < 1 && (x > 0 === num > 0))
return val ? -a : a;
}
document.write(displayRoot(36, 2));
document.write("<br>"+displayRoot(49, 2));
document.write("<br>"+displayRoot(36, -2));
document.write("<br>"+displayRoot(216, -2));
</script>
-+
</body>
</html>
|
[
{
"code": null,
"e": 1263,
"s": 1062,
"text": "To calculate the end root of a number, use Math.abs() method. Here, we’re using the Match.pow method also. You can try to run the following code to calculate the square root of numbers in JavaScript −"
},
{
"code": null,
"e": 1273,
"s": 1263,
"text": "Live Demo"
},
{
"code": null,
"e": 1942,
"s": 1273,
"text": "<html>\n <head>\n <title>Calculate root</title>\n </head>\n\n <body>\n <script>\n function displayRoot(x, num) {\n val = num % 2;\n if((val == 1) || x < 0)\n x = -x;\n var a, num;\n a = Math.pow(x, 1 / num);\n num = Math.pow(a, num);\n if(Math.abs(x - num) < 1 && (x > 0 === num > 0))\n return val ? -a : a;\n }\n document.write(displayRoot(36, 2));\n document.write(\"<br>\"+displayRoot(49, 2));\n document.write(\"<br>\"+displayRoot(36, -2));\n document.write(\"<br>\"+displayRoot(216, -2));\n </script>\n -+\n </body>\n</html>"
}
] |
Successful spark-submits for Python projects. | by Kyle Jarvis | Towards Data Science
|
TL; DR: The best way to learn is to do, and the best way to learn something hard is to do it in small steps. This is a guide for Python practitioners (probably data scientists) working on a package in an isolated development environment, who want to start successfully executing Spark jobs using that package on a cluster. The big data tech stack can seem daunting at first: this article is aimed at those who are just getting to grips with working effectively with a cluster, who want to get their project off the ground and running, then feel confident to explore, build on this experience, and refine their style.
Enough, already! Take me to the guide (scroll down).
The problem.
When writing, developing and testing our Python packages for Spark, it’s quite likely that we’ll be working in some kind of isolated development environment; on a desktop, or dedicated cloud-computing resource. Crucially, the Python environment we’ve been at liberty to put together, the one with our favourite minor versions of all the best packages, is likely to be different from the Python environment(s) accessible to a vanilla spark-submit job executed on our friendly neighbourhood cluster. Generally, it’s desirable to have some degree of flexibility, and be able to quickly incorporate additional dependencies into a prototype environment. In the heat and excitement of developing our code, the foresight to prepare a cluster-wide environment compatible with our package, ready to receive and execute our Spark job may have eluded us. Now, this unforeseen hurdle is stopping us from running our project at scale, which is sad for a data scientist.
A solution.
In what follows we’ll walk through the steps necessary to get a Python package running on Spark using spark-submit, in a transparent and accessible way. The steps that are covered in the guide are:
How to package and prepare our Python projects for successful execution on a Spark cluster.Preparing a minimal working environment with the version of Python that’s right for our project, and upload this to Hadoop, making it accessible to all the workers at execution time.Package up our project dependencies.Preparing the spark-submit script to bring all the above together, in an intelligible way.
How to package and prepare our Python projects for successful execution on a Spark cluster.
Preparing a minimal working environment with the version of Python that’s right for our project, and upload this to Hadoop, making it accessible to all the workers at execution time.
Package up our project dependencies.
Preparing the spark-submit script to bring all the above together, in an intelligible way.
Target audience.
The existing resources relevant to this topic (see further reading) are mostly aimed at producing production-grade Spark jobs with Python. They are really great, but could pose a steep learning curve to those less familiar with the intricacies and nuances of working Spark in cluster mode; there’s a lot to take in. If you’re just starting out with these kinds of big data technologies, you’ll want a good understanding of the basics. This guide focuses on the basics and key concepts, highlighting the things you’ll definitely encounter when starting out.
Preamble.
By trade, I’m a data scientist. I work on a commodity cluster running Hadoop and use Spark to build big-data pipelines for machine-learning and data-science projects, processing extremely large data sets containing billions of rows. Development happens in an isolated environment, with Anaconda as the Python distribution. Typically, I’ll have set up a couple of different virtual environments in order to decouple the Spark processing steps from other aspects of the project.
In development, my project will be structured something like this.
my_data_science_project├───data├───models├───envs│ ├───/spark_env/│ └───/ml_env/├───conf├───notebooks│ ├───model_explore.ipynb│ └───eda.ipynb└───src ├───data_pipeline │ ├───functions.py │ ├───processing.py │ └───__init__.py ├───app.py └───__init__.py
I’ll use a Jupyter notebook to play around and tweak transformations, scrutinising the results until they match what I’m trying to achieve. Eventually, once all the code is doing exactly what it should be, the next step is to package it up, and call the transformation steps from a script that we will pass to a spark-submit job. The spark-submit job will setup and configure Spark as per our instructions, execute the program we pass to it, then cleanly release the resources that were being used. A simply Python program passed to spark-submit might look like this:
"""spark_submit_example.pyAn example of the kind of script we might want to run. The modules and functions of our package can be imported and accessed in the usual way. Command line arguments can be accessed in parsed in the usual way. We can even read in files in the usual way. In fact, its all very... usual..."""import yamlimport sysimport src.data_pipeline.processingfrom src.app import get_sparkdef run(ss, appConfig): # Do some steps using the appConfig input = ss.read.parquet(appConfig['input']) output = src.data_pipeline.processing.process(input) output.write.parquet(appConfig['output'], mode = 'overwrite')if __name__ == "__main__": #Get some configuration settings args = sys.argv appConfig = args[1] with open(appConfig) as file_handler: appConfig = yaml.load(file_handler, Loader=yaml.Loader) # Suppose the Spark session builder is wrapped in this function. ss = get_spark() run(ss, appConfig)
Getting this to work smoothly on a cluster, fresh out of an isolated development environment can be tricky. There are lots of moving parts. This guide exists because, I’ve gone through this process myself, and I think having this to refer to would have sped things up considerably.
Disclaimer: I won’t begin to go into how to properly configure and create a Python object bound to a Spark session. That is a topic in its own right, and it’s assumed that you’ve had success in doing that already. Here we delegate the intricacies of this task to the hypothetical get_spark() .
1. Packaging the project.
The first step is to package up all the python files, modules and scripts that belong to the package, i.e. the contents of the./src/ directory. There’s nothing special about this step, you can read about the use of setuptools here. Create your setup.py file and python setup.py bdist_egg . After this step, we’ll have some new files and directories, including a.egg , which for the purposes of this guide is just like a .zip . When we run our spark-submit job later, we’ll let the program know about the egg file containing our project source code, and it will send this to the driver and workers. When our application is launched, the top-level of any artefacts (eggs, zips) passed to --py-files is added to PYTHON_PATH , which is how we can import our package from a program passed to spark-submit.
my_data_science_project├++ setup.py ]- python setup.py bdist_egg to produce the below.├++ dist/ │ └++ my_data_science_project-0.1-py2.7.egg└++ build/
2. Preparing a minimal working environment.
When running my Spark jobs with a Python driver program, I like to use a minimal working environment. It’s too easy to end up with a bloated virtual environment when prototyping and developing, so this is a useful point to revisit whether any pruning can be done. If the program we’re running is ultimately expressed as pure Spark (vs. doing anything with numpy, pandas) then I find I can get very far with only the builtin modules and a yaml parser.
Let’s go ahead and use conda to create a new environment without any of the packages that are installed by default (which we probably don’t need for our spark job).
conda create \--name spark_submit_env \--no-default-packages \--copy \--prefix ./envs \python=xx
Running the above command will give us an extra directory in ./envs/ that contains our minimal working environment. We are likely to use this environment over and over again as we tweak our Spark program, so we’ll upload it to the Hadoop file system, rather than shipping and distributing it every time we want to run a Spark job. We’ll upload our environment to Hadoop as a .zip, that will keep everything neat, and we can tell spark-submit that we’ve created an archive we’d like our executors to have access to using the --archives flag. To do this, first follow these steps:
cd ./envs/spark_submit_env/zip -r ..spark_submit_env.zip .
cd ./envs/spark_submit_env/
zip -r ..spark_submit_env.zip .
Now move up one level and run the following command:
hadoop fs -copyFromLocal ./spark_submit_env.zip /hdfs/env/path/
Remember this hdfs path, we’ll refer to it later in our spark-submit script. The commands ran above will have made the below additions to our project directory.
my_data_science_project├───envs│ ├───spark_env│ ├───ml_env│ ├++ spark_submit_env ]- zip this up│ └++ spark_submit_env.zip ]- upload to hdfs├───conf
3. Packing up the dependencies.
Having prepared and uploaded our spark_submit_env to hdfs, we now turn to preparing the specific dependencies that our Spark job depends upon. There are multiple ways of achieving the same result here, and it’s pretty straightforward. These steps will be intuitive for anyone who has ever packaged a project, however, we do want to make sure we have the right versions of the packages for the specific version of Python we have in our spark_submit_env . Scribble down the packages we need for our Spark job in a requirements.txt :
requirements.txtpyyamlanother_package_you_love~
Then, source activate spark_submit_env , so that which pip reassuringly tells us /path/to/your/project/envs/bin/pip . Now we can be confident the packages we need for our spark-submit job will play nicely with the environment we’ve prepared. We can now pip install the dependencies listed in requirements to a specified directory that we’ll zip up and pass to Spark.
pip install -t ./dependencies -r requirements.txt
my_data_science_project ├++ requirements.txt ]- pip install this├++ requirements/ ]- to here, then zip it up├++ requirements.zip ]- like this.
Note that we could directly package the dependencies as part of the working environment setup over the course of development and distribute this, but explicitly listing and bundling the package dependencies separately keeps things nice and transparent. We can also cut out superfluous packages that are useful for eda, visualisation etc., but not directly required for the steps delegated to Spark.
4. The spark-submit script.
This is where we bring together all the steps that we’ve been through so far. This is the script we will run to invoke Spark, and where we’ll make it aware of the Python environment we prepared, our packaged project and its dependencies. The spark-submit script will look something like this:
#!/bin/bashPYTHON_ZIP="hdfs:////hdfs/env/path/spark_submit_env.zip#pythonlib"PYSPARK_PYTHON="./pythonlib/bin/python2.7"PROJECT_EGG=./dist/my_data_science_project-0.1-py2.7.eggSPARK_CMD = "spark-submit \--conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=${PYSPARK_PYTHON} \--archives ${PYTHON27_ZIP} \--py-files ${PROJECT_EGG},./dependencies.zip \--master yarn \--deploy-mode cluster \--files ./conf/appConf.yml#appConf.yml \spark_submit_program.py appConf.yml arg2 ..."eval ${SPARK_CMD}
Let’s break this down.
PYTHON_ZIP="hdfs:////hdfs/env/path/spark_submit_env.zip#pythonlib"
Here we declare the variable PYTHON_ZIP and assign to it the file url where we uploaded our Python environment in step 2. The #pythonlib suffix is a little trick that allows us to specify name aliases when running Spark on YARN. We can use it to specify a file name alias for anything passed to --py-files or --archives . This alias is the actual name the Spark app will see. You can read more here.
--conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=${PYSPARK_PYTHON}
Here we’re setting the environment variable PYSPARK_PYTHON to point to the python executable that we package into our spark_submit_env. Search for the above here to read more.
--archives ${PYTHON_ZIP}
Anything that’s passed to --archives get’s unzipped into the working directory of each executor, so passing the hdfs url of the zipped environment is how these executors access the binaries and modules of the environment we prepared.
--files ./conf/appConf.yml#appConf.yml
Individual files passed to --files are also copied to the executors working directories, again we can name them using the /path/to/file#alias syntax. For example, we can pass a yaml file to be parsed by the driver program, as illustrated in spark_submit_example.py .
spark_submit_example.py appConf.yml arg2 arg3 ...
After specifying our [OPTIONS] we pass the actual Python file that’s executed by the driver:spark_submit_example.py, as well as any command line arguments for the program, which can be parsed in the usual way. For example, the first argument might be a yaml file appConf.yml , and there might be subsequent arguments to provide more context for the program.
RUN RUN RUN.
We’re finally in a position to execute the spark-submit script that we’ve described above:
./spark_submit_script.sh
One final word of caution, when working with virtual environments, be cautious of modifications to PATH . I’ve run into issues previously when trying to spark-submit without remembering to deactivate a particular virtual environment.
If you’ve made it this far I hope it’s because you’ve found the contents of this guide helpful — I’d love to hear if that’s the case. I’d be more than willing to expand on any specifics, should anyone be sufficiently engaged to request that. I’m very open to feedback. So, if you spot an inconsistency or mistake, please shout; I’ll promptly remove the article and delete all traces of it ever having existed, and my account, and my LinkedIn. I will leave the inhospitable environments pictogram though, that took me a long time.
When you’re confident with the steps that have been covered in this guide, you might like to look at the following resources:
How to setup the Python and Spark environment for development, with good software engineering practices
Building Production PySpark Jobs
Best Practices Writing Production-Grade PySpark Jobs
|
[
{
"code": null,
"e": 789,
"s": 172,
"text": "TL; DR: The best way to learn is to do, and the best way to learn something hard is to do it in small steps. This is a guide for Python practitioners (probably data scientists) working on a package in an isolated development environment, who want to start successfully executing Spark jobs using that package on a cluster. The big data tech stack can seem daunting at first: this article is aimed at those who are just getting to grips with working effectively with a cluster, who want to get their project off the ground and running, then feel confident to explore, build on this experience, and refine their style."
},
{
"code": null,
"e": 842,
"s": 789,
"text": "Enough, already! Take me to the guide (scroll down)."
},
{
"code": null,
"e": 855,
"s": 842,
"text": "The problem."
},
{
"code": null,
"e": 1812,
"s": 855,
"text": "When writing, developing and testing our Python packages for Spark, it’s quite likely that we’ll be working in some kind of isolated development environment; on a desktop, or dedicated cloud-computing resource. Crucially, the Python environment we’ve been at liberty to put together, the one with our favourite minor versions of all the best packages, is likely to be different from the Python environment(s) accessible to a vanilla spark-submit job executed on our friendly neighbourhood cluster. Generally, it’s desirable to have some degree of flexibility, and be able to quickly incorporate additional dependencies into a prototype environment. In the heat and excitement of developing our code, the foresight to prepare a cluster-wide environment compatible with our package, ready to receive and execute our Spark job may have eluded us. Now, this unforeseen hurdle is stopping us from running our project at scale, which is sad for a data scientist."
},
{
"code": null,
"e": 1824,
"s": 1812,
"text": "A solution."
},
{
"code": null,
"e": 2022,
"s": 1824,
"text": "In what follows we’ll walk through the steps necessary to get a Python package running on Spark using spark-submit, in a transparent and accessible way. The steps that are covered in the guide are:"
},
{
"code": null,
"e": 2422,
"s": 2022,
"text": "How to package and prepare our Python projects for successful execution on a Spark cluster.Preparing a minimal working environment with the version of Python that’s right for our project, and upload this to Hadoop, making it accessible to all the workers at execution time.Package up our project dependencies.Preparing the spark-submit script to bring all the above together, in an intelligible way."
},
{
"code": null,
"e": 2514,
"s": 2422,
"text": "How to package and prepare our Python projects for successful execution on a Spark cluster."
},
{
"code": null,
"e": 2697,
"s": 2514,
"text": "Preparing a minimal working environment with the version of Python that’s right for our project, and upload this to Hadoop, making it accessible to all the workers at execution time."
},
{
"code": null,
"e": 2734,
"s": 2697,
"text": "Package up our project dependencies."
},
{
"code": null,
"e": 2825,
"s": 2734,
"text": "Preparing the spark-submit script to bring all the above together, in an intelligible way."
},
{
"code": null,
"e": 2842,
"s": 2825,
"text": "Target audience."
},
{
"code": null,
"e": 3399,
"s": 2842,
"text": "The existing resources relevant to this topic (see further reading) are mostly aimed at producing production-grade Spark jobs with Python. They are really great, but could pose a steep learning curve to those less familiar with the intricacies and nuances of working Spark in cluster mode; there’s a lot to take in. If you’re just starting out with these kinds of big data technologies, you’ll want a good understanding of the basics. This guide focuses on the basics and key concepts, highlighting the things you’ll definitely encounter when starting out."
},
{
"code": null,
"e": 3409,
"s": 3399,
"text": "Preamble."
},
{
"code": null,
"e": 3886,
"s": 3409,
"text": "By trade, I’m a data scientist. I work on a commodity cluster running Hadoop and use Spark to build big-data pipelines for machine-learning and data-science projects, processing extremely large data sets containing billions of rows. Development happens in an isolated environment, with Anaconda as the Python distribution. Typically, I’ll have set up a couple of different virtual environments in order to decouple the Spark processing steps from other aspects of the project."
},
{
"code": null,
"e": 3953,
"s": 3886,
"text": "In development, my project will be structured something like this."
},
{
"code": null,
"e": 4236,
"s": 3953,
"text": "my_data_science_project├───data├───models├───envs│ ├───/spark_env/│ └───/ml_env/├───conf├───notebooks│ ├───model_explore.ipynb│ └───eda.ipynb└───src ├───data_pipeline │ ├───functions.py │ ├───processing.py │ └───__init__.py ├───app.py └───__init__.py"
},
{
"code": null,
"e": 4804,
"s": 4236,
"text": "I’ll use a Jupyter notebook to play around and tweak transformations, scrutinising the results until they match what I’m trying to achieve. Eventually, once all the code is doing exactly what it should be, the next step is to package it up, and call the transformation steps from a script that we will pass to a spark-submit job. The spark-submit job will setup and configure Spark as per our instructions, execute the program we pass to it, then cleanly release the resources that were being used. A simply Python program passed to spark-submit might look like this:"
},
{
"code": null,
"e": 5754,
"s": 4804,
"text": "\"\"\"spark_submit_example.pyAn example of the kind of script we might want to run. The modules and functions of our package can be imported and accessed in the usual way. Command line arguments can be accessed in parsed in the usual way. We can even read in files in the usual way. In fact, its all very... usual...\"\"\"import yamlimport sysimport src.data_pipeline.processingfrom src.app import get_sparkdef run(ss, appConfig): # Do some steps using the appConfig input = ss.read.parquet(appConfig['input']) output = src.data_pipeline.processing.process(input) output.write.parquet(appConfig['output'], mode = 'overwrite')if __name__ == \"__main__\": #Get some configuration settings args = sys.argv appConfig = args[1] with open(appConfig) as file_handler: appConfig = yaml.load(file_handler, Loader=yaml.Loader) # Suppose the Spark session builder is wrapped in this function. ss = get_spark() run(ss, appConfig)"
},
{
"code": null,
"e": 6036,
"s": 5754,
"text": "Getting this to work smoothly on a cluster, fresh out of an isolated development environment can be tricky. There are lots of moving parts. This guide exists because, I’ve gone through this process myself, and I think having this to refer to would have sped things up considerably."
},
{
"code": null,
"e": 6330,
"s": 6036,
"text": "Disclaimer: I won’t begin to go into how to properly configure and create a Python object bound to a Spark session. That is a topic in its own right, and it’s assumed that you’ve had success in doing that already. Here we delegate the intricacies of this task to the hypothetical get_spark() ."
},
{
"code": null,
"e": 6356,
"s": 6330,
"text": "1. Packaging the project."
},
{
"code": null,
"e": 7157,
"s": 6356,
"text": "The first step is to package up all the python files, modules and scripts that belong to the package, i.e. the contents of the./src/ directory. There’s nothing special about this step, you can read about the use of setuptools here. Create your setup.py file and python setup.py bdist_egg . After this step, we’ll have some new files and directories, including a.egg , which for the purposes of this guide is just like a .zip . When we run our spark-submit job later, we’ll let the program know about the egg file containing our project source code, and it will send this to the driver and workers. When our application is launched, the top-level of any artefacts (eggs, zips) passed to --py-files is added to PYTHON_PATH , which is how we can import our package from a program passed to spark-submit."
},
{
"code": null,
"e": 7356,
"s": 7157,
"text": "my_data_science_project├++ setup.py ]- python setup.py bdist_egg to produce the below.├++ dist/ │ └++ my_data_science_project-0.1-py2.7.egg└++ build/ "
},
{
"code": null,
"e": 7400,
"s": 7356,
"text": "2. Preparing a minimal working environment."
},
{
"code": null,
"e": 7851,
"s": 7400,
"text": "When running my Spark jobs with a Python driver program, I like to use a minimal working environment. It’s too easy to end up with a bloated virtual environment when prototyping and developing, so this is a useful point to revisit whether any pruning can be done. If the program we’re running is ultimately expressed as pure Spark (vs. doing anything with numpy, pandas) then I find I can get very far with only the builtin modules and a yaml parser."
},
{
"code": null,
"e": 8016,
"s": 7851,
"text": "Let’s go ahead and use conda to create a new environment without any of the packages that are installed by default (which we probably don’t need for our spark job)."
},
{
"code": null,
"e": 8114,
"s": 8016,
"text": "conda create \\--name spark_submit_env \\--no-default-packages \\--copy \\--prefix ./envs \\python=xx "
},
{
"code": null,
"e": 8693,
"s": 8114,
"text": "Running the above command will give us an extra directory in ./envs/ that contains our minimal working environment. We are likely to use this environment over and over again as we tweak our Spark program, so we’ll upload it to the Hadoop file system, rather than shipping and distributing it every time we want to run a Spark job. We’ll upload our environment to Hadoop as a .zip, that will keep everything neat, and we can tell spark-submit that we’ve created an archive we’d like our executors to have access to using the --archives flag. To do this, first follow these steps:"
},
{
"code": null,
"e": 8752,
"s": 8693,
"text": "cd ./envs/spark_submit_env/zip -r ..spark_submit_env.zip ."
},
{
"code": null,
"e": 8780,
"s": 8752,
"text": "cd ./envs/spark_submit_env/"
},
{
"code": null,
"e": 8812,
"s": 8780,
"text": "zip -r ..spark_submit_env.zip ."
},
{
"code": null,
"e": 8865,
"s": 8812,
"text": "Now move up one level and run the following command:"
},
{
"code": null,
"e": 8929,
"s": 8865,
"text": "hadoop fs -copyFromLocal ./spark_submit_env.zip /hdfs/env/path/"
},
{
"code": null,
"e": 9090,
"s": 8929,
"text": "Remember this hdfs path, we’ll refer to it later in our spark-submit script. The commands ran above will have made the below additions to our project directory."
},
{
"code": null,
"e": 9252,
"s": 9090,
"text": "my_data_science_project├───envs│ ├───spark_env│ ├───ml_env│ ├++ spark_submit_env ]- zip this up│ └++ spark_submit_env.zip ]- upload to hdfs├───conf"
},
{
"code": null,
"e": 9284,
"s": 9252,
"text": "3. Packing up the dependencies."
},
{
"code": null,
"e": 9815,
"s": 9284,
"text": "Having prepared and uploaded our spark_submit_env to hdfs, we now turn to preparing the specific dependencies that our Spark job depends upon. There are multiple ways of achieving the same result here, and it’s pretty straightforward. These steps will be intuitive for anyone who has ever packaged a project, however, we do want to make sure we have the right versions of the packages for the specific version of Python we have in our spark_submit_env . Scribble down the packages we need for our Spark job in a requirements.txt :"
},
{
"code": null,
"e": 9863,
"s": 9815,
"text": "requirements.txtpyyamlanother_package_you_love~"
},
{
"code": null,
"e": 10230,
"s": 9863,
"text": "Then, source activate spark_submit_env , so that which pip reassuringly tells us /path/to/your/project/envs/bin/pip . Now we can be confident the packages we need for our spark-submit job will play nicely with the environment we’ve prepared. We can now pip install the dependencies listed in requirements to a specified directory that we’ll zip up and pass to Spark."
},
{
"code": null,
"e": 10280,
"s": 10230,
"text": "pip install -t ./dependencies -r requirements.txt"
},
{
"code": null,
"e": 10441,
"s": 10280,
"text": "my_data_science_project ├++ requirements.txt ]- pip install this├++ requirements/ ]- to here, then zip it up├++ requirements.zip ]- like this."
},
{
"code": null,
"e": 10840,
"s": 10441,
"text": "Note that we could directly package the dependencies as part of the working environment setup over the course of development and distribute this, but explicitly listing and bundling the package dependencies separately keeps things nice and transparent. We can also cut out superfluous packages that are useful for eda, visualisation etc., but not directly required for the steps delegated to Spark."
},
{
"code": null,
"e": 10868,
"s": 10840,
"text": "4. The spark-submit script."
},
{
"code": null,
"e": 11161,
"s": 10868,
"text": "This is where we bring together all the steps that we’ve been through so far. This is the script we will run to invoke Spark, and where we’ll make it aware of the Python environment we prepared, our packaged project and its dependencies. The spark-submit script will look something like this:"
},
{
"code": null,
"e": 11643,
"s": 11161,
"text": "#!/bin/bashPYTHON_ZIP=\"hdfs:////hdfs/env/path/spark_submit_env.zip#pythonlib\"PYSPARK_PYTHON=\"./pythonlib/bin/python2.7\"PROJECT_EGG=./dist/my_data_science_project-0.1-py2.7.eggSPARK_CMD = \"spark-submit \\--conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=${PYSPARK_PYTHON} \\--archives ${PYTHON27_ZIP} \\--py-files ${PROJECT_EGG},./dependencies.zip \\--master yarn \\--deploy-mode cluster \\--files ./conf/appConf.yml#appConf.yml \\spark_submit_program.py appConf.yml arg2 ...\"eval ${SPARK_CMD}"
},
{
"code": null,
"e": 11666,
"s": 11643,
"text": "Let’s break this down."
},
{
"code": null,
"e": 11733,
"s": 11666,
"text": "PYTHON_ZIP=\"hdfs:////hdfs/env/path/spark_submit_env.zip#pythonlib\""
},
{
"code": null,
"e": 12133,
"s": 11733,
"text": "Here we declare the variable PYTHON_ZIP and assign to it the file url where we uploaded our Python environment in step 2. The #pythonlib suffix is a little trick that allows us to specify name aliases when running Spark on YARN. We can use it to specify a file name alias for anything passed to --py-files or --archives . This alias is the actual name the Spark app will see. You can read more here."
},
{
"code": null,
"e": 12197,
"s": 12133,
"text": "--conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=${PYSPARK_PYTHON}"
},
{
"code": null,
"e": 12373,
"s": 12197,
"text": "Here we’re setting the environment variable PYSPARK_PYTHON to point to the python executable that we package into our spark_submit_env. Search for the above here to read more."
},
{
"code": null,
"e": 12398,
"s": 12373,
"text": "--archives ${PYTHON_ZIP}"
},
{
"code": null,
"e": 12632,
"s": 12398,
"text": "Anything that’s passed to --archives get’s unzipped into the working directory of each executor, so passing the hdfs url of the zipped environment is how these executors access the binaries and modules of the environment we prepared."
},
{
"code": null,
"e": 12671,
"s": 12632,
"text": "--files ./conf/appConf.yml#appConf.yml"
},
{
"code": null,
"e": 12938,
"s": 12671,
"text": "Individual files passed to --files are also copied to the executors working directories, again we can name them using the /path/to/file#alias syntax. For example, we can pass a yaml file to be parsed by the driver program, as illustrated in spark_submit_example.py ."
},
{
"code": null,
"e": 12988,
"s": 12938,
"text": "spark_submit_example.py appConf.yml arg2 arg3 ..."
},
{
"code": null,
"e": 13346,
"s": 12988,
"text": "After specifying our [OPTIONS] we pass the actual Python file that’s executed by the driver:spark_submit_example.py, as well as any command line arguments for the program, which can be parsed in the usual way. For example, the first argument might be a yaml file appConf.yml , and there might be subsequent arguments to provide more context for the program."
},
{
"code": null,
"e": 13359,
"s": 13346,
"text": "RUN RUN RUN."
},
{
"code": null,
"e": 13450,
"s": 13359,
"text": "We’re finally in a position to execute the spark-submit script that we’ve described above:"
},
{
"code": null,
"e": 13475,
"s": 13450,
"text": "./spark_submit_script.sh"
},
{
"code": null,
"e": 13709,
"s": 13475,
"text": "One final word of caution, when working with virtual environments, be cautious of modifications to PATH . I’ve run into issues previously when trying to spark-submit without remembering to deactivate a particular virtual environment."
},
{
"code": null,
"e": 14239,
"s": 13709,
"text": "If you’ve made it this far I hope it’s because you’ve found the contents of this guide helpful — I’d love to hear if that’s the case. I’d be more than willing to expand on any specifics, should anyone be sufficiently engaged to request that. I’m very open to feedback. So, if you spot an inconsistency or mistake, please shout; I’ll promptly remove the article and delete all traces of it ever having existed, and my account, and my LinkedIn. I will leave the inhospitable environments pictogram though, that took me a long time."
},
{
"code": null,
"e": 14365,
"s": 14239,
"text": "When you’re confident with the steps that have been covered in this guide, you might like to look at the following resources:"
},
{
"code": null,
"e": 14469,
"s": 14365,
"text": "How to setup the Python and Spark environment for development, with good software engineering practices"
},
{
"code": null,
"e": 14502,
"s": 14469,
"text": "Building Production PySpark Jobs"
}
] |
Apache Flume - Data Transfer In Hadoop
|
Big Data, as we know, is a collection of large datasets that cannot be processed using traditional computing techniques. Big Data, when analyzed, gives valuable results. Hadoop is an open-source framework that allows to store and process Big Data in a distributed environment across clusters of computers using simple programming models.
Generally, most of the data that is to be analyzed will be produced by various data sources like applications servers, social networking sites, cloud servers, and enterprise servers. This data will be in the form of log files and events.
Log file − In general, a log file is a file that lists events/actions that occur in an operating system. For example, web servers list every request made to the server in the log files.
On harvesting such log data, we can get information about −
the application performance and locate various software and hardware failures.
the user behavior and derive better business insights.
The traditional method of transferring data into the HDFS system is to use the put command. Let us see how to use the put command.
The main challenge in handling the log data is in moving these logs produced by multiple servers to the Hadoop environment.
Hadoop File System Shell provides commands to insert data into Hadoop and read from it. You can insert data into Hadoop using the put command as shown below.
$ Hadoop fs –put /path of the required file /path in HDFS where to save the file
We can use the put command of Hadoop to transfer data from these sources to HDFS. But, it suffers from the following drawbacks −
Using put command, we can transfer only one file at a time while the data generators generate data at a much higher rate. Since the analysis made on older data is less accurate, we need to have a solution to transfer data in real time.
Using put command, we can transfer only one file at a time while the data generators generate data at a much higher rate. Since the analysis made on older data is less accurate, we need to have a solution to transfer data in real time.
If we use put command, the data is needed to be packaged and should be ready for the upload. Since the webservers generate data continuously, it is a very difficult task.
If we use put command, the data is needed to be packaged and should be ready for the upload. Since the webservers generate data continuously, it is a very difficult task.
What we need here is a solutions that can overcome the drawbacks of put command and transfer the "streaming data" from data generators to centralized stores (especially HDFS) with less delay.
In HDFS, the file exists as a directory entry and the length of the file will be considered as zero till it is closed. For example, if a source is writing data into HDFS and the network was interrupted in the middle of the operation (without closing the file), then the data written in the file will be lost.
Therefore we need a reliable, configurable, and maintainable system to transfer the log data into HDFS.
Note − In POSIX file system, whenever we are accessing a file (say performing write operation), other programs can still read this file (at least the saved portion of the file). This is because the file exists on the disc before it is closed.
To send streaming data (log files, events etc..,) from various sources to HDFS, we have the following tools available at our disposal −
Scribe is an immensely popular tool that is used to aggregate and stream log data. It is designed to scale to a very large number of nodes and be robust to network and node failures.
Kafka has been developed by Apache Software Foundation. It is an open-source message broker. Using Kafka, we can handle feeds with high-throughput and low-latency.
Apache Flume is a tool/service/data ingestion mechanism for collecting aggregating and transporting large amounts of streaming data such as log data, events (etc...) from various webserves to a centralized data store.
It is a highly reliable, distributed, and configurable tool that is principally designed to transfer streaming data from various sources to HDFS.
In this tutorial, we will discuss in detail how to use Flume with some examples.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2195,
"s": 1857,
"text": "Big Data, as we know, is a collection of large datasets that cannot be processed using traditional computing techniques. Big Data, when analyzed, gives valuable results. Hadoop is an open-source framework that allows to store and process Big Data in a distributed environment across clusters of computers using simple programming models."
},
{
"code": null,
"e": 2433,
"s": 2195,
"text": "Generally, most of the data that is to be analyzed will be produced by various data sources like applications servers, social networking sites, cloud servers, and enterprise servers. This data will be in the form of log files and events."
},
{
"code": null,
"e": 2619,
"s": 2433,
"text": "Log file − In general, a log file is a file that lists events/actions that occur in an operating system. For example, web servers list every request made to the server in the log files."
},
{
"code": null,
"e": 2679,
"s": 2619,
"text": "On harvesting such log data, we can get information about −"
},
{
"code": null,
"e": 2758,
"s": 2679,
"text": "the application performance and locate various software and hardware failures."
},
{
"code": null,
"e": 2813,
"s": 2758,
"text": "the user behavior and derive better business insights."
},
{
"code": null,
"e": 2944,
"s": 2813,
"text": "The traditional method of transferring data into the HDFS system is to use the put command. Let us see how to use the put command."
},
{
"code": null,
"e": 3068,
"s": 2944,
"text": "The main challenge in handling the log data is in moving these logs produced by multiple servers to the Hadoop environment."
},
{
"code": null,
"e": 3226,
"s": 3068,
"text": "Hadoop File System Shell provides commands to insert data into Hadoop and read from it. You can insert data into Hadoop using the put command as shown below."
},
{
"code": null,
"e": 3310,
"s": 3226,
"text": "$ Hadoop fs –put /path of the required file /path in HDFS where to save the file \n"
},
{
"code": null,
"e": 3439,
"s": 3310,
"text": "We can use the put command of Hadoop to transfer data from these sources to HDFS. But, it suffers from the following drawbacks −"
},
{
"code": null,
"e": 3675,
"s": 3439,
"text": "Using put command, we can transfer only one file at a time while the data generators generate data at a much higher rate. Since the analysis made on older data is less accurate, we need to have a solution to transfer data in real time."
},
{
"code": null,
"e": 3911,
"s": 3675,
"text": "Using put command, we can transfer only one file at a time while the data generators generate data at a much higher rate. Since the analysis made on older data is less accurate, we need to have a solution to transfer data in real time."
},
{
"code": null,
"e": 4082,
"s": 3911,
"text": "If we use put command, the data is needed to be packaged and should be ready for the upload. Since the webservers generate data continuously, it is a very difficult task."
},
{
"code": null,
"e": 4253,
"s": 4082,
"text": "If we use put command, the data is needed to be packaged and should be ready for the upload. Since the webservers generate data continuously, it is a very difficult task."
},
{
"code": null,
"e": 4445,
"s": 4253,
"text": "What we need here is a solutions that can overcome the drawbacks of put command and transfer the \"streaming data\" from data generators to centralized stores (especially HDFS) with less delay."
},
{
"code": null,
"e": 4754,
"s": 4445,
"text": "In HDFS, the file exists as a directory entry and the length of the file will be considered as zero till it is closed. For example, if a source is writing data into HDFS and the network was interrupted in the middle of the operation (without closing the file), then the data written in the file will be lost."
},
{
"code": null,
"e": 4858,
"s": 4754,
"text": "Therefore we need a reliable, configurable, and maintainable system to transfer the log data into HDFS."
},
{
"code": null,
"e": 5101,
"s": 4858,
"text": "Note − In POSIX file system, whenever we are accessing a file (say performing write operation), other programs can still read this file (at least the saved portion of the file). This is because the file exists on the disc before it is closed."
},
{
"code": null,
"e": 5237,
"s": 5101,
"text": "To send streaming data (log files, events etc..,) from various sources to HDFS, we have the following tools available at our disposal −"
},
{
"code": null,
"e": 5420,
"s": 5237,
"text": "Scribe is an immensely popular tool that is used to aggregate and stream log data. It is designed to scale to a very large number of nodes and be robust to network and node failures."
},
{
"code": null,
"e": 5584,
"s": 5420,
"text": "Kafka has been developed by Apache Software Foundation. It is an open-source message broker. Using Kafka, we can handle feeds with high-throughput and low-latency."
},
{
"code": null,
"e": 5802,
"s": 5584,
"text": "Apache Flume is a tool/service/data ingestion mechanism for collecting aggregating and transporting large amounts of streaming data such as log data, events (etc...) from various webserves to a centralized data store."
},
{
"code": null,
"e": 5948,
"s": 5802,
"text": "It is a highly reliable, distributed, and configurable tool that is principally designed to transfer streaming data from various sources to HDFS."
},
{
"code": null,
"e": 6029,
"s": 5948,
"text": "In this tutorial, we will discuss in detail how to use Flume with some examples."
},
{
"code": null,
"e": 6064,
"s": 6029,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6083,
"s": 6064,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6118,
"s": 6083,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6139,
"s": 6118,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 6172,
"s": 6139,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6185,
"s": 6172,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6220,
"s": 6185,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6238,
"s": 6220,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6271,
"s": 6238,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6289,
"s": 6271,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6322,
"s": 6289,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6340,
"s": 6322,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6347,
"s": 6340,
"text": " Print"
},
{
"code": null,
"e": 6358,
"s": 6347,
"text": " Add Notes"
}
] |
MTA Turnstile Data: Exploratory Data Analysis | by Yingzhao Ouyang | Towards Data Science
|
The first week of the Metis Data Science Bootcamp (Singapore Batch 4) has just concluded, and so far it’s been an interesting experience. Below I detail the first project that we did in that period, which was an exploratory data analysis of the MTA turnstile data set using Python paired with pandas and seaborn.
Prepared MTA turnstile data from February and March 2019 for a campaign signing people up for a summer gala.
Cleaned the data by renaming columns, adding calculated fields, removing erroneous data and aggregating by station and date.
Found that weekdays had the highest traffic, but this was less the case for some stations; certain days also had anomalous traffic flows.
Recommended that the campaign focus on stations with high weekday and low weekend traffic
Anomalies, time of day and other sources of demographic data should be considered for further analysis
Here’s the link to the GitHub repository.
Women Tech Women Yes (WTWY) has an annual gala in New York City (NYC) at the beginning of the summer each year. They try to do double duty with the gala both to fill their event space with individuals passionate about increasing the participation of women in technology, and to concurrently build awareness and reach.
To this end, they place street teams at entrances to NYC subway stations. The street teams collect email addresses and those who sign up are sent free tickets to their gala.
Our task was to use subway data from NYC’s Metropolitian Transit Authority (MTA) to help WTWY optimize the placement of their street teams, such that they can gather the most signatures, ideally from those who will attend the gala and contribute to their cause.
We used historical data from MTA’s turnstiles, deciding to focus on data from February and March 2019.
The months of February and March seem to be enough lead time before the summer months for people to be able to slot the gala into their calendar.
At this point in 2020, the COVID-19 pandemic is raging, with NYC as one of the largest hotspots in the world. As a result, it has locked down, which has heavily disrupted transport patterns and emptied its streets. This is a highly unusual situation. Were this a real-life study, my advice to the organisers would had been to avoid placing street teams entirely, and either postpone/cancel the gala or move it completely online. For the purposes of this exercise, we made the assumption that the gala would happen in the summer of 2019.
To be specific, we took data from a ten-week period from the week ending 2 February 2019 to the week ending 5 March 2019, as per the code snippet below:
We also decided to focus on collecting total traffic for each station each day, leaving out the timing of the entries. The timing would conceivably be added in a later iteration of the data analysis.
Examining mta_test.columns.values, we notice that the EXITS column of the dataset has a whole bunch of trailing spaces:
array(['C/A', 'UNIT', 'SCP', 'STATION', 'LINENAME', 'DIVISION', 'DATE', 'TIME', 'DESC', 'ENTRIES', 'EXITS '], dtype=object)
So to make our life easier, we renamed it:
mta_test.rename(columns={'EXITS ':'EXITS'}, inplace=True)
Based on the field descrpition from MTA, we know that ENTRIES and EXITS are the cumulative entry and exit register values for a given entry and exit point respectively. Since we are aggregating by day rather than by time period, we decided to subtract the first (aka smallest) and last (aka largest) counter values for entries and exits respectively.
We also aggregated entries and exits into a single column, TRAFFIC, as well as appended weekday attributes so as to make it easier to analyse the data by weekday later. Our results were put into mta_entries_exits.
The code snippet for all this is as follows:
When we sort mta_entries_exits by TRAFFIC, we find strangely large values that would appear to throw the data set off:
Further analysis of the data reveals that in certain rows of the MTA data, the counter value jumps by an inexplicable amount (example below):
A look at the distribution for entries and exits reveals that most of these values fall under 20,000:
So we removed all values of entries and exits greater than 20,000:
mta_entries_exits = mta_entries_exits[(mta_entries_exits.ENTRIES < 20000) & (mta_entries_exits.ENTRIES < 20000)]
Note that this removes data for a specific turnstile for an entire day. We deemed this acceptable for the purposes of our initial analysis as stations have many turnstiles per entry point and typically more than one entry point; however, further analysis would need the data removal to be more targeted.
Finally, we aggragated the data by station and date, as we are not looking at individual turnstiles.
mta_bystation = mta_entries_exits.groupby(['STATION','DATE','WEEKDAY', 'WEEKDAY_INDEX']).sum().reset_index()
We found the top 5 stations by aggregate traffic were as follows:
Penn StationGrand CentralHerald Square23rd StreetTimes Square
Penn Station
Grand Central
Herald Square
23rd Street
Times Square
Our recommedation would be to focus on these 5 stations.
We found that weekends see less traffic than weekdays (up to half the usual traffic). This is true in the aggregate:
And is also true for the top 5 stations:
Our recommendation would be to focus on weekdays.
We noted that not all stations followed the same pattern. For instance, the 3rd to 5th rank stations had weekday traffic volumes that were closer to the weekend traffic volumes:
This could be due to these stations being in touristy areas, Times Square being a standout example. Such short-term visitors would be unlikely to attend the summer gala, to say the least. Our recommendation there would be to focus on stations with high weekday and low weekend traffic.
We also found that for at least one of the top 5 stations, there was an unexplained drop in traffic:
Such drops (or peaks) would need to be isolated and investigated, as they could be due to special circumstances such as public holidays or emergencies. It may also be due to loss of data from the earlier data cleaning.
To gain further insights, we could do the following:
Include the TIME column so as to: a) determine peak hours so that WTWY would know when are the best times to place their teams; and b) reduce the loss of data by discarding bad data for specific timings rather than for an entire day for turnstiles.Incorporate demographic and geographical data to determine the makeup of the commuters, any geographical correlations etc.
Include the TIME column so as to: a) determine peak hours so that WTWY would know when are the best times to place their teams; and b) reduce the loss of data by discarding bad data for specific timings rather than for an entire day for turnstiles.
Incorporate demographic and geographical data to determine the makeup of the commuters, any geographical correlations etc.
This exercise in exploratory data analysis taught us the following:
The importance of inspecting column name values; it took a while to realise why we were having trouble pulling the EXITS values from the dataset.The importance of using distribution graphs and filters to tease out outliers in the data.
The importance of inspecting column name values; it took a while to realise why we were having trouble pulling the EXITS values from the dataset.
The importance of using distribution graphs and filters to tease out outliers in the data.
|
[
{
"code": null,
"e": 485,
"s": 172,
"text": "The first week of the Metis Data Science Bootcamp (Singapore Batch 4) has just concluded, and so far it’s been an interesting experience. Below I detail the first project that we did in that period, which was an exploratory data analysis of the MTA turnstile data set using Python paired with pandas and seaborn."
},
{
"code": null,
"e": 594,
"s": 485,
"text": "Prepared MTA turnstile data from February and March 2019 for a campaign signing people up for a summer gala."
},
{
"code": null,
"e": 719,
"s": 594,
"text": "Cleaned the data by renaming columns, adding calculated fields, removing erroneous data and aggregating by station and date."
},
{
"code": null,
"e": 857,
"s": 719,
"text": "Found that weekdays had the highest traffic, but this was less the case for some stations; certain days also had anomalous traffic flows."
},
{
"code": null,
"e": 947,
"s": 857,
"text": "Recommended that the campaign focus on stations with high weekday and low weekend traffic"
},
{
"code": null,
"e": 1050,
"s": 947,
"text": "Anomalies, time of day and other sources of demographic data should be considered for further analysis"
},
{
"code": null,
"e": 1092,
"s": 1050,
"text": "Here’s the link to the GitHub repository."
},
{
"code": null,
"e": 1410,
"s": 1092,
"text": "Women Tech Women Yes (WTWY) has an annual gala in New York City (NYC) at the beginning of the summer each year. They try to do double duty with the gala both to fill their event space with individuals passionate about increasing the participation of women in technology, and to concurrently build awareness and reach."
},
{
"code": null,
"e": 1584,
"s": 1410,
"text": "To this end, they place street teams at entrances to NYC subway stations. The street teams collect email addresses and those who sign up are sent free tickets to their gala."
},
{
"code": null,
"e": 1846,
"s": 1584,
"text": "Our task was to use subway data from NYC’s Metropolitian Transit Authority (MTA) to help WTWY optimize the placement of their street teams, such that they can gather the most signatures, ideally from those who will attend the gala and contribute to their cause."
},
{
"code": null,
"e": 1949,
"s": 1846,
"text": "We used historical data from MTA’s turnstiles, deciding to focus on data from February and March 2019."
},
{
"code": null,
"e": 2095,
"s": 1949,
"text": "The months of February and March seem to be enough lead time before the summer months for people to be able to slot the gala into their calendar."
},
{
"code": null,
"e": 2632,
"s": 2095,
"text": "At this point in 2020, the COVID-19 pandemic is raging, with NYC as one of the largest hotspots in the world. As a result, it has locked down, which has heavily disrupted transport patterns and emptied its streets. This is a highly unusual situation. Were this a real-life study, my advice to the organisers would had been to avoid placing street teams entirely, and either postpone/cancel the gala or move it completely online. For the purposes of this exercise, we made the assumption that the gala would happen in the summer of 2019."
},
{
"code": null,
"e": 2785,
"s": 2632,
"text": "To be specific, we took data from a ten-week period from the week ending 2 February 2019 to the week ending 5 March 2019, as per the code snippet below:"
},
{
"code": null,
"e": 2985,
"s": 2785,
"text": "We also decided to focus on collecting total traffic for each station each day, leaving out the timing of the entries. The timing would conceivably be added in a later iteration of the data analysis."
},
{
"code": null,
"e": 3105,
"s": 2985,
"text": "Examining mta_test.columns.values, we notice that the EXITS column of the dataset has a whole bunch of trailing spaces:"
},
{
"code": null,
"e": 3296,
"s": 3105,
"text": "array(['C/A', 'UNIT', 'SCP', 'STATION', 'LINENAME', 'DIVISION', 'DATE', 'TIME', 'DESC', 'ENTRIES', 'EXITS '], dtype=object)"
},
{
"code": null,
"e": 3339,
"s": 3296,
"text": "So to make our life easier, we renamed it:"
},
{
"code": null,
"e": 3459,
"s": 3339,
"text": "mta_test.rename(columns={'EXITS ':'EXITS'}, inplace=True)"
},
{
"code": null,
"e": 3810,
"s": 3459,
"text": "Based on the field descrpition from MTA, we know that ENTRIES and EXITS are the cumulative entry and exit register values for a given entry and exit point respectively. Since we are aggregating by day rather than by time period, we decided to subtract the first (aka smallest) and last (aka largest) counter values for entries and exits respectively."
},
{
"code": null,
"e": 4024,
"s": 3810,
"text": "We also aggregated entries and exits into a single column, TRAFFIC, as well as appended weekday attributes so as to make it easier to analyse the data by weekday later. Our results were put into mta_entries_exits."
},
{
"code": null,
"e": 4069,
"s": 4024,
"text": "The code snippet for all this is as follows:"
},
{
"code": null,
"e": 4188,
"s": 4069,
"text": "When we sort mta_entries_exits by TRAFFIC, we find strangely large values that would appear to throw the data set off:"
},
{
"code": null,
"e": 4330,
"s": 4188,
"text": "Further analysis of the data reveals that in certain rows of the MTA data, the counter value jumps by an inexplicable amount (example below):"
},
{
"code": null,
"e": 4432,
"s": 4330,
"text": "A look at the distribution for entries and exits reveals that most of these values fall under 20,000:"
},
{
"code": null,
"e": 4499,
"s": 4432,
"text": "So we removed all values of entries and exits greater than 20,000:"
},
{
"code": null,
"e": 4612,
"s": 4499,
"text": "mta_entries_exits = mta_entries_exits[(mta_entries_exits.ENTRIES < 20000) & (mta_entries_exits.ENTRIES < 20000)]"
},
{
"code": null,
"e": 4916,
"s": 4612,
"text": "Note that this removes data for a specific turnstile for an entire day. We deemed this acceptable for the purposes of our initial analysis as stations have many turnstiles per entry point and typically more than one entry point; however, further analysis would need the data removal to be more targeted."
},
{
"code": null,
"e": 5017,
"s": 4916,
"text": "Finally, we aggragated the data by station and date, as we are not looking at individual turnstiles."
},
{
"code": null,
"e": 5126,
"s": 5017,
"text": "mta_bystation = mta_entries_exits.groupby(['STATION','DATE','WEEKDAY', 'WEEKDAY_INDEX']).sum().reset_index()"
},
{
"code": null,
"e": 5192,
"s": 5126,
"text": "We found the top 5 stations by aggregate traffic were as follows:"
},
{
"code": null,
"e": 5254,
"s": 5192,
"text": "Penn StationGrand CentralHerald Square23rd StreetTimes Square"
},
{
"code": null,
"e": 5267,
"s": 5254,
"text": "Penn Station"
},
{
"code": null,
"e": 5281,
"s": 5267,
"text": "Grand Central"
},
{
"code": null,
"e": 5295,
"s": 5281,
"text": "Herald Square"
},
{
"code": null,
"e": 5307,
"s": 5295,
"text": "23rd Street"
},
{
"code": null,
"e": 5320,
"s": 5307,
"text": "Times Square"
},
{
"code": null,
"e": 5377,
"s": 5320,
"text": "Our recommedation would be to focus on these 5 stations."
},
{
"code": null,
"e": 5494,
"s": 5377,
"text": "We found that weekends see less traffic than weekdays (up to half the usual traffic). This is true in the aggregate:"
},
{
"code": null,
"e": 5535,
"s": 5494,
"text": "And is also true for the top 5 stations:"
},
{
"code": null,
"e": 5585,
"s": 5535,
"text": "Our recommendation would be to focus on weekdays."
},
{
"code": null,
"e": 5763,
"s": 5585,
"text": "We noted that not all stations followed the same pattern. For instance, the 3rd to 5th rank stations had weekday traffic volumes that were closer to the weekend traffic volumes:"
},
{
"code": null,
"e": 6049,
"s": 5763,
"text": "This could be due to these stations being in touristy areas, Times Square being a standout example. Such short-term visitors would be unlikely to attend the summer gala, to say the least. Our recommendation there would be to focus on stations with high weekday and low weekend traffic."
},
{
"code": null,
"e": 6150,
"s": 6049,
"text": "We also found that for at least one of the top 5 stations, there was an unexplained drop in traffic:"
},
{
"code": null,
"e": 6369,
"s": 6150,
"text": "Such drops (or peaks) would need to be isolated and investigated, as they could be due to special circumstances such as public holidays or emergencies. It may also be due to loss of data from the earlier data cleaning."
},
{
"code": null,
"e": 6422,
"s": 6369,
"text": "To gain further insights, we could do the following:"
},
{
"code": null,
"e": 6793,
"s": 6422,
"text": "Include the TIME column so as to: a) determine peak hours so that WTWY would know when are the best times to place their teams; and b) reduce the loss of data by discarding bad data for specific timings rather than for an entire day for turnstiles.Incorporate demographic and geographical data to determine the makeup of the commuters, any geographical correlations etc."
},
{
"code": null,
"e": 7042,
"s": 6793,
"text": "Include the TIME column so as to: a) determine peak hours so that WTWY would know when are the best times to place their teams; and b) reduce the loss of data by discarding bad data for specific timings rather than for an entire day for turnstiles."
},
{
"code": null,
"e": 7165,
"s": 7042,
"text": "Incorporate demographic and geographical data to determine the makeup of the commuters, any geographical correlations etc."
},
{
"code": null,
"e": 7233,
"s": 7165,
"text": "This exercise in exploratory data analysis taught us the following:"
},
{
"code": null,
"e": 7469,
"s": 7233,
"text": "The importance of inspecting column name values; it took a while to realise why we were having trouble pulling the EXITS values from the dataset.The importance of using distribution graphs and filters to tease out outliers in the data."
},
{
"code": null,
"e": 7615,
"s": 7469,
"text": "The importance of inspecting column name values; it took a while to realise why we were having trouble pulling the EXITS values from the dataset."
}
] |
Raise x to the power n using Recursion in Java
|
The power of a number can be calculated using recursion. Here the number is x and it is raised to power n.
A program that demonstrates this is given as follows:
Live Demo
public class Demo {
static double pow(double x, int n) {
if (n != 0)
return (x * pow(x, n - 1));
else
return 1;
}
public static void main(String[] args) {
System.out.println("7 to the power 3 is " + pow(7, 3));
System.out.println("4 to the power 1 is " + pow(4, 1));
System.out.println("9 to the power 0 is " + pow(9, 0));
}
}
7 to the power 3 is 343.0
4 to the power 1 is 4.0
9 to the power 0 is 1.0
Now let us understand the above program.
The method pow() calculates x raised to the power n. If n is not 0, it recursively calls itself and returns x * pow(x, n - 1). If n is 0, it returns 1. A code snippet which demonstrates this is as follows:
static double pow(double x, int n) {
if (n != 0)
return (x * pow(x, n - 1));
else
return 1;
}
In main(), the method pow() is called with different values. A code snippet which demonstrates this is as follows:
public static void main(String[] args) {
System.out.println("7 to the power 3 is " + pow(7, 3));
System.out.println("4 to the power 1 is " + pow(4, 1));
System.out.println("9 to the power 0 is " + pow(9, 0));
}
|
[
{
"code": null,
"e": 1169,
"s": 1062,
"text": "The power of a number can be calculated using recursion. Here the number is x and it is raised to power n."
},
{
"code": null,
"e": 1223,
"s": 1169,
"text": "A program that demonstrates this is given as follows:"
},
{
"code": null,
"e": 1234,
"s": 1223,
"text": " Live Demo"
},
{
"code": null,
"e": 1621,
"s": 1234,
"text": "public class Demo {\n static double pow(double x, int n) {\n if (n != 0)\n return (x * pow(x, n - 1));\n else\n return 1;\n }\n public static void main(String[] args) {\n System.out.println(\"7 to the power 3 is \" + pow(7, 3));\n System.out.println(\"4 to the power 1 is \" + pow(4, 1));\n System.out.println(\"9 to the power 0 is \" + pow(9, 0));\n }\n}"
},
{
"code": null,
"e": 1695,
"s": 1621,
"text": "7 to the power 3 is 343.0\n4 to the power 1 is 4.0\n9 to the power 0 is 1.0"
},
{
"code": null,
"e": 1736,
"s": 1695,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1942,
"s": 1736,
"text": "The method pow() calculates x raised to the power n. If n is not 0, it recursively calls itself and returns x * pow(x, n - 1). If n is 0, it returns 1. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2054,
"s": 1942,
"text": "static double pow(double x, int n) {\n if (n != 0)\n return (x * pow(x, n - 1));\n else\n return 1;\n}"
},
{
"code": null,
"e": 2169,
"s": 2054,
"text": "In main(), the method pow() is called with different values. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2389,
"s": 2169,
"text": "public static void main(String[] args) {\n System.out.println(\"7 to the power 3 is \" + pow(7, 3));\n System.out.println(\"4 to the power 1 is \" + pow(4, 1));\n System.out.println(\"9 to the power 0 is \" + pow(9, 0));\n}"
}
] |
C++ Program for Inorder Tree Traversal without Recursion
|
If a binary tree is traversed in-order, the left subtree is visited first, then the root and later the right sub-tree. The output the key in ascending order in in_order traversal. This is a C++ Program for Inorder Tree Traversal without Recursion.
Begin
Function inOrder():
Declare a stack s.
Declare the current node as root.
While current node is not null and stack is not empty do
While current node is not null do
Push the current node on the top of the stack
Make the left child node as current node
Point the current node at the top of the stack.
Pop the top most node from the stack
Print the current node.
Make the right node as current node.
Insert some elements at root, left node and right node in stack.
Call the inOrder() function to traverse the tree.
End.
Live Demo
#include<bits/stdc++.h>
using namespace std;
struct n {
int d;
struct n* l;
struct n* r;
n (int d) {
this->d = d;
l = r = NULL;
}
};
void inOrder(struct n *root) {
stack<n *> s;
n *current = root;
while (current != NULL || s.empty() == false) {
while (current != NULL) {
s.push(current);
current = current->l;
}
current = s.top();
s.pop();
cout << current->d << " ";
current = current->r;
}
}
int main() {
struct n *root = new n(7);
root->l = new n(6);
root->r = new n(2);
root->l->l = new n(1);
root->l->r = new n(9);
inOrder(root);
return 0;
}
1 6 9 7 2
|
[
{
"code": null,
"e": 1310,
"s": 1062,
"text": "If a binary tree is traversed in-order, the left subtree is visited first, then the root and later the right sub-tree. The output the key in ascending order in in_order traversal. This is a C++ Program for Inorder Tree Traversal without Recursion."
},
{
"code": null,
"e": 1940,
"s": 1310,
"text": "Begin \n Function inOrder():\n Declare a stack s.\n Declare the current node as root.\n While current node is not null and stack is not empty do\n While current node is not null do\n Push the current node on the top of the stack\n Make the left child node as current node\n Point the current node at the top of the stack.\n Pop the top most node from the stack\n Print the current node.\n Make the right node as current node. \n Insert some elements at root, left node and right node in stack.\n Call the inOrder() function to traverse the tree. \nEnd."
},
{
"code": null,
"e": 1951,
"s": 1940,
"text": " Live Demo"
},
{
"code": null,
"e": 2619,
"s": 1951,
"text": "#include<bits/stdc++.h>\nusing namespace std;\n\nstruct n {\n int d;\n struct n* l;\n struct n* r;\n n (int d) {\n this->d = d;\n l = r = NULL;\n }\n};\n\nvoid inOrder(struct n *root) {\n stack<n *> s;\n n *current = root;\n\n while (current != NULL || s.empty() == false) {\n while (current != NULL) {\n s.push(current);\n current = current->l;\n }\n\n current = s.top();\n s.pop();\n\n cout << current->d << \" \";\n current = current->r;\n }\n}\n\nint main() {\n struct n *root = new n(7);\n\n root->l = new n(6);\n root->r = new n(2);\n root->l->l = new n(1);\n root->l->r = new n(9);\n\n inOrder(root);\n return 0;\n}"
},
{
"code": null,
"e": 2629,
"s": 2619,
"text": "1 6 9 7 2"
}
] |
Python Arcade - Collision Detection - GeeksforGeeks
|
05 Oct, 2021
In this article, we will learn How we can add collisions in arcade games in Python.
You can install the Arcade module using the below command:
pip install arcade
In this example, we are going to use the check_for_collision() function to add collision between 2 sprites.
Syntax: arcade.check_for_collision( sprite1, sprite2)
Parameters:
sprite1:- First sprite
sprite2:- Second sprite
Returns: Boolean value
Below is the implementation:
Python3
# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title="Player Movement") # Initializing a variable to store # the velocity of Player1 and Player2 self.vel_x1 = 380 self.vel_x2 = 380 self.scene = None # Creating variable to store player sprite self.player1 = None # Creating variable to store player sprite self.player2 = None # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing the scene self.scene.draw() def setup(self): # Creating scene self.scene = arcade.Scene() # Adding player sprite self.player_sprite1 = arcade.Sprite("Player.png", 1) self.player_sprite2 = arcade.Sprite("Player2.png", 1) # Adding coordinates for the center of the sprite self.player_sprite1.center_x = 20 self.player_sprite1.center_y = 300 # Adding coordinates for the center of the sprite self.player_sprite2.center_x = 580 self.player_sprite2.center_y = 300 # Adding sprites in scene self.scene.add_sprite('Player', self.player_sprite1) self.scene.add_sprite('Player', self.player_sprite2) # Creating on_update function to # update the x coordinate def on_update(self, delta_time): # Changing x coordinate of players self.player_sprite1.center_x += self.vel_x1 * delta_time self.player_sprite2.center_x -= self.vel_x2 * delta_time # Checking if sprites are colliding or not colliding = arcade.check_for_collision( self.player_sprite1, self.player_sprite2) # If sprites are colliding then changing direction if colliding: self.vel_x1 *= -1 self.vel_x2 *= -1 # Changing the direction if sprites crosses the screen boundary if self.player_sprite1.center_x > 600 or self.player_sprite1.center_x < 0: self.vel_x1 *= -1 if self.player_sprite2.center_x > 600 or self.player_sprite2.center_x < 0: self.vel_x2 *= -1 # Calling MainGame classgame = MainGame()game.setup()arcade.run()
Output:
In this example, we are going to use PhysicsEnginePlatformer() function to add collision between our player and platform.
Syntax: arcade.PhysicsEnginePlatformer(player_sprite, platforms,, gravity, ladders)
Parameters:
player_sprite:- The player sprite
platforms:- The platform sprite list
gravity:- Amount of gravity
ladders:- Ladders the user can climb on
Below is the implementation:
Python3
# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title="Player Movement") # Initializing a variable to store # the velocity of the player self.vel_x = 0 # Creating scene object self.scene = None # Creating variable to store player sprite self.player = None # Creating variable for our game engine self.physics_engine = None # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing our scene self.scene.draw() def setup(self): # Initialize Scene object self.scene = arcade.Scene() # Creating different sprite lists self.scene.add_sprite_list("Player") self.scene.add_sprite_list("Platforms", use_spatial_hash=True) # Adding player sprite self.player_sprite = arcade.Sprite("Player.png", 1) # Adding coordinates for the center of the sprite self.player_sprite.center_x = 64 self.player_sprite.center_y = 600 # Adding Sprite in our scene self.scene.add_sprite("Player", self.player_sprite) # Adding platform sprite platform = arcade.Sprite("Platform.png", 1) # Adding coordinates for the center of the platform platform.center_x = 300 platform.center_y = 32 self.scene.add_sprite("Platforms", platform) # Creating Physics engine self.physics_engine = arcade.PhysicsEnginePlatformer( self.player_sprite, self.scene.get_sprite_list("Platforms"), 0.5 ) # Creating on_update function to # update the x coordinate def on_update(self, delta_time): # Changing x coordinate of player self.player_sprite.center_x += self.vel_x * delta_time # Updating the physics engine to move the player self.physics_engine.update() # Creating function to change the velocity # when button is pressed def on_key_press(self, symbol, modifier): # Checking the button pressed # and changing the value of velocity if symbol == arcade.key.LEFT: self.vel_x = -300 elif symbol == arcade.key.RIGHT: self.vel_x = 300 # Creating function to change the velocity # when button is released def on_key_release(self, symbol, modifier): # Checking the button released # and changing the value of velocity if symbol == arcade.key.LEFT: self.vel_x = 0 elif symbol == arcade.key.RIGHT: self.vel_x = 0 # Calling MainGame classgame = MainGame()game.setup()arcade.run()
Output:
varshagumber28
Python-Arcade
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23925,
"s": 23897,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 24009,
"s": 23925,
"text": "In this article, we will learn How we can add collisions in arcade games in Python."
},
{
"code": null,
"e": 24068,
"s": 24009,
"text": "You can install the Arcade module using the below command:"
},
{
"code": null,
"e": 24087,
"s": 24068,
"text": "pip install arcade"
},
{
"code": null,
"e": 24195,
"s": 24087,
"text": "In this example, we are going to use the check_for_collision() function to add collision between 2 sprites."
},
{
"code": null,
"e": 24249,
"s": 24195,
"text": "Syntax: arcade.check_for_collision( sprite1, sprite2)"
},
{
"code": null,
"e": 24261,
"s": 24249,
"text": "Parameters:"
},
{
"code": null,
"e": 24284,
"s": 24261,
"text": "sprite1:- First sprite"
},
{
"code": null,
"e": 24308,
"s": 24284,
"text": "sprite2:- Second sprite"
},
{
"code": null,
"e": 24331,
"s": 24308,
"text": "Returns: Boolean value"
},
{
"code": null,
"e": 24360,
"s": 24331,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 24368,
"s": 24360,
"text": "Python3"
},
{
"code": "# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title=\"Player Movement\") # Initializing a variable to store # the velocity of Player1 and Player2 self.vel_x1 = 380 self.vel_x2 = 380 self.scene = None # Creating variable to store player sprite self.player1 = None # Creating variable to store player sprite self.player2 = None # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing the scene self.scene.draw() def setup(self): # Creating scene self.scene = arcade.Scene() # Adding player sprite self.player_sprite1 = arcade.Sprite(\"Player.png\", 1) self.player_sprite2 = arcade.Sprite(\"Player2.png\", 1) # Adding coordinates for the center of the sprite self.player_sprite1.center_x = 20 self.player_sprite1.center_y = 300 # Adding coordinates for the center of the sprite self.player_sprite2.center_x = 580 self.player_sprite2.center_y = 300 # Adding sprites in scene self.scene.add_sprite('Player', self.player_sprite1) self.scene.add_sprite('Player', self.player_sprite2) # Creating on_update function to # update the x coordinate def on_update(self, delta_time): # Changing x coordinate of players self.player_sprite1.center_x += self.vel_x1 * delta_time self.player_sprite2.center_x -= self.vel_x2 * delta_time # Checking if sprites are colliding or not colliding = arcade.check_for_collision( self.player_sprite1, self.player_sprite2) # If sprites are colliding then changing direction if colliding: self.vel_x1 *= -1 self.vel_x2 *= -1 # Changing the direction if sprites crosses the screen boundary if self.player_sprite1.center_x > 600 or self.player_sprite1.center_x < 0: self.vel_x1 *= -1 if self.player_sprite2.center_x > 600 or self.player_sprite2.center_x < 0: self.vel_x2 *= -1 # Calling MainGame classgame = MainGame()game.setup()arcade.run()",
"e": 26619,
"s": 24368,
"text": null
},
{
"code": null,
"e": 26627,
"s": 26619,
"text": "Output:"
},
{
"code": null,
"e": 26749,
"s": 26627,
"text": "In this example, we are going to use PhysicsEnginePlatformer() function to add collision between our player and platform."
},
{
"code": null,
"e": 26833,
"s": 26749,
"text": "Syntax: arcade.PhysicsEnginePlatformer(player_sprite, platforms,, gravity, ladders)"
},
{
"code": null,
"e": 26845,
"s": 26833,
"text": "Parameters:"
},
{
"code": null,
"e": 26879,
"s": 26845,
"text": "player_sprite:- The player sprite"
},
{
"code": null,
"e": 26916,
"s": 26879,
"text": "platforms:- The platform sprite list"
},
{
"code": null,
"e": 26944,
"s": 26916,
"text": "gravity:- Amount of gravity"
},
{
"code": null,
"e": 26984,
"s": 26944,
"text": "ladders:- Ladders the user can climb on"
},
{
"code": null,
"e": 27013,
"s": 26984,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 27021,
"s": 27013,
"text": "Python3"
},
{
"code": "# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title=\"Player Movement\") # Initializing a variable to store # the velocity of the player self.vel_x = 0 # Creating scene object self.scene = None # Creating variable to store player sprite self.player = None # Creating variable for our game engine self.physics_engine = None # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing our scene self.scene.draw() def setup(self): # Initialize Scene object self.scene = arcade.Scene() # Creating different sprite lists self.scene.add_sprite_list(\"Player\") self.scene.add_sprite_list(\"Platforms\", use_spatial_hash=True) # Adding player sprite self.player_sprite = arcade.Sprite(\"Player.png\", 1) # Adding coordinates for the center of the sprite self.player_sprite.center_x = 64 self.player_sprite.center_y = 600 # Adding Sprite in our scene self.scene.add_sprite(\"Player\", self.player_sprite) # Adding platform sprite platform = arcade.Sprite(\"Platform.png\", 1) # Adding coordinates for the center of the platform platform.center_x = 300 platform.center_y = 32 self.scene.add_sprite(\"Platforms\", platform) # Creating Physics engine self.physics_engine = arcade.PhysicsEnginePlatformer( self.player_sprite, self.scene.get_sprite_list(\"Platforms\"), 0.5 ) # Creating on_update function to # update the x coordinate def on_update(self, delta_time): # Changing x coordinate of player self.player_sprite.center_x += self.vel_x * delta_time # Updating the physics engine to move the player self.physics_engine.update() # Creating function to change the velocity # when button is pressed def on_key_press(self, symbol, modifier): # Checking the button pressed # and changing the value of velocity if symbol == arcade.key.LEFT: self.vel_x = -300 elif symbol == arcade.key.RIGHT: self.vel_x = 300 # Creating function to change the velocity # when button is released def on_key_release(self, symbol, modifier): # Checking the button released # and changing the value of velocity if symbol == arcade.key.LEFT: self.vel_x = 0 elif symbol == arcade.key.RIGHT: self.vel_x = 0 # Calling MainGame classgame = MainGame()game.setup()arcade.run()",
"e": 29741,
"s": 27021,
"text": null
},
{
"code": null,
"e": 29749,
"s": 29741,
"text": "Output:"
},
{
"code": null,
"e": 29764,
"s": 29749,
"text": "varshagumber28"
},
{
"code": null,
"e": 29778,
"s": 29764,
"text": "Python-Arcade"
},
{
"code": null,
"e": 29785,
"s": 29778,
"text": "Python"
},
{
"code": null,
"e": 29883,
"s": 29785,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29892,
"s": 29883,
"text": "Comments"
},
{
"code": null,
"e": 29905,
"s": 29892,
"text": "Old Comments"
},
{
"code": null,
"e": 29937,
"s": 29905,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29993,
"s": 29937,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30035,
"s": 29993,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30077,
"s": 30035,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30113,
"s": 30077,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 30152,
"s": 30113,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30174,
"s": 30152,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30205,
"s": 30174,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30232,
"s": 30205,
"text": "Python Classes and Objects"
}
] |
How can I remove a button or make it invisible in Android using Kotlin?
|
This example demonstrates how to remove a button or make it invisible in Android using Kotlin.
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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@android:color/white"
android:padding="4dp"
android:text="Click to hide me "
android:textColor="@android:color/holo_red_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val button: Button = findViewById(R.id.button)
button.setOnClickListener {
button.visibility = View.INVISIBLE
Toast.makeText(baseContext, "Button is hidden", Toast.LENGTH_SHORT).show()
}
}
}
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 the 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": 1157,
"s": 1062,
"text": "This example demonstrates how to remove a button or make it invisible in Android using Kotlin."
},
{
"code": null,
"e": 1286,
"s": 1157,
"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": 1351,
"s": 1286,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2426,
"s": 1351,
"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 tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:background=\"@android:color/white\"\n android:padding=\"4dp\"\n android:text=\"Click to hide me \"\n android:textColor=\"@android:color/holo_red_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2481,
"s": 2426,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3077,
"s": 2481,
"text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport android.widget.Toast\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val button: Button = findViewById(R.id.button)\n button.setOnClickListener {\n button.visibility = View.INVISIBLE\n Toast.makeText(baseContext, \"Button is hidden\", Toast.LENGTH_SHORT).show()\n }\n }\n}"
},
{
"code": null,
"e": 3132,
"s": 3077,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3806,
"s": 3132,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n 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": 4155,
"s": 3806,
"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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
How to use image preprocessing to improve the accuracy of Tesseract | by Kaan Kuguoglu | Towards Data Science
|
Previously, on How to get started with Tesseract, I gave you a practical quick-start tutorial on Tesseract using Python. It is a pretty simple overview, but it should help you get started with Tesseract and clear some hurdles I faced when I was in your shoes. Now, I’m keen on showing you a few more tricks and stuff you can do with Tesseract and OpenCV to improve your overall accuracy.
In the previous story, I didn’t bother going into details for the most part. But if you liked the first story, here comes the sequel! So, where did we leave off?
Ah, we had a brief overview of rescaling, noise removal, and binarization. Now, it’s time to get down to details and show you a few settings you can play with.
The images that are rescaled are either shrunk or enlarged. If you’re interested in shrinking your image, INTER_AREA is the way to go for you. (Btw, the parameters fx and fy denote the scaling factor in the function below.)
img = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
On the other hand, as in most cases, you may need to scale your image to a larger size to recognize small characters. In this case, INTER_CUBIC generally performs better than other alternatives, though it’s slower than others.
img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
If you’d like to trade off some of your image quality for faster performance, you may want to try INTER_LINEAR for enlarging images.
img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
It’s worth mentioning that there are a few blur filters available in the OpenCV library. Image blurring is usually achieved by convolving the image with a low-pass filter kernel. While filters are usually used to blur the image or reduce noise, there are a few differences between them.
After convolving an image with a normalized box filter, this takes the average of all the pixels under the kernel area and replaces the central element. It’s pretty self-explanatory, I guess.
img = cv.blur(img,(5,5))
This works similarly to Averaging, but it uses a Gaussian kernel, instead of a normalized box filter, for convolution. Here, the dimensions of the kernel and standard deviations in both directions can be determined independently. Gaussian blurring is very useful for removing — guess what? — gaussian noise from the image. On the contrary, gaussian blurring does not preserve the edges in the input.
img = cv2.GaussianBlur(img, (5, 5), 0)
The central element in the kernel area is replaced with the median of all the pixels under the kernel. Particularly, this outperforms other blurring methods in removing salt-and-pepper noise in the images.
Median blurring is a non-linear filter. Unlike linear filters, median blurring replaces the pixel values with the median value available in the neighborhood values. So, median blurring preserves edges as the median value must be the value of one of the neighboring pixels.
img = cv2.medianBlur(img, 3)
Speaking of sharp edges, bilateral filtering is quite useful for removing the noise without smoothing the edges. Similar to Gaussian blurring, bilateral filtering also uses a gaussian filter to find the Gaussian weighted average in the neighborhood. However, it also takes pixel difference into account while blurring the nearby pixels.
Thus, it ensures only those pixels with similar intensity to the central pixel are blurred, whereas the pixels with distinct pixel values are not blurred. In doing so, the edges that have larger intensity variation, so-called edges, are preserved.
img = cv.bilateralFilter(img,9,75,75)
Overall, if you are interested in preserving the edges, go with median blurring or bilateral filtering. On the contrary, gaussian blurring is likely to be faster than median blurring. Due to its computational complexity, bilateral filtering is the slowest of all methods.
Again, you do you.
There’s not a single image thresholding method that fits all types of documents. In reality, all filters perform differently on varying images. For instance, while some filters successfully binarize some images, they may fail to binarize others. Likewise, some filters may work well with those images that other filters cannot binarize well.
I’ll try to cover the basics here, though I recommend that you read the official documentation of OpenCV on Image Thresholding for more information and the theory behind it.
You might recall a friend of yours giving you some advice about your life by saying, “things are not always black and white.” Well, for a simple threshold, things are pretty straightforward.
cv.threshold(img,127,255,cv.THRESH_BINARY)
First, you pick a threshold value, say 127. If the pixel value is greater than the threshold, it becomes black. If less, it becomes white. OpenCV provides us with different types of thresholding methods that can be passed as the fourth parameter. I often use binary threshold for most tasks, but you may visit the official documentation for other thresholding methods.
Rather than setting one global threshold value, we let the algorithm calculate the threshold for small regions of the image. Thus, we end up having various threshold values for different image regions, which is great!
cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
There are two adaptive methods for calculating the threshold value. While Adaptive Thresh Mean returns the mean of the neighborhood area, Adaptive Gaussian Mean calculates the weighted sum of the neighborhood values.
We’ve got two more parameters that determine the size of the neighborhood area and the constant value subtracted from the result: the fifth and sixth parameters, respectively.
This method particularly works well with bimodal images, which is an image whose histogram has two peaks. If this is the case, we might be keen on picking a threshold value between these peaks. This is what Otsu’s Binarization actually does, though.
cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
It’s pretty useful in some cases. But it may fail to binarize images that are not bimodal. So, please take this filter with a grain of salt.
You might have already noticed there is a parameter, or in some cases a combination of a few parameters, that are passed as arguments to determine the type of thresholding, such as THRESH_BINARY. I’m not going into detail here now, as it is explained clearly in the official documentation.
So far, we’ve discussed some of the techniques of image pre-processing. You might wonder when exactly you’re going to get your hands dirty. Well, the time has come. Before you get back to your favorite Python IDE — mine is PyCharm, btw — I’m going to show you few lines of code that will save you some time while trying to find which combination of filters and image manipulations works well with your documents.
Let’s start by defining a switcher function with a few combinations of thresholding filters and blurring methods. Once you get the idea, you could also add more filters, incorporating other image pre-processing methods like rescaling your filter set.
Here I’ve created 20 different combinations of image thresholding methods, blurring methods, and kernel sizes. The switcher function, apply_threshold, takes two arguments: OpenCV image and an integer that denotes the filter. Likewise, since this function returns the OpenCV image, it could easily be integrated into our get_string function from the previous post.
def apply_threshold(img, argument): switcher = { 1: cv2.threshold(cv2.GaussianBlur(img, (9, 9), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1], 2: cv2.threshold(cv2.GaussianBlur(img, (7, 7), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1], 3: cv2.threshold(cv2.GaussianBlur(img, (5, 5), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1], ... 18: cv2.adaptiveThreshold(cv2.medianBlur(img, 7), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2), 19: cv2.adaptiveThreshold(cv2.medianBlur(img, 5), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2), 20: cv2.adaptiveThreshold(cv2.medianBlur(img, 3), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2) } return switcher.get(argument, "Invalid method")
And, here it comes.
def get_string(img_path, method): # Read image using opencv img = cv2.imread(img_path) # Extract the file name without the file extension file_name = os.path.basename(img_path).split('.')[0] file_name = file_name.split()[0] # Create a directory for outputs output_path = os.path.join(output_dir, file_name) if not os.path.exists(output_path): os.makedirs(output_path) # Rescale the image, if needed. img = cv2.resize(img, None, fx=1.5, fy=1.5, interpolation=cv2.INTER_CUBIC) # Convert to gray img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply dilation and erosion to remove some noise kernel = np.ones((1, 1), np.uint8) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) # Apply threshold to get image with only black and white img = apply_threshold(img, method) # Save the filtered image in the output directory save_path = os.path.join(output_path, file_name + "_filter_" + str(method) + ".jpg") cv2.imwrite(save_path, img) # Recognize text with tesseract for python result = pytesseract.image_to_string(img, lang="eng") return result
Now, we need to write a simple for loop that iterates over the input directory to collect images and applies each filter on the images gathered. I prefer to use glob, or os, for collecting images from directories and argparse for passing arguments via terminal, as any other sane person would do.
Here I’ve done pretty much the same thing as in my gist if you’d like to have a look at it. However, feel free to use the tools you feel comfortable with.
So far, I’ve tried to cover a few useful image pre-processing concepts and implementations, though it’s probably just the tip of the iceberg. I don’t know how much “leisure time” I’m going to have in the upcoming weeks, so I can’t give you a specific time frame for publishing my next post. However, I’m considering adding at least one more part to this series that explains a few things I left out, such as rotation and de-skewing on images.
Until then, the best bet is to keep your wits about you and continue to look for signs.*
|
[
{
"code": null,
"e": 559,
"s": 171,
"text": "Previously, on How to get started with Tesseract, I gave you a practical quick-start tutorial on Tesseract using Python. It is a pretty simple overview, but it should help you get started with Tesseract and clear some hurdles I faced when I was in your shoes. Now, I’m keen on showing you a few more tricks and stuff you can do with Tesseract and OpenCV to improve your overall accuracy."
},
{
"code": null,
"e": 721,
"s": 559,
"text": "In the previous story, I didn’t bother going into details for the most part. But if you liked the first story, here comes the sequel! So, where did we leave off?"
},
{
"code": null,
"e": 881,
"s": 721,
"text": "Ah, we had a brief overview of rescaling, noise removal, and binarization. Now, it’s time to get down to details and show you a few settings you can play with."
},
{
"code": null,
"e": 1105,
"s": 881,
"text": "The images that are rescaled are either shrunk or enlarged. If you’re interested in shrinking your image, INTER_AREA is the way to go for you. (Btw, the parameters fx and fy denote the scaling factor in the function below.)"
},
{
"code": null,
"e": 1179,
"s": 1105,
"text": "img = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)"
},
{
"code": null,
"e": 1406,
"s": 1179,
"text": "On the other hand, as in most cases, you may need to scale your image to a larger size to recognize small characters. In this case, INTER_CUBIC generally performs better than other alternatives, though it’s slower than others."
},
{
"code": null,
"e": 1477,
"s": 1406,
"text": "img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)"
},
{
"code": null,
"e": 1610,
"s": 1477,
"text": "If you’d like to trade off some of your image quality for faster performance, you may want to try INTER_LINEAR for enlarging images."
},
{
"code": null,
"e": 1682,
"s": 1610,
"text": "img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)"
},
{
"code": null,
"e": 1969,
"s": 1682,
"text": "It’s worth mentioning that there are a few blur filters available in the OpenCV library. Image blurring is usually achieved by convolving the image with a low-pass filter kernel. While filters are usually used to blur the image or reduce noise, there are a few differences between them."
},
{
"code": null,
"e": 2161,
"s": 1969,
"text": "After convolving an image with a normalized box filter, this takes the average of all the pixels under the kernel area and replaces the central element. It’s pretty self-explanatory, I guess."
},
{
"code": null,
"e": 2186,
"s": 2161,
"text": "img = cv.blur(img,(5,5))"
},
{
"code": null,
"e": 2586,
"s": 2186,
"text": "This works similarly to Averaging, but it uses a Gaussian kernel, instead of a normalized box filter, for convolution. Here, the dimensions of the kernel and standard deviations in both directions can be determined independently. Gaussian blurring is very useful for removing — guess what? — gaussian noise from the image. On the contrary, gaussian blurring does not preserve the edges in the input."
},
{
"code": null,
"e": 2625,
"s": 2586,
"text": "img = cv2.GaussianBlur(img, (5, 5), 0)"
},
{
"code": null,
"e": 2831,
"s": 2625,
"text": "The central element in the kernel area is replaced with the median of all the pixels under the kernel. Particularly, this outperforms other blurring methods in removing salt-and-pepper noise in the images."
},
{
"code": null,
"e": 3104,
"s": 2831,
"text": "Median blurring is a non-linear filter. Unlike linear filters, median blurring replaces the pixel values with the median value available in the neighborhood values. So, median blurring preserves edges as the median value must be the value of one of the neighboring pixels."
},
{
"code": null,
"e": 3133,
"s": 3104,
"text": "img = cv2.medianBlur(img, 3)"
},
{
"code": null,
"e": 3470,
"s": 3133,
"text": "Speaking of sharp edges, bilateral filtering is quite useful for removing the noise without smoothing the edges. Similar to Gaussian blurring, bilateral filtering also uses a gaussian filter to find the Gaussian weighted average in the neighborhood. However, it also takes pixel difference into account while blurring the nearby pixels."
},
{
"code": null,
"e": 3718,
"s": 3470,
"text": "Thus, it ensures only those pixels with similar intensity to the central pixel are blurred, whereas the pixels with distinct pixel values are not blurred. In doing so, the edges that have larger intensity variation, so-called edges, are preserved."
},
{
"code": null,
"e": 3756,
"s": 3718,
"text": "img = cv.bilateralFilter(img,9,75,75)"
},
{
"code": null,
"e": 4028,
"s": 3756,
"text": "Overall, if you are interested in preserving the edges, go with median blurring or bilateral filtering. On the contrary, gaussian blurring is likely to be faster than median blurring. Due to its computational complexity, bilateral filtering is the slowest of all methods."
},
{
"code": null,
"e": 4047,
"s": 4028,
"text": "Again, you do you."
},
{
"code": null,
"e": 4389,
"s": 4047,
"text": "There’s not a single image thresholding method that fits all types of documents. In reality, all filters perform differently on varying images. For instance, while some filters successfully binarize some images, they may fail to binarize others. Likewise, some filters may work well with those images that other filters cannot binarize well."
},
{
"code": null,
"e": 4563,
"s": 4389,
"text": "I’ll try to cover the basics here, though I recommend that you read the official documentation of OpenCV on Image Thresholding for more information and the theory behind it."
},
{
"code": null,
"e": 4754,
"s": 4563,
"text": "You might recall a friend of yours giving you some advice about your life by saying, “things are not always black and white.” Well, for a simple threshold, things are pretty straightforward."
},
{
"code": null,
"e": 4797,
"s": 4754,
"text": "cv.threshold(img,127,255,cv.THRESH_BINARY)"
},
{
"code": null,
"e": 5166,
"s": 4797,
"text": "First, you pick a threshold value, say 127. If the pixel value is greater than the threshold, it becomes black. If less, it becomes white. OpenCV provides us with different types of thresholding methods that can be passed as the fourth parameter. I often use binary threshold for most tasks, but you may visit the official documentation for other thresholding methods."
},
{
"code": null,
"e": 5384,
"s": 5166,
"text": "Rather than setting one global threshold value, we let the algorithm calculate the threshold for small regions of the image. Thus, we end up having various threshold values for different image regions, which is great!"
},
{
"code": null,
"e": 5474,
"s": 5384,
"text": "cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)"
},
{
"code": null,
"e": 5691,
"s": 5474,
"text": "There are two adaptive methods for calculating the threshold value. While Adaptive Thresh Mean returns the mean of the neighborhood area, Adaptive Gaussian Mean calculates the weighted sum of the neighborhood values."
},
{
"code": null,
"e": 5867,
"s": 5691,
"text": "We’ve got two more parameters that determine the size of the neighborhood area and the constant value subtracted from the result: the fifth and sixth parameters, respectively."
},
{
"code": null,
"e": 6117,
"s": 5867,
"text": "This method particularly works well with bimodal images, which is an image whose histogram has two peaks. If this is the case, we might be keen on picking a threshold value between these peaks. This is what Otsu’s Binarization actually does, though."
},
{
"code": null,
"e": 6184,
"s": 6117,
"text": "cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]"
},
{
"code": null,
"e": 6325,
"s": 6184,
"text": "It’s pretty useful in some cases. But it may fail to binarize images that are not bimodal. So, please take this filter with a grain of salt."
},
{
"code": null,
"e": 6615,
"s": 6325,
"text": "You might have already noticed there is a parameter, or in some cases a combination of a few parameters, that are passed as arguments to determine the type of thresholding, such as THRESH_BINARY. I’m not going into detail here now, as it is explained clearly in the official documentation."
},
{
"code": null,
"e": 7028,
"s": 6615,
"text": "So far, we’ve discussed some of the techniques of image pre-processing. You might wonder when exactly you’re going to get your hands dirty. Well, the time has come. Before you get back to your favorite Python IDE — mine is PyCharm, btw — I’m going to show you few lines of code that will save you some time while trying to find which combination of filters and image manipulations works well with your documents."
},
{
"code": null,
"e": 7279,
"s": 7028,
"text": "Let’s start by defining a switcher function with a few combinations of thresholding filters and blurring methods. Once you get the idea, you could also add more filters, incorporating other image pre-processing methods like rescaling your filter set."
},
{
"code": null,
"e": 7643,
"s": 7279,
"text": "Here I’ve created 20 different combinations of image thresholding methods, blurring methods, and kernel sizes. The switcher function, apply_threshold, takes two arguments: OpenCV image and an integer that denotes the filter. Likewise, since this function returns the OpenCV image, it could easily be integrated into our get_string function from the previous post."
},
{
"code": null,
"e": 8481,
"s": 7643,
"text": "def apply_threshold(img, argument): switcher = { 1: cv2.threshold(cv2.GaussianBlur(img, (9, 9), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1], 2: cv2.threshold(cv2.GaussianBlur(img, (7, 7), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1], 3: cv2.threshold(cv2.GaussianBlur(img, (5, 5), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1], ... 18: cv2.adaptiveThreshold(cv2.medianBlur(img, 7), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2), 19: cv2.adaptiveThreshold(cv2.medianBlur(img, 5), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2), 20: cv2.adaptiveThreshold(cv2.medianBlur(img, 3), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2) } return switcher.get(argument, \"Invalid method\")"
},
{
"code": null,
"e": 8501,
"s": 8481,
"text": "And, here it comes."
},
{
"code": null,
"e": 9655,
"s": 8501,
"text": "def get_string(img_path, method): # Read image using opencv img = cv2.imread(img_path) # Extract the file name without the file extension file_name = os.path.basename(img_path).split('.')[0] file_name = file_name.split()[0] # Create a directory for outputs output_path = os.path.join(output_dir, file_name) if not os.path.exists(output_path): os.makedirs(output_path) # Rescale the image, if needed. img = cv2.resize(img, None, fx=1.5, fy=1.5, interpolation=cv2.INTER_CUBIC) # Convert to gray img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply dilation and erosion to remove some noise kernel = np.ones((1, 1), np.uint8) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) # Apply threshold to get image with only black and white img = apply_threshold(img, method) # Save the filtered image in the output directory save_path = os.path.join(output_path, file_name + \"_filter_\" + str(method) + \".jpg\") cv2.imwrite(save_path, img) # Recognize text with tesseract for python result = pytesseract.image_to_string(img, lang=\"eng\") return result"
},
{
"code": null,
"e": 9952,
"s": 9655,
"text": "Now, we need to write a simple for loop that iterates over the input directory to collect images and applies each filter on the images gathered. I prefer to use glob, or os, for collecting images from directories and argparse for passing arguments via terminal, as any other sane person would do."
},
{
"code": null,
"e": 10107,
"s": 9952,
"text": "Here I’ve done pretty much the same thing as in my gist if you’d like to have a look at it. However, feel free to use the tools you feel comfortable with."
},
{
"code": null,
"e": 10550,
"s": 10107,
"text": "So far, I’ve tried to cover a few useful image pre-processing concepts and implementations, though it’s probably just the tip of the iceberg. I don’t know how much “leisure time” I’m going to have in the upcoming weeks, so I can’t give you a specific time frame for publishing my next post. However, I’m considering adding at least one more part to this series that explains a few things I left out, such as rotation and de-skewing on images."
}
] |
Resolve Syntax error near “ORDER BY order DESC” in MySQL?
|
The word order is a reserved order in MySQL and you have used it in the query. To get rid of the syntax error, you need to use backticks(` `) around the order.
The correct syntax is as follows −
select *from yourTableName ORDER BY `order` DESC;
Let us first create a table −
mysql> create table DemoTable
(
`order` int
);
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(67);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(90);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+-------+
| order |
+-------+
| 89 |
| 67 |
| 90 |
| 56 |
+-------+
4 rows in set (0.00 sec)
Following is the query to remove syntax error near ORDER BY −
mysql> select *from DemoTable ORDER BY `order` DESC;
+-------+
| order |
+-------+
| 90 |
| 89 |
| 67 |
| 56 |
+-------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1222,
"s": 1062,
"text": "The word order is a reserved order in MySQL and you have used it in the query. To get rid of the syntax error, you need to use backticks(` `) around the order."
},
{
"code": null,
"e": 1257,
"s": 1222,
"text": "The correct syntax is as follows −"
},
{
"code": null,
"e": 1307,
"s": 1257,
"text": "select *from yourTableName ORDER BY `order` DESC;"
},
{
"code": null,
"e": 1337,
"s": 1307,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1430,
"s": 1337,
"text": "mysql> create table DemoTable\n (\n `order` int\n );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1486,
"s": 1430,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1794,
"s": 1486,
"text": "mysql> insert into DemoTable values(89);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(67);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(90);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(56);\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1854,
"s": 1794,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1885,
"s": 1854,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1990,
"s": 1885,
"text": "+-------+\n| order |\n+-------+\n| 89 |\n| 67 |\n| 90 |\n| 56 |\n+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2052,
"s": 1990,
"text": "Following is the query to remove syntax error near ORDER BY −"
},
{
"code": null,
"e": 2105,
"s": 2052,
"text": "mysql> select *from DemoTable ORDER BY `order` DESC;"
},
{
"code": null,
"e": 2210,
"s": 2105,
"text": "+-------+\n| order |\n+-------+\n| 90 |\n| 89 |\n| 67 |\n| 56 |\n+-------+\n4 rows in set (0.00 sec)"
}
] |
hash command in Linux with examples - GeeksforGeeks
|
21 May, 2019
hash command in Linux system is the built-in command of bash which is used to maintain a hash table of recently executed programs. It remembers and shows the program locations. It will give the full pathname of each command name.
Syntax:
hash [-lr] [-p pathname] [-dt] [name ...]
Options:
-d: This is used to forget the remembered location of each NAME.
-l: It will display in a format that may be reused as input.
-p: pathname use PATHNAME as the full pathname of NAME.
-r: Forget all remembered locations.
-t: To display the remembered location of each NAME, preceding each location with the corresponding NAME if multiple NAMEs are given.
Example 1: hash command without any option
hash
Example 2: hash command with -r option
Example 3: hash command with -l command
hash -l
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
mv command in Linux with examples
nohup Command in Linux with Examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 24245,
"s": 24015,
"text": "hash command in Linux system is the built-in command of bash which is used to maintain a hash table of recently executed programs. It remembers and shows the program locations. It will give the full pathname of each command name."
},
{
"code": null,
"e": 24253,
"s": 24245,
"text": "Syntax:"
},
{
"code": null,
"e": 24295,
"s": 24253,
"text": "hash [-lr] [-p pathname] [-dt] [name ...]"
},
{
"code": null,
"e": 24304,
"s": 24295,
"text": "Options:"
},
{
"code": null,
"e": 24369,
"s": 24304,
"text": "-d: This is used to forget the remembered location of each NAME."
},
{
"code": null,
"e": 24430,
"s": 24369,
"text": "-l: It will display in a format that may be reused as input."
},
{
"code": null,
"e": 24486,
"s": 24430,
"text": "-p: pathname use PATHNAME as the full pathname of NAME."
},
{
"code": null,
"e": 24523,
"s": 24486,
"text": "-r: Forget all remembered locations."
},
{
"code": null,
"e": 24657,
"s": 24523,
"text": "-t: To display the remembered location of each NAME, preceding each location with the corresponding NAME if multiple NAMEs are given."
},
{
"code": null,
"e": 24700,
"s": 24657,
"text": "Example 1: hash command without any option"
},
{
"code": null,
"e": 24705,
"s": 24700,
"text": "hash"
},
{
"code": null,
"e": 24744,
"s": 24705,
"text": "Example 2: hash command with -r option"
},
{
"code": null,
"e": 24784,
"s": 24744,
"text": "Example 3: hash command with -l command"
},
{
"code": null,
"e": 24792,
"s": 24784,
"text": "hash -l"
},
{
"code": null,
"e": 24806,
"s": 24792,
"text": "linux-command"
},
{
"code": null,
"e": 24826,
"s": 24806,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 24833,
"s": 24826,
"text": "Picked"
},
{
"code": null,
"e": 24844,
"s": 24833,
"text": "Linux-Unix"
},
{
"code": null,
"e": 24942,
"s": 24844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24951,
"s": 24942,
"text": "Comments"
},
{
"code": null,
"e": 24964,
"s": 24951,
"text": "Old Comments"
},
{
"code": null,
"e": 24990,
"s": 24964,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25024,
"s": 24990,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25061,
"s": 25024,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25096,
"s": 25061,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 25122,
"s": 25096,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 25159,
"s": 25122,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25199,
"s": 25159,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 25228,
"s": 25199,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 25270,
"s": 25228,
"text": "Named Pipe or FIFO with example C program"
}
] |
C++ Program to check if input is an integer or a string
|
Given with an input by the user and the task is to check whether the given input is an integer or a string.
Integer can be any combination of digits between 0 -9 and string can be any combination excluding 0 – 9.
Input-: 123
Output-: 123 is an integer
Input-: Tutorials Point
Output-: Tutorials Point is a string
Approach used below is as follows −
Input the data.
Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.
Print the resultant output.
Start
Step 1->declare function to check if number or string
bool check_number(string str)
Loop For int i = 0 and i < str.length() and i++
If (isdigit(str[i]) == false)
return false
End
End
return true
step 2->Int main()
set string str = "sunidhi"
IF (check_number(str))
Print " is an integer"
End
Else
Print " is a string"
End
Set string str1 = "1234"
IF (check_number(str1))
Print " is an integer"
End
Else
Print " is a string"
End
Stop
Live Demo
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main() {
string str = "sunidhi";
if (check_number(str))
cout<<str<< " is an integer"<<endl;
else
cout<<str<< " is a string"<<endl;
string str1 = "1234";
if (check_number(str1))
cout<<str1<< " is an integer";
else
cout<<str1<< " is a string";
}
sunidhi is a string
1234 is an integer
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "Given with an input by the user and the task is to check whether the given input is an integer or a string."
},
{
"code": null,
"e": 1275,
"s": 1170,
"text": "Integer can be any combination of digits between 0 -9 and string can be any combination excluding 0 – 9."
},
{
"code": null,
"e": 1375,
"s": 1275,
"text": "Input-: 123\nOutput-: 123 is an integer\nInput-: Tutorials Point\nOutput-: Tutorials Point is a string"
},
{
"code": null,
"e": 1411,
"s": 1375,
"text": "Approach used below is as follows −"
},
{
"code": null,
"e": 1427,
"s": 1411,
"text": "Input the data."
},
{
"code": null,
"e": 1605,
"s": 1427,
"text": "Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int."
},
{
"code": null,
"e": 1633,
"s": 1605,
"text": "Print the resultant output."
},
{
"code": null,
"e": 2215,
"s": 1633,
"text": "Start\nStep 1->declare function to check if number or string\n bool check_number(string str)\n Loop For int i = 0 and i < str.length() and i++\n If (isdigit(str[i]) == false)\n return false\n End\n End\n return true\nstep 2->Int main()\n set string str = \"sunidhi\"\n IF (check_number(str))\n Print \" is an integer\"\n End\n Else\n Print \" is a string\"\n End\n Set string str1 = \"1234\"\n IF (check_number(str1))\n Print \" is an integer\"\n End\n Else\n Print \" is a string\"\n End\nStop"
},
{
"code": null,
"e": 2226,
"s": 2215,
"text": " Live Demo"
},
{
"code": null,
"e": 2736,
"s": 2226,
"text": "#include <iostream>\nusing namespace std;\n//check if number or string\nbool check_number(string str) {\n for (int i = 0; i < str.length(); i++)\n if (isdigit(str[i]) == false)\n return false;\n return true;\n}\nint main() {\n string str = \"sunidhi\";\n if (check_number(str))\n cout<<str<< \" is an integer\"<<endl;\n else\n cout<<str<< \" is a string\"<<endl;\n string str1 = \"1234\";\n if (check_number(str1))\n cout<<str1<< \" is an integer\";\n else\n cout<<str1<< \" is a string\";\n}"
},
{
"code": null,
"e": 2775,
"s": 2736,
"text": "sunidhi is a string\n1234 is an integer"
}
] |
Cypress - Assertions
|
Cypress has more than one type of assertions obtained from various libraries like Mocha,Chai, and so on. The assertion types are explicit and implicit.
If an assertion is applicable to the object obtained from the parent command in a chain, it is known as the implicit assertion. The popular implicit assertions include .and/.should.
These commands cannot be used as standalone. Generally, they are used when we have to verify multiple checks on a particular object.
Let us illustrate implicit assertion with an example given below −
// test suite
describe('Tutorialspoint', function () {
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://www.tutorialspoint.com/videotutorials/index.php")
// assertion to validate count of sub-elements and class attribute value
cy.get('.toc chapters').find('li').should('have.length',5)
.and('have.class', 'dropdown')
});
});
Execution Results
The output is as follows −
The output logs show two assertions obtained with should, and commands.
If an assertion is applicable to an object directly, it is known as the explicit assertion. The popular explicit assertions include assert/expect.
The command for explicit assertion is as follows −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com")
// identify element
cy.get('h1#headingText').find('span').then(function(e){
const t = e.text()
// assertion expect
expect(t).to.contains('Sign')
})
})
})
Execution Results
The output is given below −
The output logs show assertions directly applied to objects with the expect command.
Cypress has Default Assertions which are internally handled and do not require to be
invoked specifically.
Few examples are as follows −
cy.visit () − Expects the page to show the content with 200 status code.
cy.visit () − Expects the page to show the content with 200 status code.
cy.request () − Expects the remote server to be available and sends a response.
cy.request () − Expects the remote server to be available and sends a response.
cy.contains () − Expects the web element with its properties to be available in DOM.
cy.contains () − Expects the web element with its properties to be available in DOM.
cy.get () − Expects the web element to be available in DOM.
cy.get () − Expects the web element to be available in DOM.
.find () − Expects the web element to be available in DOM.
.find () − Expects the web element to be available in DOM.
.type () − Expects the web element to turn to a type able state.
.type () − Expects the web element to turn to a type able state.
.click () − Expects the web element to turn to a clickable state.
.click () − Expects the web element to turn to a clickable state.
.its () − Expects for a web element property on the existing subject.
.its () − Expects for a web element property on the existing subject.
The other Cypress assertions are as follows −
It checks the count of elements obtained from the previously chained command.
For example,
cy.get('#txt-fld').should('have.length',5)
It checks whether the web element has a certain value.
For example,
cy.get('#txt-fld').should('have.length',5)
It checks whether the web element has a certain value.
For example,
cy.get(' #txt-fld').should('have.value', 'Cypress')
It checks whether the web element possesses a certain class.
For example,
cy.get('#txt-fld'').should('have.class', 'txt')
It checks whether the web element possesses a certain text.
For example,
cy.get('#txt-fld'').should('contain', 'Cypress')
It checks whether the web element is visible.
For example,
cy.get('#txt-fld'').should('be.visible')
It checks whether the web element is available in Document Object Model (DOM).
For example,
cy.get('#txt-fld'').should('not.exist');
It checks whether the web element possesses a certain css property.
For example,
cy.get('#txt-fld'').should('have.css', 'display', 'block');
73 Lectures
12 hours
Rahul Shetty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2649,
"s": 2497,
"text": "Cypress has more than one type of assertions obtained from various libraries like Mocha,Chai, and so on. The assertion types are explicit and implicit."
},
{
"code": null,
"e": 2831,
"s": 2649,
"text": "If an assertion is applicable to the object obtained from the parent command in a chain, it is known as the implicit assertion. The popular implicit assertions include .and/.should."
},
{
"code": null,
"e": 2964,
"s": 2831,
"text": "These commands cannot be used as standalone. Generally, they are used when we have to verify multiple checks on a particular object."
},
{
"code": null,
"e": 3031,
"s": 2964,
"text": "Let us illustrate implicit assertion with an example given below −"
},
{
"code": null,
"e": 3408,
"s": 3031,
"text": "// test suite\ndescribe('Tutorialspoint', function () {\n it('Scenario 1', function (){\n // test step to launch a URL\n cy.visit(\"https://www.tutorialspoint.com/videotutorials/index.php\")\n\t\t// assertion to validate count of sub-elements and class attribute value\n\t\tcy.get('.toc chapters').find('li').should('have.length',5)\n\t\t.and('have.class', 'dropdown')\n });\n});"
},
{
"code": null,
"e": 3426,
"s": 3408,
"text": "Execution Results"
},
{
"code": null,
"e": 3453,
"s": 3426,
"text": "The output is as follows −"
},
{
"code": null,
"e": 3525,
"s": 3453,
"text": "The output logs show two assertions obtained with should, and commands."
},
{
"code": null,
"e": 3672,
"s": 3525,
"text": "If an assertion is applicable to an object directly, it is known as the explicit assertion. The popular explicit assertions include assert/expect."
},
{
"code": null,
"e": 3723,
"s": 3672,
"text": "The command for explicit assertion is as follows −"
},
{
"code": null,
"e": 4122,
"s": 3723,
"text": "// test suite\ndescribe('Tutorialspoint', function () {\n// it function to identify test\n it('Scenario 1', function (){\n // test step to launch a URL\n cy.visit(\"https://accounts.google.com\")\n\t\t// identify element\n cy.get('h1#headingText').find('span').then(function(e){\n const t = e.text()\n // assertion expect\n expect(t).to.contains('Sign')\n })\n })\n})"
},
{
"code": null,
"e": 4140,
"s": 4122,
"text": "Execution Results"
},
{
"code": null,
"e": 4168,
"s": 4140,
"text": "The output is given below −"
},
{
"code": null,
"e": 4253,
"s": 4168,
"text": "The output logs show assertions directly applied to objects with the expect command."
},
{
"code": null,
"e": 4360,
"s": 4253,
"text": "Cypress has Default Assertions which are internally handled and do not require to be\ninvoked specifically."
},
{
"code": null,
"e": 4390,
"s": 4360,
"text": "Few examples are as follows −"
},
{
"code": null,
"e": 4463,
"s": 4390,
"text": "cy.visit () − Expects the page to show the content with 200 status code."
},
{
"code": null,
"e": 4536,
"s": 4463,
"text": "cy.visit () − Expects the page to show the content with 200 status code."
},
{
"code": null,
"e": 4616,
"s": 4536,
"text": "cy.request () − Expects the remote server to be available and sends a response."
},
{
"code": null,
"e": 4696,
"s": 4616,
"text": "cy.request () − Expects the remote server to be available and sends a response."
},
{
"code": null,
"e": 4781,
"s": 4696,
"text": "cy.contains () − Expects the web element with its properties to be available in DOM."
},
{
"code": null,
"e": 4866,
"s": 4781,
"text": "cy.contains () − Expects the web element with its properties to be available in DOM."
},
{
"code": null,
"e": 4926,
"s": 4866,
"text": "cy.get () − Expects the web element to be available in DOM."
},
{
"code": null,
"e": 4986,
"s": 4926,
"text": "cy.get () − Expects the web element to be available in DOM."
},
{
"code": null,
"e": 5045,
"s": 4986,
"text": ".find () − Expects the web element to be available in DOM."
},
{
"code": null,
"e": 5104,
"s": 5045,
"text": ".find () − Expects the web element to be available in DOM."
},
{
"code": null,
"e": 5169,
"s": 5104,
"text": ".type () − Expects the web element to turn to a type able state."
},
{
"code": null,
"e": 5234,
"s": 5169,
"text": ".type () − Expects the web element to turn to a type able state."
},
{
"code": null,
"e": 5300,
"s": 5234,
"text": ".click () − Expects the web element to turn to a clickable state."
},
{
"code": null,
"e": 5366,
"s": 5300,
"text": ".click () − Expects the web element to turn to a clickable state."
},
{
"code": null,
"e": 5436,
"s": 5366,
"text": ".its () − Expects for a web element property on the existing subject."
},
{
"code": null,
"e": 5506,
"s": 5436,
"text": ".its () − Expects for a web element property on the existing subject."
},
{
"code": null,
"e": 5552,
"s": 5506,
"text": "The other Cypress assertions are as follows −"
},
{
"code": null,
"e": 5630,
"s": 5552,
"text": "It checks the count of elements obtained from the previously chained command."
},
{
"code": null,
"e": 5643,
"s": 5630,
"text": "For example,"
},
{
"code": null,
"e": 5687,
"s": 5643,
"text": "cy.get('#txt-fld').should('have.length',5)\n"
},
{
"code": null,
"e": 5742,
"s": 5687,
"text": "It checks whether the web element has a certain value."
},
{
"code": null,
"e": 5755,
"s": 5742,
"text": "For example,"
},
{
"code": null,
"e": 5799,
"s": 5755,
"text": "cy.get('#txt-fld').should('have.length',5)\n"
},
{
"code": null,
"e": 5854,
"s": 5799,
"text": "It checks whether the web element has a certain value."
},
{
"code": null,
"e": 5867,
"s": 5854,
"text": "For example,"
},
{
"code": null,
"e": 5920,
"s": 5867,
"text": "cy.get(' #txt-fld').should('have.value', 'Cypress')\n"
},
{
"code": null,
"e": 5981,
"s": 5920,
"text": "It checks whether the web element possesses a certain class."
},
{
"code": null,
"e": 5994,
"s": 5981,
"text": "For example,"
},
{
"code": null,
"e": 6043,
"s": 5994,
"text": "cy.get('#txt-fld'').should('have.class', 'txt')\n"
},
{
"code": null,
"e": 6103,
"s": 6043,
"text": "It checks whether the web element possesses a certain text."
},
{
"code": null,
"e": 6116,
"s": 6103,
"text": "For example,"
},
{
"code": null,
"e": 6166,
"s": 6116,
"text": "cy.get('#txt-fld'').should('contain', 'Cypress')\n"
},
{
"code": null,
"e": 6212,
"s": 6166,
"text": "It checks whether the web element is visible."
},
{
"code": null,
"e": 6225,
"s": 6212,
"text": "For example,"
},
{
"code": null,
"e": 6267,
"s": 6225,
"text": "cy.get('#txt-fld'').should('be.visible')\n"
},
{
"code": null,
"e": 6346,
"s": 6267,
"text": "It checks whether the web element is available in Document Object Model (DOM)."
},
{
"code": null,
"e": 6359,
"s": 6346,
"text": "For example,"
},
{
"code": null,
"e": 6401,
"s": 6359,
"text": "cy.get('#txt-fld'').should('not.exist');\n"
},
{
"code": null,
"e": 6469,
"s": 6401,
"text": "It checks whether the web element possesses a certain css property."
},
{
"code": null,
"e": 6482,
"s": 6469,
"text": "For example,"
},
{
"code": null,
"e": 6543,
"s": 6482,
"text": "cy.get('#txt-fld'').should('have.css', 'display', 'block');\n"
},
{
"code": null,
"e": 6577,
"s": 6543,
"text": "\n 73 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 6591,
"s": 6577,
"text": " Rahul Shetty"
},
{
"code": null,
"e": 6598,
"s": 6591,
"text": " Print"
},
{
"code": null,
"e": 6609,
"s": 6598,
"text": " Add Notes"
}
] |
CakePHP - Routing
|
In this chapter, we are going to learn the following topics related to routing −
Introduction to Routing
Connecting Routes
Passing Arguments to Routes
Generating urls
Redirect urls
In this section, we will see how you can implement routes, how you can pass arguments from URL to controller’s action, how you can generate URLs, and how you can redirect to a specific URL. Normally, routes are implemented in file config/routes.php. Routing can be implemented in two ways −
static method
scoped route builder
Here, is an example presenting both the types.
// Using the scoped route builder.
Router::scope('/', function ($routes) {
$routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);
});
// Using the static method.
Router::connect('/', ['controller' => 'Articles', 'action' => 'index']);
Both the methods will execute the index method of ArticlesController. Out of the two methods, scoped route builder gives better performance.
Router::connect() method is used to connect routes. The following is the syntax of the method −
static Cake\Routing\Router::connect($route, $defaults =[], $options =[])
There are three arguments to the Router::connect() method −
The first argument is for the URL template you wish to match.
The first argument is for the URL template you wish to match.
The second argument contains default values for your route elements.
The second argument contains default values for your route elements.
The third argument contains options for the route, which generally contains regular expression rules.
The third argument contains options for the route, which generally contains regular expression rules.
Here, is the basic format of a route −
$routes->connect(
'URL template',
['default' => 'defaultValue'],
['option' => 'matchingRegex']
);
Make changes in the config/routes.php file as shown below.
config/routes.php
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
// Register scoped middleware for in scopes.
$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httpOnly' => true,
]));
$builder->applyMiddleware('csrf');
$builder->connect('/', ['controller' => 'Tests', 'action' => 'show']);
$builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
$builder->fallbacks();
});
Create a TestsController.php file at src/Controller/TestsController.php. Copy the following code in the controller file.
src/Controller/TestsController.php
<?php
declare(strict_types=1);
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\View\Exception\MissingTemplateException;
class TestsController extends AppController {
public function show()
{
}
}
Create a folder Tests under src/Template and under that folder, create a View file called show.php. Copy the following code in that file.
src/Template/Tests/show.php
<h1>This is CakePHP tutorial and this is an example of connecting routes.</h1>
Execute the above example by visiting the following URL which is available at http://localhost/cakephp4/
The above URL will yield the following output.
Passed arguments are the arguments which are passed in the URL. These arguments can be passed to controller’s action. These passed arguments are given to your controller in three ways.
Following example shows, how we can pass arguments to the action of the controller. Visit the following URL at http://localhost/cakephp4/tests/value1/value2
This will match the following route line.
$builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]);
Here, the value1 from URL will be assigned to arg1 and value2 will be assigned to arg2.
Once the argument is passed to the controller’s action, you can get the argument with the following statement.
$args = $this->request->params[‘pass’]
The arguments passed to controller’s action will be stored in $args variable.
The argument can also be passed to action by the following statement −
$routes->connect('/', ['controller' => 'Tests', 'action' => 'show',5,6]);
The above statement will pass two arguments 5, and 6 to TestController’s show() method.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
// Register scoped middleware for in scopes.
$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httpOnly' => true,
]));
$builder->applyMiddleware('csrf');
$builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]);
$builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
$builder->fallbacks();
});
Create a TestsController.php file at src/Controller/TestsController.php. Copy the following code in the controller file.
src/Controller/TestsController.php
<?php
declare(strict_types=1);
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\View\Exception\MissingTemplateException;
class TestsController extends AppController {
public function show($arg1, $arg2) {
$this->set('argument1',$arg1);
$this->set('argument2',$arg2);
}
}
Create a folder Tests at src/Template and under that folder create a View file called show.php. Copy the following code in that file.
src/Template/Tests/show.php.
<h1>This is CakePHP tutorial and this is an example of Passed arguments.</h1>
<?php
echo "Argument-1:".$argument1."<br/>";
echo "Argument-2:".$argument2."<br/>";
?>
Execute the above example by visiting the following URL http://localhost/cakephp4/tests/Virat/Kunal
Upon execution, the above URL will produce the following output.
This is a cool feature of CakePHP. Using the generated URLs, we can easily change the structure of URL in the application without modifying the whole code.
url( string|array|null $url null , boolean $full false )
The above function will take two arguments −
The first argument is an array specifying any of the following - 'controller', 'action', 'plugin'. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string.
The first argument is an array specifying any of the following - 'controller', 'action', 'plugin'. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string.
If true, the full base URL will be prepended to the result. Default is false.
If true, the full base URL will be prepended to the result. Default is false.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
// Register scoped middleware for in scopes.
$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httpOnly' => true,
]));
$builder->applyMiddleware('csrf');
$builder->connect('/generate',['controller'=>'Generates','action'=>'show']);
$builder->fallbacks();
});
Create a GeneratesController.php file at src/Controller/GeneratesController.php. Copy the following code in the controller file.
src/Controller/GeneratesController.php
<?php
declare(strict_types=1);
namespace App\Controller;
21
use Cake\Core\Configure;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\View\Exception\MissingTemplateException;
class GeneratesController extends AppController {
public function show()
{
}
}
Create a folder Generates at src/Template and under that folder, create a View file called show.php. Copy the following code in that file.
src/Template/Generates/show.php
<h1>This is CakePHP tutorial and this is an example of Generating URLs<h1>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/generate
The above URL will produce the following output −
Redirect routing is useful, when we want to inform client applications that, this URL has been moved. The URL can be redirected using the following function −
static Cake\Routing\Router::redirect($route, $url, $options =[])
There are three arguments to the above function as follows −
A string describing the template of the route.
A string describing the template of the route.
A URL to redirect to.
A URL to redirect to.
An array matching the named elements in the route to regular expressions which that element should match.
An array matching the named elements in the route to regular expressions which that element should match.
Make Changes in the config/routes.php file as shown below. Here, we have used controllers that were created previously.
config/routes.php
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
// Register scoped middleware for in scopes.
$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httpOnly' => true,
]));
$builder->applyMiddleware('csrf');
$builder->connect('/generate',['controller'=>'Generates','action'=>'show']);
$builder->redirect('/redirect','https://tutorialspoint.com/');
$builder->fallbacks();
});
Execute the above example by visiting the following URLs.
URL 1 − http://localhost/cakephp4/generate
URL 2 − http://localhost/cakephp4/redirect
You will be redirected to https://tutorialspoint.com
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2323,
"s": 2242,
"text": "In this chapter, we are going to learn the following topics related to routing −"
},
{
"code": null,
"e": 2347,
"s": 2323,
"text": "Introduction to Routing"
},
{
"code": null,
"e": 2365,
"s": 2347,
"text": "Connecting Routes"
},
{
"code": null,
"e": 2393,
"s": 2365,
"text": "Passing Arguments to Routes"
},
{
"code": null,
"e": 2409,
"s": 2393,
"text": "Generating urls"
},
{
"code": null,
"e": 2423,
"s": 2409,
"text": "Redirect urls"
},
{
"code": null,
"e": 2714,
"s": 2423,
"text": "In this section, we will see how you can implement routes, how you can pass arguments from URL to controller’s action, how you can generate URLs, and how you can redirect to a specific URL. Normally, routes are implemented in file config/routes.php. Routing can be implemented in two ways −"
},
{
"code": null,
"e": 2728,
"s": 2714,
"text": "static method"
},
{
"code": null,
"e": 2749,
"s": 2728,
"text": "scoped route builder"
},
{
"code": null,
"e": 2796,
"s": 2749,
"text": "Here, is an example presenting both the types."
},
{
"code": null,
"e": 3053,
"s": 2796,
"text": "// Using the scoped route builder.\nRouter::scope('/', function ($routes) {\n $routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);\n});\n// Using the static method.\nRouter::connect('/', ['controller' => 'Articles', 'action' => 'index']);"
},
{
"code": null,
"e": 3194,
"s": 3053,
"text": "Both the methods will execute the index method of ArticlesController. Out of the two methods, scoped route builder gives better performance."
},
{
"code": null,
"e": 3290,
"s": 3194,
"text": "Router::connect() method is used to connect routes. The following is the syntax of the method −"
},
{
"code": null,
"e": 3364,
"s": 3290,
"text": "static Cake\\Routing\\Router::connect($route, $defaults =[], $options =[])\n"
},
{
"code": null,
"e": 3424,
"s": 3364,
"text": "There are three arguments to the Router::connect() method −"
},
{
"code": null,
"e": 3486,
"s": 3424,
"text": "The first argument is for the URL template you wish to match."
},
{
"code": null,
"e": 3548,
"s": 3486,
"text": "The first argument is for the URL template you wish to match."
},
{
"code": null,
"e": 3617,
"s": 3548,
"text": "The second argument contains default values for your route elements."
},
{
"code": null,
"e": 3686,
"s": 3617,
"text": "The second argument contains default values for your route elements."
},
{
"code": null,
"e": 3788,
"s": 3686,
"text": "The third argument contains options for the route, which generally contains regular expression rules."
},
{
"code": null,
"e": 3890,
"s": 3788,
"text": "The third argument contains options for the route, which generally contains regular expression rules."
},
{
"code": null,
"e": 3929,
"s": 3890,
"text": "Here, is the basic format of a route −"
},
{
"code": null,
"e": 4037,
"s": 3929,
"text": "$routes->connect(\n 'URL template',\n ['default' => 'defaultValue'],\n ['option' => 'matchingRegex']\n);\n"
},
{
"code": null,
"e": 4096,
"s": 4037,
"text": "Make changes in the config/routes.php file as shown below."
},
{
"code": null,
"e": 4114,
"s": 4096,
"text": "config/routes.php"
},
{
"code": null,
"e": 4719,
"s": 4114,
"text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n // Register scoped middleware for in scopes.\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n $builder->connect('/', ['controller' => 'Tests', 'action' => 'show']);\n $builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);\n $builder->fallbacks();\n});"
},
{
"code": null,
"e": 4840,
"s": 4719,
"text": "Create a TestsController.php file at src/Controller/TestsController.php. Copy the following code in the controller file."
},
{
"code": null,
"e": 4875,
"s": 4840,
"text": "src/Controller/TestsController.php"
},
{
"code": null,
"e": 5202,
"s": 4875,
"text": "<?php\ndeclare(strict_types=1);\nnamespace App\\Controller;\nuse Cake\\Core\\Configure;\nuse Cake\\Http\\Exception\\ForbiddenException;\nuse Cake\\Http\\Exception\\NotFoundException;\nuse Cake\\Http\\Response;\nuse Cake\\View\\Exception\\MissingTemplateException;\nclass TestsController extends AppController {\n public function show()\n {\n }\n}"
},
{
"code": null,
"e": 5340,
"s": 5202,
"text": "Create a folder Tests under src/Template and under that folder, create a View file called show.php. Copy the following code in that file."
},
{
"code": null,
"e": 5368,
"s": 5340,
"text": "src/Template/Tests/show.php"
},
{
"code": null,
"e": 5448,
"s": 5368,
"text": "<h1>This is CakePHP tutorial and this is an example of connecting routes.</h1>\n"
},
{
"code": null,
"e": 5553,
"s": 5448,
"text": "Execute the above example by visiting the following URL which is available at http://localhost/cakephp4/"
},
{
"code": null,
"e": 5600,
"s": 5553,
"text": "The above URL will yield the following output."
},
{
"code": null,
"e": 5785,
"s": 5600,
"text": "Passed arguments are the arguments which are passed in the URL. These arguments can be passed to controller’s action. These passed arguments are given to your controller in three ways."
},
{
"code": null,
"e": 5942,
"s": 5785,
"text": "Following example shows, how we can pass arguments to the action of the controller. Visit the following URL at http://localhost/cakephp4/tests/value1/value2"
},
{
"code": null,
"e": 5984,
"s": 5942,
"text": "This will match the following route line."
},
{
"code": null,
"e": 6101,
"s": 5984,
"text": "$builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]);\n"
},
{
"code": null,
"e": 6189,
"s": 6101,
"text": "Here, the value1 from URL will be assigned to arg1 and value2 will be assigned to arg2."
},
{
"code": null,
"e": 6300,
"s": 6189,
"text": "Once the argument is passed to the controller’s action, you can get the argument with the following statement."
},
{
"code": null,
"e": 6340,
"s": 6300,
"text": "$args = $this->request->params[‘pass’]\n"
},
{
"code": null,
"e": 6418,
"s": 6340,
"text": "The arguments passed to controller’s action will be stored in $args variable."
},
{
"code": null,
"e": 6489,
"s": 6418,
"text": "The argument can also be passed to action by the following statement −"
},
{
"code": null,
"e": 6564,
"s": 6489,
"text": "$routes->connect('/', ['controller' => 'Tests', 'action' => 'show',5,6]);\n"
},
{
"code": null,
"e": 6652,
"s": 6564,
"text": "The above statement will pass two arguments 5, and 6 to TestController’s show() method."
},
{
"code": null,
"e": 6730,
"s": 6652,
"text": "Make Changes in the config/routes.php file as shown in the following program."
},
{
"code": null,
"e": 6748,
"s": 6730,
"text": "config/routes.php"
},
{
"code": null,
"e": 7389,
"s": 6748,
"text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n// Register scoped middleware for in scopes.\n$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n $builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]);\n $builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);\n $builder->fallbacks();\n});"
},
{
"code": null,
"e": 7510,
"s": 7389,
"text": "Create a TestsController.php file at src/Controller/TestsController.php. Copy the following code in the controller file."
},
{
"code": null,
"e": 7545,
"s": 7510,
"text": "src/Controller/TestsController.php"
},
{
"code": null,
"e": 7952,
"s": 7545,
"text": "<?php\ndeclare(strict_types=1);\nnamespace App\\Controller;\nuse Cake\\Core\\Configure;\nuse Cake\\Http\\Exception\\ForbiddenException;\nuse Cake\\Http\\Exception\\NotFoundException;\nuse Cake\\Http\\Response;\nuse Cake\\View\\Exception\\MissingTemplateException;\nclass TestsController extends AppController {\npublic function show($arg1, $arg2) {\n $this->set('argument1',$arg1);\n $this->set('argument2',$arg2);\n }\n}"
},
{
"code": null,
"e": 8086,
"s": 7952,
"text": "Create a folder Tests at src/Template and under that folder create a View file called show.php. Copy the following code in that file."
},
{
"code": null,
"e": 8115,
"s": 8086,
"text": "src/Template/Tests/show.php."
},
{
"code": null,
"e": 8286,
"s": 8115,
"text": "<h1>This is CakePHP tutorial and this is an example of Passed arguments.</h1>\n<?php\n echo \"Argument-1:\".$argument1.\"<br/>\";\n echo \"Argument-2:\".$argument2.\"<br/>\";\n?>"
},
{
"code": null,
"e": 8386,
"s": 8286,
"text": "Execute the above example by visiting the following URL http://localhost/cakephp4/tests/Virat/Kunal"
},
{
"code": null,
"e": 8451,
"s": 8386,
"text": "Upon execution, the above URL will produce the following output."
},
{
"code": null,
"e": 8607,
"s": 8451,
"text": "This is a cool feature of CakePHP. Using the generated URLs, we can easily change the structure of URL in the application without modifying the whole code."
},
{
"code": null,
"e": 8665,
"s": 8607,
"text": "url( string|array|null $url null , boolean $full false )\n"
},
{
"code": null,
"e": 8710,
"s": 8665,
"text": "The above function will take two arguments −"
},
{
"code": null,
"e": 8944,
"s": 8710,
"text": "The first argument is an array specifying any of the following - 'controller', 'action', 'plugin'. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string."
},
{
"code": null,
"e": 9178,
"s": 8944,
"text": "The first argument is an array specifying any of the following - 'controller', 'action', 'plugin'. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string."
},
{
"code": null,
"e": 9256,
"s": 9178,
"text": "If true, the full base URL will be prepended to the result. Default is false."
},
{
"code": null,
"e": 9334,
"s": 9256,
"text": "If true, the full base URL will be prepended to the result. Default is false."
},
{
"code": null,
"e": 9412,
"s": 9334,
"text": "Make Changes in the config/routes.php file as shown in the following program."
},
{
"code": null,
"e": 9430,
"s": 9412,
"text": "config/routes.php"
},
{
"code": null,
"e": 9954,
"s": 9430,
"text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n // Register scoped middleware for in scopes.\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n $builder->connect('/generate',['controller'=>'Generates','action'=>'show']);\n $builder->fallbacks();\n});"
},
{
"code": null,
"e": 10083,
"s": 9954,
"text": "Create a GeneratesController.php file at src/Controller/GeneratesController.php. Copy the following code in the controller file."
},
{
"code": null,
"e": 10122,
"s": 10083,
"text": "src/Controller/GeneratesController.php"
},
{
"code": null,
"e": 10456,
"s": 10122,
"text": "<?php\ndeclare(strict_types=1);\nnamespace App\\Controller;\n21\nuse Cake\\Core\\Configure;\nuse Cake\\Http\\Exception\\ForbiddenException;\nuse Cake\\Http\\Exception\\NotFoundException;\nuse Cake\\Http\\Response;\nuse Cake\\View\\Exception\\MissingTemplateException;\nclass GeneratesController extends AppController {\n public function show()\n {\n }\n}"
},
{
"code": null,
"e": 10595,
"s": 10456,
"text": "Create a folder Generates at src/Template and under that folder, create a View file called show.php. Copy the following code in that file."
},
{
"code": null,
"e": 10627,
"s": 10595,
"text": "src/Template/Generates/show.php"
},
{
"code": null,
"e": 10703,
"s": 10627,
"text": "<h1>This is CakePHP tutorial and this is an example of Generating URLs<h1>\n"
},
{
"code": null,
"e": 10761,
"s": 10703,
"text": "Execute the above example by visiting the following URL −"
},
{
"code": null,
"e": 10796,
"s": 10761,
"text": "http://localhost/cakephp4/generate"
},
{
"code": null,
"e": 10846,
"s": 10796,
"text": "The above URL will produce the following output −"
},
{
"code": null,
"e": 11005,
"s": 10846,
"text": "Redirect routing is useful, when we want to inform client applications that, this URL has been moved. The URL can be redirected using the following function −"
},
{
"code": null,
"e": 11071,
"s": 11005,
"text": "static Cake\\Routing\\Router::redirect($route, $url, $options =[])\n"
},
{
"code": null,
"e": 11132,
"s": 11071,
"text": "There are three arguments to the above function as follows −"
},
{
"code": null,
"e": 11179,
"s": 11132,
"text": "A string describing the template of the route."
},
{
"code": null,
"e": 11226,
"s": 11179,
"text": "A string describing the template of the route."
},
{
"code": null,
"e": 11248,
"s": 11226,
"text": "A URL to redirect to."
},
{
"code": null,
"e": 11270,
"s": 11248,
"text": "A URL to redirect to."
},
{
"code": null,
"e": 11376,
"s": 11270,
"text": "An array matching the named elements in the route to regular expressions which that element should match."
},
{
"code": null,
"e": 11482,
"s": 11376,
"text": "An array matching the named elements in the route to regular expressions which that element should match."
},
{
"code": null,
"e": 11602,
"s": 11482,
"text": "Make Changes in the config/routes.php file as shown below. Here, we have used controllers that were created previously."
},
{
"code": null,
"e": 11620,
"s": 11602,
"text": "config/routes.php"
},
{
"code": null,
"e": 12210,
"s": 11620,
"text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n // Register scoped middleware for in scopes.\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n $builder->connect('/generate',['controller'=>'Generates','action'=>'show']);\n $builder->redirect('/redirect','https://tutorialspoint.com/');\n $builder->fallbacks();\n});"
},
{
"code": null,
"e": 12268,
"s": 12210,
"text": "Execute the above example by visiting the following URLs."
},
{
"code": null,
"e": 12311,
"s": 12268,
"text": "URL 1 − http://localhost/cakephp4/generate"
},
{
"code": null,
"e": 12354,
"s": 12311,
"text": "URL 2 − http://localhost/cakephp4/redirect"
},
{
"code": null,
"e": 12407,
"s": 12354,
"text": "You will be redirected to https://tutorialspoint.com"
},
{
"code": null,
"e": 12414,
"s": 12407,
"text": " Print"
},
{
"code": null,
"e": 12425,
"s": 12414,
"text": " Add Notes"
}
] |
Python 3 - MySQL Database Access
|
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of database servers such as −
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
SQLite
Here is the list of available Python database interfaces − Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.
The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. This API includes the following −
Importing the API module.
Acquiring a connection with the database.
Issuing SQL statements and stored procedures.
Closing the connection
Python has an in-built support for SQLite. In this section, we would learn all the concepts using MySQL. MySQLdb module, a popular interface with MySQL is not compatible with Python 3. Instead, we shall use PyMySQL module.
PyMySQL is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and contains a pure-Python MySQL client library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb.
Before proceeding further, you make sure you have PyMySQL installed on your machine. Just type the following in your Python script and execute it −
#!/usr/bin/python3
import pymysql
If it produces the following result, then it means MySQLdb module is not installed −
Traceback (most recent call last):
File "test.py", line 3, in <module>
Import pymysql
ImportError: No module named pymysql
The last stable release is available on PyPI and can be installed with pip −
pip install pymysql
Alternatively (e.g. if pip is not available), a tarball can be downloaded from GitHub and installed with Setuptools as follows −
$ # X.X is the desired pymysql version (e.g. 0.5 or 0.6).
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz
$ cd PyMySQL*
$ python setup.py install
$ # The folder PyMySQL* can be safely removed now.
Note − Make sure you have root privilege to install the above module.
Before connecting to a MySQL database, make sure of the following points −
You have created a database TESTDB.
You have created a database TESTDB.
You have created a table EMPLOYEE in TESTDB.
You have created a table EMPLOYEE in TESTDB.
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
User ID "testuser" and password "test123" are set to access TESTDB.
Python module PyMySQL is installed properly on your machine.
Python module PyMySQL is installed properly on your machine.
You have gone through MySQL tutorial to understand MySQL Basics.
You have gone through MySQL tutorial to understand MySQL Basics.
Following is an example of connecting with MySQL database "TESTDB" −
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)
# disconnect from server
db.close()
While running this script, it produces the following result.
Database version : 5.5.20-log
If a connection is established with the datasource, then a Connection Object is returned and saved into db for further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used to execute SQL queries. Finally, before coming out, it ensures that the database connection is closed and resources are released.
Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.
Let us create a Database table EMPLOYEE −
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()
The INSERT Operation is required when you want to create your records into a database table.
The following example, executes SQL INSERT statement to create a record in the EMPLOYEE table −
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
The above example can be written as follows to create SQL queries dynamically −
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
The following code segment is another form of execution where you can pass parameters directly −
..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % \
(user_id, password))
..................................
READ Operation on any database means to fetch some useful information from the database.
Once the database connection is established, you are ready to make a query into this database. You can use either fetchone() method to fetch a single record or fetchall() method to fetch multiple values from a database table.
fetchone() − It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.
fetchone() − It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.
fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves
the remaining rows from the result set.
fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves
the remaining rows from the result set.
rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method.
rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method.
The following procedure queries all the records from EMPLOYEE table having salary more than 1000 −
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print ("fname = %s,lname = %s,age = %d,sex = %s,income = %d" % \
(fname, lname, age, sex, income ))
except:
print ("Error: unable to fetch data")
# disconnect from server
db.close()
This will produce the following result −
fname = Mac, lname = Mohan, age = 20, sex = M, income = 2000
UPDATE Operation on any database means to update one or more records, which are already available in the database.
The following procedure updates all the records having SEX as 'M'. Here, we increase the AGE of all the males by one year.
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20 −
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −
Atomicity − Either a transaction completes or nothing happens at all.
Atomicity − Either a transaction completes or nothing happens at all.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
You already know how to implement transactions. Here is a similar example −
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
Commit is an operation, which gives a green signal to the database to finalize the changes, and after this operation, no change can be reverted back.
Here is a simple example to call the commit method.
db.commit()
If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use the rollback() method.
Here is a simple example to call the rollback() method.
db.rollback()
To disconnect the Database connection, use the close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of the DB lower level implementation details, your application would be better off calling commit or rollback explicitly.
There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.
The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.
Warning
Used for non-fatal issues. Must subclass StandardError.
Error
Base class for errors. Must subclass StandardError.
InterfaceError
Used for errors in the database module, not the database itself. Must subclass Error.
DatabaseError
Used for errors in the database. Must subclass Error.
DataError
Subclass of DatabaseError that refers to errors in the data.
OperationalError
Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.
IntegrityError
Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.
InternalError
Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.
ProgrammingError
Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.
NotSupportedError
Subclass of DatabaseError that refers to trying to call unsupported functionality.
Your Python scripts should handle these errors, but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification.
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": 2463,
"s": 2340,
"text": "The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard."
},
{
"code": null,
"e": 2591,
"s": 2463,
"text": "You can choose the right database for your application. Python Database API supports a wide range of database servers such as −"
},
{
"code": null,
"e": 2598,
"s": 2591,
"text": "GadFly"
},
{
"code": null,
"e": 2603,
"s": 2598,
"text": "mSQL"
},
{
"code": null,
"e": 2609,
"s": 2603,
"text": "MySQL"
},
{
"code": null,
"e": 2620,
"s": 2609,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2646,
"s": 2620,
"text": "Microsoft SQL Server 2000"
},
{
"code": null,
"e": 2655,
"s": 2646,
"text": "Informix"
},
{
"code": null,
"e": 2665,
"s": 2655,
"text": "Interbase"
},
{
"code": null,
"e": 2672,
"s": 2665,
"text": "Oracle"
},
{
"code": null,
"e": 2679,
"s": 2672,
"text": "Sybase"
},
{
"code": null,
"e": 2686,
"s": 2679,
"text": "SQLite"
},
{
"code": null,
"e": 3012,
"s": 2686,
"text": "Here is the list of available Python database interfaces − Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules."
},
{
"code": null,
"e": 3166,
"s": 3012,
"text": "The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. This API includes the following −"
},
{
"code": null,
"e": 3192,
"s": 3166,
"text": "Importing the API module."
},
{
"code": null,
"e": 3234,
"s": 3192,
"text": "Acquiring a connection with the database."
},
{
"code": null,
"e": 3280,
"s": 3234,
"text": "Issuing SQL statements and stored procedures."
},
{
"code": null,
"e": 3303,
"s": 3280,
"text": "Closing the connection"
},
{
"code": null,
"e": 3526,
"s": 3303,
"text": "Python has an in-built support for SQLite. In this section, we would learn all the concepts using MySQL. MySQLdb module, a popular interface with MySQL is not compatible with Python 3. Instead, we shall use PyMySQL module."
},
{
"code": null,
"e": 3761,
"s": 3526,
"text": "PyMySQL is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and contains a pure-Python MySQL client library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb."
},
{
"code": null,
"e": 3909,
"s": 3761,
"text": "Before proceeding further, you make sure you have PyMySQL installed on your machine. Just type the following in your Python script and execute it −"
},
{
"code": null,
"e": 3944,
"s": 3909,
"text": "#!/usr/bin/python3\n\nimport pymysql"
},
{
"code": null,
"e": 4029,
"s": 3944,
"text": "If it produces the following result, then it means MySQLdb module is not installed −"
},
{
"code": null,
"e": 4162,
"s": 4029,
"text": "Traceback (most recent call last):\n File \"test.py\", line 3, in <module>\n Import pymysql\nImportError: No module named pymysql\n"
},
{
"code": null,
"e": 4239,
"s": 4162,
"text": "The last stable release is available on PyPI and can be installed with pip −"
},
{
"code": null,
"e": 4260,
"s": 4239,
"text": "pip install pymysql\n"
},
{
"code": null,
"e": 4389,
"s": 4260,
"text": "Alternatively (e.g. if pip is not available), a tarball can be downloaded from GitHub and installed with Setuptools as follows −"
},
{
"code": null,
"e": 4612,
"s": 4389,
"text": "$ # X.X is the desired pymysql version (e.g. 0.5 or 0.6).\n$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz\n$ cd PyMySQL*\n$ python setup.py install\n$ # The folder PyMySQL* can be safely removed now."
},
{
"code": null,
"e": 4682,
"s": 4612,
"text": "Note − Make sure you have root privilege to install the above module."
},
{
"code": null,
"e": 4757,
"s": 4682,
"text": "Before connecting to a MySQL database, make sure of the following points −"
},
{
"code": null,
"e": 4793,
"s": 4757,
"text": "You have created a database TESTDB."
},
{
"code": null,
"e": 4829,
"s": 4793,
"text": "You have created a database TESTDB."
},
{
"code": null,
"e": 4874,
"s": 4829,
"text": "You have created a table EMPLOYEE in TESTDB."
},
{
"code": null,
"e": 4919,
"s": 4874,
"text": "You have created a table EMPLOYEE in TESTDB."
},
{
"code": null,
"e": 4985,
"s": 4919,
"text": "This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME."
},
{
"code": null,
"e": 5051,
"s": 4985,
"text": "This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME."
},
{
"code": null,
"e": 5119,
"s": 5051,
"text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB."
},
{
"code": null,
"e": 5187,
"s": 5119,
"text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB."
},
{
"code": null,
"e": 5248,
"s": 5187,
"text": "Python module PyMySQL is installed properly on your machine."
},
{
"code": null,
"e": 5309,
"s": 5248,
"text": "Python module PyMySQL is installed properly on your machine."
},
{
"code": null,
"e": 5374,
"s": 5309,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 5439,
"s": 5374,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 5508,
"s": 5439,
"text": "Following is an example of connecting with MySQL database \"TESTDB\" −"
},
{
"code": null,
"e": 5935,
"s": 5508,
"text": "#!/usr/bin/python3\n\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# execute SQL query using execute() method.\ncursor.execute(\"SELECT VERSION()\")\n\n# Fetch a single row using fetchone() method.\ndata = cursor.fetchone()\nprint (\"Database version : %s \" % data)\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 5996,
"s": 5935,
"text": "While running this script, it produces the following result."
},
{
"code": null,
"e": 6027,
"s": 5996,
"text": "Database version : 5.5.20-log\n"
},
{
"code": null,
"e": 6383,
"s": 6027,
"text": "If a connection is established with the datasource, then a Connection Object is returned and saved into db for further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used to execute SQL queries. Finally, before coming out, it ensures that the database connection is closed and resources are released."
},
{
"code": null,
"e": 6536,
"s": 6383,
"text": "Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor."
},
{
"code": null,
"e": 6578,
"s": 6536,
"text": "Let us create a Database table EMPLOYEE −"
},
{
"code": null,
"e": 7117,
"s": 6578,
"text": "#!/usr/bin/python3\n\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Drop table if it already exist using execute() method.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n# Create table as per requirement\nsql = \"\"\"CREATE TABLE EMPLOYEE (\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT, \n SEX CHAR(1),\n INCOME FLOAT )\"\"\"\n\ncursor.execute(sql)\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 7210,
"s": 7117,
"text": "The INSERT Operation is required when you want to create your records into a database table."
},
{
"code": null,
"e": 7306,
"s": 7210,
"text": "The following example, executes SQL INSERT statement to create a record in the EMPLOYEE table −"
},
{
"code": null,
"e": 7898,
"s": 7306,
"text": "#!/usr/bin/python3\n\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"\"\"INSERT INTO EMPLOYEE(FIRST_NAME,\n LAST_NAME, AGE, SEX, INCOME)\n VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\"\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 7978,
"s": 7898,
"text": "The above example can be written as follows to create SQL queries dynamically −"
},
{
"code": null,
"e": 8609,
"s": 7978,
"text": "#!/usr/bin/python3\n\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"INSERT INTO EMPLOYEE(FIRST_NAME, \\\n LAST_NAME, AGE, SEX, INCOME) \\\n VALUES ('%s', '%s', '%d', '%c', '%d' )\" % \\\n ('Mac', 'Mohan', 20, 'M', 2000)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 8706,
"s": 8609,
"text": "The following code segment is another form of execution where you can pass parameters directly −"
},
{
"code": null,
"e": 8909,
"s": 8706,
"text": "..................................\nuser_id = \"test123\"\npassword = \"password\"\n\ncon.execute('insert into Login values(\"%s\", \"%s\")' % \\\n (user_id, password))\n..................................\n"
},
{
"code": null,
"e": 8998,
"s": 8909,
"text": "READ Operation on any database means to fetch some useful information from the database."
},
{
"code": null,
"e": 9224,
"s": 8998,
"text": "Once the database connection is established, you are ready to make a query into this database. You can use either fetchone() method to fetch a single record or fetchall() method to fetch multiple values from a database table."
},
{
"code": null,
"e": 9374,
"s": 9224,
"text": "fetchone() − It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table."
},
{
"code": null,
"e": 9524,
"s": 9374,
"text": "fetchone() − It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table."
},
{
"code": null,
"e": 9698,
"s": 9524,
"text": "fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves\nthe remaining rows from the result set."
},
{
"code": null,
"e": 9872,
"s": 9698,
"text": "fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves\nthe remaining rows from the result set."
},
{
"code": null,
"e": 9987,
"s": 9872,
"text": "rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method."
},
{
"code": null,
"e": 10102,
"s": 9987,
"text": "rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method."
},
{
"code": null,
"e": 10201,
"s": 10102,
"text": "The following procedure queries all the records from EMPLOYEE table having salary more than 1000 −"
},
{
"code": null,
"e": 11017,
"s": 10201,
"text": "#!/usr/bin/python3\n\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"SELECT * FROM EMPLOYEE \\\n WHERE INCOME > '%d'\" % (1000)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Fetch all the rows in a list of lists.\n results = cursor.fetchall()\n for row in results:\n fname = row[0]\n lname = row[1]\n age = row[2]\n sex = row[3]\n income = row[4]\n # Now print fetched result\n print (\"fname = %s,lname = %s,age = %d,sex = %s,income = %d\" % \\\n (fname, lname, age, sex, income ))\nexcept:\n print (\"Error: unable to fetch data\")\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 11058,
"s": 11017,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 11120,
"s": 11058,
"text": "fname = Mac, lname = Mohan, age = 20, sex = M, income = 2000\n"
},
{
"code": null,
"e": 11235,
"s": 11120,
"text": "UPDATE Operation on any database means to update one or more records, which are already available in the database."
},
{
"code": null,
"e": 11358,
"s": 11235,
"text": "The following procedure updates all the records having SEX as 'M'. Here, we increase the AGE of all the males by one year."
},
{
"code": null,
"e": 11913,
"s": 11358,
"text": "#!/usr/bin/python3\n\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to UPDATE required records\nsql = \"UPDATE EMPLOYEE SET AGE = AGE + 1\n WHERE SEX = '%c'\" % ('M')\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 12095,
"s": 11913,
"text": "DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20 −"
},
{
"code": null,
"e": 12610,
"s": 12095,
"text": "#!/usr/bin/python3\n\nimport pymysql\n\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to DELETE required records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (20)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 12720,
"s": 12610,
"text": "Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −"
},
{
"code": null,
"e": 12790,
"s": 12720,
"text": "Atomicity − Either a transaction completes or nothing happens at all."
},
{
"code": null,
"e": 12860,
"s": 12790,
"text": "Atomicity − Either a transaction completes or nothing happens at all."
},
{
"code": null,
"e": 12965,
"s": 12860,
"text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state."
},
{
"code": null,
"e": 13070,
"s": 12965,
"text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state."
},
{
"code": null,
"e": 13169,
"s": 13070,
"text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction."
},
{
"code": null,
"e": 13268,
"s": 13169,
"text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction."
},
{
"code": null,
"e": 13372,
"s": 13268,
"text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure."
},
{
"code": null,
"e": 13476,
"s": 13372,
"text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure."
},
{
"code": null,
"e": 13563,
"s": 13476,
"text": "The Python DB API 2.0 provides two methods to either commit or rollback a transaction."
},
{
"code": null,
"e": 13639,
"s": 13563,
"text": "You already know how to implement transactions. Here is a similar example −"
},
{
"code": null,
"e": 13918,
"s": 13639,
"text": "# Prepare SQL query to DELETE required records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (20)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()"
},
{
"code": null,
"e": 14068,
"s": 13918,
"text": "Commit is an operation, which gives a green signal to the database to finalize the changes, and after this operation, no change can be reverted back."
},
{
"code": null,
"e": 14120,
"s": 14068,
"text": "Here is a simple example to call the commit method."
},
{
"code": null,
"e": 14133,
"s": 14120,
"text": "db.commit()\n"
},
{
"code": null,
"e": 14276,
"s": 14133,
"text": "If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use the rollback() method."
},
{
"code": null,
"e": 14332,
"s": 14276,
"text": "Here is a simple example to call the rollback() method."
},
{
"code": null,
"e": 14347,
"s": 14332,
"text": "db.rollback()\n"
},
{
"code": null,
"e": 14410,
"s": 14347,
"text": "To disconnect the Database connection, use the close() method."
},
{
"code": null,
"e": 14422,
"s": 14410,
"text": "db.close()\n"
},
{
"code": null,
"e": 14716,
"s": 14422,
"text": "If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of the DB lower level implementation details, your application would be better off calling commit or rollback explicitly."
},
{
"code": null,
"e": 14918,
"s": 14716,
"text": "There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle."
},
{
"code": null,
"e": 15041,
"s": 14918,
"text": "The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions."
},
{
"code": null,
"e": 15049,
"s": 15041,
"text": "Warning"
},
{
"code": null,
"e": 15105,
"s": 15049,
"text": "Used for non-fatal issues. Must subclass StandardError."
},
{
"code": null,
"e": 15111,
"s": 15105,
"text": "Error"
},
{
"code": null,
"e": 15163,
"s": 15111,
"text": "Base class for errors. Must subclass StandardError."
},
{
"code": null,
"e": 15178,
"s": 15163,
"text": "InterfaceError"
},
{
"code": null,
"e": 15264,
"s": 15178,
"text": "Used for errors in the database module, not the database itself. Must subclass Error."
},
{
"code": null,
"e": 15278,
"s": 15264,
"text": "DatabaseError"
},
{
"code": null,
"e": 15332,
"s": 15278,
"text": "Used for errors in the database. Must subclass Error."
},
{
"code": null,
"e": 15342,
"s": 15332,
"text": "DataError"
},
{
"code": null,
"e": 15403,
"s": 15342,
"text": "Subclass of DatabaseError that refers to errors in the data."
},
{
"code": null,
"e": 15420,
"s": 15403,
"text": "OperationalError"
},
{
"code": null,
"e": 15592,
"s": 15420,
"text": "Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter."
},
{
"code": null,
"e": 15607,
"s": 15592,
"text": "IntegrityError"
},
{
"code": null,
"e": 15740,
"s": 15607,
"text": "Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys."
},
{
"code": null,
"e": 15754,
"s": 15740,
"text": "InternalError"
},
{
"code": null,
"e": 15876,
"s": 15754,
"text": "Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active."
},
{
"code": null,
"e": 15893,
"s": 15876,
"text": "ProgrammingError"
},
{
"code": null,
"e": 16017,
"s": 15893,
"text": "Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you."
},
{
"code": null,
"e": 16035,
"s": 16017,
"text": "NotSupportedError"
},
{
"code": null,
"e": 16118,
"s": 16035,
"text": "Subclass of DatabaseError that refers to trying to call unsupported functionality."
},
{
"code": null,
"e": 16348,
"s": 16118,
"text": "Your Python scripts should handle these errors, but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification."
},
{
"code": null,
"e": 16385,
"s": 16348,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 16401,
"s": 16385,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 16434,
"s": 16401,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 16453,
"s": 16434,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 16488,
"s": 16453,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 16510,
"s": 16488,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 16544,
"s": 16510,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 16572,
"s": 16544,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 16607,
"s": 16572,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 16621,
"s": 16607,
"text": " Lets Kode It"
},
{
"code": null,
"e": 16654,
"s": 16621,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 16671,
"s": 16654,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 16678,
"s": 16671,
"text": " Print"
},
{
"code": null,
"e": 16689,
"s": 16678,
"text": " Add Notes"
}
] |
Macroeconomic & Financial Factors and Ordinary least Square Regression | by Sarit Maitra | Towards Data Science
|
Arbitrage Pricing Theory is represented as a multivariate regression model with across‐equations restrictions. It is a multi-factor asset pricing model that holds that an asset’s returns can be forecasted with the linear relationship of an asset’s expected returns and the macro-economic variables that capture systematic risk.
Our data here are monthly stock prices for the Brent Crude index, S&P500 index, US Treasury bill rate 3-month & 10 years (short-term & long-term), US treasury bill rate (credit risk), the consumer price index, industrial production index.
We would like to examine here, whether Brent Crude Oil prices can be explained with the support of unexpected changes in a set of macroeconomic and financial variables. The best practice while working with stock prices is to use adjusted values, as they account for possible corporate actions, such as stock splits.
combine = pd.concat([h['SP500'], g, f['DGS10'], e['DTB3'], d['TEDRATE'], b['TOTALSL'],a['CPALTT01USM657N'], i['Brent spot price']], axis=1)combine.set_index('DATE', inplace=True)combine.index = pd.to_datetime(combine.index)combine.dropna(inplace=True)
Let us generate a set of changes or differences for each of the variables. The unexpected value of a variable can be defined as the difference between the actual value of the variable and its expected value.
Tao, R., & Brooks, C have presented a nice article on arbitrage pricing analysis, the reference of which I have added in the end of this article.
We will use logarithmic returns here as they aggregate over time; the log return for a given month is the sum of the log returns of the days within that month.
here, rt is the return, Pt is the price of an asset in time t.
data = DataFrame({'ted_spread' : combine['TEDRATE'] - combine['TEDRATE'].shift(1), 'consumer_credit' : combine['TOTALSL'] - combine['TOTALSL'].shift(1),'indprod' : combine['INDPRO'] - combine['INDPRO'].shift(1),'cr_crude' : np.log(combine['Brent spot price'].diff().dropna()),# (cr_crude) continuously compounded returns for crude oil'cr_sp' : np.log(combine['SP500']).diff().dropna()# (cr_sp) continuously compounded returns for S&P500'inflation' : np.log(combine['CPALTT01USM657N']).diff().dropna(),# (inflation) continuously compounded returns for consumer price index'dgs_dtb' : combine['DGS10'] - combine['DTB3'],'inflation_diff' : np.log(combine['CPALTT01USM657N']).diff().dropna() - np.log(combine['CPALTT01USM657N']).diff().dropna().shift(1),'dtb' : combine['DTB3']/12,'dgs_dtb_shift' : (combine['DGS10'] - combine['DTB3']) - (combine['DGS10'] - combine['DTB3']).shift(1),'crude_dtb' : np.log(combine['Brent spot price']).diff().dropna() - combine['DTB3']/12,# (crude_dtb3) to transform the returns, (Crude continuously compounded returns) - (3-month US Treasury bill rate)# = risk free rate'sp_dtb' : np.log(combine['SP500']).diff().dropna() - combine['DTB3']/12})# (sp_dtb3) (SP continuously compounded returns) - (3-month US Treasury bill rate)
OLS regression serves as a good prototype for ML algorithms in general. It’s a supervised algorithm that has a training procedure and a deployment procedure. It can be over-fit in some circumstances. It shares these features with other more modern function approximation algorithms. However, limitation with OLS is that, there’s no means to stop the training when it over fits.
We will use Ordinary least squares (OLS) regression to estimate the relationship between independent variables and dependent variable (crude oil here) by minimizing the sum of the squares in the difference between the observed and predicted values of the dependent variable configured as a straight line.
data = data[~data.isin([np.nan, np.inf, -np.inf]).any(1)]X = data [['cr_sp', 'indprod', 'consumer_credit', 'inflation_diff', 'ted_spread', 'dgs_dtb_shift']]y = data['cr_crude']model = sm.OLS(y, sm.add_constant(X))model_fit = model.fit()model_fit.summary()
The regression F-statistic value is 10.71. The p-value < 0.05 for indprod & dgs_dtb_shift means, null hypothesis can be rejected for these variables. p-values for rest of the variables are > 0.05. Let us test the null hypothesis that the parameters on these four variables are jointly zero using F-test.
The F-test statistic value is 2.764; p-value 0.028 with there are four restrictions and 239 usable observations. This suggests that the null hypothesis cannot be rejected.
Diagnostic plots are drawn using residuals of the model. Let us visualize these plots to see how our regression model is fitting the data and if any of the basic assumptions of an OLS model are being violated. The diagnostic plots show residuals in four different ways.
# model valuesy_fitted = model_fit.fittedvalues# model residualsmodel_residuals = model_fit.resid# normalized residualsmodel_norm_residuals = model_fit.get_influence().resid_studentized_internal# absolute squared normalized residualsmodel_norm_residuals_abs_sqrt =np.sqrt(np.abs(model_norm_residuals))# absolute residualsmodel_abs_resid = np.abs(model_residuals)# leverage, from statsmodels internalsmodel_leverage = model_fit.get_influence().hat_matrix_diag# cook's distance, from statsmodels internalsmodel_cooks = model_fit.get_influence().cooks_distance[0]
dataframe = pd.concat([X, y], axis=1)plot_lm_1 = plt.figure()plot_lm_1.axes[0] = sns.residplot(y_fitted, dataframe.columns[-1], data=dataframe, lowess=True, scatter_kws={'alpha': 0.5}, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8})plot_lm_1.axes[0].set_title('Residuals vs Fitted')plot_lm_1.axes[0].set_xlabel('Fitted values')plot_lm_1.axes[0].set_ylabel('Residuals');
Though we do not see any distinctive pattern from the above plot, it seems like, some of the non-linear features of the model are not captured well which means we are under-fitting the model. However, we will check QQ plot to determine the normality assumption.
This plot shows if the residuals are normally distributed. A good normal QQ plot has all of the residuals lying on or close to the red line.
QQ = ProbPlot(model_norm_residuals)plot_lm_2 = QQ.qqplot(line='45', alpha=0.5, color='#4C72B0', lw=1)plot_lm_2.axes[0].set_title('Normal Q-Q')plot_lm_2.axes[0].set_xlabel('Theoretical Quantiles')plot_lm_2.axes[0].set_ylabel('Standardized Residuals');# annotationsabs_norm_resid = np.flip(np.argsort(np.abs(model_norm_residuals)), 0)abs_norm_resid_top_3 = abs_norm_resid[:3]for r, i in enumerate(abs_norm_resid_top_3):plot_lm_2.axes[0].annotate(i,xy=(np.flip(QQ.theoretical_quantiles, 0)[r],model_norm_residuals[i]));
Here, most of the data points fall along the red line; Of course they wouldn’t be a perfect straight line and it looks like normality assumption is met.
Let us look at the histogram to check a normal distribution; here we expect a histogram of the residuals to be bell-shaped (with no outliers).
The histogram confirms the distribution of the residuals roughly resembles a bell-shape; although, we also find that there are some large negative outliers which might lead to a considerable negative skewness.
SkewnKurtosis measures extreme values in either tail. The kurtosis for a standard normal distribution is 3. Kurtosis with values 6.11 means residuals exceeding the tails of the normal distribution. However, in general, these inferences could be wrong; our sample is probably large enough that we need be less concerned than we would with a smaller sample.
This plot shows if residuals are spread equally along the ranges of predictors. We can check the assumption of equal variance which is homoscedasticity.
plot_lm_3 = plt.figure()plt.scatter(model_fitted_y, model_norm_residuals_abs_sqrt, alpha=0.5);sns.regplot(model_fitted_y, model_norm_residuals_abs_sqrt, scatter=False, ci=False,lowess=True, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8});plot_lm_3.axes[0].set_title('Scale-Location')plot_lm_3.axes[0].set_xlabel('Fitted values')plot_lm_3.axes[0].set_ylabel('$\sqrt{|Standardized Residuals|}$');# annotationsabs_sq_norm_resid = np.flip(np.argsort(model_norm_residuals_abs_sqrt), 0)abs_sq_norm_resid_top_3 = abs_sq_norm_resid[:3]for i in abs_norm_resid_top_3:plot_lm_3.axes[0].annotate(i,xy=(model_fitted_y[i],model_norm_residuals_abs_sqrt[i]));
The residuals appear randomly spread which is an indication of homoscedasticity. Here, the error term is the same across all values of the independent variables. This assumption of homoscedasticity is central to linear regression models.
plt.figure(figsize = (20,5))plt.plot(model_fit.resid)plt.xlabel('Date')plt.ylabel('Residuals')plt.grid(True)
By examining the patterns in the residuals over time we can also confirm homoscedastic nature of residuals.
From the test statistics and p-values, both tests lead to the conclusion that residuals are homoscedastic nature for our model with the p-values both being 0.0001 and 8.21, respectively.
This plot helps us to find outliers if any. Even though data have extreme values, they might not be influential to determine a regression line. That means, the results wouldn’t be much different if we either include or exclude them from analysis. We check for outlying values at the upper right corner or at the lower right corner. Those spots are the places where cases can be influential against a regression line.
plot_lm_4 = plt.figure();plt.scatter(model_leverage, model_norm_residuals, alpha=0.5);sns.regplot(model_leverage, model_norm_residuals,scatter=False, ci=False,lowess=True, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8});plot_lm_4.axes[0].set_xlim(0, max(model_leverage)+0.01)plot_lm_4.axes[0].set_ylim(-3, 5)plot_lm_4.axes[0].set_title('Residuals vs Leverage')plot_lm_4.axes[0].set_xlabel('Leverage')plot_lm_4.axes[0].set_ylabel('Standardized Residuals');# annotationsleverage_top_3 = np.flip(np.argsort(model_cooks), 0)[:3]for i in leverage_top_3:plot_lm_4.axes[0].annotate(i,xy=(model_leverage[i], model_norm_residuals[i]));
We only need to find leverage points that have a distance greater than 0.5. In this plot, all cases are well inside of the Cook’s distance. The plot identified the influential observation as #245. If we exclude the 245th case from the analysis, the slope coefficient and R2 values likely to improve considerably.
Through step-by-step we will iteratively construct regression model which involves automatic selection of independent variables. Python’s statsmodels doesn’t have a built-in method for choosing a linear model by forward selection. I have taken this code from here. I have used p-values threshold <0.20 to filter.
formula = 'cr_crude ~ cr_sp + indprod + consumer_credit + inflation_diff + ted_spread + dgs_dtb_shift'results = smf.ols(formula, data).fit()def forward_selected(data, endog, exg):remaining = set(data.columns)remaining = [e for e in remaining if (e not in endog)&(e not in exg)]exg = [exg]scores_with_candidates = []for candidate in remaining:formula = '{} ~ {}'.format(endog,' + '.join(exg + [candidate]))score = model_fit.pvalues[2]scores_with_candidates.append((score, candidate))scores_with_candidates.sort()for pval,candidate in scores_with_candidates:if pval < 0.2:exg.append(candidate)formula = '{} ~ {}'.format(endog, ' + '.join(exg))model = smf.ols(formula, data).fit()return modelmodel = forward_selected(data,'cr_crude','cr_sp')print(model.model.formula)cr_crude ~ cr_sp + consumer_credit
As can be seen, the regression formula crude ~ cr_sp + consumer_credit, suggesting that the S&P500 and CPI are the only determinant factors for crude oil price.
A best way to test for errors in this model is to not rely on the model’s F-statistic, significance, or R2, but instead assess the model against test-set. Accuracy is then often measured as the actual standard error, MAPE (Mean absolute percentage error), or mean error between the predicted value and the actual value in the test-data.
From the graph, we could sense the presence of some outliers; especially during 2008 is quite visible. We will have a better idea if we look at the IQR box plot of all variables.
Here, we can clearly see some outliers. Let us identify the exact dates of the outliers.
We could see that, 2 biggest outliers are on Oct & Nov of 2008. Let us create 5 extra variables with the outliers and add those with the existing data frame to run the regression again.
data['nov_2008'] = np.where(data.index == '2008-11-01', 1, 0)data['oct_2008'] = np.where(data.index == '2008-10-01', 1, 0)data['dec_2014'] = np.where(data.index == '2014-12-01', 1, 0)data['jan_2015'] = np.where(data.index == '2015-01-01', 1, 0)data['apr_2000'] = np.where(data.index == '2000-04-01', 1, 0)formula = 'cr_crude ~ cr_sp + indprod + consumer_credit + inflation_diff + ted_spread + dgs_dtb_shift +nov_2008 + oct_2008 + dec_2014 + jan_2015 + apr_2000'model = smf.ols(formula, data).fit()model.summary()
Here, we see that, all the added variables are highly significant p-values <0.05). If we compare the results, we can see that the coefficient estimates on the remaining variables remain unchanged in this instance. The significant parameters remains the same as indpro, dgs_dtb_shift parameters; Adj. R2 value has improved from 19.2% to 34.6%.
col = data[['indprod', 'consumer_credit', 'inflation_diff', 'ted_spread', 'dgs_dtb_shift']]plt.figure(figsize = (10,6))pearsoncorr = col.corr(method='pearson')sns.heatmap(pearsoncorr, xticklabels=pearsoncorr.columns,yticklabels=pearsoncorr.columns,cmap='RdBu_r',annot=True,linewidth=0.5)
Here, the largest observed correlations are 0.37 between the consumer_credit and inddprod variables, and -0.017 between the inddprod and inflation_diff. Both are quite small in real value and they can reasonably be ignored.
We have used different macro-economic factors and financial variables to estimate whether monthly return on Brent Crude oil can be explained considering unexpected changes in those variables. The regression results show that there are quite small differences among crude oil return against independent variables that we had chosen. Our statistical analysis showed that, only he changes on short-term & long-term US treasury bill yields index and the Industrial Production index are significant among the variables chosen for our analysis to determine monthly return on Brent Crude Price. However, the regression results indicate that, there is no significant pricing relation between the stock return and the tested macroeconomic and financial variables.
Connect me here.
Reference:
Gauss, Carl Friedrich. [1809] 2004. Theory of Motion of the Heavenly Bodies Moving About the Sun in Conic Sections: A Translation of Theoria Motus. Mineola, NY: Dover.Tao, R., & Brooks, C. (2019). Python Guide to Accompany Introductory Econometrics for Finance. Available at SSRN 3475303.
Gauss, Carl Friedrich. [1809] 2004. Theory of Motion of the Heavenly Bodies Moving About the Sun in Conic Sections: A Translation of Theoria Motus. Mineola, NY: Dover.
Tao, R., & Brooks, C. (2019). Python Guide to Accompany Introductory Econometrics for Finance. Available at SSRN 3475303.
|
[
{
"code": null,
"e": 500,
"s": 172,
"text": "Arbitrage Pricing Theory is represented as a multivariate regression model with across‐equations restrictions. It is a multi-factor asset pricing model that holds that an asset’s returns can be forecasted with the linear relationship of an asset’s expected returns and the macro-economic variables that capture systematic risk."
},
{
"code": null,
"e": 739,
"s": 500,
"text": "Our data here are monthly stock prices for the Brent Crude index, S&P500 index, US Treasury bill rate 3-month & 10 years (short-term & long-term), US treasury bill rate (credit risk), the consumer price index, industrial production index."
},
{
"code": null,
"e": 1055,
"s": 739,
"text": "We would like to examine here, whether Brent Crude Oil prices can be explained with the support of unexpected changes in a set of macroeconomic and financial variables. The best practice while working with stock prices is to use adjusted values, as they account for possible corporate actions, such as stock splits."
},
{
"code": null,
"e": 1307,
"s": 1055,
"text": "combine = pd.concat([h['SP500'], g, f['DGS10'], e['DTB3'], d['TEDRATE'], b['TOTALSL'],a['CPALTT01USM657N'], i['Brent spot price']], axis=1)combine.set_index('DATE', inplace=True)combine.index = pd.to_datetime(combine.index)combine.dropna(inplace=True)"
},
{
"code": null,
"e": 1515,
"s": 1307,
"text": "Let us generate a set of changes or differences for each of the variables. The unexpected value of a variable can be defined as the difference between the actual value of the variable and its expected value."
},
{
"code": null,
"e": 1661,
"s": 1515,
"text": "Tao, R., & Brooks, C have presented a nice article on arbitrage pricing analysis, the reference of which I have added in the end of this article."
},
{
"code": null,
"e": 1821,
"s": 1661,
"text": "We will use logarithmic returns here as they aggregate over time; the log return for a given month is the sum of the log returns of the days within that month."
},
{
"code": null,
"e": 1884,
"s": 1821,
"text": "here, rt is the return, Pt is the price of an asset in time t."
},
{
"code": null,
"e": 3140,
"s": 1884,
"text": "data = DataFrame({'ted_spread' : combine['TEDRATE'] - combine['TEDRATE'].shift(1), 'consumer_credit' : combine['TOTALSL'] - combine['TOTALSL'].shift(1),'indprod' : combine['INDPRO'] - combine['INDPRO'].shift(1),'cr_crude' : np.log(combine['Brent spot price'].diff().dropna()),# (cr_crude) continuously compounded returns for crude oil'cr_sp' : np.log(combine['SP500']).diff().dropna()# (cr_sp) continuously compounded returns for S&P500'inflation' : np.log(combine['CPALTT01USM657N']).diff().dropna(),# (inflation) continuously compounded returns for consumer price index'dgs_dtb' : combine['DGS10'] - combine['DTB3'],'inflation_diff' : np.log(combine['CPALTT01USM657N']).diff().dropna() - np.log(combine['CPALTT01USM657N']).diff().dropna().shift(1),'dtb' : combine['DTB3']/12,'dgs_dtb_shift' : (combine['DGS10'] - combine['DTB3']) - (combine['DGS10'] - combine['DTB3']).shift(1),'crude_dtb' : np.log(combine['Brent spot price']).diff().dropna() - combine['DTB3']/12,# (crude_dtb3) to transform the returns, (Crude continuously compounded returns) - (3-month US Treasury bill rate)# = risk free rate'sp_dtb' : np.log(combine['SP500']).diff().dropna() - combine['DTB3']/12})# (sp_dtb3) (SP continuously compounded returns) - (3-month US Treasury bill rate)"
},
{
"code": null,
"e": 3518,
"s": 3140,
"text": "OLS regression serves as a good prototype for ML algorithms in general. It’s a supervised algorithm that has a training procedure and a deployment procedure. It can be over-fit in some circumstances. It shares these features with other more modern function approximation algorithms. However, limitation with OLS is that, there’s no means to stop the training when it over fits."
},
{
"code": null,
"e": 3823,
"s": 3518,
"text": "We will use Ordinary least squares (OLS) regression to estimate the relationship between independent variables and dependent variable (crude oil here) by minimizing the sum of the squares in the difference between the observed and predicted values of the dependent variable configured as a straight line."
},
{
"code": null,
"e": 4079,
"s": 3823,
"text": "data = data[~data.isin([np.nan, np.inf, -np.inf]).any(1)]X = data [['cr_sp', 'indprod', 'consumer_credit', 'inflation_diff', 'ted_spread', 'dgs_dtb_shift']]y = data['cr_crude']model = sm.OLS(y, sm.add_constant(X))model_fit = model.fit()model_fit.summary()"
},
{
"code": null,
"e": 4383,
"s": 4079,
"text": "The regression F-statistic value is 10.71. The p-value < 0.05 for indprod & dgs_dtb_shift means, null hypothesis can be rejected for these variables. p-values for rest of the variables are > 0.05. Let us test the null hypothesis that the parameters on these four variables are jointly zero using F-test."
},
{
"code": null,
"e": 4555,
"s": 4383,
"text": "The F-test statistic value is 2.764; p-value 0.028 with there are four restrictions and 239 usable observations. This suggests that the null hypothesis cannot be rejected."
},
{
"code": null,
"e": 4825,
"s": 4555,
"text": "Diagnostic plots are drawn using residuals of the model. Let us visualize these plots to see how our regression model is fitting the data and if any of the basic assumptions of an OLS model are being violated. The diagnostic plots show residuals in four different ways."
},
{
"code": null,
"e": 5386,
"s": 4825,
"text": "# model valuesy_fitted = model_fit.fittedvalues# model residualsmodel_residuals = model_fit.resid# normalized residualsmodel_norm_residuals = model_fit.get_influence().resid_studentized_internal# absolute squared normalized residualsmodel_norm_residuals_abs_sqrt =np.sqrt(np.abs(model_norm_residuals))# absolute residualsmodel_abs_resid = np.abs(model_residuals)# leverage, from statsmodels internalsmodel_leverage = model_fit.get_influence().hat_matrix_diag# cook's distance, from statsmodels internalsmodel_cooks = model_fit.get_influence().cooks_distance[0]"
},
{
"code": null,
"e": 5758,
"s": 5386,
"text": "dataframe = pd.concat([X, y], axis=1)plot_lm_1 = plt.figure()plot_lm_1.axes[0] = sns.residplot(y_fitted, dataframe.columns[-1], data=dataframe, lowess=True, scatter_kws={'alpha': 0.5}, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8})plot_lm_1.axes[0].set_title('Residuals vs Fitted')plot_lm_1.axes[0].set_xlabel('Fitted values')plot_lm_1.axes[0].set_ylabel('Residuals');"
},
{
"code": null,
"e": 6020,
"s": 5758,
"text": "Though we do not see any distinctive pattern from the above plot, it seems like, some of the non-linear features of the model are not captured well which means we are under-fitting the model. However, we will check QQ plot to determine the normality assumption."
},
{
"code": null,
"e": 6161,
"s": 6020,
"text": "This plot shows if the residuals are normally distributed. A good normal QQ plot has all of the residuals lying on or close to the red line."
},
{
"code": null,
"e": 6678,
"s": 6161,
"text": "QQ = ProbPlot(model_norm_residuals)plot_lm_2 = QQ.qqplot(line='45', alpha=0.5, color='#4C72B0', lw=1)plot_lm_2.axes[0].set_title('Normal Q-Q')plot_lm_2.axes[0].set_xlabel('Theoretical Quantiles')plot_lm_2.axes[0].set_ylabel('Standardized Residuals');# annotationsabs_norm_resid = np.flip(np.argsort(np.abs(model_norm_residuals)), 0)abs_norm_resid_top_3 = abs_norm_resid[:3]for r, i in enumerate(abs_norm_resid_top_3):plot_lm_2.axes[0].annotate(i,xy=(np.flip(QQ.theoretical_quantiles, 0)[r],model_norm_residuals[i]));"
},
{
"code": null,
"e": 6831,
"s": 6678,
"text": "Here, most of the data points fall along the red line; Of course they wouldn’t be a perfect straight line and it looks like normality assumption is met."
},
{
"code": null,
"e": 6974,
"s": 6831,
"text": "Let us look at the histogram to check a normal distribution; here we expect a histogram of the residuals to be bell-shaped (with no outliers)."
},
{
"code": null,
"e": 7184,
"s": 6974,
"text": "The histogram confirms the distribution of the residuals roughly resembles a bell-shape; although, we also find that there are some large negative outliers which might lead to a considerable negative skewness."
},
{
"code": null,
"e": 7540,
"s": 7184,
"text": "SkewnKurtosis measures extreme values in either tail. The kurtosis for a standard normal distribution is 3. Kurtosis with values 6.11 means residuals exceeding the tails of the normal distribution. However, in general, these inferences could be wrong; our sample is probably large enough that we need be less concerned than we would with a smaller sample."
},
{
"code": null,
"e": 7693,
"s": 7540,
"text": "This plot shows if residuals are spread equally along the ranges of predictors. We can check the assumption of equal variance which is homoscedasticity."
},
{
"code": null,
"e": 8339,
"s": 7693,
"text": "plot_lm_3 = plt.figure()plt.scatter(model_fitted_y, model_norm_residuals_abs_sqrt, alpha=0.5);sns.regplot(model_fitted_y, model_norm_residuals_abs_sqrt, scatter=False, ci=False,lowess=True, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8});plot_lm_3.axes[0].set_title('Scale-Location')plot_lm_3.axes[0].set_xlabel('Fitted values')plot_lm_3.axes[0].set_ylabel('$\\sqrt{|Standardized Residuals|}$');# annotationsabs_sq_norm_resid = np.flip(np.argsort(model_norm_residuals_abs_sqrt), 0)abs_sq_norm_resid_top_3 = abs_sq_norm_resid[:3]for i in abs_norm_resid_top_3:plot_lm_3.axes[0].annotate(i,xy=(model_fitted_y[i],model_norm_residuals_abs_sqrt[i]));"
},
{
"code": null,
"e": 8577,
"s": 8339,
"text": "The residuals appear randomly spread which is an indication of homoscedasticity. Here, the error term is the same across all values of the independent variables. This assumption of homoscedasticity is central to linear regression models."
},
{
"code": null,
"e": 8686,
"s": 8577,
"text": "plt.figure(figsize = (20,5))plt.plot(model_fit.resid)plt.xlabel('Date')plt.ylabel('Residuals')plt.grid(True)"
},
{
"code": null,
"e": 8794,
"s": 8686,
"text": "By examining the patterns in the residuals over time we can also confirm homoscedastic nature of residuals."
},
{
"code": null,
"e": 8981,
"s": 8794,
"text": "From the test statistics and p-values, both tests lead to the conclusion that residuals are homoscedastic nature for our model with the p-values both being 0.0001 and 8.21, respectively."
},
{
"code": null,
"e": 9398,
"s": 8981,
"text": "This plot helps us to find outliers if any. Even though data have extreme values, they might not be influential to determine a regression line. That means, the results wouldn’t be much different if we either include or exclude them from analysis. We check for outlying values at the upper right corner or at the lower right corner. Those spots are the places where cases can be influential against a regression line."
},
{
"code": null,
"e": 10027,
"s": 9398,
"text": "plot_lm_4 = plt.figure();plt.scatter(model_leverage, model_norm_residuals, alpha=0.5);sns.regplot(model_leverage, model_norm_residuals,scatter=False, ci=False,lowess=True, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8});plot_lm_4.axes[0].set_xlim(0, max(model_leverage)+0.01)plot_lm_4.axes[0].set_ylim(-3, 5)plot_lm_4.axes[0].set_title('Residuals vs Leverage')plot_lm_4.axes[0].set_xlabel('Leverage')plot_lm_4.axes[0].set_ylabel('Standardized Residuals');# annotationsleverage_top_3 = np.flip(np.argsort(model_cooks), 0)[:3]for i in leverage_top_3:plot_lm_4.axes[0].annotate(i,xy=(model_leverage[i], model_norm_residuals[i]));"
},
{
"code": null,
"e": 10340,
"s": 10027,
"text": "We only need to find leverage points that have a distance greater than 0.5. In this plot, all cases are well inside of the Cook’s distance. The plot identified the influential observation as #245. If we exclude the 245th case from the analysis, the slope coefficient and R2 values likely to improve considerably."
},
{
"code": null,
"e": 10653,
"s": 10340,
"text": "Through step-by-step we will iteratively construct regression model which involves automatic selection of independent variables. Python’s statsmodels doesn’t have a built-in method for choosing a linear model by forward selection. I have taken this code from here. I have used p-values threshold <0.20 to filter."
},
{
"code": null,
"e": 11452,
"s": 10653,
"text": "formula = 'cr_crude ~ cr_sp + indprod + consumer_credit + inflation_diff + ted_spread + dgs_dtb_shift'results = smf.ols(formula, data).fit()def forward_selected(data, endog, exg):remaining = set(data.columns)remaining = [e for e in remaining if (e not in endog)&(e not in exg)]exg = [exg]scores_with_candidates = []for candidate in remaining:formula = '{} ~ {}'.format(endog,' + '.join(exg + [candidate]))score = model_fit.pvalues[2]scores_with_candidates.append((score, candidate))scores_with_candidates.sort()for pval,candidate in scores_with_candidates:if pval < 0.2:exg.append(candidate)formula = '{} ~ {}'.format(endog, ' + '.join(exg))model = smf.ols(formula, data).fit()return modelmodel = forward_selected(data,'cr_crude','cr_sp')print(model.model.formula)cr_crude ~ cr_sp + consumer_credit"
},
{
"code": null,
"e": 11613,
"s": 11452,
"text": "As can be seen, the regression formula crude ~ cr_sp + consumer_credit, suggesting that the S&P500 and CPI are the only determinant factors for crude oil price."
},
{
"code": null,
"e": 11950,
"s": 11613,
"text": "A best way to test for errors in this model is to not rely on the model’s F-statistic, significance, or R2, but instead assess the model against test-set. Accuracy is then often measured as the actual standard error, MAPE (Mean absolute percentage error), or mean error between the predicted value and the actual value in the test-data."
},
{
"code": null,
"e": 12129,
"s": 11950,
"text": "From the graph, we could sense the presence of some outliers; especially during 2008 is quite visible. We will have a better idea if we look at the IQR box plot of all variables."
},
{
"code": null,
"e": 12218,
"s": 12129,
"text": "Here, we can clearly see some outliers. Let us identify the exact dates of the outliers."
},
{
"code": null,
"e": 12404,
"s": 12218,
"text": "We could see that, 2 biggest outliers are on Oct & Nov of 2008. Let us create 5 extra variables with the outliers and add those with the existing data frame to run the regression again."
},
{
"code": null,
"e": 12917,
"s": 12404,
"text": "data['nov_2008'] = np.where(data.index == '2008-11-01', 1, 0)data['oct_2008'] = np.where(data.index == '2008-10-01', 1, 0)data['dec_2014'] = np.where(data.index == '2014-12-01', 1, 0)data['jan_2015'] = np.where(data.index == '2015-01-01', 1, 0)data['apr_2000'] = np.where(data.index == '2000-04-01', 1, 0)formula = 'cr_crude ~ cr_sp + indprod + consumer_credit + inflation_diff + ted_spread + dgs_dtb_shift +nov_2008 + oct_2008 + dec_2014 + jan_2015 + apr_2000'model = smf.ols(formula, data).fit()model.summary()"
},
{
"code": null,
"e": 13260,
"s": 12917,
"text": "Here, we see that, all the added variables are highly significant p-values <0.05). If we compare the results, we can see that the coefficient estimates on the remaining variables remain unchanged in this instance. The significant parameters remains the same as indpro, dgs_dtb_shift parameters; Adj. R2 value has improved from 19.2% to 34.6%."
},
{
"code": null,
"e": 13548,
"s": 13260,
"text": "col = data[['indprod', 'consumer_credit', 'inflation_diff', 'ted_spread', 'dgs_dtb_shift']]plt.figure(figsize = (10,6))pearsoncorr = col.corr(method='pearson')sns.heatmap(pearsoncorr, xticklabels=pearsoncorr.columns,yticklabels=pearsoncorr.columns,cmap='RdBu_r',annot=True,linewidth=0.5)"
},
{
"code": null,
"e": 13772,
"s": 13548,
"text": "Here, the largest observed correlations are 0.37 between the consumer_credit and inddprod variables, and -0.017 between the inddprod and inflation_diff. Both are quite small in real value and they can reasonably be ignored."
},
{
"code": null,
"e": 14527,
"s": 13772,
"text": "We have used different macro-economic factors and financial variables to estimate whether monthly return on Brent Crude oil can be explained considering unexpected changes in those variables. The regression results show that there are quite small differences among crude oil return against independent variables that we had chosen. Our statistical analysis showed that, only he changes on short-term & long-term US treasury bill yields index and the Industrial Production index are significant among the variables chosen for our analysis to determine monthly return on Brent Crude Price. However, the regression results indicate that, there is no significant pricing relation between the stock return and the tested macroeconomic and financial variables."
},
{
"code": null,
"e": 14544,
"s": 14527,
"text": "Connect me here."
},
{
"code": null,
"e": 14555,
"s": 14544,
"text": "Reference:"
},
{
"code": null,
"e": 14844,
"s": 14555,
"text": "Gauss, Carl Friedrich. [1809] 2004. Theory of Motion of the Heavenly Bodies Moving About the Sun in Conic Sections: A Translation of Theoria Motus. Mineola, NY: Dover.Tao, R., & Brooks, C. (2019). Python Guide to Accompany Introductory Econometrics for Finance. Available at SSRN 3475303."
},
{
"code": null,
"e": 15012,
"s": 14844,
"text": "Gauss, Carl Friedrich. [1809] 2004. Theory of Motion of the Heavenly Bodies Moving About the Sun in Conic Sections: A Translation of Theoria Motus. Mineola, NY: Dover."
}
] |
VB.Net - Select Case Statement
|
A Select Case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each select case.
The syntax for a Select Case statement in VB.Net is as follows −
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort.
expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort.
expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are separated by commas.
expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are separated by commas.
statements − statements following Case that run if the select expression matches any clause in expressionlist.
statements − statements following Case that run if the select expression matches any clause in expressionlist.
elsestatements − statements following Case Else that run if the select expression does not match any clause in the expressionlist of any of the Case statements.
elsestatements − statements following Case Else that run if the select expression does not match any clause in the expressionlist of any of the Case statements.
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2491,
"s": 2300,
"text": "A Select Case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each select case."
},
{
"code": null,
"e": 2556,
"s": 2491,
"text": "The syntax for a Select Case statement in VB.Net is as follows −"
},
{
"code": null,
"e": 2685,
"s": 2556,
"text": "Select [ Case ] expression\n [ Case expressionlist\n [ statements ] ]\n [ Case Else\n [ elsestatements ] ]\nEnd Select\n"
},
{
"code": null,
"e": 2692,
"s": 2685,
"text": "Where,"
},
{
"code": null,
"e": 2919,
"s": 2692,
"text": "expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort."
},
{
"code": null,
"e": 3146,
"s": 2919,
"text": "expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort."
},
{
"code": null,
"e": 3285,
"s": 3146,
"text": "expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are separated by commas."
},
{
"code": null,
"e": 3424,
"s": 3285,
"text": "expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are separated by commas."
},
{
"code": null,
"e": 3535,
"s": 3424,
"text": "statements − statements following Case that run if the select expression matches any clause in expressionlist."
},
{
"code": null,
"e": 3646,
"s": 3535,
"text": "statements − statements following Case that run if the select expression matches any clause in expressionlist."
},
{
"code": null,
"e": 3807,
"s": 3646,
"text": "elsestatements − statements following Case Else that run if the select expression does not match any clause in the expressionlist of any of the Case statements."
},
{
"code": null,
"e": 3968,
"s": 3807,
"text": "elsestatements − statements following Case Else that run if the select expression does not match any clause in the expressionlist of any of the Case statements."
},
{
"code": null,
"e": 4549,
"s": 3968,
"text": "Module decisions\n Sub Main()\n 'local variable definition\n Dim grade As Char\n grade = \"B\"\n Select grade\n Case \"A\"\n Console.WriteLine(\"Excellent!\")\n Case \"B\", \"C\"\n Console.WriteLine(\"Well done\")\n Case \"D\"\n Console.WriteLine(\"You passed\")\n Case \"F\"\n Console.WriteLine(\"Better try again\")\n Case Else\n Console.WriteLine(\"Invalid grade\")\n End Select\n Console.WriteLine(\"Your grade is {0}\", grade)\n Console.ReadLine()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 4630,
"s": 4549,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4657,
"s": 4630,
"text": "Well done\nYour grade is B\n"
},
{
"code": null,
"e": 4690,
"s": 4657,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4707,
"s": 4690,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4742,
"s": 4707,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4757,
"s": 4742,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4792,
"s": 4757,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4807,
"s": 4792,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4840,
"s": 4807,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4855,
"s": 4840,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4862,
"s": 4855,
"text": " Print"
},
{
"code": null,
"e": 4873,
"s": 4862,
"text": " Add Notes"
}
] |
TypeScript - Parameterized a Function
|
Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined.
While calling a function, there are two ways that arguments can be passed to a function −
Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Call by pointer
This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter
Following are the ways in which parameters can be used by functions −
function func_name( param1 [:datatype], ( param2 [:datatype]) {
}
function test_param(n1:number,s1:string) {
console.log(n1)
console.log(s1)
}
test_param(123,"this is a string")
The snippet declares a function test_param with three parameters namely, n1, s1 and p1.
The snippet declares a function test_param with three parameters namely, n1, s1 and p1.
It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameter is considered to be of the type any. In the above example, the third parameter will be of the type any.
It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameter is considered to be of the type any. In the above example, the third parameter will be of the type any.
The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error.
The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
function test_param(n1, s1) {
console.log(n1);
console.log(s1);
}
test_param(123, "this is a string");
The output of the above code is as follows −
123
this is a string
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2343,
"s": 2048,
"text": "Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined."
},
{
"code": null,
"e": 2433,
"s": 2343,
"text": "While calling a function, there are two ways that arguments can be passed to a function −"
},
{
"code": null,
"e": 2447,
"s": 2433,
"text": "Call by value"
},
{
"code": null,
"e": 2637,
"s": 2447,
"text": "This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument."
},
{
"code": null,
"e": 2653,
"s": 2637,
"text": "Call by pointer"
},
{
"code": null,
"e": 2861,
"s": 2653,
"text": "This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter"
},
{
"code": null,
"e": 2931,
"s": 2861,
"text": "Following are the ways in which parameters can be used by functions −"
},
{
"code": null,
"e": 3001,
"s": 2931,
"text": "function func_name( param1 [:datatype], ( param2 [:datatype]) { \n}\n"
},
{
"code": null,
"e": 3124,
"s": 3001,
"text": "function test_param(n1:number,s1:string) { \n console.log(n1) \n console.log(s1) \n} \ntest_param(123,\"this is a string\")\n"
},
{
"code": null,
"e": 3212,
"s": 3124,
"text": "The snippet declares a function test_param with three parameters namely, n1, s1 and p1."
},
{
"code": null,
"e": 3300,
"s": 3212,
"text": "The snippet declares a function test_param with three parameters namely, n1, s1 and p1."
},
{
"code": null,
"e": 3512,
"s": 3300,
"text": "It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameter is considered to be of the type any. In the above example, the third parameter will be of the type any."
},
{
"code": null,
"e": 3724,
"s": 3512,
"text": "It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameter is considered to be of the type any. In the above example, the third parameter will be of the type any."
},
{
"code": null,
"e": 3885,
"s": 3724,
"text": "The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error."
},
{
"code": null,
"e": 4046,
"s": 3885,
"text": "The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error."
},
{
"code": null,
"e": 4104,
"s": 4046,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 4247,
"s": 4104,
"text": "//Generated by typescript 1.8.10\nfunction test_param(n1, s1) {\n console.log(n1);\n console.log(s1);\n}\ntest_param(123, \"this is a string\");\n"
},
{
"code": null,
"e": 4292,
"s": 4247,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 4315,
"s": 4292,
"text": "123 \nthis is a string\n"
},
{
"code": null,
"e": 4348,
"s": 4315,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4362,
"s": 4348,
"text": " Antonio Papa"
},
{
"code": null,
"e": 4395,
"s": 4362,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4409,
"s": 4395,
"text": " Haider Malik"
},
{
"code": null,
"e": 4444,
"s": 4409,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4464,
"s": 4444,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4497,
"s": 4464,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4511,
"s": 4497,
"text": " Sean Bradley"
},
{
"code": null,
"e": 4546,
"s": 4511,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4562,
"s": 4546,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4595,
"s": 4562,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4615,
"s": 4595,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 4622,
"s": 4615,
"text": " Print"
},
{
"code": null,
"e": 4633,
"s": 4622,
"text": " Add Notes"
}
] |
Go - break statement
|
The break statement in Go programming language has the following two usages −
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in a switch statement.
It can be used to terminate a case in a switch statement.
If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
The syntax for a break statement in Go is as follows −
break;
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
/* for loop execution */
for a < 20 {
fmt.Printf("value of a: %d\n", a);
a++;
if a > 15 {
/* terminate the loop using break statement */
break;
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
64 Lectures
6.5 hours
Ridhi Arora
20 Lectures
2.5 hours
Asif Hussain
22 Lectures
4 hours
Dilip Padmanabhan
48 Lectures
6 hours
Arnab Chakraborty
7 Lectures
1 hours
Aditya Kulkarni
44 Lectures
3 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2015,
"s": 1937,
"text": "The break statement in Go programming language has the following two usages −"
},
{
"code": null,
"e": 2177,
"s": 2015,
"text": "When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2339,
"s": 2177,
"text": "When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2397,
"s": 2339,
"text": "It can be used to terminate a case in a switch statement."
},
{
"code": null,
"e": 2455,
"s": 2397,
"text": "It can be used to terminate a case in a switch statement."
},
{
"code": null,
"e": 2611,
"s": 2455,
"text": "If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block."
},
{
"code": null,
"e": 2666,
"s": 2611,
"text": "The syntax for a break statement in Go is as follows −"
},
{
"code": null,
"e": 2674,
"s": 2666,
"text": "break;\n"
},
{
"code": null,
"e": 2971,
"s": 2674,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable definition */\n var a int = 10\n\n /* for loop execution */\n for a < 20 {\n fmt.Printf(\"value of a: %d\\n\", a);\n a++;\n if a > 15 {\n /* terminate the loop using break statement */\n break;\n }\n }\n}"
},
{
"code": null,
"e": 3052,
"s": 2971,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3143,
"s": 3052,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\n"
},
{
"code": null,
"e": 3178,
"s": 3143,
"text": "\n 64 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3191,
"s": 3178,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 3226,
"s": 3191,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3240,
"s": 3226,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3273,
"s": 3240,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3292,
"s": 3273,
"text": " Dilip Padmanabhan"
},
{
"code": null,
"e": 3325,
"s": 3292,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3344,
"s": 3325,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3376,
"s": 3344,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3393,
"s": 3376,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 3426,
"s": 3393,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3445,
"s": 3426,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3452,
"s": 3445,
"text": " Print"
},
{
"code": null,
"e": 3463,
"s": 3452,
"text": " Add Notes"
}
] |
Python: I Have Tested Quandl API and How to Get Real Estates & Economics Data in One Line of Code. | by Sajid Lhessani | Towards Data Science
|
In this article, you will learn how to request and download a wide range of data, such as economics, real estates or even market data for free—using a free Python package without calling an expensive API. I have tested it for you. Does that work? Let’s see.
If you are keen to hack it yourselves now, you can get the full Python code at the end of this article.
Now let’s go guys !!!! & Merry Christmas :)
First, let’s start by defining Quandl API.
Quandl delivers market data from hundreds of sources (officials such as Bank of England/India etc or independent providers) via an API key. These data can be requested through different languages such as Python, R or Excel.
The types of data which can be requested through Quandl are broad; you can ask end of the day US Market data, economic indicator from Bank of Brazil, Federal Reserve Economic Data(growth, employment, inflation, labour, manufacturing and many more US financial data), official GDP per country, or even company hiring activities and many others.
And during this test, we are going to focus on three types of data:
US Stock exchange market data.
Federal Reserve Economic Data for the commodity price, which is a trendy investment at the moment.
Zillow Real Estate and Rental Market Place Data — This dataset is the leading real estate and rental marketplace.
Now that we have introduced Quandl, let’s start with the tests.
First of all, if you want to track my progress and before to start, you will need to have installed on your machine a Python 3 version and the following packages:
Pandas
NumPy
Quandl
Plotly (Not mandatory, but useful for plotting)
If any of these packages are not already installed, you can use the pip command, as shown below.
pip install quandlpip install plotly
Once you have ensured that the following packages are installed, we can start.
If you already have experience with Python, you can jump to the second step. The first step will consist of importing data.
The first step will consist of importing the necessary packages.
You will start by importing your packages previously installed by using the following lines of code:
Once we are set up, let’s pursue the next step.
As explained above, if you are an investor, you must be aware that in 2020 & 2021, one of the trendiest commodity is Gold.
Indeed, Gold is correlated negatively to economic growth, and in time of the pandemic, that has been a lucrative investment for multiple investors.
Now, the question is, how to get robust and trustful Gold price data for a specific local currency (either if you are American, Canadian, Indian, British ... )?
Let’s analyze now how you can hack it using Quandl.
Quandl API is working using a tick code & an API key, which can be accessed for free. (All explanations in the tutorial videos in the last part, plus a gift). The user will need to insert the following 3 arguments (tick code, start & end date) and type the following code structure in order to request data:
quandl.get(tick code, start_date, end_date)
Now that we got the structure, the first step will consist of researching “Gold Price”, in the research bar at the top left corner.
Once the research has been performed, we will select a free dataset of our choice.
I am going to use the dataset provided by the London Bullion Market Association for the test. According to Quandl, LBMA is an international trade association in the London gold and silver market, consisting of central banks, private investors, producers, refiners, and other agents & an official data provider.
The tick code associated is “LBMA/GOLD”. So, let’s type the following line of code:
And here is the output:
Now if you want to plot your data:
You can have the full code explanation in the video tutorial(Part III, minute 8:25 to 11:20).
Overall, the data looks accurate (less than 1$ difference) if you compare it to Bloomberg.
The first test is positive.
The second test, how can we upload and request US stock exchange data for investment and algorithmic trading?
If you want to learn how to start with algorithmic trading with Python and impress your colleague at work or university. I highly recommend the following course, most of the code has been taken from this source:
www.udemy.com
Similarly to the request above, we are going to start by searching for market data.
We will choose wiki continuous future as a data source and request to get data for GOOGLE. The ticker for this request is “WIKI/GOOG”. So, let’s type the following line of code:
Once we have executed the line of code above, here is the output:
Boom! We got the data, plus extra information regarding split ratio, volume & dividends.
The possibility to download market data through Quandl API is not the most efficient. I have tested a couple of other API in the past, such as Yahoo Finance or Bloomberg, and the difference is important. You can find the full test below and see by yourselves the difference:
towardsdatascience.com.
However, I like the fact that Quandl is providing the possibility to get dividends day and the amount. As an investor and algorithmic trader that an excellent point to add to our model.
Now, that we have tested the market data import, let’s jump to the last test.
Did you ever ask yourselves if your monthly rent is over or underpriced? Or based on your area, if your one-bedroom apartment bought was overpriced?
In this section, we are going to explore how to download local real estates data using Quandl.
Similarly to what we have done previously, you will need your ticker code. To find it we are going to search “Zillow New York” in the search bar at the top left corner.
Once you have chosen the New-York’s borough data that you want, you should type the tick code and execute the following line of code:
In the line above we are requesting the data for a one-bedroom apartment in Harlem vs Manhattan midtown. (Full explanation in the video below. Minute 12:20 to 17:50)
And here is the final output of the price of a 1 bedroom apartment of 2 New York borough over-time:
I hope you enjoyed this test; I took a lot of fun to decorticate this API. You can go further using Quandl API and test it yourselves.
Overall, Quandl has a lot of strength and disadvantage. The aim behind this article was to propose you to discover an API which you will be able to use in the future.
I am teaching data science to my son sometimes, and I like using Quandl because you can get a clean and official dataset in one line of code. Suppose you want to test your Artificial Intelligence and Machine Learning models. In that case, it can be an excellent way to have the necessary randomized data (mainly for a neural network which require a massive input dataset).
Furthermore, the types of data are wide. If you are working in medical, you can request plenty of data concerning healthcare, or if you are a statistician, you can explore data provided by the government on this platform to enhance your analysis.
If you want to know more about API’s test and how to code an algorithm for trading, I recommend the following youtube channel:
https://www.youtube.com/channel/UCZorZ8KWmTON7aO84JJBwlQ?
Thank you for your attention
Happy coding
Learn algorithmic trading in one day (Full training):
www.udemy.com
Live Trading Test:
medium.com
YahooFinance API Test:
|
[
{
"code": null,
"e": 430,
"s": 172,
"text": "In this article, you will learn how to request and download a wide range of data, such as economics, real estates or even market data for free—using a free Python package without calling an expensive API. I have tested it for you. Does that work? Let’s see."
},
{
"code": null,
"e": 534,
"s": 430,
"text": "If you are keen to hack it yourselves now, you can get the full Python code at the end of this article."
},
{
"code": null,
"e": 578,
"s": 534,
"text": "Now let’s go guys !!!! & Merry Christmas :)"
},
{
"code": null,
"e": 621,
"s": 578,
"text": "First, let’s start by defining Quandl API."
},
{
"code": null,
"e": 845,
"s": 621,
"text": "Quandl delivers market data from hundreds of sources (officials such as Bank of England/India etc or independent providers) via an API key. These data can be requested through different languages such as Python, R or Excel."
},
{
"code": null,
"e": 1189,
"s": 845,
"text": "The types of data which can be requested through Quandl are broad; you can ask end of the day US Market data, economic indicator from Bank of Brazil, Federal Reserve Economic Data(growth, employment, inflation, labour, manufacturing and many more US financial data), official GDP per country, or even company hiring activities and many others."
},
{
"code": null,
"e": 1257,
"s": 1189,
"text": "And during this test, we are going to focus on three types of data:"
},
{
"code": null,
"e": 1288,
"s": 1257,
"text": "US Stock exchange market data."
},
{
"code": null,
"e": 1387,
"s": 1288,
"text": "Federal Reserve Economic Data for the commodity price, which is a trendy investment at the moment."
},
{
"code": null,
"e": 1501,
"s": 1387,
"text": "Zillow Real Estate and Rental Market Place Data — This dataset is the leading real estate and rental marketplace."
},
{
"code": null,
"e": 1565,
"s": 1501,
"text": "Now that we have introduced Quandl, let’s start with the tests."
},
{
"code": null,
"e": 1728,
"s": 1565,
"text": "First of all, if you want to track my progress and before to start, you will need to have installed on your machine a Python 3 version and the following packages:"
},
{
"code": null,
"e": 1735,
"s": 1728,
"text": "Pandas"
},
{
"code": null,
"e": 1741,
"s": 1735,
"text": "NumPy"
},
{
"code": null,
"e": 1748,
"s": 1741,
"text": "Quandl"
},
{
"code": null,
"e": 1796,
"s": 1748,
"text": "Plotly (Not mandatory, but useful for plotting)"
},
{
"code": null,
"e": 1893,
"s": 1796,
"text": "If any of these packages are not already installed, you can use the pip command, as shown below."
},
{
"code": null,
"e": 1930,
"s": 1893,
"text": "pip install quandlpip install plotly"
},
{
"code": null,
"e": 2009,
"s": 1930,
"text": "Once you have ensured that the following packages are installed, we can start."
},
{
"code": null,
"e": 2133,
"s": 2009,
"text": "If you already have experience with Python, you can jump to the second step. The first step will consist of importing data."
},
{
"code": null,
"e": 2198,
"s": 2133,
"text": "The first step will consist of importing the necessary packages."
},
{
"code": null,
"e": 2299,
"s": 2198,
"text": "You will start by importing your packages previously installed by using the following lines of code:"
},
{
"code": null,
"e": 2347,
"s": 2299,
"text": "Once we are set up, let’s pursue the next step."
},
{
"code": null,
"e": 2470,
"s": 2347,
"text": "As explained above, if you are an investor, you must be aware that in 2020 & 2021, one of the trendiest commodity is Gold."
},
{
"code": null,
"e": 2618,
"s": 2470,
"text": "Indeed, Gold is correlated negatively to economic growth, and in time of the pandemic, that has been a lucrative investment for multiple investors."
},
{
"code": null,
"e": 2779,
"s": 2618,
"text": "Now, the question is, how to get robust and trustful Gold price data for a specific local currency (either if you are American, Canadian, Indian, British ... )?"
},
{
"code": null,
"e": 2831,
"s": 2779,
"text": "Let’s analyze now how you can hack it using Quandl."
},
{
"code": null,
"e": 3139,
"s": 2831,
"text": "Quandl API is working using a tick code & an API key, which can be accessed for free. (All explanations in the tutorial videos in the last part, plus a gift). The user will need to insert the following 3 arguments (tick code, start & end date) and type the following code structure in order to request data:"
},
{
"code": null,
"e": 3183,
"s": 3139,
"text": "quandl.get(tick code, start_date, end_date)"
},
{
"code": null,
"e": 3315,
"s": 3183,
"text": "Now that we got the structure, the first step will consist of researching “Gold Price”, in the research bar at the top left corner."
},
{
"code": null,
"e": 3398,
"s": 3315,
"text": "Once the research has been performed, we will select a free dataset of our choice."
},
{
"code": null,
"e": 3709,
"s": 3398,
"text": "I am going to use the dataset provided by the London Bullion Market Association for the test. According to Quandl, LBMA is an international trade association in the London gold and silver market, consisting of central banks, private investors, producers, refiners, and other agents & an official data provider."
},
{
"code": null,
"e": 3793,
"s": 3709,
"text": "The tick code associated is “LBMA/GOLD”. So, let’s type the following line of code:"
},
{
"code": null,
"e": 3817,
"s": 3793,
"text": "And here is the output:"
},
{
"code": null,
"e": 3852,
"s": 3817,
"text": "Now if you want to plot your data:"
},
{
"code": null,
"e": 3946,
"s": 3852,
"text": "You can have the full code explanation in the video tutorial(Part III, minute 8:25 to 11:20)."
},
{
"code": null,
"e": 4037,
"s": 3946,
"text": "Overall, the data looks accurate (less than 1$ difference) if you compare it to Bloomberg."
},
{
"code": null,
"e": 4065,
"s": 4037,
"text": "The first test is positive."
},
{
"code": null,
"e": 4175,
"s": 4065,
"text": "The second test, how can we upload and request US stock exchange data for investment and algorithmic trading?"
},
{
"code": null,
"e": 4387,
"s": 4175,
"text": "If you want to learn how to start with algorithmic trading with Python and impress your colleague at work or university. I highly recommend the following course, most of the code has been taken from this source:"
},
{
"code": null,
"e": 4401,
"s": 4387,
"text": "www.udemy.com"
},
{
"code": null,
"e": 4485,
"s": 4401,
"text": "Similarly to the request above, we are going to start by searching for market data."
},
{
"code": null,
"e": 4663,
"s": 4485,
"text": "We will choose wiki continuous future as a data source and request to get data for GOOGLE. The ticker for this request is “WIKI/GOOG”. So, let’s type the following line of code:"
},
{
"code": null,
"e": 4729,
"s": 4663,
"text": "Once we have executed the line of code above, here is the output:"
},
{
"code": null,
"e": 4818,
"s": 4729,
"text": "Boom! We got the data, plus extra information regarding split ratio, volume & dividends."
},
{
"code": null,
"e": 5093,
"s": 4818,
"text": "The possibility to download market data through Quandl API is not the most efficient. I have tested a couple of other API in the past, such as Yahoo Finance or Bloomberg, and the difference is important. You can find the full test below and see by yourselves the difference:"
},
{
"code": null,
"e": 5117,
"s": 5093,
"text": "towardsdatascience.com."
},
{
"code": null,
"e": 5303,
"s": 5117,
"text": "However, I like the fact that Quandl is providing the possibility to get dividends day and the amount. As an investor and algorithmic trader that an excellent point to add to our model."
},
{
"code": null,
"e": 5381,
"s": 5303,
"text": "Now, that we have tested the market data import, let’s jump to the last test."
},
{
"code": null,
"e": 5530,
"s": 5381,
"text": "Did you ever ask yourselves if your monthly rent is over or underpriced? Or based on your area, if your one-bedroom apartment bought was overpriced?"
},
{
"code": null,
"e": 5625,
"s": 5530,
"text": "In this section, we are going to explore how to download local real estates data using Quandl."
},
{
"code": null,
"e": 5794,
"s": 5625,
"text": "Similarly to what we have done previously, you will need your ticker code. To find it we are going to search “Zillow New York” in the search bar at the top left corner."
},
{
"code": null,
"e": 5928,
"s": 5794,
"text": "Once you have chosen the New-York’s borough data that you want, you should type the tick code and execute the following line of code:"
},
{
"code": null,
"e": 6094,
"s": 5928,
"text": "In the line above we are requesting the data for a one-bedroom apartment in Harlem vs Manhattan midtown. (Full explanation in the video below. Minute 12:20 to 17:50)"
},
{
"code": null,
"e": 6194,
"s": 6094,
"text": "And here is the final output of the price of a 1 bedroom apartment of 2 New York borough over-time:"
},
{
"code": null,
"e": 6329,
"s": 6194,
"text": "I hope you enjoyed this test; I took a lot of fun to decorticate this API. You can go further using Quandl API and test it yourselves."
},
{
"code": null,
"e": 6496,
"s": 6329,
"text": "Overall, Quandl has a lot of strength and disadvantage. The aim behind this article was to propose you to discover an API which you will be able to use in the future."
},
{
"code": null,
"e": 6869,
"s": 6496,
"text": "I am teaching data science to my son sometimes, and I like using Quandl because you can get a clean and official dataset in one line of code. Suppose you want to test your Artificial Intelligence and Machine Learning models. In that case, it can be an excellent way to have the necessary randomized data (mainly for a neural network which require a massive input dataset)."
},
{
"code": null,
"e": 7116,
"s": 6869,
"text": "Furthermore, the types of data are wide. If you are working in medical, you can request plenty of data concerning healthcare, or if you are a statistician, you can explore data provided by the government on this platform to enhance your analysis."
},
{
"code": null,
"e": 7243,
"s": 7116,
"text": "If you want to know more about API’s test and how to code an algorithm for trading, I recommend the following youtube channel:"
},
{
"code": null,
"e": 7301,
"s": 7243,
"text": "https://www.youtube.com/channel/UCZorZ8KWmTON7aO84JJBwlQ?"
},
{
"code": null,
"e": 7330,
"s": 7301,
"text": "Thank you for your attention"
},
{
"code": null,
"e": 7343,
"s": 7330,
"text": "Happy coding"
},
{
"code": null,
"e": 7397,
"s": 7343,
"text": "Learn algorithmic trading in one day (Full training):"
},
{
"code": null,
"e": 7411,
"s": 7397,
"text": "www.udemy.com"
},
{
"code": null,
"e": 7430,
"s": 7411,
"text": "Live Trading Test:"
},
{
"code": null,
"e": 7441,
"s": 7430,
"text": "medium.com"
}
] |
Tk - Canvas Polygon Widget
|
Polygon widget is used to draw a polygon shape in canvas. The syntax for polygon widget is shown below −
canvasName create polygon x1 y1 x2 y2 ... xn yn options
x1 y1 and x2 y2 ... xn yn are used to determine the end points of a polygon.
The options available for the polygon widget are listed below in the following table −
-outline color
Determines the outline color.
-fill color
The fill color fills the oval with the color.
-stipple bitmap
The stipple pattern to use if the -fill option is being used.
-width number
Determines the width.
-smooth boolean
This can be set to true make the line segments to be rendered with a set of Bezier splines.
-splinesteps number
Determines the number of line segment for bezier splines.
A simple example for polygon widget is shown below −
#!/usr/bin/wish
canvas .myCanvas -background red -width 200 -height 200
pack .myCanvas
.myCanvas create polygon 50 50 100 80 120 120 100 190 -fill yellow -outline green
When we run the above program, we will get the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2306,
"s": 2201,
"text": "Polygon widget is used to draw a polygon shape in canvas. The syntax for polygon widget is shown below −"
},
{
"code": null,
"e": 2362,
"s": 2306,
"text": "canvasName create polygon x1 y1 x2 y2 ... xn yn options"
},
{
"code": null,
"e": 2439,
"s": 2362,
"text": "x1 y1 and x2 y2 ... xn yn are used to determine the end points of a polygon."
},
{
"code": null,
"e": 2527,
"s": 2439,
"text": "The options available for the polygon widget are listed below in the following table −"
},
{
"code": null,
"e": 2542,
"s": 2527,
"text": "-outline color"
},
{
"code": null,
"e": 2572,
"s": 2542,
"text": "Determines the outline color."
},
{
"code": null,
"e": 2584,
"s": 2572,
"text": "-fill color"
},
{
"code": null,
"e": 2630,
"s": 2584,
"text": "The fill color fills the oval with the color."
},
{
"code": null,
"e": 2646,
"s": 2630,
"text": "-stipple bitmap"
},
{
"code": null,
"e": 2708,
"s": 2646,
"text": "The stipple pattern to use if the -fill option is being used."
},
{
"code": null,
"e": 2722,
"s": 2708,
"text": "-width number"
},
{
"code": null,
"e": 2744,
"s": 2722,
"text": "Determines the width."
},
{
"code": null,
"e": 2760,
"s": 2744,
"text": "-smooth boolean"
},
{
"code": null,
"e": 2852,
"s": 2760,
"text": "This can be set to true make the line segments to be rendered with a set of Bezier splines."
},
{
"code": null,
"e": 2872,
"s": 2852,
"text": "-splinesteps number"
},
{
"code": null,
"e": 2930,
"s": 2872,
"text": "Determines the number of line segment for bezier splines."
},
{
"code": null,
"e": 2983,
"s": 2930,
"text": "A simple example for polygon widget is shown below −"
},
{
"code": null,
"e": 3154,
"s": 2983,
"text": "#!/usr/bin/wish\n\ncanvas .myCanvas -background red -width 200 -height 200 \npack .myCanvas\n.myCanvas create polygon 50 50 100 80 120 120 100 190 -fill yellow -outline green"
},
{
"code": null,
"e": 3220,
"s": 3154,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 3227,
"s": 3220,
"text": " Print"
},
{
"code": null,
"e": 3238,
"s": 3227,
"text": " Add Notes"
}
] |
Ruby - Object Oriented
|
Ruby is a pure object-oriented language and everything appears to Ruby as an object. Every value in Ruby is an object, even the most primitive things: strings, numbers and even true and false. Even a class itself is an object that is an instance of the Class class. This chapter will take you through all the major functionalities related to Object Oriented Ruby.
A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and methods within a class are called members of the class.
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name and is delimited with an end. For example, we defined the Box class using the keyword class as follows −
class Box
code
end
The name must begin with a capital letter and by convention names that contain more than one word are run together with each word capitalized and no separating characters (CamelCase).
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class using new keyword. Following statements declare two objects of class Box −
box1 = Box.new
box2 = Box.new
The initialize method is a standard Ruby class method and works almost same way as constructor works in other object oriented programming languages. The initialize method is useful when you want to initialize some class variables at the time of object creation. This method may take a list of parameters and like any other ruby method it would be preceded by def keyword as shown below −
class Box
def initialize(w,h)
@width, @height = w, h
end
end
The instance variables are kind of class attributes and they become properties of objects once objects are created using the class. Every object's attributes are assigned individually and share no value with other objects. They are accessed using the @ operator within the class but to access them outside of the class we use public methods, which are called accessor methods. If we take the above defined class Box then @width and @height are instance variables for the class Box.
class Box
def initialize(w,h)
# assign instance variables
@width, @height = w, h
end
end
To make the variables available from outside the class, they must be defined within accessor methods, these accessor methods are also known as a getter methods. Following example shows the usage of accessor methods −
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# accessor methods
def printWidth
@width
end
def printHeight
@height
end
end
# create an object
box = Box.new(10, 20)
# use accessor methods
x = box.printWidth()
y = box.printHeight()
puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"
When the above code is executed, it produces the following result −
Width of the box is : 10
Height of the box is : 20
Similar to accessor methods, which are used to access the value of the variables, Ruby provides a way to set the values of those variables from outside of the class using setter methods, which are defined as below −
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# accessor methods
def getWidth
@width
end
def getHeight
@height
end
# setter methods
def setWidth=(value)
@width = value
end
def setHeight=(value)
@height = value
end
end
# create an object
box = Box.new(10, 20)
# use setter methods
box.setWidth = 30
box.setHeight = 50
# use accessor methods
x = box.getWidth()
y = box.getHeight()
puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"
When the above code is executed, it produces the following result −
Width of the box is : 30
Height of the box is : 50
The instance methods are also defined in the same way as we define any other method using def keyword and they can be used using a class instance only as shown below. Their functionality is not limited to access the instance variables, but also they can do a lot more as per your requirement.
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method
def getArea
@width * @height
end
end
# create an object
box = Box.new(10, 20)
# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
When the above code is executed, it produces the following result −
Area of the box is : 200
The class variables is a variable, which is shared between all instances of a class. In other words, there is one instance of the variable and it is accessed by object instances. Class variables are prefixed with two @ characters (@@). A class variable must be initialized within the class definition as shown below.
A class method is defined using def self.methodname(), which ends with end delimiter and would be called using the class name as classname.methodname as shown in the following example −
#!/usr/bin/ruby -w
class Box
# Initialize our class variables
@@count = 0
def initialize(w,h)
# assign instance avriables
@width, @height = w, h
@@count += 1
end
def self.printCount()
puts "Box count is : #@@count"
end
end
# create two object
box1 = Box.new(10, 20)
box2 = Box.new(30, 100)
# call class method to print box count
Box.printCount()
When the above code is executed, it produces the following result −
Box count is : 2
Any class you define should have a to_s instance method to return a string representation of the object. Following is a simple example to represent a Box object in terms of width and height −
#!/usr/bin/ruby -w
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# define to_s method
def to_s
"(w:#@width,h:#@height)" # string formatting of the object.
end
end
# create an object
box = Box.new(10, 20)
# to_s method will be called in reference of string automatically.
puts "String representation of box is : #{box}"
When the above code is executed, it produces the following result −
String representation of box is : (w:10,h:20)
Ruby gives you three levels of protection at instance methods level, which may be public, private, or protected. Ruby does not apply any access control over instance and class variables.
Public Methods − Public methods can be called by anyone. Methods are public by default except for initialize, which is always private.
Public Methods − Public methods can be called by anyone. Methods are public by default except for initialize, which is always private.
Private Methods − Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members.
Private Methods − Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members.
Protected Methods − A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
Protected Methods − A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
Following is a simple example to show the syntax of all the three access modifiers −
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method by default it is public
def getArea
getWidth() * getHeight
end
# define private accessor methods
def getWidth
@width
end
def getHeight
@height
end
# make them private
private :getWidth, :getHeight
# instance method to print area
def printArea
@area = getWidth() * getHeight
puts "Big box area is : #@area"
end
# make it protected
protected :printArea
end
# create an object
box = Box.new(10, 20)
# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
# try to call protected or methods
box.printArea()
When the above code is executed, it produces the following result. Here, first method is called successfully but second method gave a problem.
Area of the box is : 200
test.rb:42: protected method `printArea' called for #
<Box:0xb7f11280 @height = 20, @width = 10> (NoMethodError)
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application.
Inheritance also provides an opportunity to reuse the code functionality and fast implementation time but unfortunately Ruby does not support multiple levels of inheritances but Ruby supports mixins. A mixin is like a specialized implementation of multiple inheritance in which only the interface portion is inherited.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or superclass, and the new class is referred to as the derived class or sub-class.
Ruby also supports the concept of subclassing, i.e., inheritance and following example explains the concept. The syntax for extending a class is simple. Just add a < character and the name of the superclass to your class statement. For example, following define a class BigBox as a subclass of Box −
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method
def getArea
@width * @height
end
end
# define a subclass
class BigBox < Box
# add a new instance method
def printArea
@area = @width * @height
puts "Big box area is : #@area"
end
end
# create an object
box = BigBox.new(10, 20)
# print the area
box.printArea()
When the above code is executed, it produces the following result −
Big box area is : 200
Though you can add new functionality in a derived class, but sometimes you would like to change the behavior of already defined method in a parent class. You can do so simply by keeping the method name same and overriding the functionality of the method as shown below in the example −
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method
def getArea
@width * @height
end
end
# define a subclass
class BigBox < Box
# change existing getArea method as follows
def getArea
@area = @width * @height
puts "Big box area is : #@area"
end
end
# create an object
box = BigBox.new(10, 20)
# print the area using overriden method.
box.getArea()
We'd like the + operator to perform vector addition of two Box objects using +, the * operator to multiply a Box width and height by a scalar, and the unary - operator to do negate the width and height of the Box. Here is a version of the Box class with mathematical operators defined −
class Box
def initialize(w,h) # Initialize the width and height
@width,@height = w, h
end
def +(other) # Define + to do vector addition
Box.new(@width + other.width, @height + other.height)
end
def -@ # Define unary minus to negate width and height
Box.new(-@width, -@height)
end
def *(scalar) # To perform scalar multiplication
Box.new(@width*scalar, @height*scalar)
end
end
Sometimes, we want to prevent an object from being changed. The freeze method in Object allows us to do this, effectively turning an object into a constant. Any object can be frozen by invoking Object.freeze. A frozen object may not be modified: you can't change its instance variables.
You can check if a given object is already frozen or not using Object.frozen? method, which returns true in case the object is frozen otherwise a false value is return. Following example clears the concept −
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# accessor methods
def getWidth
@width
end
def getHeight
@height
end
# setter methods
def setWidth=(value)
@width = value
end
def setHeight=(value)
@height = value
end
end
# create an object
box = Box.new(10, 20)
# let us freez this object
box.freeze
if( box.frozen? )
puts "Box object is frozen object"
else
puts "Box object is normal object"
end
# now try using setter methods
box.setWidth = 30
box.setHeight = 50
# use accessor methods
x = box.getWidth()
y = box.getHeight()
puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"
When the above code is executed, it produces the following result −
Box object is frozen object
test.rb:20:in `setWidth=': can't modify frozen object (TypeError)
from test.rb:39
You can define a constant inside a class by assigning a direct numeric or string value to a variable, which is defined without using either @ or @@. By convention, we keep constant names in upper case.
Once a constant is defined, you cannot change its value but you can access a constant directly inside a class much like a variable but if you want to access a constant outside of the class then you would have to use classname::constant as shown in the below example.
#!/usr/bin/ruby -w
# define a class
class Box
BOX_COMPANY = "TATA Inc"
BOXWEIGHT = 10
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method
def getArea
@width * @height
end
end
# create an object
box = Box.new(10, 20)
# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
puts Box::BOX_COMPANY
puts "Box weight is: #{Box::BOXWEIGHT}"
When the above code is executed, it produces the following result −
Area of the box is : 200
TATA Inc
Box weight is: 10
Class constants are inherited and can be overridden like instance methods.
There may be a situation when you want to create an object without calling its constructor initialize i.e. using new method, in such case you can call allocate, which will create an uninitialized object for you as in the following example −
#!/usr/bin/ruby -w
# define a class
class Box
attr_accessor :width, :height
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method
def getArea
@width * @height
end
end
# create an object using new
box1 = Box.new(10, 20)
# create another object using allocate
box2 = Box.allocate
# call instance method using box1
a = box1.getArea()
puts "Area of the box is : #{a}"
# call instance method using box2
a = box2.getArea()
puts "Area of the box is : #{a}"
When the above code is executed, it produces the following result −
Area of the box is : 200
test.rb:14: warning: instance variable @width not initialized
test.rb:14: warning: instance variable @height not initialized
test.rb:14:in `getArea': undefined method `*'
for nil:NilClass (NoMethodError) from test.rb:29
If class definitions are executable code, this implies that they execute in the context of some object: self must reference something. Let's find out what it is.
#!/usr/bin/ruby -w
class Box
# print class information
puts "Type of self = #{self.type}"
puts "Name of self = #{self.name}"
end
When the above code is executed, it produces the following result −
Type of self = Class
Name of self = Box
This means that a class definition is executed with that class as the current object. This means that methods in the metaclass and its superclasses will be available during the execution of the method definition.
46 Lectures
9.5 hours
Eduonix Learning Solutions
97 Lectures
7.5 hours
Skillbakerystudios
227 Lectures
40 hours
YouAccel
19 Lectures
10 hours
Programming Line
51 Lectures
5 hours
Stone River ELearning
39 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2658,
"s": 2294,
"text": "Ruby is a pure object-oriented language and everything appears to Ruby as an object. Every value in Ruby is an object, even the most primitive things: strings, numbers and even true and false. Even a class itself is an object that is an instance of the Class class. This chapter will take you through all the major functionalities related to Object Oriented Ruby."
},
{
"code": null,
"e": 2874,
"s": 2658,
"text": "A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and methods within a class are called members of the class."
},
{
"code": null,
"e": 3133,
"s": 2874,
"text": "When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object."
},
{
"code": null,
"e": 3314,
"s": 3133,
"text": "A class definition starts with the keyword class followed by the class name and is delimited with an end. For example, we defined the Box class using the keyword class as follows −"
},
{
"code": null,
"e": 3337,
"s": 3314,
"text": "class Box\n code\nend\n"
},
{
"code": null,
"e": 3521,
"s": 3337,
"text": "The name must begin with a capital letter and by convention names that contain more than one word are run together with each word capitalized and no separating characters (CamelCase)."
},
{
"code": null,
"e": 3719,
"s": 3521,
"text": "A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class using new keyword. Following statements declare two objects of class Box −"
},
{
"code": null,
"e": 3750,
"s": 3719,
"text": "box1 = Box.new\nbox2 = Box.new\n"
},
{
"code": null,
"e": 4138,
"s": 3750,
"text": "The initialize method is a standard Ruby class method and works almost same way as constructor works in other object oriented programming languages. The initialize method is useful when you want to initialize some class variables at the time of object creation. This method may take a list of parameters and like any other ruby method it would be preceded by def keyword as shown below −"
},
{
"code": null,
"e": 4211,
"s": 4138,
"text": "class Box\n def initialize(w,h)\n @width, @height = w, h\n end\nend"
},
{
"code": null,
"e": 4693,
"s": 4211,
"text": "The instance variables are kind of class attributes and they become properties of objects once objects are created using the class. Every object's attributes are assigned individually and share no value with other objects. They are accessed using the @ operator within the class but to access them outside of the class we use public methods, which are called accessor methods. If we take the above defined class Box then @width and @height are instance variables for the class Box."
},
{
"code": null,
"e": 4800,
"s": 4693,
"text": "class Box\n def initialize(w,h)\n # assign instance variables\n @width, @height = w, h\n end\nend"
},
{
"code": null,
"e": 5017,
"s": 4800,
"text": "To make the variables available from outside the class, they must be defined within accessor methods, these accessor methods are also known as a getter methods. Following example shows the usage of accessor methods −"
},
{
"code": null,
"e": 5432,
"s": 5017,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n\n # accessor methods\n def printWidth\n @width\n end\n\n def printHeight\n @height\n end\nend\n\n# create an object\nbox = Box.new(10, 20)\n\n# use accessor methods\nx = box.printWidth()\ny = box.printHeight()\n\nputs \"Width of the box is : #{x}\"\nputs \"Height of the box is : #{y}\""
},
{
"code": null,
"e": 5500,
"s": 5432,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 5552,
"s": 5500,
"text": "Width of the box is : 10\nHeight of the box is : 20\n"
},
{
"code": null,
"e": 5768,
"s": 5552,
"text": "Similar to accessor methods, which are used to access the value of the variables, Ruby provides a way to set the values of those variables from outside of the class using setter methods, which are defined as below −"
},
{
"code": null,
"e": 6360,
"s": 5768,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n\n # accessor methods\n def getWidth\n @width\n end\n def getHeight\n @height\n end\n\n # setter methods\n def setWidth=(value)\n @width = value\n end\n def setHeight=(value)\n @height = value\n end\nend\n\n# create an object\nbox = Box.new(10, 20)\n\n# use setter methods\nbox.setWidth = 30\nbox.setHeight = 50\n\n# use accessor methods\nx = box.getWidth()\ny = box.getHeight()\n\nputs \"Width of the box is : #{x}\"\nputs \"Height of the box is : #{y}\""
},
{
"code": null,
"e": 6428,
"s": 6360,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 6480,
"s": 6428,
"text": "Width of the box is : 30\nHeight of the box is : 50\n"
},
{
"code": null,
"e": 6773,
"s": 6480,
"text": "The instance methods are also defined in the same way as we define any other method using def keyword and they can be used using a class instance only as shown below. Their functionality is not limited to access the instance variables, but also they can do a lot more as per your requirement."
},
{
"code": null,
"e": 7091,
"s": 6773,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n # instance method\n def getArea\n @width * @height\n end\nend\n\n# create an object\nbox = Box.new(10, 20)\n\n# call instance methods\na = box.getArea()\nputs \"Area of the box is : #{a}\""
},
{
"code": null,
"e": 7159,
"s": 7091,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 7185,
"s": 7159,
"text": "Area of the box is : 200\n"
},
{
"code": null,
"e": 7502,
"s": 7185,
"text": "The class variables is a variable, which is shared between all instances of a class. In other words, there is one instance of the variable and it is accessed by object instances. Class variables are prefixed with two @ characters (@@). A class variable must be initialized within the class definition as shown below."
},
{
"code": null,
"e": 7688,
"s": 7502,
"text": "A class method is defined using def self.methodname(), which ends with end delimiter and would be called using the class name as classname.methodname as shown in the following example −"
},
{
"code": null,
"e": 8081,
"s": 7688,
"text": "#!/usr/bin/ruby -w\n\nclass Box\n # Initialize our class variables\n @@count = 0\n def initialize(w,h)\n # assign instance avriables\n @width, @height = w, h\n\n @@count += 1\n end\n\n def self.printCount()\n puts \"Box count is : #@@count\"\n end\nend\n\n# create two object\nbox1 = Box.new(10, 20)\nbox2 = Box.new(30, 100)\n\n# call class method to print box count\nBox.printCount()"
},
{
"code": null,
"e": 8149,
"s": 8081,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 8167,
"s": 8149,
"text": "Box count is : 2\n"
},
{
"code": null,
"e": 8359,
"s": 8167,
"text": "Any class you define should have a to_s instance method to return a string representation of the object. Following is a simple example to represent a Box object in terms of width and height −"
},
{
"code": null,
"e": 8744,
"s": 8359,
"text": "#!/usr/bin/ruby -w\n\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n # define to_s method\n def to_s\n \"(w:#@width,h:#@height)\" # string formatting of the object.\n end\nend\n\n# create an object\nbox = Box.new(10, 20)\n\n# to_s method will be called in reference of string automatically.\nputs \"String representation of box is : #{box}\""
},
{
"code": null,
"e": 8812,
"s": 8744,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 8859,
"s": 8812,
"text": "String representation of box is : (w:10,h:20)\n"
},
{
"code": null,
"e": 9046,
"s": 8859,
"text": "Ruby gives you three levels of protection at instance methods level, which may be public, private, or protected. Ruby does not apply any access control over instance and class variables."
},
{
"code": null,
"e": 9181,
"s": 9046,
"text": "Public Methods − Public methods can be called by anyone. Methods are public by default except for initialize, which is always private."
},
{
"code": null,
"e": 9316,
"s": 9181,
"text": "Public Methods − Public methods can be called by anyone. Methods are public by default except for initialize, which is always private."
},
{
"code": null,
"e": 9460,
"s": 9316,
"text": "Private Methods − Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members."
},
{
"code": null,
"e": 9604,
"s": 9460,
"text": "Private Methods − Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members."
},
{
"code": null,
"e": 9751,
"s": 9604,
"text": "Protected Methods − A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family."
},
{
"code": null,
"e": 9898,
"s": 9751,
"text": "Protected Methods − A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family."
},
{
"code": null,
"e": 9983,
"s": 9898,
"text": "Following is a simple example to show the syntax of all the three access modifiers −"
},
{
"code": null,
"e": 10734,
"s": 9983,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n\n # instance method by default it is public\n def getArea\n getWidth() * getHeight\n end\n\n # define private accessor methods\n def getWidth\n @width\n end\n def getHeight\n @height\n end\n # make them private\n private :getWidth, :getHeight\n\n # instance method to print area\n def printArea\n @area = getWidth() * getHeight\n puts \"Big box area is : #@area\"\n end\n # make it protected\n protected :printArea\nend\n\n# create an object\nbox = Box.new(10, 20)\n\n# call instance methods\na = box.getArea()\nputs \"Area of the box is : #{a}\"\n\n# try to call protected or methods\nbox.printArea()"
},
{
"code": null,
"e": 10877,
"s": 10734,
"text": "When the above code is executed, it produces the following result. Here, first method is called successfully but second method gave a problem."
},
{
"code": null,
"e": 11016,
"s": 10877,
"text": "Area of the box is : 200\ntest.rb:42: protected method `printArea' called for #\n<Box:0xb7f11280 @height = 20, @width = 10> (NoMethodError)\n"
},
{
"code": null,
"e": 11234,
"s": 11016,
"text": "One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application."
},
{
"code": null,
"e": 11553,
"s": 11234,
"text": "Inheritance also provides an opportunity to reuse the code functionality and fast implementation time but unfortunately Ruby does not support multiple levels of inheritances but Ruby supports mixins. A mixin is like a specialized implementation of multiple inheritance in which only the interface portion is inherited."
},
{
"code": null,
"e": 11870,
"s": 11553,
"text": "When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or superclass, and the new class is referred to as the derived class or sub-class."
},
{
"code": null,
"e": 12170,
"s": 11870,
"text": "Ruby also supports the concept of subclassing, i.e., inheritance and following example explains the concept. The syntax for extending a class is simple. Just add a < character and the name of the superclass to your class statement. For example, following define a class BigBox as a subclass of Box −"
},
{
"code": null,
"e": 12618,
"s": 12170,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n # instance method\n def getArea\n @width * @height\n end\nend\n\n# define a subclass\nclass BigBox < Box\n\n # add a new instance method\n def printArea\n @area = @width * @height\n puts \"Big box area is : #@area\"\n end\nend\n\n# create an object\nbox = BigBox.new(10, 20)\n\n# print the area\nbox.printArea()"
},
{
"code": null,
"e": 12686,
"s": 12618,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 12709,
"s": 12686,
"text": "Big box area is : 200\n"
},
{
"code": null,
"e": 12995,
"s": 12709,
"text": "Though you can add new functionality in a derived class, but sometimes you would like to change the behavior of already defined method in a parent class. You can do so simply by keeping the method name same and overriding the functionality of the method as shown below in the example −"
},
{
"code": null,
"e": 13479,
"s": 12995,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n # instance method\n def getArea\n @width * @height\n end\nend\n\n# define a subclass\nclass BigBox < Box\n\n # change existing getArea method as follows\n def getArea\n @area = @width * @height\n puts \"Big box area is : #@area\"\n end\nend\n\n# create an object\nbox = BigBox.new(10, 20)\n\n# print the area using overriden method.\nbox.getArea()"
},
{
"code": null,
"e": 13766,
"s": 13479,
"text": "We'd like the + operator to perform vector addition of two Box objects using +, the * operator to multiply a Box width and height by a scalar, and the unary - operator to do negate the width and height of the Box. Here is a version of the Box class with mathematical operators defined −"
},
{
"code": null,
"e": 14223,
"s": 13766,
"text": "class Box\n def initialize(w,h) # Initialize the width and height\n @width,@height = w, h\n end\n\n def +(other) # Define + to do vector addition\n Box.new(@width + other.width, @height + other.height)\n end\n\n def -@ # Define unary minus to negate width and height\n Box.new(-@width, -@height)\n end\n\n def *(scalar) # To perform scalar multiplication\n Box.new(@width*scalar, @height*scalar)\n end\nend"
},
{
"code": null,
"e": 14510,
"s": 14223,
"text": "Sometimes, we want to prevent an object from being changed. The freeze method in Object allows us to do this, effectively turning an object into a constant. Any object can be frozen by invoking Object.freeze. A frozen object may not be modified: you can't change its instance variables."
},
{
"code": null,
"e": 14718,
"s": 14510,
"text": "You can check if a given object is already frozen or not using Object.frozen? method, which returns true in case the object is frozen otherwise a false value is return. Following example clears the concept −"
},
{
"code": null,
"e": 15462,
"s": 14718,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n\n # accessor methods\n def getWidth\n @width\n end\n def getHeight\n @height\n end\n\n # setter methods\n def setWidth=(value)\n @width = value\n end\n def setHeight=(value)\n @height = value\n end\nend\n\n# create an object\nbox = Box.new(10, 20)\n\n# let us freez this object\nbox.freeze\nif( box.frozen? )\n puts \"Box object is frozen object\"\nelse\n puts \"Box object is normal object\"\nend\n\n# now try using setter methods\nbox.setWidth = 30\nbox.setHeight = 50\n\n# use accessor methods\nx = box.getWidth()\ny = box.getHeight()\n\nputs \"Width of the box is : #{x}\"\nputs \"Height of the box is : #{y}\""
},
{
"code": null,
"e": 15530,
"s": 15462,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 15644,
"s": 15530,
"text": "Box object is frozen object\ntest.rb:20:in `setWidth=': can't modify frozen object (TypeError)\n from test.rb:39\n"
},
{
"code": null,
"e": 15846,
"s": 15644,
"text": "You can define a constant inside a class by assigning a direct numeric or string value to a variable, which is defined without using either @ or @@. By convention, we keep constant names in upper case."
},
{
"code": null,
"e": 16113,
"s": 15846,
"text": "Once a constant is defined, you cannot change its value but you can access a constant directly inside a class much like a variable but if you want to access a constant outside of the class then you would have to use classname::constant as shown in the below example."
},
{
"code": null,
"e": 16539,
"s": 16113,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n BOX_COMPANY = \"TATA Inc\"\n BOXWEIGHT = 10\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n # instance method\n def getArea\n @width * @height\n end\nend\n\n# create an object\nbox = Box.new(10, 20)\n\n# call instance methods\na = box.getArea()\nputs \"Area of the box is : #{a}\"\nputs Box::BOX_COMPANY\nputs \"Box weight is: #{Box::BOXWEIGHT}\""
},
{
"code": null,
"e": 16607,
"s": 16539,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 16660,
"s": 16607,
"text": "Area of the box is : 200\nTATA Inc\nBox weight is: 10\n"
},
{
"code": null,
"e": 16735,
"s": 16660,
"text": "Class constants are inherited and can be overridden like instance methods."
},
{
"code": null,
"e": 16976,
"s": 16735,
"text": "There may be a situation when you want to create an object without calling its constructor initialize i.e. using new method, in such case you can call allocate, which will create an uninitialized object for you as in the following example −"
},
{
"code": null,
"e": 17498,
"s": 16976,
"text": "#!/usr/bin/ruby -w\n\n# define a class\nclass Box\n attr_accessor :width, :height\n\n # constructor method\n def initialize(w,h)\n @width, @height = w, h\n end\n\n # instance method\n def getArea\n @width * @height\n end\nend\n\n# create an object using new\nbox1 = Box.new(10, 20)\n\n# create another object using allocate\nbox2 = Box.allocate\n\n# call instance method using box1\na = box1.getArea()\nputs \"Area of the box is : #{a}\"\n\n# call instance method using box2\na = box2.getArea()\nputs \"Area of the box is : #{a}\""
},
{
"code": null,
"e": 17566,
"s": 17498,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 17816,
"s": 17566,
"text": "Area of the box is : 200\ntest.rb:14: warning: instance variable @width not initialized\ntest.rb:14: warning: instance variable @height not initialized\ntest.rb:14:in `getArea': undefined method `*' \n for nil:NilClass (NoMethodError) from test.rb:29\n"
},
{
"code": null,
"e": 17978,
"s": 17816,
"text": "If class definitions are executable code, this implies that they execute in the context of some object: self must reference something. Let's find out what it is."
},
{
"code": null,
"e": 18117,
"s": 17978,
"text": "#!/usr/bin/ruby -w\n\nclass Box\n # print class information\n puts \"Type of self = #{self.type}\"\n puts \"Name of self = #{self.name}\"\nend"
},
{
"code": null,
"e": 18185,
"s": 18117,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 18226,
"s": 18185,
"text": "Type of self = Class\nName of self = Box\n"
},
{
"code": null,
"e": 18439,
"s": 18226,
"text": "This means that a class definition is executed with that class as the current object. This means that methods in the metaclass and its superclasses will be available during the execution of the method definition."
},
{
"code": null,
"e": 18474,
"s": 18439,
"text": "\n 46 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 18502,
"s": 18474,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 18537,
"s": 18502,
"text": "\n 97 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 18557,
"s": 18537,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 18592,
"s": 18557,
"text": "\n 227 Lectures \n 40 hours \n"
},
{
"code": null,
"e": 18602,
"s": 18592,
"text": " YouAccel"
},
{
"code": null,
"e": 18636,
"s": 18602,
"text": "\n 19 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 18654,
"s": 18636,
"text": " Programming Line"
},
{
"code": null,
"e": 18687,
"s": 18654,
"text": "\n 51 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 18710,
"s": 18687,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 18745,
"s": 18710,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 18768,
"s": 18745,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 18775,
"s": 18768,
"text": " Print"
},
{
"code": null,
"e": 18786,
"s": 18775,
"text": " Add Notes"
}
] |
Python - User object in Tweepy - GeeksforGeeks
|
03 Jul, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The User object in Tweepy module contains the information about a user.
Here are the list of attributes in the User object :
id : The ID of the user.
id_str : The ID of the user as a string.
name : The name of the user.
screen_name : The screen name of the user
location : The location of the user.
profile_location : The location of the the profile.
description : The description of the user account.
url : The URL of the user account.
entities : A dictionary containing URLs.
protected : Indicates if the user profile is protected or not.
followers_count : The number of followers the account has.
friends_count : The number of friends the account has.
listed_count : The number of public lists the account has been added to.
created_at : The time at which the account was created.
favourites_count : The number of statuses the account has favourited.
utc_offset : The UTC offset of the profile.
geo_enabled : Indicates whether the account is geo enabled or not.
verified : Indicates whether the user is verified or not.
statuses_count : The number of statuses updated by the user.
lang : The language of the account.
status : Fetches the latest status updated by the user.
contributors_enabled : Indicates whether the contributors are enabled or not.
is_translator : Indicates whether there is a translator or not.
is_translation_enabled : Indicates whether the translation is available or not.
profile_background_color : The background color of the profile.
profile_background_image_url : The URL of the background image of the profile.
profile_background_image_url_https : The secure URL of the background image of the profile.
profile_background_tile : The title of the background profile.
profile_image_url : The URL of the profile image.
profile_image_url_https : The secure URL of the profile image.
profile_banner_url : The URL of the profile banner.
profile_link_color : The color of the profile link.
profile_sidebar_border_color : The color of the profile sidebar border.
profile_sidebar_fill_color : The color of the profile sidebar.
profile_text_color : The color of the profile text.
profile_use_background_image : Indicates whether the profile is to use a background image or not.
has_extended_profile : Indicates whether the profile is extended or not.
default_profile : The default profile.
default_profile_image : The image of the default profile.
following : Indicates whether the authenticated user is following the user or not.
follow_request_sent : Indicates whether the authenticated user has requested to follow the user or not.
notifications: Indicates whether the authenticated user has turned on the notifications for the user or not.
Example : Consider the twitter account of GeeksforGeeks. Use get_user() method to fetch the user.
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the screen name of the userscreen_name = "geeksforgeeks" # fetching the useruser = api.get_user(screen_name) # printing the informationprint("The id is : " + str(user.id))print("The id_str is : " + user.id_str)print("The name is : " + user.name)print("The screen_name is : " + user.screen_name)print("The location is : " + str(user.location))print("The profile_location is : " + str(user.profile_location))print("The description is : " + user.description) print("The url is : " + user.url)print("The entities are : " + str(user.entities))print("Is the account protected? : " + str(user.protected)) print("The followers_count is : " + str(user.followers_count))print("The friends_count is : " + str(user.friends_count))print("The listed_count is : " + str(user.listed_count))print("The account was created on : " + str(user.created_at))print("The favourites_count is : " + str(user.favourites_count))print("The utc_offset is : " + str(user.utc_offset))print("The geo_enabled is : " + str(user.geo_enabled))print("The verified is : " + str(user.verified))print("The statuses_count is : " + str(user.statuses_count))print("The lang is : " + str(user.lang))print("The status ID is : " + str(user.status.id))print("The contributors_enabled is : " + str(user.contributors_enabled))print("The is_translator is : " + str(user.is_translator))print("The is_translation_enabled is : " + str(user.is_translation_enabled)) print("The profile_background_color is : " + user.profile_background_color)print("The profile_background_image_url is : " + user.profile_background_image_url)print("The profile_background_image_url_https is : " + user.profile_background_image_url_https)print("The profile_background_tile is : " + str(user.profile_background_tile))print("The profile_image_url is : " + user.profile_image_url)print("The profile_image_url_https is : " + user.profile_image_url_https)print("The profile_banner_url is : " + user.profile_banner_url)print("The profile_link_color is : " + user.profile_link_color)print("The profile_sidebar_border_color is : " + user.profile_sidebar_border_color)print("The profile_sidebar_fill_color is : " + user.profile_sidebar_fill_color)print("The profile_text_color is : " + user.profile_text_color)print("The profile_use_background_image is : " + str(user.profile_use_background_image)) print("The has_extended_profile is : " + str(user.has_extended_profile))print("The default_profile is : " + str(user.default_profile))print("The default_profile_image is : " + str(user.default_profile_image))print("Is the authenticated user following the account? : " + str(user.following)) print("Has the authenticated user requested to follow the account? : " + str(user.follow_request_sent))print("Are notifications of the authenticated user turned on for the account? : " + str(user.notifications))
Output :
The id is : 57741058The id_str is : 57741058The name is : GeeksforGeeksThe screen_name is : geeksforgeeksThe location is : IndiaThe profile_location is : NoneThe description is : Your one-stop destination to attain Coding Nirvana...The url is : http://t.co/k2iUfxLRBjThe entities are : {‘url’: {‘urls’: [{‘url’: ‘http://t.co/k2iUfxLRBj’, ‘expanded_url’: ‘http://geeksforgeeks.org/’, ‘display_url’: ‘geeksforgeeks.org’, ‘indices’: [0, 22]}]}, ‘description’: {‘urls’: []}}Is the account protected? : FalseThe followers_count is : 17706The friends_count is : 11The listed_count is : 142The account was created on : 2009-07-17 20:02:09The favourites_count is : 465The utc_offset is : NoneThe geo_enabled is : FalseThe verified is : FalseThe statuses_count is : 13231The lang is : NoneThe status ID is : 1271404442068422662The contributors_enabled is : FalseThe is_translator is : FalseThe is_translation_enabled is : FalseThe profile_background_color is : FFFDF7The profile_background_image_url is : http://abs.twimg.com/images/themes/theme13/bg.gifThe profile_background_image_url_https is : https://abs.twimg.com/images/themes/theme13/bg.gifThe profile_background_tile is : FalseThe profile_image_url is : http://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv_normal.pngThe profile_image_url_https is : https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv_normal.pngThe profile_banner_url is : https://pbs.twimg.com/profile_banners/57741058/1591281311The profile_link_color is : 119E39The profile_sidebar_border_color is : D3D2CFThe profile_sidebar_fill_color is : E3E2DEThe profile_text_color is : 0D0C0C
Python-Tweepy
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24476,
"s": 24448,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 24876,
"s": 24476,
"text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication."
},
{
"code": null,
"e": 24948,
"s": 24876,
"text": "The User object in Tweepy module contains the information about a user."
},
{
"code": null,
"e": 25001,
"s": 24948,
"text": "Here are the list of attributes in the User object :"
},
{
"code": null,
"e": 25026,
"s": 25001,
"text": "id : The ID of the user."
},
{
"code": null,
"e": 25067,
"s": 25026,
"text": "id_str : The ID of the user as a string."
},
{
"code": null,
"e": 25096,
"s": 25067,
"text": "name : The name of the user."
},
{
"code": null,
"e": 25138,
"s": 25096,
"text": "screen_name : The screen name of the user"
},
{
"code": null,
"e": 25175,
"s": 25138,
"text": "location : The location of the user."
},
{
"code": null,
"e": 25227,
"s": 25175,
"text": "profile_location : The location of the the profile."
},
{
"code": null,
"e": 25278,
"s": 25227,
"text": "description : The description of the user account."
},
{
"code": null,
"e": 25313,
"s": 25278,
"text": "url : The URL of the user account."
},
{
"code": null,
"e": 25354,
"s": 25313,
"text": "entities : A dictionary containing URLs."
},
{
"code": null,
"e": 25417,
"s": 25354,
"text": "protected : Indicates if the user profile is protected or not."
},
{
"code": null,
"e": 25476,
"s": 25417,
"text": "followers_count : The number of followers the account has."
},
{
"code": null,
"e": 25531,
"s": 25476,
"text": "friends_count : The number of friends the account has."
},
{
"code": null,
"e": 25604,
"s": 25531,
"text": "listed_count : The number of public lists the account has been added to."
},
{
"code": null,
"e": 25660,
"s": 25604,
"text": "created_at : The time at which the account was created."
},
{
"code": null,
"e": 25730,
"s": 25660,
"text": "favourites_count : The number of statuses the account has favourited."
},
{
"code": null,
"e": 25774,
"s": 25730,
"text": "utc_offset : The UTC offset of the profile."
},
{
"code": null,
"e": 25841,
"s": 25774,
"text": "geo_enabled : Indicates whether the account is geo enabled or not."
},
{
"code": null,
"e": 25899,
"s": 25841,
"text": "verified : Indicates whether the user is verified or not."
},
{
"code": null,
"e": 25960,
"s": 25899,
"text": "statuses_count : The number of statuses updated by the user."
},
{
"code": null,
"e": 25996,
"s": 25960,
"text": "lang : The language of the account."
},
{
"code": null,
"e": 26052,
"s": 25996,
"text": "status : Fetches the latest status updated by the user."
},
{
"code": null,
"e": 26130,
"s": 26052,
"text": "contributors_enabled : Indicates whether the contributors are enabled or not."
},
{
"code": null,
"e": 26194,
"s": 26130,
"text": "is_translator : Indicates whether there is a translator or not."
},
{
"code": null,
"e": 26274,
"s": 26194,
"text": "is_translation_enabled : Indicates whether the translation is available or not."
},
{
"code": null,
"e": 26338,
"s": 26274,
"text": "profile_background_color : The background color of the profile."
},
{
"code": null,
"e": 26417,
"s": 26338,
"text": "profile_background_image_url : The URL of the background image of the profile."
},
{
"code": null,
"e": 26509,
"s": 26417,
"text": "profile_background_image_url_https : The secure URL of the background image of the profile."
},
{
"code": null,
"e": 26572,
"s": 26509,
"text": "profile_background_tile : The title of the background profile."
},
{
"code": null,
"e": 26622,
"s": 26572,
"text": "profile_image_url : The URL of the profile image."
},
{
"code": null,
"e": 26685,
"s": 26622,
"text": "profile_image_url_https : The secure URL of the profile image."
},
{
"code": null,
"e": 26737,
"s": 26685,
"text": "profile_banner_url : The URL of the profile banner."
},
{
"code": null,
"e": 26789,
"s": 26737,
"text": "profile_link_color : The color of the profile link."
},
{
"code": null,
"e": 26861,
"s": 26789,
"text": "profile_sidebar_border_color : The color of the profile sidebar border."
},
{
"code": null,
"e": 26924,
"s": 26861,
"text": "profile_sidebar_fill_color : The color of the profile sidebar."
},
{
"code": null,
"e": 26976,
"s": 26924,
"text": "profile_text_color : The color of the profile text."
},
{
"code": null,
"e": 27074,
"s": 26976,
"text": "profile_use_background_image : Indicates whether the profile is to use a background image or not."
},
{
"code": null,
"e": 27147,
"s": 27074,
"text": "has_extended_profile : Indicates whether the profile is extended or not."
},
{
"code": null,
"e": 27186,
"s": 27147,
"text": "default_profile : The default profile."
},
{
"code": null,
"e": 27244,
"s": 27186,
"text": "default_profile_image : The image of the default profile."
},
{
"code": null,
"e": 27327,
"s": 27244,
"text": "following : Indicates whether the authenticated user is following the user or not."
},
{
"code": null,
"e": 27431,
"s": 27327,
"text": "follow_request_sent : Indicates whether the authenticated user has requested to follow the user or not."
},
{
"code": null,
"e": 27540,
"s": 27431,
"text": "notifications: Indicates whether the authenticated user has turned on the notifications for the user or not."
},
{
"code": null,
"e": 27638,
"s": 27540,
"text": "Example : Consider the twitter account of GeeksforGeeks. Use get_user() method to fetch the user."
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the screen name of the userscreen_name = \"geeksforgeeks\" # fetching the useruser = api.get_user(screen_name) # printing the informationprint(\"The id is : \" + str(user.id))print(\"The id_str is : \" + user.id_str)print(\"The name is : \" + user.name)print(\"The screen_name is : \" + user.screen_name)print(\"The location is : \" + str(user.location))print(\"The profile_location is : \" + str(user.profile_location))print(\"The description is : \" + user.description) print(\"The url is : \" + user.url)print(\"The entities are : \" + str(user.entities))print(\"Is the account protected? : \" + str(user.protected)) print(\"The followers_count is : \" + str(user.followers_count))print(\"The friends_count is : \" + str(user.friends_count))print(\"The listed_count is : \" + str(user.listed_count))print(\"The account was created on : \" + str(user.created_at))print(\"The favourites_count is : \" + str(user.favourites_count))print(\"The utc_offset is : \" + str(user.utc_offset))print(\"The geo_enabled is : \" + str(user.geo_enabled))print(\"The verified is : \" + str(user.verified))print(\"The statuses_count is : \" + str(user.statuses_count))print(\"The lang is : \" + str(user.lang))print(\"The status ID is : \" + str(user.status.id))print(\"The contributors_enabled is : \" + str(user.contributors_enabled))print(\"The is_translator is : \" + str(user.is_translator))print(\"The is_translation_enabled is : \" + str(user.is_translation_enabled)) print(\"The profile_background_color is : \" + user.profile_background_color)print(\"The profile_background_image_url is : \" + user.profile_background_image_url)print(\"The profile_background_image_url_https is : \" + user.profile_background_image_url_https)print(\"The profile_background_tile is : \" + str(user.profile_background_tile))print(\"The profile_image_url is : \" + user.profile_image_url)print(\"The profile_image_url_https is : \" + user.profile_image_url_https)print(\"The profile_banner_url is : \" + user.profile_banner_url)print(\"The profile_link_color is : \" + user.profile_link_color)print(\"The profile_sidebar_border_color is : \" + user.profile_sidebar_border_color)print(\"The profile_sidebar_fill_color is : \" + user.profile_sidebar_fill_color)print(\"The profile_text_color is : \" + user.profile_text_color)print(\"The profile_use_background_image is : \" + str(user.profile_use_background_image)) print(\"The has_extended_profile is : \" + str(user.has_extended_profile))print(\"The default_profile is : \" + str(user.default_profile))print(\"The default_profile_image is : \" + str(user.default_profile_image))print(\"Is the authenticated user following the account? : \" + str(user.following)) print(\"Has the authenticated user requested to follow the account? : \" + str(user.follow_request_sent))print(\"Are notifications of the authenticated user turned on for the account? : \" + str(user.notifications))",
"e": 30874,
"s": 27638,
"text": null
},
{
"code": null,
"e": 30883,
"s": 30874,
"text": "Output :"
},
{
"code": null,
"e": 32511,
"s": 30883,
"text": "The id is : 57741058The id_str is : 57741058The name is : GeeksforGeeksThe screen_name is : geeksforgeeksThe location is : IndiaThe profile_location is : NoneThe description is : Your one-stop destination to attain Coding Nirvana...The url is : http://t.co/k2iUfxLRBjThe entities are : {‘url’: {‘urls’: [{‘url’: ‘http://t.co/k2iUfxLRBj’, ‘expanded_url’: ‘http://geeksforgeeks.org/’, ‘display_url’: ‘geeksforgeeks.org’, ‘indices’: [0, 22]}]}, ‘description’: {‘urls’: []}}Is the account protected? : FalseThe followers_count is : 17706The friends_count is : 11The listed_count is : 142The account was created on : 2009-07-17 20:02:09The favourites_count is : 465The utc_offset is : NoneThe geo_enabled is : FalseThe verified is : FalseThe statuses_count is : 13231The lang is : NoneThe status ID is : 1271404442068422662The contributors_enabled is : FalseThe is_translator is : FalseThe is_translation_enabled is : FalseThe profile_background_color is : FFFDF7The profile_background_image_url is : http://abs.twimg.com/images/themes/theme13/bg.gifThe profile_background_image_url_https is : https://abs.twimg.com/images/themes/theme13/bg.gifThe profile_background_tile is : FalseThe profile_image_url is : http://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv_normal.pngThe profile_image_url_https is : https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv_normal.pngThe profile_banner_url is : https://pbs.twimg.com/profile_banners/57741058/1591281311The profile_link_color is : 119E39The profile_sidebar_border_color is : D3D2CFThe profile_sidebar_fill_color is : E3E2DEThe profile_text_color is : 0D0C0C"
},
{
"code": null,
"e": 32525,
"s": 32511,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 32532,
"s": 32525,
"text": "Python"
},
{
"code": null,
"e": 32630,
"s": 32532,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32648,
"s": 32630,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32683,
"s": 32648,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 32705,
"s": 32683,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 32737,
"s": 32705,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32767,
"s": 32737,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 32809,
"s": 32767,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 32835,
"s": 32809,
"text": "Python String | replace()"
},
{
"code": null,
"e": 32872,
"s": 32835,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 32915,
"s": 32872,
"text": "Python program to convert a list to string"
}
] |
Deep Transfer Learning for Image Classification | by Vegard Flovik | Towards Data Science
|
The following tutorial covers how to set up a state of the art deep learning model for image classification. The approach is based on the machine learning frameworks “Tensorflow” and “Keras”, and includes all the code needed to replicate the results in this tutorial (unfortunately, the syntax when including code blocks in medium articles does not look very nice, but it should hopefully be readable).
The prerequisites for setting up the model is access to labelled data, and as an example case I have used images of various traffic signs (which can be downloaded here). The task of the model is thus to predict what kind of traffic sign it sees. To make the example case more realistic, I have reduced the amount of data to max 200 images per class (as limited amount of data is usually the case in practical applications of machine learning).
These images are of course only included as an example to get you started. They can easily be replaced with your own images as long as you follow the same folder structure as the current setup, as explained below.
Place your images in subfolders under the main folder “data/” with the name of the image category as subfolder name, as in the example folder structure shown below. First, you need to split your images into training, validation and test data. The images from the “training_data” folder are the actual images used to train the model, whereas images from “validation_data” are used for optimizing training and model hyper-parameters. The test data is then used as the final assesment, to evaluate the accuracy of the model on a completely independent set of images.
Example folder structure with included dataset:
data/train/category_1 : Images of signs from category 1
data/train/category_2 : Images of signs from category 2
.........................................
data/val/category_1 : Images of signs from category 1
data/val/category_2 : Images of signs from category 2
.........................................
data/test/category_1 : Images of signs from category 1
data/test/category_2 : Images of signs from category 2
.........................................
One way of splitting the images between “train” “validate” and “test” is e.g to use 80% of the images for training the model, and validate/test on 10% each. For a brief introduction to the importance of seperating “train”, “validation” and “test” data, you can also have a read here
These are some useful python libraries/packages that make our life a lot easier, as we do not have to write all the code and functionality from scratch. Building a deep learning model without these libraries/packages would actually be quite a tremendous task!
import numpy as npimport osimport matplotlib.pyplot as pltimport seaborn as snsfrom numpy.random import seedseed(1337)from tensorflow import set_random_seedset_random_seed(42)from tensorflow.python.keras.applications import vgg16from tensorflow.python.keras.applications.vgg16 import preprocess_inputfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator, load_imgfrom tensorflow.python.keras.callbacks import ModelCheckpointfrom tensorflow.python.keras import layers, models, Model, optimizersfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_scorefrom plot_conf_matr import plot_confusion_matrix
Here, we define the location of train/val/test images and the names of all the different categories we want to classify. We then plot the number of images per category in the training set.
train_data_dir = "data/train"val_data_dir = "data/val"test_data_dir = "data/test"category_names = sorted(os.listdir('data/train'))nb_categories = len(category_names)img_pr_cat = []for category in category_names: folder = 'data/train' + '/' + category img_pr_cat.append(len(os.listdir(folder)))sns.barplot(y=category_names, x=img_pr_cat).set_title("Number of training images per category:")
Let us also plot a few example images from the various sign categories, to visualize the typical image quality:
for subdir, dirs, files in os.walk('data/train'): for file in files: img_file = subdir + '/' + file image = load_img(img_file) plt.figure() plt.title(subdir) plt.imshow(image) break
As you can see from the example images above, the resolution and quality are not great. However, both image quality and amount of data are often quite limited in practical applications of machine learning. As such, low quality images limited to a maximum of 200 training images per class represents a more realistic example than using thousands of “perfect” high quality images.
There is no need at this stage to understand all the details of various types of deep learning models, but a summary of some common ways of building models can be found here for those interested.
In this tutorial, we use a pre-trained deep learning model (VGG16) as the basis for our image classifier model, and then retrain the model on our own data, i.e. transfer learning
img_height, img_width = 224,224conv_base = vgg16.VGG16(weights='imagenet', include_top=False, pooling='max', input_shape = (img_width, img_height, 3))
You might notice the parameter “pooling= ‘max’ “ above. The reason for that, is that rather than connecting the convolutional base of the VGG16 model to a couple of fully connected layers before the final output layer (which is done in the original VGG16 model), we rather use a max-pooling output(one can also use “average pooling”, as it depends on the use case which approach works best). This approach is an alternative to using fully connected layers to transition from feature maps to an output prediction for the model. In my experience this approach usually works very well, and makes the model less prone to overfitting, as also described in this paper:
Conventional convolutional neural networks perform convolution in the lower layers of the network. For classification, the feature maps of the last convolutional layer are vectorized and fed into fully connected layers followed by a softmax logistic regression layer. This structure bridges the convolutional structure with traditional neural network classifiers. It treats the convolutional layers as feature extractors, and the resulting feature is classified in a traditional way.
However, the fully connected layers are prone to overfitting, thus hampering the generalization ability of the overall network. In this paper, we propose another strategy called global average pooling to replace the traditional fully connected layers in CNN. Instead of adding fully connected layers on top of the feature maps, we take the average of each feature map, and the resulting vector is fed directly into the softmax layer. One advantage of global average pooling over the fully connected layers is that it is more native to the convolution structure by enforcing correspondences between feature maps and categories. Thus the feature maps can be easily interpreted as categories confidence maps. Another advantage is that there is no parameter to optimize in the global average pooling thus overfitting is avoided at this layer. Futhermore, global average pooling sums out the spatial information, thus it is more robust to spatial translations of the input. We can see global average pooling as a structural regularizer that explicitly enforces feature maps to be confidence maps of concepts (categories).
Having loaded the pre-trained VGG16 model, we can also choose to freeze the “deeper layers” of the model in the code block below, and only re-train the last few layers on our own data. This is a common transfer learning strategy, and is often a good approach when the amount of data available for training is limited.
This option is currently commented out from the code (using the #symbol), and we are thus retraining all layers of the model. The number of layers to train represents a parameter you can experiment with yourselves. How does the number of trainable layers affect model performance?
#for layer in conv_base.layers[:-13]:# layer.trainable = False
As a check we can also print a list of all layers of the model, and whether they are trainable or not (True/False)
for layer in conv_base.layers: print(layer, layer.trainable)
Using the VGG16 model as a basis, we now build a final classification layer on top to predict our defined classes. We then print a model summary, lisiting the number of parameters of the model. If you decide to “freeze” some of the layers, you will notice that the number of “Trainable parameters” below will be lower.
model = models.Sequential()model.add(conv_base)model.add(layers.Dense(nb_categories, activation='softmax'))model.summary()
As you can see, the output shape of the final layer of the model corresponds to the number of classes, which in our case is 10.
We then need to define some functions that read images from our folders and feeds them to the image classifier model. As a part of this we also add some basic image preprocessing, where the input images are scaled to have pixel values in the range [0,1], (from 0–255 in the original images).
#Number of images to load at each iterationbatch_size = 32# only rescalingtrain_datagen = ImageDataGenerator( rescale=1./255)test_datagen = ImageDataGenerator( rescale=1./255)# these are generators for train/test data that will read pictures #found in the defined subfolders of 'data/'print('Total number of images for "training":')train_generator = train_datagen.flow_from_directory(train_data_dir,target_size = (img_height, img_width),batch_size = batch_size, class_mode = "categorical")print('Total number of images for "validation":')val_generator = test_datagen.flow_from_directory(val_data_dir,target_size = (img_height, img_width),batch_size = batch_size,class_mode = "categorical",shuffle=False)print('Total number of images for "testing":')test_generator = test_datagen.flow_from_directory(test_data_dir,target_size = (img_height, img_width),batch_size = batch_size,class_mode = "categorical",shuffle=False)
Here, we define some of the parameters that controls the training process of the model. Important parameters are e.g. training rate, how many epochs to train the model and which optimizer to use. You do not need to understand all these terms to follow the tutorial, but those interested can have a quick read here.
We also define a checkpoint parameter, where we keep track of the validation accuracy after each epoch during training. Using this, we always keep a copy of the model that performs best during the training process.
learning_rate = 5e-5epochs = 10checkpoint = ModelCheckpoint("sign_classifier.h5", monitor = 'val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)model.compile(loss="categorical_crossentropy", optimizer=optimizers.Adam(lr=learning_rate, clipnorm = 1.), metrics = ['acc'])
We are now ready to start training the model on our own data, and for each “epoch” we print the training and validation loss and accuracy. The model accuracy, as measured on the training data, is given by “acc”, and the accuracy on the images in the validation set is given by “val_acc”. This is the most important quantity, as it tells us how accurate the model is on images it has not already seen during the training process.
Ideally, the “val_acc” should increase for each epoch as we keep training the model, and eventually reach a steady value when our model is not able to learn any more useful information from our training data.
history = model.fit_generator(train_generator, epochs=epochs, shuffle=True, validation_data=val_generator, callbacks=[checkpoint] )
From the output shown above, we see that the loss decreases while the accuracy increases during the training process. Each time the validation accuracy reaches a new maximum value, the checkpoint file is saved (output: “saving model to sign_classifier.h5”. After the training has completed, we then load the checkpoint file which had the best validation accuracy during training:
model = models.load_model("sign_classifier.h5")
We first visualize the changes in model accuracy and loss during the training process, as this gives us important information to evaluate what we can do to improve accuracy. For a nice introduction to this topic, you can also have a look at this video:
Code for plotting and saving the learning curves:
acc = 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.figure()plt.plot(epochs, acc, 'b', label = 'Training accuracy')plt.plot(epochs, val_acc, 'r', label='Validation accuracy')plt.title('Training and validation accuracy')plt.legend()plt.savefig('Accuracy.jpg')plt.figure()plt.plot(epochs, loss, 'b', label = 'Training loss')plt.plot(epochs, val_loss, 'r', label='Validation loss')plt.title('Training and validation loss')plt.legend()plt.savefig('Loss.jpg')
Starting with the left figure, showing the training/valication accuracy: The blue line represents the model accuracy as measured on the training images, and we see that this quickly reaches a value of almost 1 (which represents classifying 100% of the training images correctly). However, the validation accuracy is the accuracy measured on the validation set, which is the accuracy we really care about. In this case, the accuracy leveled off at around 97–98%, meaning that we succesfully classified almost all of the images in our validation set to the correct category.
To learn more about the accuracy for the different categories, we can calculate and plot the “confusion matrix”. This represents an illustrative way of evaluating model accuracy, as it compares the “true” vs. “predicted” class for all images in the test set. Note: do not worry if you do not get exactly the same numbers when re-running the code! There are some inherent randomness in model initialization etc. which make the results differ slightly from time to time.
(The code to calculate and plot the confusion matrix is included below the figure)
Y_pred = model.predict_generator(test_generator)y_pred = np.argmax(Y_pred, axis=1)cm = confusion_matrix(test_generator.classes, y_pred)plot_confusion_matrix(cm, classes = category_names, title='Confusion Matrix', normalize=False, figname = 'Confusion_matrix_concrete.jpg')
The is the code from the script “plot_conf.py”, which contains the function for plotting the confusion matrix, “plot_confusion_matrix”.
import numpy as npimport matplotlib.pyplot as pltdef plot_confusion_matrix(cm, classes, figname, normalize=False, title=’Confusion matrix’, cmap=plt.cm.Blues): “”” This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. “”” import numpy as np import matplotlib.pyplot as plt import itertools if normalize: cm = cm.astype(‘float’) / cm.sum(axis=1)[:, np.newaxis] print(“Normalized confusion matrix”) else: print(‘Confusion matrix, without normalization’)plt.figure(figsize=(8,8)) plt.imshow(cm, interpolation=’nearest’, cmap=cmap) plt.title(title) #plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes)fmt = ‘.2f’ if normalize else ‘d’ thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=”center”, color=”white” if cm[i, j] > thresh else “black”)plt.ylabel(‘True label’) plt.xlabel(‘Predicted label’) plt.tight_layout() plt.savefig(figname)
As seen from the confusion matrix above, the main category the model misclassified was“Intersection”, where it mistakes the category with that of “Yield” in 10 of the images. As a final metric, we can also calculate the total accuracy evaluated on the test set
accuracy = accuracy_score(test_generator.classes, y_pred)print("Accuracy in test set: %0.1f%% " % (accuracy * 100))
This gives as output an accuracy of 98%, which is not bad! But, can we do better? We have a limited amount of data, so how about trying to improve that using image augmentation?
In our case, the model already performs very well, with an accuracy of 97–98%. However, one strategy when dealing with limited amount of training data is that of “image augmentation”. That is, we make a collection of copies of the existing images, but with some minor changes. Those changes could be transformations like e.g. slight rotations, zooming, flipping images horizontally, ++. Further examples of image augmentation are also covered here.
In the following, we define the same model as before, but here we also incorporate image augmentation as a way of artficially increasing the amount of training data.
Code to build a new model, using the same convolutional base and model structure as before:
conv_base = vgg16.VGG16(weights='imagenet', include_top=False, pooling='max', input_shape = (img_width, img_height, 3))#for layer in conv_base.layers[:-13]:# layer.trainable = Falsemodel = models.Sequential()model.add(conv_base)model.add(layers.Dense(nb_categories, activation='softmax'))
The only thing we need to change in our code, is the definition of the training data generator shown below. We can here add some data augmentation strategies, such as e.g. random rotations in the range [-10,10] degrees, a random zoom and width/height shift in the range +-10%, and changes in brightness in the range +-10%.
As examples of augmented images, we can save them to a specified folder “augm_images” as defined in the function “train_generator” below. This option is currently commented out (to avoid saving thousands of images), but you can change that if you want to visualize the augmentations you incorporate. This is often a good idea, just to make sure that the augmented images still make sense for the use-case you are working on.
train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=10, zoom_range=0.1, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=False, brightness_range = (0.9,1.1), fill_mode='nearest' )# this is a generator that will read pictures found in# subfolers of 'data/train', and indefinitely generate# batches of augmented image datatrain_generator = train_datagen.flow_from_directory(train_data_dir,target_size = (img_height, img_width),batch_size = batch_size, #save_to_dir='augm_images', save_prefix='aug', save_format='jpg',class_mode = "categorical")
We are now ready to train the same model using additional augmented data, which should hopefully increase model accuracy.
learning_rate = 5e-5epochs = 20checkpoint = ModelCheckpoint("sign_classifier_augm.h5", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)model.compile(loss="categorical_crossentropy", optimizer=optimizers.Adam(lr=learning_rate, clipnorm=1.), metrics = ['acc'])history = model.fit_generator(train_generator, epochs=epochs, shuffle=True, validation_data=test_generator, callbacks=[checkpoint] )
After the training has completed, we again load the checkpoint file which had the best validation accuracy during training:
model = models.load_model("sign_classifier_augm.h5")
acc = 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.figure()plt.plot(epochs, acc, 'b', label = 'Training accuracy')plt.plot(epochs, val_acc, 'r', label='Validation accuracy')plt.title('Training and validation accuracy')plt.legend()#plt.savefig('Accuracy_Augmented.jpg')plt.figure()plt.plot(epochs, loss, 'b', label = 'Training loss')plt.plot(epochs, val_loss, 'r', label='Validation loss')plt.title('Training and validation loss')plt.legend()#plt.savefig('Loss_Augmented.jpg')
Y_pred = model.predict_generator(test_generator)y_pred = np.argmax(Y_pred, axis=1)cm_aug = confusion_matrix(test_generator.classes, y_pred)plot_confusion_matrix(cm_aug, classes = category_names, title='Confusion Matrix', normalize=False, figname = 'Confusion_matrix_Augm.jpg')
Calculate the final accuracy, as evaluated on the test set:
accuracy = accuracy_score(test_generator.classes, y_pred)print("Accuracy in test set: %0.1f%% " % (accuracy * 100))
This gives an output of 99.3%, which is an improvement compared to our initial model without augmented images!
As seen from the above results for model accuracy, data augmentation indeed increased the accuracy of our model. In the current example, we obtained a final accuracy of approximately 99%. In addition, by inspecting the confusion matrix above, we can check which of the sign categories the model classifies incorrectly. Here, we notice that the model still misclassified “Intersection” as “Yield” in a few cases, but significantly better than the model without image augmentation.
Note: Do not worry if you do not get exactly the same numbers when re-running the code! There is some inherent randomness in the model initialization etc. which could make the results differ slightly from time to time.
As a final visualization of model accuracy, we can plot a subset of the test images along with the corresponding model prediction.
Define a folder for “test_subset”, where I have included 50 of the images from the test set:
test_subset_data_dir = "data/test_subset"test_subset_generator = test_datagen.flow_from_directory(test_subset_data_dir,batch_size = batch_size,target_size = (img_height, img_width),class_mode = "categorical",shuffle=False)
Make predictions for the images contained in this folder, and visualize the images along with the predicted and actual class. Do you agree with the classifications?
Y_pred = model.predict_generator(test_subset_generator)y_pred = np.argmax(Y_pred, axis=1)img_nr = 0for subdir, dirs, files in os.walk('data/test_subset'): for file in files: img_file = subdir + '/' + file image = load_img(img_file,target_size=(img_height,img_width)) pred_emotion = category_names[y_pred[img_nr]] real_emotion = category_names[test_subset_generator.classes[img_nr]] plt.figure() plt.title('Predicted: ' + pred_emotion + '\n' + 'Actual: ' + real_emotion) plt.imshow(image) img_nr = img_nr +1
If you managed to run through the entire tutorial using the included dataset, you have hopefully gotten a feeling for how deep learning and image recognition can be used to solve a real-world problem of traffic sign classification. Best of luck exploring the model further with other images, either from your company or from resources such as e.g. kaggle, or simply google image search!
If you want some more detailed information regarding this image classification tutorial (and machine learning in general), I also cover the material in the workshop presentation below: “ From hype to real-world applications”. (tutorial walkthrough starts approx. 35 minutes into the video).
Good luck!
Did you find the article interesting? If so, you might also like some of my other articles on topics such as AI, Machine Learning, physics, etc., which you can find in the links below and on my medium author profile: https://medium.com/@vflovik
And, if you would like to become a Medium member to access all material on the platform freely, you can also do so using my referral link below. (Note: If you sign up using this link, I will also receive a portion of the membership fee)
medium.com
A Gentle Introduction to Monte Carlo MethodsThe transition from Physics to Data ScienceWhat is Graph theory, and why should you care?How (not) to use Machine Learning for time series forecasting: The sequelBuilding an AI that can read your mindThe hidden risk of AI and Big DataHow to use machine learning for anomaly detection and condition monitoringHow (not) to use Machine Learning for time series forecasting: Avoiding the pitfallsHow to use machine learning for production optimization: Using data to improve performanceHow do you teach physics to AI systems?Can we build artificial brain networks using nanoscale magnets?Artificial Intelligence in Supply Chain Management: Utilizing data to drive operational performance
A Gentle Introduction to Monte Carlo Methods
The transition from Physics to Data Science
What is Graph theory, and why should you care?
How (not) to use Machine Learning for time series forecasting: The sequel
Building an AI that can read your mind
The hidden risk of AI and Big Data
How to use machine learning for anomaly detection and condition monitoring
How (not) to use Machine Learning for time series forecasting: Avoiding the pitfalls
How to use machine learning for production optimization: Using data to improve performance
How do you teach physics to AI systems?
Can we build artificial brain networks using nanoscale magnets?
Artificial Intelligence in Supply Chain Management: Utilizing data to drive operational performance
|
[
{
"code": null,
"e": 575,
"s": 172,
"text": "The following tutorial covers how to set up a state of the art deep learning model for image classification. The approach is based on the machine learning frameworks “Tensorflow” and “Keras”, and includes all the code needed to replicate the results in this tutorial (unfortunately, the syntax when including code blocks in medium articles does not look very nice, but it should hopefully be readable)."
},
{
"code": null,
"e": 1019,
"s": 575,
"text": "The prerequisites for setting up the model is access to labelled data, and as an example case I have used images of various traffic signs (which can be downloaded here). The task of the model is thus to predict what kind of traffic sign it sees. To make the example case more realistic, I have reduced the amount of data to max 200 images per class (as limited amount of data is usually the case in practical applications of machine learning)."
},
{
"code": null,
"e": 1233,
"s": 1019,
"text": "These images are of course only included as an example to get you started. They can easily be replaced with your own images as long as you follow the same folder structure as the current setup, as explained below."
},
{
"code": null,
"e": 1797,
"s": 1233,
"text": "Place your images in subfolders under the main folder “data/” with the name of the image category as subfolder name, as in the example folder structure shown below. First, you need to split your images into training, validation and test data. The images from the “training_data” folder are the actual images used to train the model, whereas images from “validation_data” are used for optimizing training and model hyper-parameters. The test data is then used as the final assesment, to evaluate the accuracy of the model on a completely independent set of images."
},
{
"code": null,
"e": 1845,
"s": 1797,
"text": "Example folder structure with included dataset:"
},
{
"code": null,
"e": 1901,
"s": 1845,
"text": "data/train/category_1 : Images of signs from category 1"
},
{
"code": null,
"e": 1957,
"s": 1901,
"text": "data/train/category_2 : Images of signs from category 2"
},
{
"code": null,
"e": 1999,
"s": 1957,
"text": "........................................."
},
{
"code": null,
"e": 2053,
"s": 1999,
"text": "data/val/category_1 : Images of signs from category 1"
},
{
"code": null,
"e": 2107,
"s": 2053,
"text": "data/val/category_2 : Images of signs from category 2"
},
{
"code": null,
"e": 2149,
"s": 2107,
"text": "........................................."
},
{
"code": null,
"e": 2204,
"s": 2149,
"text": "data/test/category_1 : Images of signs from category 1"
},
{
"code": null,
"e": 2259,
"s": 2204,
"text": "data/test/category_2 : Images of signs from category 2"
},
{
"code": null,
"e": 2301,
"s": 2259,
"text": "........................................."
},
{
"code": null,
"e": 2584,
"s": 2301,
"text": "One way of splitting the images between “train” “validate” and “test” is e.g to use 80% of the images for training the model, and validate/test on 10% each. For a brief introduction to the importance of seperating “train”, “validation” and “test” data, you can also have a read here"
},
{
"code": null,
"e": 2844,
"s": 2584,
"text": "These are some useful python libraries/packages that make our life a lot easier, as we do not have to write all the code and functionality from scratch. Building a deep learning model without these libraries/packages would actually be quite a tremendous task!"
},
{
"code": null,
"e": 3490,
"s": 2844,
"text": "import numpy as npimport osimport matplotlib.pyplot as pltimport seaborn as snsfrom numpy.random import seedseed(1337)from tensorflow import set_random_seedset_random_seed(42)from tensorflow.python.keras.applications import vgg16from tensorflow.python.keras.applications.vgg16 import preprocess_inputfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator, load_imgfrom tensorflow.python.keras.callbacks import ModelCheckpointfrom tensorflow.python.keras import layers, models, Model, optimizersfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_scorefrom plot_conf_matr import plot_confusion_matrix"
},
{
"code": null,
"e": 3679,
"s": 3490,
"text": "Here, we define the location of train/val/test images and the names of all the different categories we want to classify. We then plot the number of images per category in the training set."
},
{
"code": null,
"e": 4075,
"s": 3679,
"text": "train_data_dir = \"data/train\"val_data_dir = \"data/val\"test_data_dir = \"data/test\"category_names = sorted(os.listdir('data/train'))nb_categories = len(category_names)img_pr_cat = []for category in category_names: folder = 'data/train' + '/' + category img_pr_cat.append(len(os.listdir(folder)))sns.barplot(y=category_names, x=img_pr_cat).set_title(\"Number of training images per category:\")"
},
{
"code": null,
"e": 4187,
"s": 4075,
"text": "Let us also plot a few example images from the various sign categories, to visualize the typical image quality:"
},
{
"code": null,
"e": 4414,
"s": 4187,
"text": "for subdir, dirs, files in os.walk('data/train'): for file in files: img_file = subdir + '/' + file image = load_img(img_file) plt.figure() plt.title(subdir) plt.imshow(image) break"
},
{
"code": null,
"e": 4793,
"s": 4414,
"text": "As you can see from the example images above, the resolution and quality are not great. However, both image quality and amount of data are often quite limited in practical applications of machine learning. As such, low quality images limited to a maximum of 200 training images per class represents a more realistic example than using thousands of “perfect” high quality images."
},
{
"code": null,
"e": 4989,
"s": 4793,
"text": "There is no need at this stage to understand all the details of various types of deep learning models, but a summary of some common ways of building models can be found here for those interested."
},
{
"code": null,
"e": 5168,
"s": 4989,
"text": "In this tutorial, we use a pre-trained deep learning model (VGG16) as the basis for our image classifier model, and then retrain the model on our own data, i.e. transfer learning"
},
{
"code": null,
"e": 5319,
"s": 5168,
"text": "img_height, img_width = 224,224conv_base = vgg16.VGG16(weights='imagenet', include_top=False, pooling='max', input_shape = (img_width, img_height, 3))"
},
{
"code": null,
"e": 5982,
"s": 5319,
"text": "You might notice the parameter “pooling= ‘max’ “ above. The reason for that, is that rather than connecting the convolutional base of the VGG16 model to a couple of fully connected layers before the final output layer (which is done in the original VGG16 model), we rather use a max-pooling output(one can also use “average pooling”, as it depends on the use case which approach works best). This approach is an alternative to using fully connected layers to transition from feature maps to an output prediction for the model. In my experience this approach usually works very well, and makes the model less prone to overfitting, as also described in this paper:"
},
{
"code": null,
"e": 6466,
"s": 5982,
"text": "Conventional convolutional neural networks perform convolution in the lower layers of the network. For classification, the feature maps of the last convolutional layer are vectorized and fed into fully connected layers followed by a softmax logistic regression layer. This structure bridges the convolutional structure with traditional neural network classifiers. It treats the convolutional layers as feature extractors, and the resulting feature is classified in a traditional way."
},
{
"code": null,
"e": 7583,
"s": 6466,
"text": "However, the fully connected layers are prone to overfitting, thus hampering the generalization ability of the overall network. In this paper, we propose another strategy called global average pooling to replace the traditional fully connected layers in CNN. Instead of adding fully connected layers on top of the feature maps, we take the average of each feature map, and the resulting vector is fed directly into the softmax layer. One advantage of global average pooling over the fully connected layers is that it is more native to the convolution structure by enforcing correspondences between feature maps and categories. Thus the feature maps can be easily interpreted as categories confidence maps. Another advantage is that there is no parameter to optimize in the global average pooling thus overfitting is avoided at this layer. Futhermore, global average pooling sums out the spatial information, thus it is more robust to spatial translations of the input. We can see global average pooling as a structural regularizer that explicitly enforces feature maps to be confidence maps of concepts (categories)."
},
{
"code": null,
"e": 7901,
"s": 7583,
"text": "Having loaded the pre-trained VGG16 model, we can also choose to freeze the “deeper layers” of the model in the code block below, and only re-train the last few layers on our own data. This is a common transfer learning strategy, and is often a good approach when the amount of data available for training is limited."
},
{
"code": null,
"e": 8182,
"s": 7901,
"text": "This option is currently commented out from the code (using the #symbol), and we are thus retraining all layers of the model. The number of layers to train represents a parameter you can experiment with yourselves. How does the number of trainable layers affect model performance?"
},
{
"code": null,
"e": 8248,
"s": 8182,
"text": "#for layer in conv_base.layers[:-13]:# layer.trainable = False"
},
{
"code": null,
"e": 8363,
"s": 8248,
"text": "As a check we can also print a list of all layers of the model, and whether they are trainable or not (True/False)"
},
{
"code": null,
"e": 8427,
"s": 8363,
"text": "for layer in conv_base.layers: print(layer, layer.trainable)"
},
{
"code": null,
"e": 8746,
"s": 8427,
"text": "Using the VGG16 model as a basis, we now build a final classification layer on top to predict our defined classes. We then print a model summary, lisiting the number of parameters of the model. If you decide to “freeze” some of the layers, you will notice that the number of “Trainable parameters” below will be lower."
},
{
"code": null,
"e": 8869,
"s": 8746,
"text": "model = models.Sequential()model.add(conv_base)model.add(layers.Dense(nb_categories, activation='softmax'))model.summary()"
},
{
"code": null,
"e": 8997,
"s": 8869,
"text": "As you can see, the output shape of the final layer of the model corresponds to the number of classes, which in our case is 10."
},
{
"code": null,
"e": 9289,
"s": 8997,
"text": "We then need to define some functions that read images from our folders and feeds them to the image classifier model. As a part of this we also add some basic image preprocessing, where the input images are scaled to have pixel values in the range [0,1], (from 0–255 in the original images)."
},
{
"code": null,
"e": 10214,
"s": 9289,
"text": "#Number of images to load at each iterationbatch_size = 32# only rescalingtrain_datagen = ImageDataGenerator( rescale=1./255)test_datagen = ImageDataGenerator( rescale=1./255)# these are generators for train/test data that will read pictures #found in the defined subfolders of 'data/'print('Total number of images for \"training\":')train_generator = train_datagen.flow_from_directory(train_data_dir,target_size = (img_height, img_width),batch_size = batch_size, class_mode = \"categorical\")print('Total number of images for \"validation\":')val_generator = test_datagen.flow_from_directory(val_data_dir,target_size = (img_height, img_width),batch_size = batch_size,class_mode = \"categorical\",shuffle=False)print('Total number of images for \"testing\":')test_generator = test_datagen.flow_from_directory(test_data_dir,target_size = (img_height, img_width),batch_size = batch_size,class_mode = \"categorical\",shuffle=False)"
},
{
"code": null,
"e": 10529,
"s": 10214,
"text": "Here, we define some of the parameters that controls the training process of the model. Important parameters are e.g. training rate, how many epochs to train the model and which optimizer to use. You do not need to understand all these terms to follow the tutorial, but those interested can have a quick read here."
},
{
"code": null,
"e": 10744,
"s": 10529,
"text": "We also define a checkpoint parameter, where we keep track of the validation accuracy after each epoch during training. Using this, we always keep a copy of the model that performs best during the training process."
},
{
"code": null,
"e": 11052,
"s": 10744,
"text": "learning_rate = 5e-5epochs = 10checkpoint = ModelCheckpoint(\"sign_classifier.h5\", monitor = 'val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)model.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=learning_rate, clipnorm = 1.), metrics = ['acc'])"
},
{
"code": null,
"e": 11481,
"s": 11052,
"text": "We are now ready to start training the model on our own data, and for each “epoch” we print the training and validation loss and accuracy. The model accuracy, as measured on the training data, is given by “acc”, and the accuracy on the images in the validation set is given by “val_acc”. This is the most important quantity, as it tells us how accurate the model is on images it has not already seen during the training process."
},
{
"code": null,
"e": 11690,
"s": 11481,
"text": "Ideally, the “val_acc” should increase for each epoch as we keep training the model, and eventually reach a steady value when our model is not able to learn any more useful information from our training data."
},
{
"code": null,
"e": 11970,
"s": 11690,
"text": "history = model.fit_generator(train_generator, epochs=epochs, shuffle=True, validation_data=val_generator, callbacks=[checkpoint] )"
},
{
"code": null,
"e": 12350,
"s": 11970,
"text": "From the output shown above, we see that the loss decreases while the accuracy increases during the training process. Each time the validation accuracy reaches a new maximum value, the checkpoint file is saved (output: “saving model to sign_classifier.h5”. After the training has completed, we then load the checkpoint file which had the best validation accuracy during training:"
},
{
"code": null,
"e": 12398,
"s": 12350,
"text": "model = models.load_model(\"sign_classifier.h5\")"
},
{
"code": null,
"e": 12651,
"s": 12398,
"text": "We first visualize the changes in model accuracy and loss during the training process, as this gives us important information to evaluate what we can do to improve accuracy. For a nice introduction to this topic, you can also have a look at this video:"
},
{
"code": null,
"e": 12701,
"s": 12651,
"text": "Code for plotting and saving the learning curves:"
},
{
"code": null,
"e": 13268,
"s": 12701,
"text": "acc = 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.figure()plt.plot(epochs, acc, 'b', label = 'Training accuracy')plt.plot(epochs, val_acc, 'r', label='Validation accuracy')plt.title('Training and validation accuracy')plt.legend()plt.savefig('Accuracy.jpg')plt.figure()plt.plot(epochs, loss, 'b', label = 'Training loss')plt.plot(epochs, val_loss, 'r', label='Validation loss')plt.title('Training and validation loss')plt.legend()plt.savefig('Loss.jpg')"
},
{
"code": null,
"e": 13841,
"s": 13268,
"text": "Starting with the left figure, showing the training/valication accuracy: The blue line represents the model accuracy as measured on the training images, and we see that this quickly reaches a value of almost 1 (which represents classifying 100% of the training images correctly). However, the validation accuracy is the accuracy measured on the validation set, which is the accuracy we really care about. In this case, the accuracy leveled off at around 97–98%, meaning that we succesfully classified almost all of the images in our validation set to the correct category."
},
{
"code": null,
"e": 14310,
"s": 13841,
"text": "To learn more about the accuracy for the different categories, we can calculate and plot the “confusion matrix”. This represents an illustrative way of evaluating model accuracy, as it compares the “true” vs. “predicted” class for all images in the test set. Note: do not worry if you do not get exactly the same numbers when re-running the code! There are some inherent randomness in model initialization etc. which make the results differ slightly from time to time."
},
{
"code": null,
"e": 14393,
"s": 14310,
"text": "(The code to calculate and plot the confusion matrix is included below the figure)"
},
{
"code": null,
"e": 14666,
"s": 14393,
"text": "Y_pred = model.predict_generator(test_generator)y_pred = np.argmax(Y_pred, axis=1)cm = confusion_matrix(test_generator.classes, y_pred)plot_confusion_matrix(cm, classes = category_names, title='Confusion Matrix', normalize=False, figname = 'Confusion_matrix_concrete.jpg')"
},
{
"code": null,
"e": 14802,
"s": 14666,
"text": "The is the code from the script “plot_conf.py”, which contains the function for plotting the confusion matrix, “plot_confusion_matrix”."
},
{
"code": null,
"e": 15872,
"s": 14802,
"text": "import numpy as npimport matplotlib.pyplot as pltdef plot_confusion_matrix(cm, classes, figname, normalize=False, title=’Confusion matrix’, cmap=plt.cm.Blues): “”” This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. “”” import numpy as np import matplotlib.pyplot as plt import itertools if normalize: cm = cm.astype(‘float’) / cm.sum(axis=1)[:, np.newaxis] print(“Normalized confusion matrix”) else: print(‘Confusion matrix, without normalization’)plt.figure(figsize=(8,8)) plt.imshow(cm, interpolation=’nearest’, cmap=cmap) plt.title(title) #plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes)fmt = ‘.2f’ if normalize else ‘d’ thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=”center”, color=”white” if cm[i, j] > thresh else “black”)plt.ylabel(‘True label’) plt.xlabel(‘Predicted label’) plt.tight_layout() plt.savefig(figname)"
},
{
"code": null,
"e": 16133,
"s": 15872,
"text": "As seen from the confusion matrix above, the main category the model misclassified was“Intersection”, where it mistakes the category with that of “Yield” in 10 of the images. As a final metric, we can also calculate the total accuracy evaluated on the test set"
},
{
"code": null,
"e": 16249,
"s": 16133,
"text": "accuracy = accuracy_score(test_generator.classes, y_pred)print(\"Accuracy in test set: %0.1f%% \" % (accuracy * 100))"
},
{
"code": null,
"e": 16427,
"s": 16249,
"text": "This gives as output an accuracy of 98%, which is not bad! But, can we do better? We have a limited amount of data, so how about trying to improve that using image augmentation?"
},
{
"code": null,
"e": 16876,
"s": 16427,
"text": "In our case, the model already performs very well, with an accuracy of 97–98%. However, one strategy when dealing with limited amount of training data is that of “image augmentation”. That is, we make a collection of copies of the existing images, but with some minor changes. Those changes could be transformations like e.g. slight rotations, zooming, flipping images horizontally, ++. Further examples of image augmentation are also covered here."
},
{
"code": null,
"e": 17042,
"s": 16876,
"text": "In the following, we define the same model as before, but here we also incorporate image augmentation as a way of artficially increasing the amount of training data."
},
{
"code": null,
"e": 17134,
"s": 17042,
"text": "Code to build a new model, using the same convolutional base and model structure as before:"
},
{
"code": null,
"e": 17426,
"s": 17134,
"text": "conv_base = vgg16.VGG16(weights='imagenet', include_top=False, pooling='max', input_shape = (img_width, img_height, 3))#for layer in conv_base.layers[:-13]:# layer.trainable = Falsemodel = models.Sequential()model.add(conv_base)model.add(layers.Dense(nb_categories, activation='softmax'))"
},
{
"code": null,
"e": 17749,
"s": 17426,
"text": "The only thing we need to change in our code, is the definition of the training data generator shown below. We can here add some data augmentation strategies, such as e.g. random rotations in the range [-10,10] degrees, a random zoom and width/height shift in the range +-10%, and changes in brightness in the range +-10%."
},
{
"code": null,
"e": 18174,
"s": 17749,
"text": "As examples of augmented images, we can save them to a specified folder “augm_images” as defined in the function “train_generator” below. This option is currently commented out (to avoid saving thousands of images), but you can change that if you want to visualize the augmentations you incorporate. This is often a good idea, just to make sure that the augmented images still make sense for the use-case you are working on."
},
{
"code": null,
"e": 18809,
"s": 18174,
"text": "train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=10, zoom_range=0.1, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=False, brightness_range = (0.9,1.1), fill_mode='nearest' )# this is a generator that will read pictures found in# subfolers of 'data/train', and indefinitely generate# batches of augmented image datatrain_generator = train_datagen.flow_from_directory(train_data_dir,target_size = (img_height, img_width),batch_size = batch_size, #save_to_dir='augm_images', save_prefix='aug', save_format='jpg',class_mode = \"categorical\")"
},
{
"code": null,
"e": 18931,
"s": 18809,
"text": "We are now ready to train the same model using additional augmented data, which should hopefully increase model accuracy."
},
{
"code": null,
"e": 19520,
"s": 18931,
"text": "learning_rate = 5e-5epochs = 20checkpoint = ModelCheckpoint(\"sign_classifier_augm.h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)model.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=learning_rate, clipnorm=1.), metrics = ['acc'])history = model.fit_generator(train_generator, epochs=epochs, shuffle=True, validation_data=test_generator, callbacks=[checkpoint] )"
},
{
"code": null,
"e": 19644,
"s": 19520,
"text": "After the training has completed, we again load the checkpoint file which had the best validation accuracy during training:"
},
{
"code": null,
"e": 19697,
"s": 19644,
"text": "model = models.load_model(\"sign_classifier_augm.h5\")"
},
{
"code": null,
"e": 20286,
"s": 19697,
"text": "acc = 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.figure()plt.plot(epochs, acc, 'b', label = 'Training accuracy')plt.plot(epochs, val_acc, 'r', label='Validation accuracy')plt.title('Training and validation accuracy')plt.legend()#plt.savefig('Accuracy_Augmented.jpg')plt.figure()plt.plot(epochs, loss, 'b', label = 'Training loss')plt.plot(epochs, val_loss, 'r', label='Validation loss')plt.title('Training and validation loss')plt.legend()#plt.savefig('Loss_Augmented.jpg')"
},
{
"code": null,
"e": 20563,
"s": 20286,
"text": "Y_pred = model.predict_generator(test_generator)y_pred = np.argmax(Y_pred, axis=1)cm_aug = confusion_matrix(test_generator.classes, y_pred)plot_confusion_matrix(cm_aug, classes = category_names, title='Confusion Matrix', normalize=False, figname = 'Confusion_matrix_Augm.jpg')"
},
{
"code": null,
"e": 20623,
"s": 20563,
"text": "Calculate the final accuracy, as evaluated on the test set:"
},
{
"code": null,
"e": 20739,
"s": 20623,
"text": "accuracy = accuracy_score(test_generator.classes, y_pred)print(\"Accuracy in test set: %0.1f%% \" % (accuracy * 100))"
},
{
"code": null,
"e": 20850,
"s": 20739,
"text": "This gives an output of 99.3%, which is an improvement compared to our initial model without augmented images!"
},
{
"code": null,
"e": 21330,
"s": 20850,
"text": "As seen from the above results for model accuracy, data augmentation indeed increased the accuracy of our model. In the current example, we obtained a final accuracy of approximately 99%. In addition, by inspecting the confusion matrix above, we can check which of the sign categories the model classifies incorrectly. Here, we notice that the model still misclassified “Intersection” as “Yield” in a few cases, but significantly better than the model without image augmentation."
},
{
"code": null,
"e": 21549,
"s": 21330,
"text": "Note: Do not worry if you do not get exactly the same numbers when re-running the code! There is some inherent randomness in the model initialization etc. which could make the results differ slightly from time to time."
},
{
"code": null,
"e": 21680,
"s": 21549,
"text": "As a final visualization of model accuracy, we can plot a subset of the test images along with the corresponding model prediction."
},
{
"code": null,
"e": 21773,
"s": 21680,
"text": "Define a folder for “test_subset”, where I have included 50 of the images from the test set:"
},
{
"code": null,
"e": 21996,
"s": 21773,
"text": "test_subset_data_dir = \"data/test_subset\"test_subset_generator = test_datagen.flow_from_directory(test_subset_data_dir,batch_size = batch_size,target_size = (img_height, img_width),class_mode = \"categorical\",shuffle=False)"
},
{
"code": null,
"e": 22161,
"s": 21996,
"text": "Make predictions for the images contained in this folder, and visualize the images along with the predicted and actual class. Do you agree with the classifications?"
},
{
"code": null,
"e": 22732,
"s": 22161,
"text": "Y_pred = model.predict_generator(test_subset_generator)y_pred = np.argmax(Y_pred, axis=1)img_nr = 0for subdir, dirs, files in os.walk('data/test_subset'): for file in files: img_file = subdir + '/' + file image = load_img(img_file,target_size=(img_height,img_width)) pred_emotion = category_names[y_pred[img_nr]] real_emotion = category_names[test_subset_generator.classes[img_nr]] plt.figure() plt.title('Predicted: ' + pred_emotion + '\\n' + 'Actual: ' + real_emotion) plt.imshow(image) img_nr = img_nr +1"
},
{
"code": null,
"e": 23119,
"s": 22732,
"text": "If you managed to run through the entire tutorial using the included dataset, you have hopefully gotten a feeling for how deep learning and image recognition can be used to solve a real-world problem of traffic sign classification. Best of luck exploring the model further with other images, either from your company or from resources such as e.g. kaggle, or simply google image search!"
},
{
"code": null,
"e": 23410,
"s": 23119,
"text": "If you want some more detailed information regarding this image classification tutorial (and machine learning in general), I also cover the material in the workshop presentation below: “ From hype to real-world applications”. (tutorial walkthrough starts approx. 35 minutes into the video)."
},
{
"code": null,
"e": 23421,
"s": 23410,
"text": "Good luck!"
},
{
"code": null,
"e": 23666,
"s": 23421,
"text": "Did you find the article interesting? If so, you might also like some of my other articles on topics such as AI, Machine Learning, physics, etc., which you can find in the links below and on my medium author profile: https://medium.com/@vflovik"
},
{
"code": null,
"e": 23903,
"s": 23666,
"text": "And, if you would like to become a Medium member to access all material on the platform freely, you can also do so using my referral link below. (Note: If you sign up using this link, I will also receive a portion of the membership fee)"
},
{
"code": null,
"e": 23914,
"s": 23903,
"text": "medium.com"
},
{
"code": null,
"e": 24642,
"s": 23914,
"text": "A Gentle Introduction to Monte Carlo MethodsThe transition from Physics to Data ScienceWhat is Graph theory, and why should you care?How (not) to use Machine Learning for time series forecasting: The sequelBuilding an AI that can read your mindThe hidden risk of AI and Big DataHow to use machine learning for anomaly detection and condition monitoringHow (not) to use Machine Learning for time series forecasting: Avoiding the pitfallsHow to use machine learning for production optimization: Using data to improve performanceHow do you teach physics to AI systems?Can we build artificial brain networks using nanoscale magnets?Artificial Intelligence in Supply Chain Management: Utilizing data to drive operational performance"
},
{
"code": null,
"e": 24687,
"s": 24642,
"text": "A Gentle Introduction to Monte Carlo Methods"
},
{
"code": null,
"e": 24731,
"s": 24687,
"text": "The transition from Physics to Data Science"
},
{
"code": null,
"e": 24778,
"s": 24731,
"text": "What is Graph theory, and why should you care?"
},
{
"code": null,
"e": 24852,
"s": 24778,
"text": "How (not) to use Machine Learning for time series forecasting: The sequel"
},
{
"code": null,
"e": 24891,
"s": 24852,
"text": "Building an AI that can read your mind"
},
{
"code": null,
"e": 24926,
"s": 24891,
"text": "The hidden risk of AI and Big Data"
},
{
"code": null,
"e": 25001,
"s": 24926,
"text": "How to use machine learning for anomaly detection and condition monitoring"
},
{
"code": null,
"e": 25086,
"s": 25001,
"text": "How (not) to use Machine Learning for time series forecasting: Avoiding the pitfalls"
},
{
"code": null,
"e": 25177,
"s": 25086,
"text": "How to use machine learning for production optimization: Using data to improve performance"
},
{
"code": null,
"e": 25217,
"s": 25177,
"text": "How do you teach physics to AI systems?"
},
{
"code": null,
"e": 25281,
"s": 25217,
"text": "Can we build artificial brain networks using nanoscale magnets?"
}
] |
Introduction to Keras, Part One: Data Loading | by Samhita Alla | Towards Data Science
|
Keras is a Deep Learning API of TensorFlow 2.0 used for easy and fast experimentation. It is simple to understand, flexible to extend and deploy, and powerful enough to build any neural network.
With the increase in the usage of deep learning to solve real-time problems, it has become quite a necessity to lessen the time consumed to build robust machine learning algorithms, i.e., the time taken from designing an algorithm to putting it into practice to generate the desired model has to be minimal.
Keras has been designed for this very purpose. It is a high-level deep learning API running on top of TensorFlow, a machine learning/deep learning framework. It provides an easy to use, modular, and an organised interface to solve deep learning problems. It is simple to understand and is expressive. It is a flexible API that promotes innovative research in the fields of deep learning.
Keras can be used by researchers and engineers alike to build small and large deep learning applications. With Keras, you can model any deep learning algorithm within no time!
Data Loading is the first step that goes into modeling a deep learning problem. In this article, you will learn the various data loading techniques that you can avail of, to load data into your workspace with ease.
Keras is available in the TensorFlow library. You can directly import it using the following command:
from tensorflow import keras
Raw data cannot be directly processed by a Keras model. The data has to be converted into a suitable format to enable the model to interpret. For example, text has to be converted to numeric tensors, images to floating-point tensors, so on and so forth.
Keras in general accepts three types of inputs — NumPy arrays, TensorFlow Dataset objects, and Python generators.
A NumPy array pertains to a low-level array representation of the data, a Dataset object produces a high-level representation, and a Generator pertains to a batch of data with certain properties.
Here’s an overview of a wide variety of data loading techniques to load several types of data in Keras.
Keras comes with a few in-built datasets — cleaned and vectorized, to help you build simple deep learning models. MNIST, CIFAR10, CIFAR100, IMDB, Fashion MNIST, Reuters newswire, and Boston housing price datasets are available within Keras.
For example, to load MNIST dataset — a dataset comprising handwritten digits each of size 28 * 28 pixels, you can run the code:
This gives the following output:
(60000, 28, 28)(60000,)(10000, 28, 28)(10000,)
You’ve got both train and test datasets by importing the dataset from tf.keras.datasets library. The path parameter is to create a local cache of the MNIST dataset, stored as a compressed NumPy file. The output here tells us that there are 60000 train and 10000 test images.
To load images from a URL, use the get_file() method to fetch the data by passing the URL as an arguement. This stores the data in a local directory.
To load images from a local directory, use image_dataset_from_directory() method to convert the directory to a valid dataset to be used by a deep learning model.
On running the code, you get the following output:
Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz228818944/228813984 [==============================] - 2s 0us/stepFound 3670 files belonging to 5 classes.<class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'>
image_size and batch_size parameters specify the size of an image and the number of dataset batches respectively.
Now check the shape of training data and labels present in the dataset.
On running this code, you get the following output:
(64, 180, 180, 3)(64,)
Each RGB image is of size 180 * 180, and each batch has 64 such images. Data labels is a 1D array specifying a label against every image.
Using matplotlib library, you can show the images present in the dataset.
An Image Generator class can be used to specify certain traits to the images in a dataset. Using the data_dir which you generated in section 2.2. Loading Images, initialize an image generator and apply it onto the dataset.
The parameters used in ImageDataGenerator class are as follows:
rescale is the rescaling factor,
rotation_range specifies the degree to be used for random rotations of the images,
width_shift_range specifies the upper bound by which the image is to be randomly shifted, either left or right,
height_shift_range specifies the upper bound by which the image is to be randomly shifted, either up or down,
and vertical_flip flips the image vertically.
On running the code, you get the following output:
Found 3670 images belonging to 5 classes.(32, 256, 256, 3)(32, 5)
Here’s how the image data now looks like:
To load a file comprising text present locally, you can run the following command:
data = open("sample_data/mnist_test.csv").read()
If the data is to be fetched from a URL or is present in a local directory, run the following commands:
Here, you are importing a tarred directory. You are later untarring it and fetching the directory which has the actual dataset.
On running this code, you get the following output:
Downloading data from https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz84131840/84125825 [==============================] - 2s 0us/step
Now print the directories present in dataset_dir.
os.listdir(dataset_dir)
You’ll receive the following output:
['neg','urls_unsup.txt','labeledBow.feat','urls_neg.txt','unsup','urls_pos.txt','pos','unsupBow.feat']
To get to know the data, pick a random file and read the content.
open(os.path.join(dataset_dir, 'train/urls_neg.txt'), 'r').read()
The output you get is:
http://www.imdb.com/title/tt0064354/usercommentshttp://www.imdb.com/title/tt0100680/usercommentshttp://www.imdb.com/title/tt0100680/usercommentshttp://www.imdb.com/title/tt0100680/usercommentshttp://www.imdb.com/title/tt0047200/usercomments...
CSV data can be loaded using Python’s pandas library. You can run the below code snippet to load a CSV into your workspace.
The read_csv() method converts a CSV file to a pandas object. You can print the first 5 values in the dataset using the method head().
Length Diameter Height ... Viscera weight Shell weight Age0 0.435 0.335 0.110 ... 0.0775 0.0965 71 0.585 0.450 0.125 ... 0.2075 0.2250 62 0.655 0.510 0.160 ... 0.2825 0.3700 143 0.545 0.425 0.125 ... 0.1495 0.2600 164 0.545 0.420 0.130 ... 0.1695 0.2300 13[5 rows x 8 columns]
You can also convert a pandas object to a numpy array as follows:
The output you see is:
array([[ 0.435 , 0.335 , 0.11 , ..., 0.0775, 0.0965, 7. ],[ 0.585 , 0.45 , 0.125 , ..., 0.2075, 0.225 , 6. ],[ 0.655 , 0.51 , 0.16 , ..., 0.2825, 0.37 , 14. ],...,])
You get a 2D numpy array.
Again, you can also convert a pandas object to a Dataset object as follows:
The from_tensor_slices() method creates a separate row for each input. Age attribute here, is considered as the dataset label.
The output you get on running the above code is:
tf.Tensor([0.435 0.335 0.11 0.334 0.1355 0.0775 0.0965 7. ], shape=(8,), dtype=float64)tf.Tensor(7, shape=(), dtype=int64)
For ease of training a model, you can also convert a numpy array into a Dataset object. First, initialize a numpy array and pass it as an argument to from_tensor_slices() method.
tf.data.Dataset.from_tensor_slices(([[1, 2, 0.5, 0.3], [0.3, 0.4, 6, 7]], ['Lily', 'Jasmine']))
This creates a Dataset object as follows:
<TensorSliceDataset shapes: ((4,), ()), types: (tf.float32, tf.string)>
Consider a case where you are building your dataset using a Python function.
def repetition(x): i = 0 while i <= x: yield i i += 1
On calling this function with an argument 5, you get 0, 1, 2, 3, 4, and 5. Say, you want to build a dataset from this — where the dataset has 4 rows and each row has 5 items.
The from_generator() method in the code snippet creates such a dataset using the function repetition. batch(5) indicates the length per batch and take(4), the number of batches.
On running this code, you get the following output:
[0 1 2 3 4][5 0 1 2 3][4 5 0 1 2][3 4 5 0 1]
Altogether, here’s the full-fledged code:
Data Loading is a significant preliminary step to build any deep learning model. Depending on the data that you want to train your model using, you have to load and preprocess it.
In this article, you learned how to load images, text, csv(s), pandas objects and numpy arrays using Keras.
In the next part of this series, you shall learn the techniques used for Data Preprocessing in Keras.
Thanks for reading!
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "Keras is a Deep Learning API of TensorFlow 2.0 used for easy and fast experimentation. It is simple to understand, flexible to extend and deploy, and powerful enough to build any neural network."
},
{
"code": null,
"e": 675,
"s": 367,
"text": "With the increase in the usage of deep learning to solve real-time problems, it has become quite a necessity to lessen the time consumed to build robust machine learning algorithms, i.e., the time taken from designing an algorithm to putting it into practice to generate the desired model has to be minimal."
},
{
"code": null,
"e": 1063,
"s": 675,
"text": "Keras has been designed for this very purpose. It is a high-level deep learning API running on top of TensorFlow, a machine learning/deep learning framework. It provides an easy to use, modular, and an organised interface to solve deep learning problems. It is simple to understand and is expressive. It is a flexible API that promotes innovative research in the fields of deep learning."
},
{
"code": null,
"e": 1239,
"s": 1063,
"text": "Keras can be used by researchers and engineers alike to build small and large deep learning applications. With Keras, you can model any deep learning algorithm within no time!"
},
{
"code": null,
"e": 1454,
"s": 1239,
"text": "Data Loading is the first step that goes into modeling a deep learning problem. In this article, you will learn the various data loading techniques that you can avail of, to load data into your workspace with ease."
},
{
"code": null,
"e": 1556,
"s": 1454,
"text": "Keras is available in the TensorFlow library. You can directly import it using the following command:"
},
{
"code": null,
"e": 1585,
"s": 1556,
"text": "from tensorflow import keras"
},
{
"code": null,
"e": 1839,
"s": 1585,
"text": "Raw data cannot be directly processed by a Keras model. The data has to be converted into a suitable format to enable the model to interpret. For example, text has to be converted to numeric tensors, images to floating-point tensors, so on and so forth."
},
{
"code": null,
"e": 1953,
"s": 1839,
"text": "Keras in general accepts three types of inputs — NumPy arrays, TensorFlow Dataset objects, and Python generators."
},
{
"code": null,
"e": 2149,
"s": 1953,
"text": "A NumPy array pertains to a low-level array representation of the data, a Dataset object produces a high-level representation, and a Generator pertains to a batch of data with certain properties."
},
{
"code": null,
"e": 2253,
"s": 2149,
"text": "Here’s an overview of a wide variety of data loading techniques to load several types of data in Keras."
},
{
"code": null,
"e": 2494,
"s": 2253,
"text": "Keras comes with a few in-built datasets — cleaned and vectorized, to help you build simple deep learning models. MNIST, CIFAR10, CIFAR100, IMDB, Fashion MNIST, Reuters newswire, and Boston housing price datasets are available within Keras."
},
{
"code": null,
"e": 2622,
"s": 2494,
"text": "For example, to load MNIST dataset — a dataset comprising handwritten digits each of size 28 * 28 pixels, you can run the code:"
},
{
"code": null,
"e": 2655,
"s": 2622,
"text": "This gives the following output:"
},
{
"code": null,
"e": 2702,
"s": 2655,
"text": "(60000, 28, 28)(60000,)(10000, 28, 28)(10000,)"
},
{
"code": null,
"e": 2977,
"s": 2702,
"text": "You’ve got both train and test datasets by importing the dataset from tf.keras.datasets library. The path parameter is to create a local cache of the MNIST dataset, stored as a compressed NumPy file. The output here tells us that there are 60000 train and 10000 test images."
},
{
"code": null,
"e": 3127,
"s": 2977,
"text": "To load images from a URL, use the get_file() method to fetch the data by passing the URL as an arguement. This stores the data in a local directory."
},
{
"code": null,
"e": 3289,
"s": 3127,
"text": "To load images from a local directory, use image_dataset_from_directory() method to convert the directory to a valid dataset to be used by a deep learning model."
},
{
"code": null,
"e": 3340,
"s": 3289,
"text": "On running the code, you get the following output:"
},
{
"code": null,
"e": 3617,
"s": 3340,
"text": "Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz228818944/228813984 [==============================] - 2s 0us/stepFound 3670 files belonging to 5 classes.<class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'>"
},
{
"code": null,
"e": 3731,
"s": 3617,
"text": "image_size and batch_size parameters specify the size of an image and the number of dataset batches respectively."
},
{
"code": null,
"e": 3803,
"s": 3731,
"text": "Now check the shape of training data and labels present in the dataset."
},
{
"code": null,
"e": 3855,
"s": 3803,
"text": "On running this code, you get the following output:"
},
{
"code": null,
"e": 3878,
"s": 3855,
"text": "(64, 180, 180, 3)(64,)"
},
{
"code": null,
"e": 4016,
"s": 3878,
"text": "Each RGB image is of size 180 * 180, and each batch has 64 such images. Data labels is a 1D array specifying a label against every image."
},
{
"code": null,
"e": 4090,
"s": 4016,
"text": "Using matplotlib library, you can show the images present in the dataset."
},
{
"code": null,
"e": 4313,
"s": 4090,
"text": "An Image Generator class can be used to specify certain traits to the images in a dataset. Using the data_dir which you generated in section 2.2. Loading Images, initialize an image generator and apply it onto the dataset."
},
{
"code": null,
"e": 4377,
"s": 4313,
"text": "The parameters used in ImageDataGenerator class are as follows:"
},
{
"code": null,
"e": 4410,
"s": 4377,
"text": "rescale is the rescaling factor,"
},
{
"code": null,
"e": 4493,
"s": 4410,
"text": "rotation_range specifies the degree to be used for random rotations of the images,"
},
{
"code": null,
"e": 4605,
"s": 4493,
"text": "width_shift_range specifies the upper bound by which the image is to be randomly shifted, either left or right,"
},
{
"code": null,
"e": 4715,
"s": 4605,
"text": "height_shift_range specifies the upper bound by which the image is to be randomly shifted, either up or down,"
},
{
"code": null,
"e": 4761,
"s": 4715,
"text": "and vertical_flip flips the image vertically."
},
{
"code": null,
"e": 4812,
"s": 4761,
"text": "On running the code, you get the following output:"
},
{
"code": null,
"e": 4878,
"s": 4812,
"text": "Found 3670 images belonging to 5 classes.(32, 256, 256, 3)(32, 5)"
},
{
"code": null,
"e": 4920,
"s": 4878,
"text": "Here’s how the image data now looks like:"
},
{
"code": null,
"e": 5003,
"s": 4920,
"text": "To load a file comprising text present locally, you can run the following command:"
},
{
"code": null,
"e": 5052,
"s": 5003,
"text": "data = open(\"sample_data/mnist_test.csv\").read()"
},
{
"code": null,
"e": 5156,
"s": 5052,
"text": "If the data is to be fetched from a URL or is present in a local directory, run the following commands:"
},
{
"code": null,
"e": 5284,
"s": 5156,
"text": "Here, you are importing a tarred directory. You are later untarring it and fetching the directory which has the actual dataset."
},
{
"code": null,
"e": 5336,
"s": 5284,
"text": "On running this code, you get the following output:"
},
{
"code": null,
"e": 5486,
"s": 5336,
"text": "Downloading data from https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz84131840/84125825 [==============================] - 2s 0us/step"
},
{
"code": null,
"e": 5536,
"s": 5486,
"text": "Now print the directories present in dataset_dir."
},
{
"code": null,
"e": 5560,
"s": 5536,
"text": "os.listdir(dataset_dir)"
},
{
"code": null,
"e": 5597,
"s": 5560,
"text": "You’ll receive the following output:"
},
{
"code": null,
"e": 5700,
"s": 5597,
"text": "['neg','urls_unsup.txt','labeledBow.feat','urls_neg.txt','unsup','urls_pos.txt','pos','unsupBow.feat']"
},
{
"code": null,
"e": 5766,
"s": 5700,
"text": "To get to know the data, pick a random file and read the content."
},
{
"code": null,
"e": 5832,
"s": 5766,
"text": "open(os.path.join(dataset_dir, 'train/urls_neg.txt'), 'r').read()"
},
{
"code": null,
"e": 5855,
"s": 5832,
"text": "The output you get is:"
},
{
"code": null,
"e": 6099,
"s": 5855,
"text": "http://www.imdb.com/title/tt0064354/usercommentshttp://www.imdb.com/title/tt0100680/usercommentshttp://www.imdb.com/title/tt0100680/usercommentshttp://www.imdb.com/title/tt0100680/usercommentshttp://www.imdb.com/title/tt0047200/usercomments..."
},
{
"code": null,
"e": 6223,
"s": 6099,
"text": "CSV data can be loaded using Python’s pandas library. You can run the below code snippet to load a CSV into your workspace."
},
{
"code": null,
"e": 6358,
"s": 6223,
"text": "The read_csv() method converts a CSV file to a pandas object. You can print the first 5 values in the dataset using the method head()."
},
{
"code": null,
"e": 6778,
"s": 6358,
"text": "Length Diameter Height ... Viscera weight Shell weight Age0 0.435 0.335 0.110 ... 0.0775 0.0965 71 0.585 0.450 0.125 ... 0.2075 0.2250 62 0.655 0.510 0.160 ... 0.2825 0.3700 143 0.545 0.425 0.125 ... 0.1495 0.2600 164 0.545 0.420 0.130 ... 0.1695 0.2300 13[5 rows x 8 columns]"
},
{
"code": null,
"e": 6844,
"s": 6778,
"text": "You can also convert a pandas object to a numpy array as follows:"
},
{
"code": null,
"e": 6867,
"s": 6844,
"text": "The output you see is:"
},
{
"code": null,
"e": 7061,
"s": 6867,
"text": "array([[ 0.435 , 0.335 , 0.11 , ..., 0.0775, 0.0965, 7. ],[ 0.585 , 0.45 , 0.125 , ..., 0.2075, 0.225 , 6. ],[ 0.655 , 0.51 , 0.16 , ..., 0.2825, 0.37 , 14. ],...,])"
},
{
"code": null,
"e": 7087,
"s": 7061,
"text": "You get a 2D numpy array."
},
{
"code": null,
"e": 7163,
"s": 7087,
"text": "Again, you can also convert a pandas object to a Dataset object as follows:"
},
{
"code": null,
"e": 7290,
"s": 7163,
"text": "The from_tensor_slices() method creates a separate row for each input. Age attribute here, is considered as the dataset label."
},
{
"code": null,
"e": 7339,
"s": 7290,
"text": "The output you get on running the above code is:"
},
{
"code": null,
"e": 7470,
"s": 7339,
"text": "tf.Tensor([0.435 0.335 0.11 0.334 0.1355 0.0775 0.0965 7. ], shape=(8,), dtype=float64)tf.Tensor(7, shape=(), dtype=int64)"
},
{
"code": null,
"e": 7649,
"s": 7470,
"text": "For ease of training a model, you can also convert a numpy array into a Dataset object. First, initialize a numpy array and pass it as an argument to from_tensor_slices() method."
},
{
"code": null,
"e": 7745,
"s": 7649,
"text": "tf.data.Dataset.from_tensor_slices(([[1, 2, 0.5, 0.3], [0.3, 0.4, 6, 7]], ['Lily', 'Jasmine']))"
},
{
"code": null,
"e": 7787,
"s": 7745,
"text": "This creates a Dataset object as follows:"
},
{
"code": null,
"e": 7859,
"s": 7787,
"text": "<TensorSliceDataset shapes: ((4,), ()), types: (tf.float32, tf.string)>"
},
{
"code": null,
"e": 7936,
"s": 7859,
"text": "Consider a case where you are building your dataset using a Python function."
},
{
"code": null,
"e": 8010,
"s": 7936,
"text": "def repetition(x): i = 0 while i <= x: yield i i += 1"
},
{
"code": null,
"e": 8185,
"s": 8010,
"text": "On calling this function with an argument 5, you get 0, 1, 2, 3, 4, and 5. Say, you want to build a dataset from this — where the dataset has 4 rows and each row has 5 items."
},
{
"code": null,
"e": 8363,
"s": 8185,
"text": "The from_generator() method in the code snippet creates such a dataset using the function repetition. batch(5) indicates the length per batch and take(4), the number of batches."
},
{
"code": null,
"e": 8415,
"s": 8363,
"text": "On running this code, you get the following output:"
},
{
"code": null,
"e": 8460,
"s": 8415,
"text": "[0 1 2 3 4][5 0 1 2 3][4 5 0 1 2][3 4 5 0 1]"
},
{
"code": null,
"e": 8502,
"s": 8460,
"text": "Altogether, here’s the full-fledged code:"
},
{
"code": null,
"e": 8682,
"s": 8502,
"text": "Data Loading is a significant preliminary step to build any deep learning model. Depending on the data that you want to train your model using, you have to load and preprocess it."
},
{
"code": null,
"e": 8790,
"s": 8682,
"text": "In this article, you learned how to load images, text, csv(s), pandas objects and numpy arrays using Keras."
},
{
"code": null,
"e": 8892,
"s": 8790,
"text": "In the next part of this series, you shall learn the techniques used for Data Preprocessing in Keras."
}
] |
Bootstrap | Scrollspy - GeeksforGeeks
|
08 Aug, 2021
Sometimes while designing the website, we include some attractive features which makes website eye-catching. One of the features is Bootstrap scrollspy which target the navigation bar contents automatically on scrolling the area. Example 1 : Scrollspy Vertical Navigation bar
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <style> body { position: relative; } ul.nav-pills { top: 20px; position: fixed; } div.col-sm-9 div { height: 250px; font-size: 18px; } a { color: green; } #section1 {color: white; background-color: green;} #section2 {color: green; background-color: white;} #section3 {color: white; background-color: green;} #section4 {color: green; background-color: white;} @media screen and (max-width: 810px) { #section1, #section2, #section3, #section4 { margin-left: 150px; } } </style></head><body data-spy="scroll" data-target="#myScrollspy" data-offset="20"> <div class="container"> <div class="row"> <nav class="col-sm-3" id="myScrollspy"> <ul class="nav nav-pills nav-stacked"> <li class="active"><a href="#section1">Section 1</a></li> <li><a href="#section2">Section 2</a></li> <li><a href="#section3">Section 3</a></li> <li><a href="#section4">Section 4</a></li> </ul> </nav> <div class="col-sm-9"> <div id="section1"> <center><h1>Section 1</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal has been created to provide well written, well thoughtand well explained solutions for selected questions related to programming,algorithms, other computer science subjects.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> <div id="section2"> <center><h1>Section 2</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal also provide GATE previous year papers,short notes for the aspirants.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> <div id="section3"> <center> <h1>Section 3</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>This portal also provide interview questions asked by private and public sectors.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> <div id="section4"> <center><h1>Section 4</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>It also provide Internship aor contributor program for students.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> </div> </div></div> </body></html>
Output :
Example 2 : Scrollspy Horizontal Navigation bar
html
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <style> body { position: relative; } p { font-size: 18px; } #section1 {padding-top:50px;height:500px;color: white; background-color: green;} #section2 {padding-top:50px;height:500px;color: green; background-color: white;} #section3 {padding-top:50px;height:500px;color: white; background-color: green;} #section4 {padding-top:50px;height:500px;color: green; background-color: white;} </style></head><body data-spy="scroll" data-target=".navbar" data-offset="50"> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle"data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">GeeksforGeeks</a> </div> <div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li><a href="#section1">Section 1</a></li> <li><a href="#section2">Section 2</a></li> <li><a href="#section3">Section 3</a></li> <li><a href="#section4">Section 4</a></li> </ul> </div> </div> </div></nav> <div id="section1" class="container-fluid"> <h1>Section 1</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal has been created to provide well written, well thought and well explained solutions for selected questions related to programming, algorithms, other computer science subjects.</h6> <p>Scroll this section.</p> </div><div id="section2" class="container-fluid"> <h1>Section 2</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal also provide GATE previous year papers, short notes for the aspirants.</h6> <p>Scroll this section.</p> </div><div id="section3" class="container-fluid"> <h1>Section 3</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>This portal also provide interview questionsasked by private and public sectors.</h6> <p>Scroll this section.</p> </div><div id="section4" class="container-fluid"> <h1>Section 4</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>It also provide Internship or contributor program for students.</h6> <p>Scroll this section.</p> </div> </body></html>
Output :
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
Some attributes are added with the elements for the implementation of this feature. These are –
data-spy It is an attribute that is to be added with the element which is using as the scrollable area (in the above example we are taken it as the body). The value of data-spy is scroll.data-target This attribute is used to connect navigation bar with the scrollable area. It takes the value as the name of the ID or class of the navigation bar.data-offset This attribute specifies the number of pixels to offset from top when calculating the position of scroll.
data-spy It is an attribute that is to be added with the element which is using as the scrollable area (in the above example we are taken it as the body). The value of data-spy is scroll.
data-target This attribute is used to connect navigation bar with the scrollable area. It takes the value as the name of the ID or class of the navigation bar.
data-offset This attribute specifies the number of pixels to offset from top when calculating the position of scroll.
ysachin2314
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to change navigation bar color in Bootstrap ?
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
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": 28466,
"s": 28438,
"text": "\n08 Aug, 2021"
},
{
"code": null,
"e": 28743,
"s": 28466,
"text": "Sometimes while designing the website, we include some attractive features which makes website eye-catching. One of the features is Bootstrap scrollspy which target the navigation bar contents automatically on scrolling the area. Example 1 : Scrollspy Vertical Navigation bar "
},
{
"code": null,
"e": 28748,
"s": 28743,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\"href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script> <style> body { position: relative; } ul.nav-pills { top: 20px; position: fixed; } div.col-sm-9 div { height: 250px; font-size: 18px; } a { color: green; } #section1 {color: white; background-color: green;} #section2 {color: green; background-color: white;} #section3 {color: white; background-color: green;} #section4 {color: green; background-color: white;} @media screen and (max-width: 810px) { #section1, #section2, #section3, #section4 { margin-left: 150px; } } </style></head><body data-spy=\"scroll\" data-target=\"#myScrollspy\" data-offset=\"20\"> <div class=\"container\"> <div class=\"row\"> <nav class=\"col-sm-3\" id=\"myScrollspy\"> <ul class=\"nav nav-pills nav-stacked\"> <li class=\"active\"><a href=\"#section1\">Section 1</a></li> <li><a href=\"#section2\">Section 2</a></li> <li><a href=\"#section3\">Section 3</a></li> <li><a href=\"#section4\">Section 4</a></li> </ul> </nav> <div class=\"col-sm-9\"> <div id=\"section1\"> <center><h1>Section 1</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal has been created to provide well written, well thoughtand well explained solutions for selected questions related to programming,algorithms, other computer science subjects.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> <div id=\"section2\"> <center><h1>Section 2</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal also provide GATE previous year papers,short notes for the aspirants.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> <div id=\"section3\"> <center> <h1>Section 3</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>This portal also provide interview questions asked by private and public sectors.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> <div id=\"section4\"> <center><h1>Section 4</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>It also provide Internship aor contributor program for students.</h6> <p>Scroll this section and see the navigation list while scrolling.</p> </center> </div> </div> </div></div> </body></html>",
"e": 31627,
"s": 28748,
"text": null
},
{
"code": null,
"e": 31638,
"s": 31627,
"text": "Output : "
},
{
"code": null,
"e": 31689,
"s": 31640,
"text": "Example 2 : Scrollspy Horizontal Navigation bar "
},
{
"code": null,
"e": 31694,
"s": 31689,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <style> body { position: relative; } p { font-size: 18px; } #section1 {padding-top:50px;height:500px;color: white; background-color: green;} #section2 {padding-top:50px;height:500px;color: green; background-color: white;} #section3 {padding-top:50px;height:500px;color: white; background-color: green;} #section4 {padding-top:50px;height:500px;color: green; background-color: white;} </style></head><body data-spy=\"scroll\" data-target=\".navbar\" data-offset=\"50\"> <nav class=\"navbar navbar-inverse navbar-fixed-top\"> <div class=\"container-fluid\"> <div class=\"navbar-header\"> <button type=\"button\" class=\"navbar-toggle\"data-toggle=\"collapse\" data-target=\"#myNavbar\"> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> </button> <a class=\"navbar-brand\" href=\"#\">GeeksforGeeks</a> </div> <div> <div class=\"collapse navbar-collapse\" id=\"myNavbar\"> <ul class=\"nav navbar-nav\"> <li><a href=\"#section1\">Section 1</a></li> <li><a href=\"#section2\">Section 2</a></li> <li><a href=\"#section3\">Section 3</a></li> <li><a href=\"#section4\">Section 4</a></li> </ul> </div> </div> </div></nav> <div id=\"section1\" class=\"container-fluid\"> <h1>Section 1</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal has been created to provide well written, well thought and well explained solutions for selected questions related to programming, algorithms, other computer science subjects.</h6> <p>Scroll this section.</p> </div><div id=\"section2\" class=\"container-fluid\"> <h1>Section 2</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6> This portal also provide GATE previous year papers, short notes for the aspirants.</h6> <p>Scroll this section.</p> </div><div id=\"section3\" class=\"container-fluid\"> <h1>Section 3</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>This portal also provide interview questionsasked by private and public sectors.</h6> <p>Scroll this section.</p> </div><div id=\"section4\" class=\"container-fluid\"> <h1>Section 4</h1><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks.</h5><h6>It also provide Internship or contributor program for students.</h6> <p>Scroll this section.</p> </div> </body></html>",
"e": 34522,
"s": 31694,
"text": null
},
{
"code": null,
"e": 34532,
"s": 34522,
"text": "Output : "
},
{
"code": null,
"e": 34557,
"s": 34538,
"text": "Supported Browser:"
},
{
"code": null,
"e": 34571,
"s": 34557,
"text": "Google Chrome"
},
{
"code": null,
"e": 34586,
"s": 34571,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 34594,
"s": 34586,
"text": "Firefox"
},
{
"code": null,
"e": 34600,
"s": 34594,
"text": "Opera"
},
{
"code": null,
"e": 34607,
"s": 34600,
"text": "Safari"
},
{
"code": null,
"e": 34705,
"s": 34607,
"text": "Some attributes are added with the elements for the implementation of this feature. These are – "
},
{
"code": null,
"e": 35169,
"s": 34705,
"text": "data-spy It is an attribute that is to be added with the element which is using as the scrollable area (in the above example we are taken it as the body). The value of data-spy is scroll.data-target This attribute is used to connect navigation bar with the scrollable area. It takes the value as the name of the ID or class of the navigation bar.data-offset This attribute specifies the number of pixels to offset from top when calculating the position of scroll."
},
{
"code": null,
"e": 35357,
"s": 35169,
"text": "data-spy It is an attribute that is to be added with the element which is using as the scrollable area (in the above example we are taken it as the body). The value of data-spy is scroll."
},
{
"code": null,
"e": 35517,
"s": 35357,
"text": "data-target This attribute is used to connect navigation bar with the scrollable area. It takes the value as the name of the ID or class of the navigation bar."
},
{
"code": null,
"e": 35635,
"s": 35517,
"text": "data-offset This attribute specifies the number of pixels to offset from top when calculating the position of scroll."
},
{
"code": null,
"e": 35649,
"s": 35637,
"text": "ysachin2314"
},
{
"code": null,
"e": 35659,
"s": 35649,
"text": "Bootstrap"
},
{
"code": null,
"e": 35676,
"s": 35659,
"text": "Web Technologies"
},
{
"code": null,
"e": 35774,
"s": 35676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35783,
"s": 35774,
"text": "Comments"
},
{
"code": null,
"e": 35796,
"s": 35783,
"text": "Old Comments"
},
{
"code": null,
"e": 35825,
"s": 35796,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 35875,
"s": 35825,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 35916,
"s": 35875,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 35972,
"s": 35916,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 36013,
"s": 35972,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 36055,
"s": 36013,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 36088,
"s": 36055,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36131,
"s": 36088,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 36193,
"s": 36131,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Connecting two discrete VNets using VNet peering and ARM Templates | by Sulabh Shrestha | Towards Data Science
|
Connecting Virtual Networks might be messy sometimes if not done right. Creating it, again and again, will be more error-prone. So, we will be utilizing a service from Azure called Azure ARM Templates to deploy our infrastructure in an idempotent way. We will also be using Portal for only some tasks but most of it will be done from the templates.
Azure AccountAzure Virtual MachineAzure VNetARM templates
Azure Account
Azure Virtual Machine
Azure VNet
ARM templates
Azure Virtual Network is a network of Azure in the cloud. This VNet can be subdivided into different subnets. For this exercise, we will be creating two VNets: east and west, with two subnets for each VM, where east VNET is restricted to private IPs and west has access to public IPs like the above architecture. Later on, we will use VNet peering to connect these two different VNet’s in different regions.
ARM Templates are the idempotent way to write infrastructure in the form of JSON for maximum usability. Creating a VM, VNets, and subnets is a very lengthy process and we may have errors on the way while creating them and so for that reason, ARM Templates are preferred. I have already created the ARM Templates and are here on my GitHub. But do not worry I will teach you how to write ARM Templates, more so generate them as it’s quite difficult to write from scratch.
Let’s say I have created some infrastructure and I want to have an ARM Template for it. Go to the Resource Groups, Select Resources, and Export Template.
Then click on the Download button.
You will get template.json and parameter.json. Template.json contains what infrastructure you want to make with its details and parameter.json contains the unique name that you want to give to the resource. For this post, I will be adding my own default values. You can add your unique names through parameter.json and enter the commands given below.
After you hit the commands using the CLI it might not work on the fly as you must do some housekeeping on the JSON files like removing the subscription id for dynamic usability and also removing unnecessary key values pairs. For this post, you don't have to worry as the JSON I have provided works to its fullest. After you open the code here are the commands that you need to enter linearly.
az group create --name oss-east-rg --location eastusaz group create --name oss-west-rg --location westusaz deployment group create --resource-group oss-east-rg --template-file template.jsonaz deployment group create --resource-group oss-west-rg --template-file template.json
We will be using a portal to peer both the VNets. Go to the east Virtual Network, Settings, Peerings and +Add
We should keep in mind that we are connecting east to west but also west to east, so is the reason that there are two blanks with the Peering link name. Fill in the basic details and hit Add.
Now, let's connect to the VM which have a public IP address(west) and then connect to the east using a private IP address on a different VNet. I have provided the PEM file in the repository. Let’s start from the west VM.
sudo ssh -i vm.pem azureuser@104.40.10.98
A connection has been established.
Now, let's connect to the east VM using the private IP. Remember to copy the PEM file into the VM itself.
sudo ssh -i vm.pem azureuser@10.0.0.4
A connection has been established again.
We have demonstrated how we can leverage Azure ARM Templates to create even the complex infrastructure with ease. This is a bare minimum as we can add more and more to the ARM Templates. There are other tools such as Terraform and Pulumi which we can leverage to write IaC code as well in declarative and imperative ways. The possibilities are endless, the choices are endless and it’s up to you for what you want to make it. If you encounter any problems or have difficulty following the steps, comment below on this post or message me at tsulabh4@gmail.com. You can also connect with me on Linkedin and GitHub.
[1] Azure Virtual Network: https://docs.microsoft.com/en-us/azure/virtual-network/virtual-networks-overview
[2] ARM templates: https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/overview
|
[
{
"code": null,
"e": 521,
"s": 172,
"text": "Connecting Virtual Networks might be messy sometimes if not done right. Creating it, again and again, will be more error-prone. So, we will be utilizing a service from Azure called Azure ARM Templates to deploy our infrastructure in an idempotent way. We will also be using Portal for only some tasks but most of it will be done from the templates."
},
{
"code": null,
"e": 579,
"s": 521,
"text": "Azure AccountAzure Virtual MachineAzure VNetARM templates"
},
{
"code": null,
"e": 593,
"s": 579,
"text": "Azure Account"
},
{
"code": null,
"e": 615,
"s": 593,
"text": "Azure Virtual Machine"
},
{
"code": null,
"e": 626,
"s": 615,
"text": "Azure VNet"
},
{
"code": null,
"e": 640,
"s": 626,
"text": "ARM templates"
},
{
"code": null,
"e": 1048,
"s": 640,
"text": "Azure Virtual Network is a network of Azure in the cloud. This VNet can be subdivided into different subnets. For this exercise, we will be creating two VNets: east and west, with two subnets for each VM, where east VNET is restricted to private IPs and west has access to public IPs like the above architecture. Later on, we will use VNet peering to connect these two different VNet’s in different regions."
},
{
"code": null,
"e": 1518,
"s": 1048,
"text": "ARM Templates are the idempotent way to write infrastructure in the form of JSON for maximum usability. Creating a VM, VNets, and subnets is a very lengthy process and we may have errors on the way while creating them and so for that reason, ARM Templates are preferred. I have already created the ARM Templates and are here on my GitHub. But do not worry I will teach you how to write ARM Templates, more so generate them as it’s quite difficult to write from scratch."
},
{
"code": null,
"e": 1672,
"s": 1518,
"text": "Let’s say I have created some infrastructure and I want to have an ARM Template for it. Go to the Resource Groups, Select Resources, and Export Template."
},
{
"code": null,
"e": 1707,
"s": 1672,
"text": "Then click on the Download button."
},
{
"code": null,
"e": 2058,
"s": 1707,
"text": "You will get template.json and parameter.json. Template.json contains what infrastructure you want to make with its details and parameter.json contains the unique name that you want to give to the resource. For this post, I will be adding my own default values. You can add your unique names through parameter.json and enter the commands given below."
},
{
"code": null,
"e": 2451,
"s": 2058,
"text": "After you hit the commands using the CLI it might not work on the fly as you must do some housekeeping on the JSON files like removing the subscription id for dynamic usability and also removing unnecessary key values pairs. For this post, you don't have to worry as the JSON I have provided works to its fullest. After you open the code here are the commands that you need to enter linearly."
},
{
"code": null,
"e": 2726,
"s": 2451,
"text": "az group create --name oss-east-rg --location eastusaz group create --name oss-west-rg --location westusaz deployment group create --resource-group oss-east-rg --template-file template.jsonaz deployment group create --resource-group oss-west-rg --template-file template.json"
},
{
"code": null,
"e": 2836,
"s": 2726,
"text": "We will be using a portal to peer both the VNets. Go to the east Virtual Network, Settings, Peerings and +Add"
},
{
"code": null,
"e": 3028,
"s": 2836,
"text": "We should keep in mind that we are connecting east to west but also west to east, so is the reason that there are two blanks with the Peering link name. Fill in the basic details and hit Add."
},
{
"code": null,
"e": 3249,
"s": 3028,
"text": "Now, let's connect to the VM which have a public IP address(west) and then connect to the east using a private IP address on a different VNet. I have provided the PEM file in the repository. Let’s start from the west VM."
},
{
"code": null,
"e": 3291,
"s": 3249,
"text": "sudo ssh -i vm.pem azureuser@104.40.10.98"
},
{
"code": null,
"e": 3326,
"s": 3291,
"text": "A connection has been established."
},
{
"code": null,
"e": 3432,
"s": 3326,
"text": "Now, let's connect to the east VM using the private IP. Remember to copy the PEM file into the VM itself."
},
{
"code": null,
"e": 3470,
"s": 3432,
"text": "sudo ssh -i vm.pem azureuser@10.0.0.4"
},
{
"code": null,
"e": 3511,
"s": 3470,
"text": "A connection has been established again."
},
{
"code": null,
"e": 4124,
"s": 3511,
"text": "We have demonstrated how we can leverage Azure ARM Templates to create even the complex infrastructure with ease. This is a bare minimum as we can add more and more to the ARM Templates. There are other tools such as Terraform and Pulumi which we can leverage to write IaC code as well in declarative and imperative ways. The possibilities are endless, the choices are endless and it’s up to you for what you want to make it. If you encounter any problems or have difficulty following the steps, comment below on this post or message me at tsulabh4@gmail.com. You can also connect with me on Linkedin and GitHub."
},
{
"code": null,
"e": 4232,
"s": 4124,
"text": "[1] Azure Virtual Network: https://docs.microsoft.com/en-us/azure/virtual-network/virtual-networks-overview"
}
] |
How to set the size of the Button in C#? - GeeksforGeeks
|
26 Jun, 2019
A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In windows forms, you are allowed to set the size of the button automatically using the AutoSize Property of the button.It is provided by Button class which helps programmers to create a button whose size is increased or decrease according to the content it contains. If you want to resize the button automatically according to its contents, then set the value of this property to true. And if you want to resize the button manually, then set the value of this property to false. You can use this property in two different methods:
1. Design-Time: It is the easiest method to resize the button automatically. Using the following steps you will set the AutoSize property of the button:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Button control to set the AutoSize property of the Button.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the AutoSize property of the Button programmatically with the help of given syntax:
public override bool AutoSize { get; set; }
The value of this property is of System.Boolean type. Following steps are used to set the AutoSize property of the Button:
Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class
Button MyButton = new Button();
// Creating Button using Button class
Button MyButton = new Button();
Step 2: After creating Button, set the AutoSize property of the Button provided by the Button class.// Set the AutoSize property of the button
Mybutton.AutoSize = true;
// Set the AutoSize property of the button
Mybutton.AutoSize = true;
Step 3: And last add this button control to from using Add() method.// Add this Button to form
this.Controls.Add(Mybutton);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = false; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:Before setting the AutoSize property of the cancel button to false the output is like this:After setting the AutoSize property of the cancel button to false the output is like this:
// Add this Button to form
this.Controls.Add(Mybutton);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = false; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton1); }}}
Output:Before setting the AutoSize property of the cancel button to false the output is like this:
After setting the AutoSize property of the cancel button to false the output is like this:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
Destructors in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
C# | Inheritance
Partial Classes in C#
Lambda Expressions in C#
Convert String to Character Array in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n26 Jun, 2019"
},
{
"code": null,
"e": 24973,
"s": 24302,
"text": "A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In windows forms, you are allowed to set the size of the button automatically using the AutoSize Property of the button.It is provided by Button class which helps programmers to create a button whose size is increased or decrease according to the content it contains. If you want to resize the button automatically according to its contents, then set the value of this property to true. And if you want to resize the button manually, then set the value of this property to false. You can use this property in two different methods:"
},
{
"code": null,
"e": 25126,
"s": 24973,
"text": "1. Design-Time: It is the easiest method to resize the button automatically. Using the following steps you will set the AutoSize property of the button:"
},
{
"code": null,
"e": 25242,
"s": 25126,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 25419,
"s": 25242,
"text": "Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 25550,
"s": 25419,
"text": "Step 3: After drag and drop you will go to the properties of the Button control to set the AutoSize property of the Button.Output:"
},
{
"code": null,
"e": 25558,
"s": 25550,
"text": "Output:"
},
{
"code": null,
"e": 25734,
"s": 25558,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the AutoSize property of the Button programmatically with the help of given syntax:"
},
{
"code": null,
"e": 25778,
"s": 25734,
"text": "public override bool AutoSize { get; set; }"
},
{
"code": null,
"e": 25901,
"s": 25778,
"text": "The value of this property is of System.Boolean type. Following steps are used to set the AutoSize property of the Button:"
},
{
"code": null,
"e": 26059,
"s": 25901,
"text": "Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class\nButton MyButton = new Button();\n"
},
{
"code": null,
"e": 26130,
"s": 26059,
"text": "// Creating Button using Button class\nButton MyButton = new Button();\n"
},
{
"code": null,
"e": 26300,
"s": 26130,
"text": "Step 2: After creating Button, set the AutoSize property of the Button provided by the Button class.// Set the AutoSize property of the button\nMybutton.AutoSize = true;\n"
},
{
"code": null,
"e": 26370,
"s": 26300,
"text": "// Set the AutoSize property of the button\nMybutton.AutoSize = true;\n"
},
{
"code": null,
"e": 28117,
"s": 26370,
"text": "Step 3: And last add this button control to from using Add() method.// Add this Button to form\nthis.Controls.Add(Mybutton);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = false; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:Before setting the AutoSize property of the cancel button to false the output is like this:After setting the AutoSize property of the cancel button to false the output is like this:"
},
{
"code": null,
"e": 28174,
"s": 28117,
"text": "// Add this Button to form\nthis.Controls.Add(Mybutton);\n"
},
{
"code": null,
"e": 28183,
"s": 28174,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = false; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); // Adding this button to form this.Controls.Add(Mybutton1); }}}",
"e": 29610,
"s": 28183,
"text": null
},
{
"code": null,
"e": 29709,
"s": 29610,
"text": "Output:Before setting the AutoSize property of the cancel button to false the output is like this:"
},
{
"code": null,
"e": 29800,
"s": 29709,
"text": "After setting the AutoSize property of the cancel button to false the output is like this:"
},
{
"code": null,
"e": 29803,
"s": 29800,
"text": "C#"
},
{
"code": null,
"e": 29901,
"s": 29803,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29924,
"s": 29901,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29942,
"s": 29924,
"text": "Destructors in C#"
},
{
"code": null,
"e": 29970,
"s": 29942,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 30010,
"s": 29970,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 30053,
"s": 30010,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 30069,
"s": 30053,
"text": "C# | List Class"
},
{
"code": null,
"e": 30086,
"s": 30069,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 30108,
"s": 30086,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 30133,
"s": 30108,
"text": "Lambda Expressions in C#"
}
] |
How to create an index in MongoDB using Java?
|
In MongoDB to create an index, you need to use createIndex() method.
db.COLLECTION_NAME.createIndex({KEY:1})
Where the key is the name of the file on which you want to create index and 1 is for ascending order. To create an index in descending order you need to use -1.
In Java, you can create an Index using the createIndex() method, to this method you need to pass the type of the index (ascending or descending) and the field name on which you want to create the index, as −
createIndex(Indexes.descinding("name"));
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import com.mongodb.MongoClient;
public class CreatingIndex {
public static void main( String args[] ) {
//Creating a MongoDB client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//Accessing the database
MongoDatabase database = mongo.getDatabase("myDatabase");
//Creating a collection
database.createCollection("sampleCollection");
//Retrieving the collection on which you want to create the index
MongoCollection<Document> coll = database.getCollection("sampleCollection");
//Creating an index
coll.createIndex(Indexes.ascending("age"));
System.out.println("Index created successfully");
//Printing the list of indices in the collection
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
}
}
Index created successfully
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "In MongoDB to create an index, you need to use createIndex() method."
},
{
"code": null,
"e": 1171,
"s": 1131,
"text": "db.COLLECTION_NAME.createIndex({KEY:1})"
},
{
"code": null,
"e": 1332,
"s": 1171,
"text": "Where the key is the name of the file on which you want to create index and 1 is for ascending order. To create an index in descending order you need to use -1."
},
{
"code": null,
"e": 1540,
"s": 1332,
"text": "In Java, you can create an Index using the createIndex() method, to this method you need to pass the type of the index (ascending or descending) and the field name on which you want to create the index, as −"
},
{
"code": null,
"e": 1581,
"s": 1540,
"text": "createIndex(Indexes.descinding(\"name\"));"
},
{
"code": null,
"e": 2569,
"s": 1581,
"text": "import com.mongodb.client.MongoCollection;\nimport com.mongodb.client.MongoDatabase;\nimport com.mongodb.client.model.Indexes;\nimport org.bson.Document;\nimport com.mongodb.MongoClient;\npublic class CreatingIndex {\n public static void main( String args[] ) {\n //Creating a MongoDB client\n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n //Accessing the database\n MongoDatabase database = mongo.getDatabase(\"myDatabase\");\n //Creating a collection\n database.createCollection(\"sampleCollection\");\n //Retrieving the collection on which you want to create the index\n MongoCollection<Document> coll = database.getCollection(\"sampleCollection\");\n //Creating an index\n coll.createIndex(Indexes.ascending(\"age\"));\n System.out.println(\"Index created successfully\");\n //Printing the list of indices in the collection\n for (Document index : coll.listIndexes()) {\n System.out.println(index.toJson());\n }\n }\n}"
},
{
"code": null,
"e": 2759,
"s": 2569,
"text": "Index created successfully\n{\"v\": 2, \"key\": {\"_id\": 1}, \"name\": \"_id_\", \"ns\": \"myDatabase.sampleCollection\"}\n{\"v\": 2, \"key\": {\"age\": 1}, \"name\": \"age_1\", \"ns\": \"myDatabase.sampleCollection\"}"
}
] |
Multi-Armed Bandits: Upper Confidence Bound Algorithms with Python Code | Towards Data Science
|
In this series of posts, we experiment with different bandit algorithms in order to optimise our movie nights — more specifically how we select movies and restaurants for food delivery!
For newcomers, the name bandit comes from slot-machines (known as one-armed bandits). You can think of it as something that can reward you (or not) every time you interact with it (pull its arm). The objective is, given a bunch of bandits that give different rewards, to identify the one that gives the highest ones, as fast as possible. As we start playing and continuously collect data about each bandit, the bandit algorithm helps us choose between exploiting the one that gave us the highest rewards so far and exploring others.
In our story, we use restaurants instead of bandits and our reward is food satisfaction! :)
medium.com
medium.com
It’s been a while since you and your friend started using bandit algorithms to optimise your movie nights. So far, you’ve been using Epsilon-Greedy (with ε=1/#actions) to help with finding the best restaurant and your friend has stubbornly been using the Optimistic Initial Values algorithm to pick movie directors (even if your simulations have shown that it’s likely not as good for your use case).
While killing time on the internet, being trapped inside because of the lockdown, you come across some bandit algorithms based on Upper Confidence Bounds (UCB). Excited about the possibility of improving your search for the best restaurant, and more efficiently solving the exploitation-exploration dilemma, you start reading in anticipation of the next movie night.
Will one of them be better than Epsilon-Greedy? Let’s find out!
The idea is to use probability theory to come up with an upper bound on the average reward of each bandit, using the data we have collected so far. We will call this upper bound the upper confidence index of the bandit, like in the original paper. As with confidence intervals, this bound around the sample mean will be wide if we don’t have a lot of data. At each step, we select the bandit with the highest upper confidence index, get the reward and subsequently update its index.
This sounds a bit similar to the Optimistic Initial Values Algorithm, right? Coming up with this index may seem more complicated than just choosing an optimistic initial value, but the implementation remains relatively simple (I swear). They, really, are simpler to use as they don’t have any parameters that need to be chosen by us!
In general, the upper confidence index for each bandit has the following form.
Bandit Upper Confidence Index = X_sample_mean + Cwhere X_sample_mean: sample mean for rewards so far C > 0: size of one sided confidence interval
C should decrease as we gather more data for the bandit, which makes sense since we become more certain on the possible values for the average reward. Bandits that have not been sufficiently explored will have a larger C that will cause us to select them for exploration.
In pseudo-code:
Choose n # number of iterationsInitialisation step. # for UCB1 & UCB1-Tuned we play each bandit oncefor i = 1 to n do: current_bandit = pick bandit with greatest upper confidence index reward = current_bandit.pull_arm() Update upper confidence index for current_bandit
OK... We know how to calculate sample means, but how do we calculate C? Well, it depends!
There are a few UCB algorithms presented in the original paper, each with different definitions for C. UCB1 and UCB1-Tuned were designed for rewards that are either 0 or 1, i.e. rewards from a Bernoulli distribution (see this article). If your rewards come from a Normal distribution, there is another algorithm, called UCB-Normal, that was designed for that. You could use UCB1 for rewards from other distributions but the performance is said to not be as good (we will test this).
The upper confidence index for a bandit for UCB1 is equal to
Bandit Upper Confidence Index = Sample Mean + √(2logN / n)where N = total rounds (e.g. number of movie nights so far) n = number of times we've played the bandit ( e.g. number of times we've ordered from a restaurant ).
It is derived using the Chernoff-Hoeffding bound, that states
P( Sample Mean + t ≤ True Mean) ≤ exp(-2nt2) for t > 0
where nis the number of data points we have collected so far from the specific bandit. This means, that the probability that the error of the sample mean is greater than t decreases as n increases.
To derive the upper bound, we start by setting the right-hand side equal to b and solving for t.
Let b = exp(-2nt2).Then logb = -2nt2 <=> t = √(-logb / (2n))Choose (this is a heuristic) b = (1 / N4)Then t = √(2logN / n)
In the above, n is the number of times we’ve played the specific bandit and N is the number of times we’ve played in total (number of rounds or movie nights if you like). You can think of b as a hyperparameter.
We know P( Sample Mean + t ≤ True Mean) ≤ exp(-2nt2) for t > 0Substitute for t P( Sample Mean + √(2logN / n) ≤ True Mean) ≤ 1 / N4Define Upper Confidence Index = Sample Mean + √(2logN / n)Hence C = √(2logN / n)
From the above, we can deduce that the probability that the true mean is greater than the upper confidence index is less than 1 / N4 — this converges to 0 as the number of rounds N increases. Therefore it makes sense to use it as an upper bound.
One thing to note is the ratio logN / n. As the gap between the number of rounds N and number of times we’ve played the bandit n increases so does the bound.
For UCB1-Tuned, we replace C with the following
C = √( (logN / n) x min(1/4, V(n)) )where V(n) is an upper confidence bound on the variance of the bandit, i.e.V(n) = Σ(x_i2 / n) - (Σ x_i / n)2 + √(2log(N) / n) and x_i are the rewards we got from the bandit so far.
In the original paper (see section 4), UCB1-Tuned outperformed UCB1 in every experiment.
For UCB1-Normal, C is based on the sample variance and, in contrast to the previous two algorithms, is designed for rewards from normal distributions.
C = √( 16 SV(n) log(N - 1) / n )where the sample variance is SV(n) = ( Σ x_i2 - n (Σ x_i / n)2 ) / (n - 1) x_i are the rewards we got from the bandit so far
UCB1-Normal does not normally have an initialisation step. Instead, at each round N , it checks if there’s a bandit that has been played less than the ceiling of 8logN and plays that one instead of looking at the upper confidence index. However, to calculate C we need n to be at least 2 so that we don’t divide by zero. Hence, we will play each bandit twice as an initialisation step.
Phew.... that was a lot of bounds. Some of this code has been presented in previous posts, but I will include it here as well for completeness. First, we need some classes to represent the bandits, one for Bernoulli rewards and one for Normal rewards.
Next, we will define some bases classes for the Agents (and a helper class to keep track of the rewards — if you went through the previous article BanditRewardsLog has been modified to keep track of the sum of the squared rewards).
We still need to define the classes for the Epsilon-Greedy Agent, as we will use it for comparison purposes, and the UCB Agents. They will inherit from the Agent class and need to implement take_action as it is an abstract method.
We now have all the necessary classes for the bandits and the agents. Time for some fun!
We will go straight into throwing all UCB algorithms and Epsilon-Greedy into the battleground. We will consider two cases, one with rewards from a Bernoulli distribution and one with rewards from a Normal distribution.
We will make use of the following utility functions.
def compare_agents( agents: List[Agent], bandits: List[Bandit], iterations: int, show_plot=True,): for agent in agents: logger.info("Running for agent = %s", agent) agent.bandits = bandits if isinstance(agent, ucb.UCBAgent): agent.initialise() N = iterations - agent.rewards_log.total_actions agent.take_actions(N) if show_plot: cumulative_rewards = np.cumsum( agent.rewards_log.all_rewards, ) plt.plot(cumulative_rewards, label=str(agent)) if show_plot: plt.xlabel("iteration") plt.ylabel("total rewards") plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show()def get_agents(): agents = [ EpsilonGreedyAgent(), ucb.UCB1Agent(), ucb.UCB1TunedAgent(), ucb.UCB1NormalAgent(), ] return agentsdef run_comparison_ucb(bandits): win_count = [0, 0, 0, 0] for _ in range(1000): agents = get_agents() iterations = 1000 compare_agents(agents, bandits, iterations, show_plot=False) rewards = [ agent.rewards_log.total_rewards for agent in agents ] win_count[np.argmax(rewards)] += 1 return win_count
May the best algorithm win!
Let’s define our bandits and agents.
probs = [0.6, 0.7, 0.8, 0.9]bernoulli_bandits = [BernoulliBandit(p) for p in probs]agents = get_agents()
Then we can simply do
compare_agents(agents, bernoulli_bandits, 1000, show_plot=True)
It looks like Epsilon-Greedy and UCB1-Tuned are doing better than the other two, but it’s close. We will run_comparison_ucb to repeat this experiment 1000 times and keep count of which agent got the most rewards.
run_comparison_ucb(bernoulli_bandits)
My results were 497 wins for Epsilon-Greedy, 3 for UCB1, 500 for UCB1-Tuned and 0 of UCB1-Normal. Looks like choosing either Epsilon-Greedy or UCB1-Tuned is the way to go.
We repeat the same experiment but this time with bandits that give rewards according to a normal distribution.
means = [3, 5, 7, 9]normal_bandits = [Bandit(m=m, sigma=1) for m in means]
Surprisingly, the worst one seems to be UCB1-Normal... shame. It’s not clear which one is the best from the other three, so we will repeat the experiment a bunch of times and keep count of which agent got the most rewards.
I got 156 wins for Epsilon-Greedy, 364 for UCB1, 480 for UCB1-Tuned and 0 (boooo) for UCB1-Normal.
In this post, we’ve looked into how Upper Confidence Bound bandit algorithms work, coded them in Python and compared them against each other and Epsilon-Greedy (with ε=1/#actions).
We found that UCB1-Tuned performed the best for both Bernoulli and Normal rewards, even though it wasn’t designed for Normal rewards. The worst of the bunch was UCB1-Normal by far — which is probably the reason it is not as popular as the others.
[1] Auer, P., Cesa-Bianchi, N. & Fischer, P. Finite-time Analysis of the Multiarmed Bandit Problem. Machine Learning 47, 235–256 (2002). https://doi.org/10.1023/A:1013689704352
eminik355.medium.com
Become a member of Medium and get full access to all stories. Your membership fee directly supports the writers you read.
More from the same author.
|
[
{
"code": null,
"e": 357,
"s": 171,
"text": "In this series of posts, we experiment with different bandit algorithms in order to optimise our movie nights — more specifically how we select movies and restaurants for food delivery!"
},
{
"code": null,
"e": 890,
"s": 357,
"text": "For newcomers, the name bandit comes from slot-machines (known as one-armed bandits). You can think of it as something that can reward you (or not) every time you interact with it (pull its arm). The objective is, given a bunch of bandits that give different rewards, to identify the one that gives the highest ones, as fast as possible. As we start playing and continuously collect data about each bandit, the bandit algorithm helps us choose between exploiting the one that gave us the highest rewards so far and exploring others."
},
{
"code": null,
"e": 982,
"s": 890,
"text": "In our story, we use restaurants instead of bandits and our reward is food satisfaction! :)"
},
{
"code": null,
"e": 993,
"s": 982,
"text": "medium.com"
},
{
"code": null,
"e": 1004,
"s": 993,
"text": "medium.com"
},
{
"code": null,
"e": 1405,
"s": 1004,
"text": "It’s been a while since you and your friend started using bandit algorithms to optimise your movie nights. So far, you’ve been using Epsilon-Greedy (with ε=1/#actions) to help with finding the best restaurant and your friend has stubbornly been using the Optimistic Initial Values algorithm to pick movie directors (even if your simulations have shown that it’s likely not as good for your use case)."
},
{
"code": null,
"e": 1772,
"s": 1405,
"text": "While killing time on the internet, being trapped inside because of the lockdown, you come across some bandit algorithms based on Upper Confidence Bounds (UCB). Excited about the possibility of improving your search for the best restaurant, and more efficiently solving the exploitation-exploration dilemma, you start reading in anticipation of the next movie night."
},
{
"code": null,
"e": 1836,
"s": 1772,
"text": "Will one of them be better than Epsilon-Greedy? Let’s find out!"
},
{
"code": null,
"e": 2319,
"s": 1836,
"text": "The idea is to use probability theory to come up with an upper bound on the average reward of each bandit, using the data we have collected so far. We will call this upper bound the upper confidence index of the bandit, like in the original paper. As with confidence intervals, this bound around the sample mean will be wide if we don’t have a lot of data. At each step, we select the bandit with the highest upper confidence index, get the reward and subsequently update its index."
},
{
"code": null,
"e": 2653,
"s": 2319,
"text": "This sounds a bit similar to the Optimistic Initial Values Algorithm, right? Coming up with this index may seem more complicated than just choosing an optimistic initial value, but the implementation remains relatively simple (I swear). They, really, are simpler to use as they don’t have any parameters that need to be chosen by us!"
},
{
"code": null,
"e": 2732,
"s": 2653,
"text": "In general, the upper confidence index for each bandit has the following form."
},
{
"code": null,
"e": 2888,
"s": 2732,
"text": "Bandit Upper Confidence Index = X_sample_mean + Cwhere X_sample_mean: sample mean for rewards so far C > 0: size of one sided confidence interval"
},
{
"code": null,
"e": 3160,
"s": 2888,
"text": "C should decrease as we gather more data for the bandit, which makes sense since we become more certain on the possible values for the average reward. Bandits that have not been sufficiently explored will have a larger C that will cause us to select them for exploration."
},
{
"code": null,
"e": 3176,
"s": 3160,
"text": "In pseudo-code:"
},
{
"code": null,
"e": 3450,
"s": 3176,
"text": "Choose n # number of iterationsInitialisation step. # for UCB1 & UCB1-Tuned we play each bandit oncefor i = 1 to n do: current_bandit = pick bandit with greatest upper confidence index reward = current_bandit.pull_arm() Update upper confidence index for current_bandit"
},
{
"code": null,
"e": 3540,
"s": 3450,
"text": "OK... We know how to calculate sample means, but how do we calculate C? Well, it depends!"
},
{
"code": null,
"e": 4023,
"s": 3540,
"text": "There are a few UCB algorithms presented in the original paper, each with different definitions for C. UCB1 and UCB1-Tuned were designed for rewards that are either 0 or 1, i.e. rewards from a Bernoulli distribution (see this article). If your rewards come from a Normal distribution, there is another algorithm, called UCB-Normal, that was designed for that. You could use UCB1 for rewards from other distributions but the performance is said to not be as good (we will test this)."
},
{
"code": null,
"e": 4084,
"s": 4023,
"text": "The upper confidence index for a bandit for UCB1 is equal to"
},
{
"code": null,
"e": 4311,
"s": 4084,
"text": "Bandit Upper Confidence Index = Sample Mean + √(2logN / n)where N = total rounds (e.g. number of movie nights so far) n = number of times we've played the bandit ( e.g. number of times we've ordered from a restaurant )."
},
{
"code": null,
"e": 4373,
"s": 4311,
"text": "It is derived using the Chernoff-Hoeffding bound, that states"
},
{
"code": null,
"e": 4428,
"s": 4373,
"text": "P( Sample Mean + t ≤ True Mean) ≤ exp(-2nt2) for t > 0"
},
{
"code": null,
"e": 4626,
"s": 4428,
"text": "where nis the number of data points we have collected so far from the specific bandit. This means, that the probability that the error of the sample mean is greater than t decreases as n increases."
},
{
"code": null,
"e": 4723,
"s": 4626,
"text": "To derive the upper bound, we start by setting the right-hand side equal to b and solving for t."
},
{
"code": null,
"e": 4847,
"s": 4723,
"text": "Let b = exp(-2nt2).Then logb = -2nt2 <=> t = √(-logb / (2n))Choose (this is a heuristic) b = (1 / N4)Then t = √(2logN / n)"
},
{
"code": null,
"e": 5058,
"s": 4847,
"text": "In the above, n is the number of times we’ve played the specific bandit and N is the number of times we’ve played in total (number of rounds or movie nights if you like). You can think of b as a hyperparameter."
},
{
"code": null,
"e": 5273,
"s": 5058,
"text": "We know P( Sample Mean + t ≤ True Mean) ≤ exp(-2nt2) for t > 0Substitute for t P( Sample Mean + √(2logN / n) ≤ True Mean) ≤ 1 / N4Define Upper Confidence Index = Sample Mean + √(2logN / n)Hence C = √(2logN / n)"
},
{
"code": null,
"e": 5519,
"s": 5273,
"text": "From the above, we can deduce that the probability that the true mean is greater than the upper confidence index is less than 1 / N4 — this converges to 0 as the number of rounds N increases. Therefore it makes sense to use it as an upper bound."
},
{
"code": null,
"e": 5677,
"s": 5519,
"text": "One thing to note is the ratio logN / n. As the gap between the number of rounds N and number of times we’ve played the bandit n increases so does the bound."
},
{
"code": null,
"e": 5725,
"s": 5677,
"text": "For UCB1-Tuned, we replace C with the following"
},
{
"code": null,
"e": 5942,
"s": 5725,
"text": "C = √( (logN / n) x min(1/4, V(n)) )where V(n) is an upper confidence bound on the variance of the bandit, i.e.V(n) = Σ(x_i2 / n) - (Σ x_i / n)2 + √(2log(N) / n) and x_i are the rewards we got from the bandit so far."
},
{
"code": null,
"e": 6031,
"s": 5942,
"text": "In the original paper (see section 4), UCB1-Tuned outperformed UCB1 in every experiment."
},
{
"code": null,
"e": 6182,
"s": 6031,
"text": "For UCB1-Normal, C is based on the sample variance and, in contrast to the previous two algorithms, is designed for rewards from normal distributions."
},
{
"code": null,
"e": 6341,
"s": 6182,
"text": "C = √( 16 SV(n) log(N - 1) / n )where the sample variance is SV(n) = ( Σ x_i2 - n (Σ x_i / n)2 ) / (n - 1) x_i are the rewards we got from the bandit so far"
},
{
"code": null,
"e": 6727,
"s": 6341,
"text": "UCB1-Normal does not normally have an initialisation step. Instead, at each round N , it checks if there’s a bandit that has been played less than the ceiling of 8logN and plays that one instead of looking at the upper confidence index. However, to calculate C we need n to be at least 2 so that we don’t divide by zero. Hence, we will play each bandit twice as an initialisation step."
},
{
"code": null,
"e": 6979,
"s": 6727,
"text": "Phew.... that was a lot of bounds. Some of this code has been presented in previous posts, but I will include it here as well for completeness. First, we need some classes to represent the bandits, one for Bernoulli rewards and one for Normal rewards."
},
{
"code": null,
"e": 7211,
"s": 6979,
"text": "Next, we will define some bases classes for the Agents (and a helper class to keep track of the rewards — if you went through the previous article BanditRewardsLog has been modified to keep track of the sum of the squared rewards)."
},
{
"code": null,
"e": 7442,
"s": 7211,
"text": "We still need to define the classes for the Epsilon-Greedy Agent, as we will use it for comparison purposes, and the UCB Agents. They will inherit from the Agent class and need to implement take_action as it is an abstract method."
},
{
"code": null,
"e": 7531,
"s": 7442,
"text": "We now have all the necessary classes for the bandits and the agents. Time for some fun!"
},
{
"code": null,
"e": 7750,
"s": 7531,
"text": "We will go straight into throwing all UCB algorithms and Epsilon-Greedy into the battleground. We will consider two cases, one with rewards from a Bernoulli distribution and one with rewards from a Normal distribution."
},
{
"code": null,
"e": 7803,
"s": 7750,
"text": "We will make use of the following utility functions."
},
{
"code": null,
"e": 9078,
"s": 7803,
"text": "def compare_agents( agents: List[Agent], bandits: List[Bandit], iterations: int, show_plot=True,): for agent in agents: logger.info(\"Running for agent = %s\", agent) agent.bandits = bandits if isinstance(agent, ucb.UCBAgent): agent.initialise() N = iterations - agent.rewards_log.total_actions agent.take_actions(N) if show_plot: cumulative_rewards = np.cumsum( agent.rewards_log.all_rewards, ) plt.plot(cumulative_rewards, label=str(agent)) if show_plot: plt.xlabel(\"iteration\") plt.ylabel(\"total rewards\") plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show()def get_agents(): agents = [ EpsilonGreedyAgent(), ucb.UCB1Agent(), ucb.UCB1TunedAgent(), ucb.UCB1NormalAgent(), ] return agentsdef run_comparison_ucb(bandits): win_count = [0, 0, 0, 0] for _ in range(1000): agents = get_agents() iterations = 1000 compare_agents(agents, bandits, iterations, show_plot=False) rewards = [ agent.rewards_log.total_rewards for agent in agents ] win_count[np.argmax(rewards)] += 1 return win_count"
},
{
"code": null,
"e": 9106,
"s": 9078,
"text": "May the best algorithm win!"
},
{
"code": null,
"e": 9143,
"s": 9106,
"text": "Let’s define our bandits and agents."
},
{
"code": null,
"e": 9248,
"s": 9143,
"text": "probs = [0.6, 0.7, 0.8, 0.9]bernoulli_bandits = [BernoulliBandit(p) for p in probs]agents = get_agents()"
},
{
"code": null,
"e": 9270,
"s": 9248,
"text": "Then we can simply do"
},
{
"code": null,
"e": 9334,
"s": 9270,
"text": "compare_agents(agents, bernoulli_bandits, 1000, show_plot=True)"
},
{
"code": null,
"e": 9547,
"s": 9334,
"text": "It looks like Epsilon-Greedy and UCB1-Tuned are doing better than the other two, but it’s close. We will run_comparison_ucb to repeat this experiment 1000 times and keep count of which agent got the most rewards."
},
{
"code": null,
"e": 9585,
"s": 9547,
"text": "run_comparison_ucb(bernoulli_bandits)"
},
{
"code": null,
"e": 9757,
"s": 9585,
"text": "My results were 497 wins for Epsilon-Greedy, 3 for UCB1, 500 for UCB1-Tuned and 0 of UCB1-Normal. Looks like choosing either Epsilon-Greedy or UCB1-Tuned is the way to go."
},
{
"code": null,
"e": 9868,
"s": 9757,
"text": "We repeat the same experiment but this time with bandits that give rewards according to a normal distribution."
},
{
"code": null,
"e": 9943,
"s": 9868,
"text": "means = [3, 5, 7, 9]normal_bandits = [Bandit(m=m, sigma=1) for m in means]"
},
{
"code": null,
"e": 10166,
"s": 9943,
"text": "Surprisingly, the worst one seems to be UCB1-Normal... shame. It’s not clear which one is the best from the other three, so we will repeat the experiment a bunch of times and keep count of which agent got the most rewards."
},
{
"code": null,
"e": 10265,
"s": 10166,
"text": "I got 156 wins for Epsilon-Greedy, 364 for UCB1, 480 for UCB1-Tuned and 0 (boooo) for UCB1-Normal."
},
{
"code": null,
"e": 10446,
"s": 10265,
"text": "In this post, we’ve looked into how Upper Confidence Bound bandit algorithms work, coded them in Python and compared them against each other and Epsilon-Greedy (with ε=1/#actions)."
},
{
"code": null,
"e": 10693,
"s": 10446,
"text": "We found that UCB1-Tuned performed the best for both Bernoulli and Normal rewards, even though it wasn’t designed for Normal rewards. The worst of the bunch was UCB1-Normal by far — which is probably the reason it is not as popular as the others."
},
{
"code": null,
"e": 10870,
"s": 10693,
"text": "[1] Auer, P., Cesa-Bianchi, N. & Fischer, P. Finite-time Analysis of the Multiarmed Bandit Problem. Machine Learning 47, 235–256 (2002). https://doi.org/10.1023/A:1013689704352"
},
{
"code": null,
"e": 10891,
"s": 10870,
"text": "eminik355.medium.com"
},
{
"code": null,
"e": 11013,
"s": 10891,
"text": "Become a member of Medium and get full access to all stories. Your membership fee directly supports the writers you read."
}
] |
C# Program to Demonstrate the Example of an Array of Delegates - GeeksforGeeks
|
04 Jan, 2022
In C#, a delegate is an object which refers to a method or it is a reference type variable that can hold a reference to the methods. Delegates are similar to the C/C++ function pointer. It also provides a way that tells which method is to be called when an event is triggered. As the name suggests an array of delegates means declaring an array of delegates in the array using the following syntax:
Syntax:
name[] object = new name[size];
Where name is the delegate array and size is the delegate array size. We can also pass the methods to a delegate array through its index.
name[0] = method1;
name[1] = method2;
-----------------
-----------------
name[n] = methodn;
We can call the delegate by using its name.
delegate_array();
Now we will create three methods and create an array of delegates to point the methods and we call methods using an array of delegates.
Approach:
1. Declare the delegate here Myrect() is the delegate.
delegate void Myrect(double len, double width);
2. Create three normal methods named Area, Perimeter, and Diagonal.
3. Create an array of delegates of size 3.
Myrect[] del = new Myrect[3];
4. Pass these methods to each array index of the delegate.
del[0] = Area;
del[1] = Perimeter;
del[2] = Diagonal;
5. Call the delegate iterating the array inside for loop.
for(int i = 0; i < 3; i++)
{
del[i](len, width);
}
Example:
C#
// C# program to illustrate how to create// an array of delegates.using System; // Creating delegatesdelegate void Myrect(double len, double width); class GFG{ // Finding Area of rectanglestatic void Area(double len, double width){ double res1 = len * width; Console.WriteLine("Area:" + res1);} // Finding perimeter of rectanglestatic void Perimeter(double len, double width){ double res2 = 2 * (len + width); Console.WriteLine("Perimeter:" + res2);} // Finding diagonal of rectanglestatic void Diagonal(double len, double width){ double res3 = Math.Sqrt(len * len + width * width); Console.WriteLine("Diagonal:" + res3);} // Driver codestatic void Main(){ double len = 4, width = 5; // Create an array of delegates // with array size 3 Myrect[] del = new Myrect[3]; // Pass the methods to array index del[0] = Area; del[1] = Perimeter; del[2] = Diagonal; Console.WriteLine("Data:"); for(int i = 0; i < 3; i++) { del[i](len, width); }}}
Output:
Data:
Area:20
Perimeter:18
Diagonal:6.40312423743285
Explanation: In the above example, we create a delegate named “Myrect(double len, double width)” and it takes two parameters. Now we create a class named “GFG” that contains three methods named Area, Perimeter, and Diagonal, and these methods take two arguments named len(i.e., length of the rectangle) and width(i.e., width of the rectangle). In the main method, we create two variables and initialize them with the length and width of the rectangle(i.e., 4, and 5). Now we create an array of delegates of size 3 named “del” and pass these methods to each array index of the delegate. i.e., del[0] = Area; del[1] = Perimeter; del[2] = Diagonal;. Display the data by calling the delegate(i.e, del[i](len, width)) iterating the array inside for loop(Here the for loop iterate three times).
as5853535
CSharp-Delegates
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24701,
"s": 24302,
"text": "In C#, a delegate is an object which refers to a method or it is a reference type variable that can hold a reference to the methods. Delegates are similar to the C/C++ function pointer. It also provides a way that tells which method is to be called when an event is triggered. As the name suggests an array of delegates means declaring an array of delegates in the array using the following syntax:"
},
{
"code": null,
"e": 24709,
"s": 24701,
"text": "Syntax:"
},
{
"code": null,
"e": 24741,
"s": 24709,
"text": "name[] object = new name[size];"
},
{
"code": null,
"e": 24879,
"s": 24741,
"text": "Where name is the delegate array and size is the delegate array size. We can also pass the methods to a delegate array through its index."
},
{
"code": null,
"e": 24972,
"s": 24879,
"text": "name[0] = method1;\nname[1] = method2;\n-----------------\n-----------------\nname[n] = methodn;"
},
{
"code": null,
"e": 25016,
"s": 24972,
"text": "We can call the delegate by using its name."
},
{
"code": null,
"e": 25034,
"s": 25016,
"text": "delegate_array();"
},
{
"code": null,
"e": 25170,
"s": 25034,
"text": "Now we will create three methods and create an array of delegates to point the methods and we call methods using an array of delegates."
},
{
"code": null,
"e": 25180,
"s": 25170,
"text": "Approach:"
},
{
"code": null,
"e": 25235,
"s": 25180,
"text": "1. Declare the delegate here Myrect() is the delegate."
},
{
"code": null,
"e": 25283,
"s": 25235,
"text": "delegate void Myrect(double len, double width);"
},
{
"code": null,
"e": 25351,
"s": 25283,
"text": "2. Create three normal methods named Area, Perimeter, and Diagonal."
},
{
"code": null,
"e": 25394,
"s": 25351,
"text": "3. Create an array of delegates of size 3."
},
{
"code": null,
"e": 25424,
"s": 25394,
"text": "Myrect[] del = new Myrect[3];"
},
{
"code": null,
"e": 25483,
"s": 25424,
"text": "4. Pass these methods to each array index of the delegate."
},
{
"code": null,
"e": 25537,
"s": 25483,
"text": "del[0] = Area;\ndel[1] = Perimeter;\ndel[2] = Diagonal;"
},
{
"code": null,
"e": 25595,
"s": 25537,
"text": "5. Call the delegate iterating the array inside for loop."
},
{
"code": null,
"e": 25650,
"s": 25595,
"text": "for(int i = 0; i < 3; i++)\n{\n del[i](len, width);\n}"
},
{
"code": null,
"e": 25659,
"s": 25650,
"text": "Example:"
},
{
"code": null,
"e": 25662,
"s": 25659,
"text": "C#"
},
{
"code": "// C# program to illustrate how to create// an array of delegates.using System; // Creating delegatesdelegate void Myrect(double len, double width); class GFG{ // Finding Area of rectanglestatic void Area(double len, double width){ double res1 = len * width; Console.WriteLine(\"Area:\" + res1);} // Finding perimeter of rectanglestatic void Perimeter(double len, double width){ double res2 = 2 * (len + width); Console.WriteLine(\"Perimeter:\" + res2);} // Finding diagonal of rectanglestatic void Diagonal(double len, double width){ double res3 = Math.Sqrt(len * len + width * width); Console.WriteLine(\"Diagonal:\" + res3);} // Driver codestatic void Main(){ double len = 4, width = 5; // Create an array of delegates // with array size 3 Myrect[] del = new Myrect[3]; // Pass the methods to array index del[0] = Area; del[1] = Perimeter; del[2] = Diagonal; Console.WriteLine(\"Data:\"); for(int i = 0; i < 3; i++) { del[i](len, width); }}}",
"e": 26677,
"s": 25662,
"text": null
},
{
"code": null,
"e": 26685,
"s": 26677,
"text": "Output:"
},
{
"code": null,
"e": 26738,
"s": 26685,
"text": "Data:\nArea:20\nPerimeter:18\nDiagonal:6.40312423743285"
},
{
"code": null,
"e": 27527,
"s": 26738,
"text": "Explanation: In the above example, we create a delegate named “Myrect(double len, double width)” and it takes two parameters. Now we create a class named “GFG” that contains three methods named Area, Perimeter, and Diagonal, and these methods take two arguments named len(i.e., length of the rectangle) and width(i.e., width of the rectangle). In the main method, we create two variables and initialize them with the length and width of the rectangle(i.e., 4, and 5). Now we create an array of delegates of size 3 named “del” and pass these methods to each array index of the delegate. i.e., del[0] = Area; del[1] = Perimeter; del[2] = Diagonal;. Display the data by calling the delegate(i.e, del[i](len, width)) iterating the array inside for loop(Here the for loop iterate three times)."
},
{
"code": null,
"e": 27537,
"s": 27527,
"text": "as5853535"
},
{
"code": null,
"e": 27554,
"s": 27537,
"text": "CSharp-Delegates"
},
{
"code": null,
"e": 27561,
"s": 27554,
"text": "Picked"
},
{
"code": null,
"e": 27564,
"s": 27561,
"text": "C#"
},
{
"code": null,
"e": 27576,
"s": 27564,
"text": "C# Programs"
},
{
"code": null,
"e": 27674,
"s": 27576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27683,
"s": 27674,
"text": "Comments"
},
{
"code": null,
"e": 27696,
"s": 27683,
"text": "Old Comments"
},
{
"code": null,
"e": 27719,
"s": 27696,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27747,
"s": 27719,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27787,
"s": 27747,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27830,
"s": 27787,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27847,
"s": 27830,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27887,
"s": 27847,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27912,
"s": 27887,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 27946,
"s": 27912,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 27992,
"s": 27946,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
2-Satisfiability (2-SAT) Problem - GeeksforGeeks
|
07 Feb, 2022
Boolean Satisfiability or simply SAT is the problem of determining if a Boolean formula is satisfiable or unsatisfiable.
Satisfiable : If the Boolean variables can be assigned values such that the formula turns out to be TRUE, then we say that the formula is satisfiable.
Unsatisfiable : If it is not possible to assign such values, then we say that the formula is unsatisfiable.
Examples:
, is satisfiable, because A = TRUE and B = FALSE makes F = TRUE.
, is unsatisfiable, because:
Note : Boolean satisfiability problem is NP-complete (For proof, refer Cook’s Theorem).
2-SAT is a special case of Boolean Satisfiability Problem and can be solved in polynomial time.
To understand this better, first let us see what is Conjunctive Normal Form (CNF) or also known as Product of Sums (POS). CNF : CNF is a conjunction (AND) of clauses, where every clause is a disjunction (OR).Now, 2-SAT limits the problem of SAT to only those Boolean formula which are expressed as a CNF with every clause having only 2 terms(also called 2-CNF).Example: Thus, Problem of 2-Satisfiability can be stated as:Given CNF with each clause having only 2 terms, is it possible to assign such values to the variables so that the CNF is TRUE?Examples:
Input :
Output : The given expression is satisfiable.
(for x1 = FALSE, x2 = TRUE)
Input :
Output : The given expression is unsatisfiable.
(for all possible combinations of x1 and x2)
For the CNF value to come TRUE, value of every clause should be TRUE. Let one of the clause be .= TRUE
If A = 0, B must be 1 i.e.
If B = 0, A must be 1 i.e.
Thus,
= TRUE is equivalent to
Now, we can express the CNF as an Implication. So, we create an Implication Graph which has 2 edges for every clause of the CNF. is expressed in Implication Graph as Thus, for a Boolean formula with ‘m’ clauses, we make an Implication Graph with:
2 edges for every clause i.e. ‘2m’ edges.
1 node for every Boolean variable involved in the Boolean formula.
Let’s see one example of Implication Graph.
Note: The implication (if A then B) is equivalent to its contrapositive (if then ).Now, consider the following cases:
CASE 1: If [Tex]exists in the graph[/Tex]
This means
If X = TRUE, = TRUE, which is a contradiction.
But if X = FALSE, there are no implication constraints.
Thus, X = FALSE
CASE 2: If [Tex]exists in the graph[/Tex]
This means
If = TRUE, X = TRUE, which is a contradiction.
But if = FALSE, there are no implication constraints.
Thus, = FALSE i.e. X = TRUE
CASE 3: If [Tex]both exist in the graph[/Tex]
One edge requires X to be TRUE and the other one requires X to be FALSE.
Thus, there is no possible assignment in such a case.
CONCLUSION: If any two variables and are on a cycle i.e. both exists, then the CNF is unsatisfiable. Otherwise, there is a possible assignment and the CNF is satisfiable. Note here that, we use path due to the following property of implication: If we have Thus, if we have a path in the Implication Graph, that is pretty much same as having a direct edge.CONCLUSION FROM IMPLEMENTATION POINT OF VIEW: If both X and lie in the same SCC (Strongly Connected Component), the CNF is unsatisfiable. A Strongly Connected Component of a directed graph has nodes such that every node can be reach from every another node in that SCC. Now, if X and lie on the same SCC, we will definitely have present and hence the conclusion.Checking of the SCC can be done in O(E+V) using the Kosaraju’s Algorithm
C++
Java
// C++ implementation to find if the given// expression is satisfiable using the// Kosaraju's Algorithm#include <bits/stdc++.h>using namespace std; const int MAX = 100000; // data structures used to implement Kosaraju's// Algorithm. Please refer// https://www.geeksforgeeks.org/strongly-connected-components/vector<int> adj[MAX];vector<int> adjInv[MAX];bool visited[MAX];bool visitedInv[MAX];stack<int> s; // this array will store the SCC that the// particular node belongs toint scc[MAX]; // counter maintains the number of the SCCint counter = 1; // adds edges to form the original graphvoid addEdges(int a, int b){ adj[a].push_back(b);} // add edges to form the inverse graphvoid addEdgesInverse(int a, int b){ adjInv[b].push_back(a);} // for STEP 1 of Kosaraju's Algorithmvoid dfsFirst(int u){ if(visited[u]) return; visited[u] = 1; for (int i=0;i<adj[u].size();i++) dfsFirst(adj[u][i]); s.push(u);} // for STEP 2 of Kosaraju's Algorithmvoid dfsSecond(int u){ if(visitedInv[u]) return; visitedInv[u] = 1; for (int i=0;i<adjInv[u].size();i++) dfsSecond(adjInv[u][i]); scc[u] = counter;} // function to check 2-Satisfiabilityvoid is2Satisfiable(int n, int m, int a[], int b[]){ // adding edges to the graph for(int i=0;i<m;i++) { // variable x is mapped to x // variable -x is mapped to n+x = n-(-x) // for a[i] or b[i], addEdges -a[i] -> b[i] // AND -b[i] -> a[i] if (a[i]>0 && b[i]>0) { addEdges(a[i]+n, b[i]); addEdgesInverse(a[i]+n, b[i]); addEdges(b[i]+n, a[i]); addEdgesInverse(b[i]+n, a[i]); } else if (a[i]>0 && b[i]<0) { addEdges(a[i]+n, n-b[i]); addEdgesInverse(a[i]+n, n-b[i]); addEdges(-b[i], a[i]); addEdgesInverse(-b[i], a[i]); } else if (a[i]<0 && b[i]>0) { addEdges(-a[i], b[i]); addEdgesInverse(-a[i], b[i]); addEdges(b[i]+n, n-a[i]); addEdgesInverse(b[i]+n, n-a[i]); } else { addEdges(-a[i], n-b[i]); addEdgesInverse(-a[i], n-b[i]); addEdges(-b[i], n-a[i]); addEdgesInverse(-b[i], n-a[i]); } } // STEP 1 of Kosaraju's Algorithm which // traverses the original graph for (int i=1;i<=2*n;i++) if (!visited[i]) dfsFirst(i); // STEP 2 of Kosaraju's Algorithm which // traverses the inverse graph. After this, // array scc[] stores the corresponding value while (!s.empty()) { int n = s.top(); s.pop(); if (!visitedInv[n]) { dfsSecond(n); counter++; } } for (int i=1;i<=n;i++) { // for any 2 variable x and -x lie in // same SCC if(scc[i]==scc[i+n]) { cout << "The given expression " "is unsatisfiable." << endl; return; } } // no such variables x and -x exist which lie // in same SCC cout << "The given expression is satisfiable." << endl; return;} // Driver function to test above functionsint main(){ // n is the number of variables // 2n is the total number of nodes // m is the number of clauses int n = 5, m = 7; // each clause is of the form a or b // for m clauses, we have a[m], b[m] // representing a[i] or b[i] // Note: // 1 <= x <= N for an uncomplemented variable x // -N <= x <= -1 for a complemented variable x // -x is the complement of a variable x // The CNF being handled is: // '+' implies 'OR' and '*' implies 'AND' // (x1+x2)*(x2’+x3)*(x1’+x2’)*(x3+x4)*(x3’+x5)* // (x4’+x5’)*(x3’+x4) int a[] = {1, -2, -1, 3, -3, -4, -3}; int b[] = {2, 3, -2, 4, 5, -5, 4}; // We have considered the same example for which // Implication Graph was made is2Satisfiable(n, m, a, b); return 0;}
// Java implementation to find if the given// expression is satisfiable using the// Kosaraju's Algorithmimport java.io.*;import java.util.*; class GFG{ static final int MAX = 100000; // Data structures used to implement Kosaraju's// Algorithm. Please refer// https://www.geeksforgeeks.org/strongly-connected-components/@SuppressWarnings("unchecked")static List<List<Integer> > adj = new ArrayList(); @SuppressWarnings("unchecked")static List<List<Integer> > adjInv = new ArrayList();static boolean[] visited = new boolean[MAX];static boolean[] visitedInv = new boolean[MAX];static Stack<Integer> s = new Stack<Integer>(); // This array will store the SCC that the// particular node belongs tostatic int[] scc = new int[MAX]; // counter maintains the number of the SCCstatic int counter = 1; // Adds edges to form the original graph voidstatic void addEdges(int a, int b){ adj.get(a).add(b);} // Add edges to form the inverse graphstatic void addEdgesInverse(int a, int b){ adjInv.get(b).add(a);} // For STEP 1 of Kosaraju's Algorithmstatic void dfsFirst(int u){ if (visited[u]) return; visited[u] = true; for(int i = 0; i < adj.get(u).size(); i++) dfsFirst(adj.get(u).get(i)); s.push(u);} // For STEP 2 of Kosaraju's Algorithmstatic void dfsSecond(int u){ if (visitedInv[u]) return; visitedInv[u] = true; for(int i = 0; i < adjInv.get(u).size(); i++) dfsSecond(adjInv.get(u).get(i)); scc[u] = counter;} // Function to check 2-Satisfiabilitystatic void is2Satisfiable(int n, int m, int a[], int b[]){ // Adding edges to the graph for(int i = 0; i < m; i++) { // variable x is mapped to x // variable -x is mapped to n+x = n-(-x) // for a[i] or b[i], addEdges -a[i] -> b[i] // AND -b[i] -> a[i] if (a[i] > 0 && b[i] > 0) { addEdges(a[i] + n, b[i]); addEdgesInverse(a[i] + n, b[i]); addEdges(b[i] + n, a[i]); addEdgesInverse(b[i] + n, a[i]); } else if (a[i] > 0 && b[i] < 0) { addEdges(a[i] + n, n - b[i]); addEdgesInverse(a[i] + n, n - b[i]); addEdges(-b[i], a[i]); addEdgesInverse(-b[i], a[i]); } else if (a[i] < 0 && b[i] > 0) { addEdges(-a[i], b[i]); addEdgesInverse(-a[i], b[i]); addEdges(b[i] + n, n - a[i]); addEdgesInverse(b[i] + n, n - a[i]); } else { addEdges(-a[i], n - b[i]); addEdgesInverse(-a[i], n - b[i]); addEdges(-b[i], n - a[i]); addEdgesInverse(-b[i], n - a[i]); } } // STEP 1 of Kosaraju's Algorithm which // traverses the original graph for(int i = 1; i <= 2 * n; i++) if (!visited[i]) dfsFirst(i); // STEP 2 of Kosaraju's Algorithm which // traverses the inverse graph. After this, // array scc[] stores the corresponding value while (!s.isEmpty()) { int top = s.peek(); s.pop(); if (!visitedInv[top]) { dfsSecond(top); counter++; } } for(int i = 1; i <= n; i++) { // For any 2 variable x and -x lie in // same SCC if (scc[i] == scc[i + n]) { System.out.println("The given expression" + "is unsatisfiable."); return; } } // No such variables x and -x exist which lie // in same SCC System.out.println("The given expression " + "is satisfiable.");} // Driver codepublic static void main(String[] args){ // n is the number of variables // 2n is the total number of nodes // m is the number of clauses int n = 5, m = 7; for(int i = 0; i < MAX; i++) { adj.add(new ArrayList<Integer>()); adjInv.add(new ArrayList<Integer>()); } // Each clause is of the form a or b // for m clauses, we have a[m], b[m] // representing a[i] or b[i] // Note: // 1 <= x <= N for an uncomplemented variable x // -N <= x <= -1 for a complemented variable x // -x is the complement of a variable x // The CNF being handled is: // '+' implies 'OR' and '*' implies 'AND' // (x1+x2)*(x2â+x3)*(x1â+x2â)*(x3+x4)*(x3â+x5)* // (x4â+x5â)*(x3â+x4) int a[] = { 1, -2, -1, 3, -3, -4, -3 }; int b[] = { 2, 3, -2, 4, 5, -5, 4 }; // We have considered the same example // for which Implication Graph was made is2Satisfiable(n, m, a, b);}} // This code is contributed by jithin
Output:
The given expression is satisfiable.
More Test Cases:
Input : n = 2, m = 3
a[] = {1, 2, -1}
b[] = {2, -1, -2}
Output : The given expression is satisfiable.
Input : n = 2, m = 4
a[] = {1, -1, 1, -1}
b[] = {2, 2, -2, -2}
Output : The given expression is unsatisfiable.
This article is contributed by Aanya Jindal. 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.
danielagfavero
jithin
201851037
kk9826225
sumitgumber28
sagar0719kumar
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Best First Search (Informed Search)
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Eulerian path and circuit for undirected graph
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Kruskal's Minimum Spanning Tree using STL in C++
Longest Path in a Directed Acyclic Graph
Shortest Path in a weighted Graph where weight of an edge is 1 or 2
Printing Paths in Dijkstra's Shortest Path Algorithm
|
[
{
"code": null,
"e": 25092,
"s": 25064,
"text": "\n07 Feb, 2022"
},
{
"code": null,
"e": 25215,
"s": 25092,
"text": "Boolean Satisfiability or simply SAT is the problem of determining if a Boolean formula is satisfiable or unsatisfiable. "
},
{
"code": null,
"e": 25366,
"s": 25215,
"text": "Satisfiable : If the Boolean variables can be assigned values such that the formula turns out to be TRUE, then we say that the formula is satisfiable."
},
{
"code": null,
"e": 25474,
"s": 25366,
"text": "Unsatisfiable : If it is not possible to assign such values, then we say that the formula is unsatisfiable."
},
{
"code": null,
"e": 25486,
"s": 25474,
"text": "Examples: "
},
{
"code": null,
"e": 25551,
"s": 25486,
"text": ", is satisfiable, because A = TRUE and B = FALSE makes F = TRUE."
},
{
"code": null,
"e": 25582,
"s": 25551,
"text": ", is unsatisfiable, because: "
},
{
"code": null,
"e": 25672,
"s": 25584,
"text": "Note : Boolean satisfiability problem is NP-complete (For proof, refer Cook’s Theorem)."
},
{
"code": null,
"e": 25770,
"s": 25674,
"text": "2-SAT is a special case of Boolean Satisfiability Problem and can be solved in polynomial time."
},
{
"code": null,
"e": 26329,
"s": 25770,
"text": "To understand this better, first let us see what is Conjunctive Normal Form (CNF) or also known as Product of Sums (POS). CNF : CNF is a conjunction (AND) of clauses, where every clause is a disjunction (OR).Now, 2-SAT limits the problem of SAT to only those Boolean formula which are expressed as a CNF with every clause having only 2 terms(also called 2-CNF).Example: Thus, Problem of 2-Satisfiability can be stated as:Given CNF with each clause having only 2 terms, is it possible to assign such values to the variables so that the CNF is TRUE?Examples: "
},
{
"code": null,
"e": 26516,
"s": 26329,
"text": "Input : \nOutput : The given expression is satisfiable. \n(for x1 = FALSE, x2 = TRUE)\nInput : \nOutput : The given expression is unsatisfiable. \n(for all possible combinations of x1 and x2)"
},
{
"code": null,
"e": 26621,
"s": 26516,
"text": "For the CNF value to come TRUE, value of every clause should be TRUE. Let one of the clause be .= TRUE "
},
{
"code": null,
"e": 26649,
"s": 26621,
"text": "If A = 0, B must be 1 i.e. "
},
{
"code": null,
"e": 26677,
"s": 26649,
"text": "If B = 0, A must be 1 i.e. "
},
{
"code": null,
"e": 26684,
"s": 26677,
"text": "Thus, "
},
{
"code": null,
"e": 26710,
"s": 26684,
"text": " = TRUE is equivalent to "
},
{
"code": null,
"e": 26959,
"s": 26710,
"text": "Now, we can express the CNF as an Implication. So, we create an Implication Graph which has 2 edges for every clause of the CNF. is expressed in Implication Graph as Thus, for a Boolean formula with ‘m’ clauses, we make an Implication Graph with: "
},
{
"code": null,
"e": 27001,
"s": 26959,
"text": "2 edges for every clause i.e. ‘2m’ edges."
},
{
"code": null,
"e": 27068,
"s": 27001,
"text": "1 node for every Boolean variable involved in the Boolean formula."
},
{
"code": null,
"e": 27114,
"s": 27068,
"text": "Let’s see one example of Implication Graph. "
},
{
"code": null,
"e": 27233,
"s": 27114,
"text": "Note: The implication (if A then B) is equivalent to its contrapositive (if then ).Now, consider the following cases: "
},
{
"code": null,
"e": 27407,
"s": 27233,
"text": "CASE 1: If [Tex]exists in the graph[/Tex]\nThis means \nIf X = TRUE, = TRUE, which is a contradiction.\nBut if X = FALSE, there are no implication constraints.\nThus, X = FALSE"
},
{
"code": null,
"e": 27595,
"s": 27409,
"text": "CASE 2: If [Tex]exists in the graph[/Tex]\nThis means \nIf = TRUE, X = TRUE, which is a contradiction.\nBut if = FALSE, there are no implication constraints.\nThus, = FALSE i.e. X = TRUE"
},
{
"code": null,
"e": 27770,
"s": 27597,
"text": "CASE 3: If [Tex]both exist in the graph[/Tex]\nOne edge requires X to be TRUE and the other one requires X to be FALSE.\nThus, there is no possible assignment in such a case."
},
{
"code": null,
"e": 28561,
"s": 27770,
"text": "CONCLUSION: If any two variables and are on a cycle i.e. both exists, then the CNF is unsatisfiable. Otherwise, there is a possible assignment and the CNF is satisfiable. Note here that, we use path due to the following property of implication: If we have Thus, if we have a path in the Implication Graph, that is pretty much same as having a direct edge.CONCLUSION FROM IMPLEMENTATION POINT OF VIEW: If both X and lie in the same SCC (Strongly Connected Component), the CNF is unsatisfiable. A Strongly Connected Component of a directed graph has nodes such that every node can be reach from every another node in that SCC. Now, if X and lie on the same SCC, we will definitely have present and hence the conclusion.Checking of the SCC can be done in O(E+V) using the Kosaraju’s Algorithm "
},
{
"code": null,
"e": 28565,
"s": 28561,
"text": "C++"
},
{
"code": null,
"e": 28570,
"s": 28565,
"text": "Java"
},
{
"code": "// C++ implementation to find if the given// expression is satisfiable using the// Kosaraju's Algorithm#include <bits/stdc++.h>using namespace std; const int MAX = 100000; // data structures used to implement Kosaraju's// Algorithm. Please refer// https://www.geeksforgeeks.org/strongly-connected-components/vector<int> adj[MAX];vector<int> adjInv[MAX];bool visited[MAX];bool visitedInv[MAX];stack<int> s; // this array will store the SCC that the// particular node belongs toint scc[MAX]; // counter maintains the number of the SCCint counter = 1; // adds edges to form the original graphvoid addEdges(int a, int b){ adj[a].push_back(b);} // add edges to form the inverse graphvoid addEdgesInverse(int a, int b){ adjInv[b].push_back(a);} // for STEP 1 of Kosaraju's Algorithmvoid dfsFirst(int u){ if(visited[u]) return; visited[u] = 1; for (int i=0;i<adj[u].size();i++) dfsFirst(adj[u][i]); s.push(u);} // for STEP 2 of Kosaraju's Algorithmvoid dfsSecond(int u){ if(visitedInv[u]) return; visitedInv[u] = 1; for (int i=0;i<adjInv[u].size();i++) dfsSecond(adjInv[u][i]); scc[u] = counter;} // function to check 2-Satisfiabilityvoid is2Satisfiable(int n, int m, int a[], int b[]){ // adding edges to the graph for(int i=0;i<m;i++) { // variable x is mapped to x // variable -x is mapped to n+x = n-(-x) // for a[i] or b[i], addEdges -a[i] -> b[i] // AND -b[i] -> a[i] if (a[i]>0 && b[i]>0) { addEdges(a[i]+n, b[i]); addEdgesInverse(a[i]+n, b[i]); addEdges(b[i]+n, a[i]); addEdgesInverse(b[i]+n, a[i]); } else if (a[i]>0 && b[i]<0) { addEdges(a[i]+n, n-b[i]); addEdgesInverse(a[i]+n, n-b[i]); addEdges(-b[i], a[i]); addEdgesInverse(-b[i], a[i]); } else if (a[i]<0 && b[i]>0) { addEdges(-a[i], b[i]); addEdgesInverse(-a[i], b[i]); addEdges(b[i]+n, n-a[i]); addEdgesInverse(b[i]+n, n-a[i]); } else { addEdges(-a[i], n-b[i]); addEdgesInverse(-a[i], n-b[i]); addEdges(-b[i], n-a[i]); addEdgesInverse(-b[i], n-a[i]); } } // STEP 1 of Kosaraju's Algorithm which // traverses the original graph for (int i=1;i<=2*n;i++) if (!visited[i]) dfsFirst(i); // STEP 2 of Kosaraju's Algorithm which // traverses the inverse graph. After this, // array scc[] stores the corresponding value while (!s.empty()) { int n = s.top(); s.pop(); if (!visitedInv[n]) { dfsSecond(n); counter++; } } for (int i=1;i<=n;i++) { // for any 2 variable x and -x lie in // same SCC if(scc[i]==scc[i+n]) { cout << \"The given expression \" \"is unsatisfiable.\" << endl; return; } } // no such variables x and -x exist which lie // in same SCC cout << \"The given expression is satisfiable.\" << endl; return;} // Driver function to test above functionsint main(){ // n is the number of variables // 2n is the total number of nodes // m is the number of clauses int n = 5, m = 7; // each clause is of the form a or b // for m clauses, we have a[m], b[m] // representing a[i] or b[i] // Note: // 1 <= x <= N for an uncomplemented variable x // -N <= x <= -1 for a complemented variable x // -x is the complement of a variable x // The CNF being handled is: // '+' implies 'OR' and '*' implies 'AND' // (x1+x2)*(x2’+x3)*(x1’+x2’)*(x3+x4)*(x3’+x5)* // (x4’+x5’)*(x3’+x4) int a[] = {1, -2, -1, 3, -3, -4, -3}; int b[] = {2, 3, -2, 4, 5, -5, 4}; // We have considered the same example for which // Implication Graph was made is2Satisfiable(n, m, a, b); return 0;}",
"e": 32530,
"s": 28570,
"text": null
},
{
"code": "// Java implementation to find if the given// expression is satisfiable using the// Kosaraju's Algorithmimport java.io.*;import java.util.*; class GFG{ static final int MAX = 100000; // Data structures used to implement Kosaraju's// Algorithm. Please refer// https://www.geeksforgeeks.org/strongly-connected-components/@SuppressWarnings(\"unchecked\")static List<List<Integer> > adj = new ArrayList(); @SuppressWarnings(\"unchecked\")static List<List<Integer> > adjInv = new ArrayList();static boolean[] visited = new boolean[MAX];static boolean[] visitedInv = new boolean[MAX];static Stack<Integer> s = new Stack<Integer>(); // This array will store the SCC that the// particular node belongs tostatic int[] scc = new int[MAX]; // counter maintains the number of the SCCstatic int counter = 1; // Adds edges to form the original graph voidstatic void addEdges(int a, int b){ adj.get(a).add(b);} // Add edges to form the inverse graphstatic void addEdgesInverse(int a, int b){ adjInv.get(b).add(a);} // For STEP 1 of Kosaraju's Algorithmstatic void dfsFirst(int u){ if (visited[u]) return; visited[u] = true; for(int i = 0; i < adj.get(u).size(); i++) dfsFirst(adj.get(u).get(i)); s.push(u);} // For STEP 2 of Kosaraju's Algorithmstatic void dfsSecond(int u){ if (visitedInv[u]) return; visitedInv[u] = true; for(int i = 0; i < adjInv.get(u).size(); i++) dfsSecond(adjInv.get(u).get(i)); scc[u] = counter;} // Function to check 2-Satisfiabilitystatic void is2Satisfiable(int n, int m, int a[], int b[]){ // Adding edges to the graph for(int i = 0; i < m; i++) { // variable x is mapped to x // variable -x is mapped to n+x = n-(-x) // for a[i] or b[i], addEdges -a[i] -> b[i] // AND -b[i] -> a[i] if (a[i] > 0 && b[i] > 0) { addEdges(a[i] + n, b[i]); addEdgesInverse(a[i] + n, b[i]); addEdges(b[i] + n, a[i]); addEdgesInverse(b[i] + n, a[i]); } else if (a[i] > 0 && b[i] < 0) { addEdges(a[i] + n, n - b[i]); addEdgesInverse(a[i] + n, n - b[i]); addEdges(-b[i], a[i]); addEdgesInverse(-b[i], a[i]); } else if (a[i] < 0 && b[i] > 0) { addEdges(-a[i], b[i]); addEdgesInverse(-a[i], b[i]); addEdges(b[i] + n, n - a[i]); addEdgesInverse(b[i] + n, n - a[i]); } else { addEdges(-a[i], n - b[i]); addEdgesInverse(-a[i], n - b[i]); addEdges(-b[i], n - a[i]); addEdgesInverse(-b[i], n - a[i]); } } // STEP 1 of Kosaraju's Algorithm which // traverses the original graph for(int i = 1; i <= 2 * n; i++) if (!visited[i]) dfsFirst(i); // STEP 2 of Kosaraju's Algorithm which // traverses the inverse graph. After this, // array scc[] stores the corresponding value while (!s.isEmpty()) { int top = s.peek(); s.pop(); if (!visitedInv[top]) { dfsSecond(top); counter++; } } for(int i = 1; i <= n; i++) { // For any 2 variable x and -x lie in // same SCC if (scc[i] == scc[i + n]) { System.out.println(\"The given expression\" + \"is unsatisfiable.\"); return; } } // No such variables x and -x exist which lie // in same SCC System.out.println(\"The given expression \" + \"is satisfiable.\");} // Driver codepublic static void main(String[] args){ // n is the number of variables // 2n is the total number of nodes // m is the number of clauses int n = 5, m = 7; for(int i = 0; i < MAX; i++) { adj.add(new ArrayList<Integer>()); adjInv.add(new ArrayList<Integer>()); } // Each clause is of the form a or b // for m clauses, we have a[m], b[m] // representing a[i] or b[i] // Note: // 1 <= x <= N for an uncomplemented variable x // -N <= x <= -1 for a complemented variable x // -x is the complement of a variable x // The CNF being handled is: // '+' implies 'OR' and '*' implies 'AND' // (x1+x2)*(x2â+x3)*(x1â+x2â)*(x3+x4)*(x3â+x5)* // (x4â+x5â)*(x3â+x4) int a[] = { 1, -2, -1, 3, -3, -4, -3 }; int b[] = { 2, 3, -2, 4, 5, -5, 4 }; // We have considered the same example // for which Implication Graph was made is2Satisfiable(n, m, a, b);}} // This code is contributed by jithin",
"e": 37150,
"s": 32530,
"text": null
},
{
"code": null,
"e": 37160,
"s": 37150,
"text": "Output: "
},
{
"code": null,
"e": 37197,
"s": 37160,
"text": "The given expression is satisfiable."
},
{
"code": null,
"e": 37216,
"s": 37197,
"text": "More Test Cases: "
},
{
"code": null,
"e": 37462,
"s": 37216,
"text": "Input : n = 2, m = 3\n a[] = {1, 2, -1}\n b[] = {2, -1, -2}\nOutput : The given expression is satisfiable.\n\nInput : n = 2, m = 4\n a[] = {1, -1, 1, -1}\n b[] = {2, 2, -2, -2}\nOutput : The given expression is unsatisfiable."
},
{
"code": null,
"e": 37883,
"s": 37462,
"text": "This article is contributed by Aanya Jindal. 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": 37898,
"s": 37883,
"text": "danielagfavero"
},
{
"code": null,
"e": 37905,
"s": 37898,
"text": "jithin"
},
{
"code": null,
"e": 37915,
"s": 37905,
"text": "201851037"
},
{
"code": null,
"e": 37925,
"s": 37915,
"text": "kk9826225"
},
{
"code": null,
"e": 37939,
"s": 37925,
"text": "sumitgumber28"
},
{
"code": null,
"e": 37954,
"s": 37939,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 37960,
"s": 37954,
"text": "Graph"
},
{
"code": null,
"e": 37966,
"s": 37960,
"text": "Graph"
},
{
"code": null,
"e": 38064,
"s": 37966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38073,
"s": 38064,
"text": "Comments"
},
{
"code": null,
"e": 38086,
"s": 38073,
"text": "Old Comments"
},
{
"code": null,
"e": 38122,
"s": 38086,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 38192,
"s": 38122,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 38234,
"s": 38192,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 38299,
"s": 38234,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 38346,
"s": 38299,
"text": "Eulerian path and circuit for undirected graph"
},
{
"code": null,
"e": 38427,
"s": 38346,
"text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)"
},
{
"code": null,
"e": 38476,
"s": 38427,
"text": "Kruskal's Minimum Spanning Tree using STL in C++"
},
{
"code": null,
"e": 38517,
"s": 38476,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 38585,
"s": 38517,
"text": "Shortest Path in a weighted Graph where weight of an edge is 1 or 2"
}
] |
VBScript DateAdd Function
|
A Function, which returns a date to which a specified time interval has been added.
DateAdd(interval,number,date)
Interval, a Required Parameter. It can take the following values −
Interval, a Required Parameter. It can take the following values −
d − day of the year.
d − day of the year.
m − month of the year
m − month of the year
y − year of the year
y − year of the year
yyyy − year
yyyy − year
w − weekday
w − weekday
ww − week
ww − week
q − quarter
q − quarter
h − hour
h − hour
m − minute
m − minute
s − second
s − second
Number, a Required parameter. It can take both positive and negative parameters.
Number, a Required parameter. It can take both positive and negative parameters.
Date, a Required parameter. A Variant or literal representing the date to which interval is added.
Date, a Required parameter. A Variant or literal representing the date to which interval is added.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
' Positive Interal
date1 = 01-Jan-2013
document.write("Line 1 : " &DateAdd("yyyy",1,date1) & "<br />")
document.write("Line 2 : " &DateAdd("q",1,date1) & "<br />")
document.write("Line 3 : " &DateAdd("m",1,date1) & "<br />")
document.write("Line 4 : " &DateAdd("y",1,date1) & "<br />")
document.write("Line 5 : " &DateAdd("d",1,date1) & "<br />")
document.write("Line 6 : " &DateAdd("w",1,date1) & "<br />")
document.write("Line 7 : " &DateAdd("ww",1,date1) & "<br />")
document.write("Line 8 : " &DateAdd("h",1,"01-Jan-2013 12:00:00") & "<br />")
document.write("Line 9 : " &DateAdd("n",1,"01-Jan-2013 12:00:00") & "<br />")
document.write("Line 10 : "&DateAdd("s",1,"01-Jan-2013 12:00:00") & "<br />")
' Negative Interval
document.write("Line 11 : " &DateAdd("yyyy",-1,date1) & "<br />")
document.write("Line 12 : " &DateAdd("q",-1,date1) & "<br />")
document.write("Line 13 : " &DateAdd("m",-1,date1) & "<br />")
document.write("Line 14 : " &DateAdd("y",-1,date1) & "<br />")
document.write("Line 15 : " &DateAdd("d",-1,date1) & "<br />")
document.write("Line 16 : " &DateAdd("w",-1,date1) & "<br />")
document.write("Line 17 : " &DateAdd("ww",-1,date1) & "<br />")
document.write("Line 18 : " &DateAdd("h",-1,"01-Jan-2013 12:00:00") & "<br />")
document.write("Line 19 : " &DateAdd("n",-1,"01-Jan-2013 12:00:00") & "<br />")
document.write("Line 20 : " &DateAdd("s",-1,"01-Jan-2013 12:00:00") & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : 27/06/1895
Line 2 : 27/09/1894
Line 3 : 27/07/1894
Line 4 : 28/06/1894
Line 5 : 28/06/1894
Line 6 : 28/06/1894
Line 7 : 4/07/1894
Line 8 : 1/01/2013 1:00:00 PM
Line 9 : 1/01/2013 12:01:00 PM
Line 10 : 1/01/2013 12:00:01 PM
Line 11 : 27/06/1893
Line 12 : 27/03/1894
Line 13 : 27/05/1894
Line 14 : 26/06/1894
Line 15 : 26/06/1894
Line 16 : 26/06/1894
Line 17 : 20/06/1894
Line 18 : 1/01/2013 11:00:00 AM
Line 19 : 1/01/2013 11:59:00 AM
Line 20 : 1/01/2013 11:59:59 AM
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2164,
"s": 2080,
"text": "A Function, which returns a date to which a specified time interval has been added."
},
{
"code": null,
"e": 2196,
"s": 2164,
"text": "DateAdd(interval,number,date) \n"
},
{
"code": null,
"e": 2263,
"s": 2196,
"text": "Interval, a Required Parameter. It can take the following values −"
},
{
"code": null,
"e": 2330,
"s": 2263,
"text": "Interval, a Required Parameter. It can take the following values −"
},
{
"code": null,
"e": 2351,
"s": 2330,
"text": "d − day of the year."
},
{
"code": null,
"e": 2372,
"s": 2351,
"text": "d − day of the year."
},
{
"code": null,
"e": 2394,
"s": 2372,
"text": "m − month of the year"
},
{
"code": null,
"e": 2416,
"s": 2394,
"text": "m − month of the year"
},
{
"code": null,
"e": 2437,
"s": 2416,
"text": "y − year of the year"
},
{
"code": null,
"e": 2458,
"s": 2437,
"text": "y − year of the year"
},
{
"code": null,
"e": 2470,
"s": 2458,
"text": "yyyy − year"
},
{
"code": null,
"e": 2482,
"s": 2470,
"text": "yyyy − year"
},
{
"code": null,
"e": 2494,
"s": 2482,
"text": "w − weekday"
},
{
"code": null,
"e": 2506,
"s": 2494,
"text": "w − weekday"
},
{
"code": null,
"e": 2516,
"s": 2506,
"text": "ww − week"
},
{
"code": null,
"e": 2526,
"s": 2516,
"text": "ww − week"
},
{
"code": null,
"e": 2538,
"s": 2526,
"text": "q − quarter"
},
{
"code": null,
"e": 2550,
"s": 2538,
"text": "q − quarter"
},
{
"code": null,
"e": 2559,
"s": 2550,
"text": "h − hour"
},
{
"code": null,
"e": 2568,
"s": 2559,
"text": "h − hour"
},
{
"code": null,
"e": 2579,
"s": 2568,
"text": "m − minute"
},
{
"code": null,
"e": 2590,
"s": 2579,
"text": "m − minute"
},
{
"code": null,
"e": 2601,
"s": 2590,
"text": "s − second"
},
{
"code": null,
"e": 2612,
"s": 2601,
"text": "s − second"
},
{
"code": null,
"e": 2693,
"s": 2612,
"text": "Number, a Required parameter. It can take both positive and negative parameters."
},
{
"code": null,
"e": 2774,
"s": 2693,
"text": "Number, a Required parameter. It can take both positive and negative parameters."
},
{
"code": null,
"e": 2873,
"s": 2774,
"text": "Date, a Required parameter. A Variant or literal representing the date to which interval is added."
},
{
"code": null,
"e": 2972,
"s": 2873,
"text": "Date, a Required parameter. A Variant or literal representing the date to which interval is added."
},
{
"code": null,
"e": 4738,
"s": 2972,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n ' Positive Interal\n date1 = 01-Jan-2013\n document.write(\"Line 1 : \" &DateAdd(\"yyyy\",1,date1) & \"<br />\")\n document.write(\"Line 2 : \" &DateAdd(\"q\",1,date1) & \"<br />\")\n document.write(\"Line 3 : \" &DateAdd(\"m\",1,date1) & \"<br />\")\n document.write(\"Line 4 : \" &DateAdd(\"y\",1,date1) & \"<br />\")\n document.write(\"Line 5 : \" &DateAdd(\"d\",1,date1) & \"<br />\")\n \n document.write(\"Line 6 : \" &DateAdd(\"w\",1,date1) & \"<br />\")\n document.write(\"Line 7 : \" &DateAdd(\"ww\",1,date1) & \"<br />\")\n document.write(\"Line 8 : \" &DateAdd(\"h\",1,\"01-Jan-2013 12:00:00\") & \"<br />\")\n document.write(\"Line 9 : \" &DateAdd(\"n\",1,\"01-Jan-2013 12:00:00\") & \"<br />\")\n document.write(\"Line 10 : \"&DateAdd(\"s\",1,\"01-Jan-2013 12:00:00\") & \"<br />\")\n\n ' Negative Interval\n document.write(\"Line 11 : \" &DateAdd(\"yyyy\",-1,date1) & \"<br />\")\n document.write(\"Line 12 : \" &DateAdd(\"q\",-1,date1) & \"<br />\")\n document.write(\"Line 13 : \" &DateAdd(\"m\",-1,date1) & \"<br />\")\n document.write(\"Line 14 : \" &DateAdd(\"y\",-1,date1) & \"<br />\")\n document.write(\"Line 15 : \" &DateAdd(\"d\",-1,date1) & \"<br />\")\n \n document.write(\"Line 16 : \" &DateAdd(\"w\",-1,date1) & \"<br />\")\n document.write(\"Line 17 : \" &DateAdd(\"ww\",-1,date1) & \"<br />\")\n document.write(\"Line 18 : \" &DateAdd(\"h\",-1,\"01-Jan-2013 12:00:00\") & \"<br />\")\n document.write(\"Line 19 : \" &DateAdd(\"n\",-1,\"01-Jan-2013 12:00:00\") & \"<br />\")\n document.write(\"Line 20 : \" &DateAdd(\"s\",-1,\"01-Jan-2013 12:00:00\") & \"<br />\") \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4859,
"s": 4738,
"text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −"
},
{
"code": null,
"e": 5334,
"s": 4859,
"text": "Line 1 : 27/06/1895\nLine 2 : 27/09/1894\nLine 3 : 27/07/1894\nLine 4 : 28/06/1894\nLine 5 : 28/06/1894\nLine 6 : 28/06/1894\nLine 7 : 4/07/1894\nLine 8 : 1/01/2013 1:00:00 PM\nLine 9 : 1/01/2013 12:01:00 PM\nLine 10 : 1/01/2013 12:00:01 PM\nLine 11 : 27/06/1893\nLine 12 : 27/03/1894\nLine 13 : 27/05/1894\nLine 14 : 26/06/1894\nLine 15 : 26/06/1894\nLine 16 : 26/06/1894\nLine 17 : 20/06/1894\nLine 18 : 1/01/2013 11:00:00 AM\nLine 19 : 1/01/2013 11:59:00 AM\nLine 20 : 1/01/2013 11:59:59 AM"
},
{
"code": null,
"e": 5367,
"s": 5334,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5384,
"s": 5367,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5391,
"s": 5384,
"text": " Print"
},
{
"code": null,
"e": 5402,
"s": 5391,
"text": " Add Notes"
}
] |
Carryover and Shape Effects in Media Mix Modeling: Paper Review | by Chris Barton | Towards Data Science
|
The full paper can be found here: link
Table of Contents
Media Mix Modeling
Lagged Effects
Shape Effects
Full Model
Simulation
Calculating ROAS / mROAS
Optimizing marketing budget
— — —
To begin, media mix models (MMM) aim to uncover the causal effect of paid media on a metric of interest, typically sales. Historically, the problem has largely been modeled via linear regression and the causal impact has been derived using Rubin’s potential outcomes framework.
In simple (data science) terms, this translates to
Training a regression model that predicts sales using media spend and control variables.Deriving causal impact by comparing sales when media spend is at observed amount and when it is set to zero.
Training a regression model that predicts sales using media spend and control variables.
Deriving causal impact by comparing sales when media spend is at observed amount and when it is set to zero.
Estimating casual impact from observational data has a number of issues i.e. “correlation doesn’t equal causation” for starters. And media mix models have a host of unique issues to take note of. An excellent review of these issues can be found here: Challenges And Opportunities In Media Mix Modeling
This paper focuses on two specific issues:
Carryover Effects i.e. lagged effects
Shape Effects i.e. diminishing returns
While also providing a Bayesian model, ROAS calculations and optimization methods.
Carryover effects, often called lagged effects, occur when media spend effects sales across a number of days. For example, if we spend $100 on display advertising today, we may not see the effects of this spend for several days. The adstock function attempts to parameterize this phenomenon and the paper takes two approaches to adstock modeling:
Geometric
This is a weighted average going back L days, where L can vary by media channel.
The effect has the largest impact on the day of spend and decays thereafter.
Delayed Adstock
The effect of media spend spikes T (theta) days after media spend.
def geoDecay(alpha, L): ''' weighted average with geometric decay weight_T = alpha ^ T-1 returns: weights of length L to calculate weighted averages with. ''' return alpha**(np.ones(L).cumsum()-1)def delayed_adstock(alpha, theta, L): ''' weighted average with dealyed adstock function weight_T = returns: weights of length L to calculate weighted averages with. ''' return alpha**((np.ones(L).cumsum()-1)-theta)**2def carryover(x, alpha, L, theta = None, func='geo'): ''' 1. x is a vector of media spend going back L timeslots, so it should be len(x) == L 2. Weights is a vector of length L showing how much previous time periods spend has on current period. 3. L is max length of Lag. returns transformed vector of spend # update with numpy average # np.average(x[:2], weights=[1,.9]) ''' transformed_x = [] if func=='geo': weights = geoDecay(alpha, L) elif func=='delayed': weights = delayed_adstock(alpha, theta, L) for t in range(x.shape[0]): upper_window = t+1 lower_window = max(0,upper_window-L) current_window_x = x[:upper_window] t_in_window = len(current_window_x) if t < L: new_x = (current_window_x*np.flip(weights[:t_in_window], axis=0)).sum() transformed_x.append(new_x/weights[:t_in_window].sum()) elif t >= L: current_window_x = x[upper_window-L:upper_window] ext_weights = np.flip(weights, axis=0) new_x = (current_window_x*ext_weights).sum() transformed_x.append(new_x/ext_weights.sum()) return np.array(transformed_x)
Above, we can see the shape of geometric and delayed adstock functions with the given parameters. As expected, the geometric functions starts with a strong impact and then steadily declines whereas the delayed adstock functions spikes 3 days (theta=3) after spend and then rapidly declines.
Next, the paper addresses the phenomenon of diminishing returns, referred to as the shape effects in the paper. This arises when a media channel starts to loose its effectiveness i.e. the difference between spending $0 and $50 is much larger than $200 and $250.
The Hill function is used to model this, which has its roots in biochemistry.
where;
S = Slope; greater than 0
K = Half Saturation Point; greater than 0
beta = Coefficient for channel; greater than 0
x = media spend
def beta_hill(x, S, K, beta): return beta - (K**S*beta)/(x**S+K**S)
The equation above is a modified version of the original. In the original Hill function, as X approaches infinity the function approaches 1, therefore we multiply by a beta coefficient to account for various strengths of marketing channels. If we excluded the beta variable each channel would have the same effectiveness.
The paper does point out that the function has poor identifiability. For example, when K (the half saturation) point is outside of the observed media spend.
We can see this in the graph below in the blue line. Notice that we don’t observe the half-saturation point i.e. the blue line hasn’t started to flatten due to diminishing returns, therefore it is impossible for our model to find the correct value. As a result, our model could incorrectly project high returns as media spend continues to increase.
The graph above illustrates various shapes the hill function can take on.
Next, we need a way to combine the carryover and shape effects. The paper suggest two possible approaches.
Apply the adstock function first and then the shape function.Apply the shape function first and then the adstock function.
Apply the adstock function first and then the shape function.
Apply the shape function first and then the adstock function.
The paper recommends route 1 if there is small spend for any given time period. This makes sense as the shape effect is likely not to be activated by small spend. Alternatively, for large sustained spend it makes sense to first apply the shape (diminishing return) effect and then apply the adstock function.
Now we can specify the functional form of our (the papers) media mix model:
where Xt has been transformed through the Adstock function and Z represents the control variables.
Next we move onto simulation. Simulation is always important when estimating causal effects from observational studies. With simulation we can generate a synthetic dataset, use our model to estimate causal effects and compare our estimates to the ground truth. This allows us to test our model in a way that isn’t possible with observational data.
The simulated data set will contain:
Two Years of Sales Data
Three Media Channels
One Control Variable (Price)
Media spend is generated by adding white noise to a sinusoidal seasonality with one year as a period
Price is generated via an AR(1) series
# media channels N = 102 # number of data pointst = np.linspace(0, 4*np.pi, N)data = 3+np.sin(t+0.001) + 0.5 + np.random.randn(N)media_1 = ((data-min(data))/(max(data)-min(data)) ) t = np.linspace(0, 4*np.pi, N)data = 3+np.sin(t+0.001) + 0.5 + np.random.randn(N)media_2 = ((data-min(data))/(max(data)-min(data)) ) t = np.linspace(0, 4*np.pi, N)data = 3+np.sin(t+0.001) + 0.5 + np.random.randn(N)media_3 = ((data-min(data))/(max(data)-min(data)) ) # price from statsmodels.tsa import arima_process as arimaarparams = np.array([.7, .6])maparams = np.array([.1, .02])ar = np.r_[1, arparams] # add zero-lag and negatema = np.r_[1, maparams] price_variable = arima.arma_generate_sample(ar,ma,102)alpha_media_1 = .6theta_media_1 = 5k_media_1 = .2s_media_1 = 1beta_media_1 = .8alpha_media_2 = .8theta_media_2 = 3k_media_2 = .2s_media_2 = 2beta_media_2 = .6 alpha_media_3 = .8theta_media_3 = 4k_media_3 = .2s_media_3 = 2beta_media_3 = .3L=13ru=4lamb = -.5ep = .05**2m1 = [beta_hill(x, s_media_1, k_media_1, beta_media_1) for x in carryover(media_1, alpha_media_1, L, theta = theta_media_1, func='delayed')]m2 = [beta_hill(x, s_media_2, k_media_2, beta_media_2) for x in carryover(media_2, alpha_media_2, L, theta = theta_media_2, func='delayed')]m3 = [beta_hill(x, s_media_3, k_media_3, beta_media_3) for x in carryover(media_3, alpha_media_3, L, theta = theta_media_3, func='delayed')] y = np.repeat(ru, N) + m1 + m2 + m3 + (lamb*price_variable) + np.random.normal(0, ep, N)
Now that the dataset has been simulated it is time to fit the model. The paper uses STAN, however, I use Python/PyMC3.
import arviz as azimport pymc3 as pmwith pm.Model() as m: alpha = pm.Beta('alpha' , 3 , 3 , shape=3) theta = pm.Uniform('theta' , 0 , 12 , shape=3) k = pm.Beta('k' , 2 , 2 , shape=3) s = pm.Gamma('s' , 3 , 1 , shape=3) beta = pm.HalfNormal('beta' , 1 , shape=3) ru = pm.HalfNormal('intercept', 5) lamb = pm.Normal('lamb' , 0 , 1) noise = pm.InverseGamma('noise' , 0.05, 0.0005) transpose_m1 = [beta_hill(x, s[0], k[0], beta[0]) for x in carryover(media_1, alpha[0], L, theta = theta[0], func='delayed')] transpose_m2 = [beta_hill(x, s[1], k[1], beta[1]) for x in carryover(media_2, alpha[1], L, theta = theta[1], func='delayed')] transpose_m3 = [beta_hill(x, s[2], k[2], beta[2]) for x in carryover(media_3, alpha[2], L, theta = theta[2], func='delayed')] y_hat = pm.Normal('y_hat', mu=ru + transpose_m1 + transpose_m2 + transpose_m3 + lamb * price_variable, sigma=noise, observed=y)trace = pm.fit(method='svgd')
MAPE: 0.12
MAE: 0.026
As expected the in-sample fit (MAPE/MAE) is pretty good 1) because it’s in-sample and 2) because we generated the data with the same functional form we are modeling. So, it boils down to how well the MCMC approximation works.
Below, we can see the posterior distribution of model parameters versus the true model parameter (blue line). This allows us to understand how well our model performed at recovering the true model parameters.
Now we calculate ROAS and mROAS with the following equations.
In English, the equations above translate to what predicted sales will be with all media channels turned on minus predicted sales with all but the M-th media channel, divided by spend. The only catch is that we have to factor in the post-period effect (i.e. carryover effects after synthetic experiment ends). So, instead of just calculating for the change period we have to include the post period as well.
# simulate ROAS media_1_roas = []media_2_roas = []media_3_roas = []burnin=500for i in range(1000): burnin=5 s = np.random.randint(1,1000-burnin) intercept = t['intercept'][s] s_sample1, s_sample2, s_sample3 = t['s'][:,0][burnin:][s], t['s'][:,1][burnin:][s], t['s'][:,2][burnin:][s] k_sample1, k_sample2, k_sample3 = t['k'][:,0][burnin:][s], t['k'][:,1][burnin:][s], t['k'][:,2][burnin:][s] b_sample1, b_sample2, b_sample3 = t['beta'][:,0][burnin:][s], t['beta'][:,1][burnin:][s], t['beta'][:,2][burnin:][s] a_sample1, a_sample2, a_sample3 = t['alpha'][:,0][burnin:][s], t['alpha'][:,1][burnin:][s], t['alpha'][:,2][burnin:][s] t_sample1, t_sample2, t_sample3 = t['theta'][:,0][burnin:][s], t['theta'][:,1][burnin:][s], t['theta'][:,2][burnin:][s] fitted_m1 = [beta_hill(x, s_sample1, k_sample1, b_sample1) for x in carryover(media_1, a_sample1, L, theta = t_sample1, func='delayed')] fitted_m2 = [beta_hill(x, s_sample2, k_sample2, b_sample2) for x in carryover(media_2, a_sample2, L, theta = t_sample2, func='delayed')] fitted_m3 = [beta_hill(x, s_sample3, k_sample3, b_sample3) for x in carryover(media_3, a_sample3, L, theta = t_sample3, func='delayed')] y_hat = intercept + fitted_m1 + fitted_m2 + fitted_m3 + t['lamb'][burnin:][s] * price_variable y_hat_m1 = intercept + fitted_m2 + fitted_m3 + t['lamb'][burnin:][s] * price_variable y_hat_m2 = intercept + fitted_m1 + fitted_m3 + t['lamb'][burnin:][s] * price_variable y_hat_m3 = intercept + fitted_m1 + fitted_m2 + t['lamb'][burnin:][s] * price_variable media_1_roas.append(sum(y_hat[L:]-y_hat_m1[L:]) / media_1[L:len(media_1)-L].sum()) media_2_roas.append(sum(y_hat[L:]-y_hat_m2[L:]) / media_2[L:len(media_1)-L].sum()) media_3_roas.append(sum(y_hat[L:]-y_hat_m3[L:]) / media_3[L:len(media_1)-L].sum())
Lastly, we move onto optimizing a budget. To do this we take our modeled ROAS numbers and translate this into a constrained optimization problem.
To implement this we can plug in our ROAS numbers into a SciPy optimization function to find at what spend our sales are maximized.
The paper explores many facets related to media mix modeling with a focus on carryover and shape effects, but also provides specifications for a bayesian model and explores it effectiveness at recovering true model parameters on a synthetic dataset and the effects of priors and sample size (not covered).
As a next step, I’d find it interesting to see how one can make decisions with this model to not only maximize sales, but to also maximize the “knowledge” of the model. We can think of this as the “exploration” phase in reinforcement learning.
|
[
{
"code": null,
"e": 211,
"s": 172,
"text": "The full paper can be found here: link"
},
{
"code": null,
"e": 229,
"s": 211,
"text": "Table of Contents"
},
{
"code": null,
"e": 248,
"s": 229,
"text": "Media Mix Modeling"
},
{
"code": null,
"e": 263,
"s": 248,
"text": "Lagged Effects"
},
{
"code": null,
"e": 277,
"s": 263,
"text": "Shape Effects"
},
{
"code": null,
"e": 288,
"s": 277,
"text": "Full Model"
},
{
"code": null,
"e": 299,
"s": 288,
"text": "Simulation"
},
{
"code": null,
"e": 324,
"s": 299,
"text": "Calculating ROAS / mROAS"
},
{
"code": null,
"e": 352,
"s": 324,
"text": "Optimizing marketing budget"
},
{
"code": null,
"e": 358,
"s": 352,
"text": "— — —"
},
{
"code": null,
"e": 636,
"s": 358,
"text": "To begin, media mix models (MMM) aim to uncover the causal effect of paid media on a metric of interest, typically sales. Historically, the problem has largely been modeled via linear regression and the causal impact has been derived using Rubin’s potential outcomes framework."
},
{
"code": null,
"e": 687,
"s": 636,
"text": "In simple (data science) terms, this translates to"
},
{
"code": null,
"e": 884,
"s": 687,
"text": "Training a regression model that predicts sales using media spend and control variables.Deriving causal impact by comparing sales when media spend is at observed amount and when it is set to zero."
},
{
"code": null,
"e": 973,
"s": 884,
"text": "Training a regression model that predicts sales using media spend and control variables."
},
{
"code": null,
"e": 1082,
"s": 973,
"text": "Deriving causal impact by comparing sales when media spend is at observed amount and when it is set to zero."
},
{
"code": null,
"e": 1384,
"s": 1082,
"text": "Estimating casual impact from observational data has a number of issues i.e. “correlation doesn’t equal causation” for starters. And media mix models have a host of unique issues to take note of. An excellent review of these issues can be found here: Challenges And Opportunities In Media Mix Modeling"
},
{
"code": null,
"e": 1427,
"s": 1384,
"text": "This paper focuses on two specific issues:"
},
{
"code": null,
"e": 1465,
"s": 1427,
"text": "Carryover Effects i.e. lagged effects"
},
{
"code": null,
"e": 1504,
"s": 1465,
"text": "Shape Effects i.e. diminishing returns"
},
{
"code": null,
"e": 1587,
"s": 1504,
"text": "While also providing a Bayesian model, ROAS calculations and optimization methods."
},
{
"code": null,
"e": 1934,
"s": 1587,
"text": "Carryover effects, often called lagged effects, occur when media spend effects sales across a number of days. For example, if we spend $100 on display advertising today, we may not see the effects of this spend for several days. The adstock function attempts to parameterize this phenomenon and the paper takes two approaches to adstock modeling:"
},
{
"code": null,
"e": 1944,
"s": 1934,
"text": "Geometric"
},
{
"code": null,
"e": 2025,
"s": 1944,
"text": "This is a weighted average going back L days, where L can vary by media channel."
},
{
"code": null,
"e": 2102,
"s": 2025,
"text": "The effect has the largest impact on the day of spend and decays thereafter."
},
{
"code": null,
"e": 2118,
"s": 2102,
"text": "Delayed Adstock"
},
{
"code": null,
"e": 2185,
"s": 2118,
"text": "The effect of media spend spikes T (theta) days after media spend."
},
{
"code": null,
"e": 3886,
"s": 2185,
"text": "def geoDecay(alpha, L): ''' weighted average with geometric decay weight_T = alpha ^ T-1 returns: weights of length L to calculate weighted averages with. ''' return alpha**(np.ones(L).cumsum()-1)def delayed_adstock(alpha, theta, L): ''' weighted average with dealyed adstock function weight_T = returns: weights of length L to calculate weighted averages with. ''' return alpha**((np.ones(L).cumsum()-1)-theta)**2def carryover(x, alpha, L, theta = None, func='geo'): ''' 1. x is a vector of media spend going back L timeslots, so it should be len(x) == L 2. Weights is a vector of length L showing how much previous time periods spend has on current period. 3. L is max length of Lag. returns transformed vector of spend # update with numpy average # np.average(x[:2], weights=[1,.9]) ''' transformed_x = [] if func=='geo': weights = geoDecay(alpha, L) elif func=='delayed': weights = delayed_adstock(alpha, theta, L) for t in range(x.shape[0]): upper_window = t+1 lower_window = max(0,upper_window-L) current_window_x = x[:upper_window] t_in_window = len(current_window_x) if t < L: new_x = (current_window_x*np.flip(weights[:t_in_window], axis=0)).sum() transformed_x.append(new_x/weights[:t_in_window].sum()) elif t >= L: current_window_x = x[upper_window-L:upper_window] ext_weights = np.flip(weights, axis=0) new_x = (current_window_x*ext_weights).sum() transformed_x.append(new_x/ext_weights.sum()) return np.array(transformed_x)"
},
{
"code": null,
"e": 4177,
"s": 3886,
"text": "Above, we can see the shape of geometric and delayed adstock functions with the given parameters. As expected, the geometric functions starts with a strong impact and then steadily declines whereas the delayed adstock functions spikes 3 days (theta=3) after spend and then rapidly declines."
},
{
"code": null,
"e": 4439,
"s": 4177,
"text": "Next, the paper addresses the phenomenon of diminishing returns, referred to as the shape effects in the paper. This arises when a media channel starts to loose its effectiveness i.e. the difference between spending $0 and $50 is much larger than $200 and $250."
},
{
"code": null,
"e": 4517,
"s": 4439,
"text": "The Hill function is used to model this, which has its roots in biochemistry."
},
{
"code": null,
"e": 4524,
"s": 4517,
"text": "where;"
},
{
"code": null,
"e": 4550,
"s": 4524,
"text": "S = Slope; greater than 0"
},
{
"code": null,
"e": 4592,
"s": 4550,
"text": "K = Half Saturation Point; greater than 0"
},
{
"code": null,
"e": 4639,
"s": 4592,
"text": "beta = Coefficient for channel; greater than 0"
},
{
"code": null,
"e": 4655,
"s": 4639,
"text": "x = media spend"
},
{
"code": null,
"e": 4726,
"s": 4655,
"text": "def beta_hill(x, S, K, beta): return beta - (K**S*beta)/(x**S+K**S)"
},
{
"code": null,
"e": 5048,
"s": 4726,
"text": "The equation above is a modified version of the original. In the original Hill function, as X approaches infinity the function approaches 1, therefore we multiply by a beta coefficient to account for various strengths of marketing channels. If we excluded the beta variable each channel would have the same effectiveness."
},
{
"code": null,
"e": 5205,
"s": 5048,
"text": "The paper does point out that the function has poor identifiability. For example, when K (the half saturation) point is outside of the observed media spend."
},
{
"code": null,
"e": 5554,
"s": 5205,
"text": "We can see this in the graph below in the blue line. Notice that we don’t observe the half-saturation point i.e. the blue line hasn’t started to flatten due to diminishing returns, therefore it is impossible for our model to find the correct value. As a result, our model could incorrectly project high returns as media spend continues to increase."
},
{
"code": null,
"e": 5628,
"s": 5554,
"text": "The graph above illustrates various shapes the hill function can take on."
},
{
"code": null,
"e": 5735,
"s": 5628,
"text": "Next, we need a way to combine the carryover and shape effects. The paper suggest two possible approaches."
},
{
"code": null,
"e": 5858,
"s": 5735,
"text": "Apply the adstock function first and then the shape function.Apply the shape function first and then the adstock function."
},
{
"code": null,
"e": 5920,
"s": 5858,
"text": "Apply the adstock function first and then the shape function."
},
{
"code": null,
"e": 5982,
"s": 5920,
"text": "Apply the shape function first and then the adstock function."
},
{
"code": null,
"e": 6291,
"s": 5982,
"text": "The paper recommends route 1 if there is small spend for any given time period. This makes sense as the shape effect is likely not to be activated by small spend. Alternatively, for large sustained spend it makes sense to first apply the shape (diminishing return) effect and then apply the adstock function."
},
{
"code": null,
"e": 6367,
"s": 6291,
"text": "Now we can specify the functional form of our (the papers) media mix model:"
},
{
"code": null,
"e": 6466,
"s": 6367,
"text": "where Xt has been transformed through the Adstock function and Z represents the control variables."
},
{
"code": null,
"e": 6814,
"s": 6466,
"text": "Next we move onto simulation. Simulation is always important when estimating causal effects from observational studies. With simulation we can generate a synthetic dataset, use our model to estimate causal effects and compare our estimates to the ground truth. This allows us to test our model in a way that isn’t possible with observational data."
},
{
"code": null,
"e": 6851,
"s": 6814,
"text": "The simulated data set will contain:"
},
{
"code": null,
"e": 6875,
"s": 6851,
"text": "Two Years of Sales Data"
},
{
"code": null,
"e": 6896,
"s": 6875,
"text": "Three Media Channels"
},
{
"code": null,
"e": 6925,
"s": 6896,
"text": "One Control Variable (Price)"
},
{
"code": null,
"e": 7026,
"s": 6925,
"text": "Media spend is generated by adding white noise to a sinusoidal seasonality with one year as a period"
},
{
"code": null,
"e": 7065,
"s": 7026,
"text": "Price is generated via an AR(1) series"
},
{
"code": null,
"e": 8562,
"s": 7065,
"text": "# media channels N = 102 # number of data pointst = np.linspace(0, 4*np.pi, N)data = 3+np.sin(t+0.001) + 0.5 + np.random.randn(N)media_1 = ((data-min(data))/(max(data)-min(data)) ) t = np.linspace(0, 4*np.pi, N)data = 3+np.sin(t+0.001) + 0.5 + np.random.randn(N)media_2 = ((data-min(data))/(max(data)-min(data)) ) t = np.linspace(0, 4*np.pi, N)data = 3+np.sin(t+0.001) + 0.5 + np.random.randn(N)media_3 = ((data-min(data))/(max(data)-min(data)) ) # price from statsmodels.tsa import arima_process as arimaarparams = np.array([.7, .6])maparams = np.array([.1, .02])ar = np.r_[1, arparams] # add zero-lag and negatema = np.r_[1, maparams] price_variable = arima.arma_generate_sample(ar,ma,102)alpha_media_1 = .6theta_media_1 = 5k_media_1 = .2s_media_1 = 1beta_media_1 = .8alpha_media_2 = .8theta_media_2 = 3k_media_2 = .2s_media_2 = 2beta_media_2 = .6 alpha_media_3 = .8theta_media_3 = 4k_media_3 = .2s_media_3 = 2beta_media_3 = .3L=13ru=4lamb = -.5ep = .05**2m1 = [beta_hill(x, s_media_1, k_media_1, beta_media_1) for x in carryover(media_1, alpha_media_1, L, theta = theta_media_1, func='delayed')]m2 = [beta_hill(x, s_media_2, k_media_2, beta_media_2) for x in carryover(media_2, alpha_media_2, L, theta = theta_media_2, func='delayed')]m3 = [beta_hill(x, s_media_3, k_media_3, beta_media_3) for x in carryover(media_3, alpha_media_3, L, theta = theta_media_3, func='delayed')] y = np.repeat(ru, N) + m1 + m2 + m3 + (lamb*price_variable) + np.random.normal(0, ep, N)"
},
{
"code": null,
"e": 8681,
"s": 8562,
"text": "Now that the dataset has been simulated it is time to fit the model. The paper uses STAN, however, I use Python/PyMC3."
},
{
"code": null,
"e": 9753,
"s": 8681,
"text": "import arviz as azimport pymc3 as pmwith pm.Model() as m: alpha = pm.Beta('alpha' , 3 , 3 , shape=3) theta = pm.Uniform('theta' , 0 , 12 , shape=3) k = pm.Beta('k' , 2 , 2 , shape=3) s = pm.Gamma('s' , 3 , 1 , shape=3) beta = pm.HalfNormal('beta' , 1 , shape=3) ru = pm.HalfNormal('intercept', 5) lamb = pm.Normal('lamb' , 0 , 1) noise = pm.InverseGamma('noise' , 0.05, 0.0005) transpose_m1 = [beta_hill(x, s[0], k[0], beta[0]) for x in carryover(media_1, alpha[0], L, theta = theta[0], func='delayed')] transpose_m2 = [beta_hill(x, s[1], k[1], beta[1]) for x in carryover(media_2, alpha[1], L, theta = theta[1], func='delayed')] transpose_m3 = [beta_hill(x, s[2], k[2], beta[2]) for x in carryover(media_3, alpha[2], L, theta = theta[2], func='delayed')] y_hat = pm.Normal('y_hat', mu=ru + transpose_m1 + transpose_m2 + transpose_m3 + lamb * price_variable, sigma=noise, observed=y)trace = pm.fit(method='svgd')"
},
{
"code": null,
"e": 9764,
"s": 9753,
"text": "MAPE: 0.12"
},
{
"code": null,
"e": 9775,
"s": 9764,
"text": "MAE: 0.026"
},
{
"code": null,
"e": 10001,
"s": 9775,
"text": "As expected the in-sample fit (MAPE/MAE) is pretty good 1) because it’s in-sample and 2) because we generated the data with the same functional form we are modeling. So, it boils down to how well the MCMC approximation works."
},
{
"code": null,
"e": 10210,
"s": 10001,
"text": "Below, we can see the posterior distribution of model parameters versus the true model parameter (blue line). This allows us to understand how well our model performed at recovering the true model parameters."
},
{
"code": null,
"e": 10272,
"s": 10210,
"text": "Now we calculate ROAS and mROAS with the following equations."
},
{
"code": null,
"e": 10680,
"s": 10272,
"text": "In English, the equations above translate to what predicted sales will be with all media channels turned on minus predicted sales with all but the M-th media channel, divided by spend. The only catch is that we have to factor in the post-period effect (i.e. carryover effects after synthetic experiment ends). So, instead of just calculating for the change period we have to include the post period as well."
},
{
"code": null,
"e": 12528,
"s": 10680,
"text": "# simulate ROAS media_1_roas = []media_2_roas = []media_3_roas = []burnin=500for i in range(1000): burnin=5 s = np.random.randint(1,1000-burnin) intercept = t['intercept'][s] s_sample1, s_sample2, s_sample3 = t['s'][:,0][burnin:][s], t['s'][:,1][burnin:][s], t['s'][:,2][burnin:][s] k_sample1, k_sample2, k_sample3 = t['k'][:,0][burnin:][s], t['k'][:,1][burnin:][s], t['k'][:,2][burnin:][s] b_sample1, b_sample2, b_sample3 = t['beta'][:,0][burnin:][s], t['beta'][:,1][burnin:][s], t['beta'][:,2][burnin:][s] a_sample1, a_sample2, a_sample3 = t['alpha'][:,0][burnin:][s], t['alpha'][:,1][burnin:][s], t['alpha'][:,2][burnin:][s] t_sample1, t_sample2, t_sample3 = t['theta'][:,0][burnin:][s], t['theta'][:,1][burnin:][s], t['theta'][:,2][burnin:][s] fitted_m1 = [beta_hill(x, s_sample1, k_sample1, b_sample1) for x in carryover(media_1, a_sample1, L, theta = t_sample1, func='delayed')] fitted_m2 = [beta_hill(x, s_sample2, k_sample2, b_sample2) for x in carryover(media_2, a_sample2, L, theta = t_sample2, func='delayed')] fitted_m3 = [beta_hill(x, s_sample3, k_sample3, b_sample3) for x in carryover(media_3, a_sample3, L, theta = t_sample3, func='delayed')] y_hat = intercept + fitted_m1 + fitted_m2 + fitted_m3 + t['lamb'][burnin:][s] * price_variable y_hat_m1 = intercept + fitted_m2 + fitted_m3 + t['lamb'][burnin:][s] * price_variable y_hat_m2 = intercept + fitted_m1 + fitted_m3 + t['lamb'][burnin:][s] * price_variable y_hat_m3 = intercept + fitted_m1 + fitted_m2 + t['lamb'][burnin:][s] * price_variable media_1_roas.append(sum(y_hat[L:]-y_hat_m1[L:]) / media_1[L:len(media_1)-L].sum()) media_2_roas.append(sum(y_hat[L:]-y_hat_m2[L:]) / media_2[L:len(media_1)-L].sum()) media_3_roas.append(sum(y_hat[L:]-y_hat_m3[L:]) / media_3[L:len(media_1)-L].sum())"
},
{
"code": null,
"e": 12674,
"s": 12528,
"text": "Lastly, we move onto optimizing a budget. To do this we take our modeled ROAS numbers and translate this into a constrained optimization problem."
},
{
"code": null,
"e": 12806,
"s": 12674,
"text": "To implement this we can plug in our ROAS numbers into a SciPy optimization function to find at what spend our sales are maximized."
},
{
"code": null,
"e": 13112,
"s": 12806,
"text": "The paper explores many facets related to media mix modeling with a focus on carryover and shape effects, but also provides specifications for a bayesian model and explores it effectiveness at recovering true model parameters on a synthetic dataset and the effects of priors and sample size (not covered)."
}
] |
Introduction to Clustering in Python with PyCaret | by Moez Ali | Towards Data Science
|
PyCaret is an open-source, low-code machine learning library in Python that automates machine learning workflows. It is an end-to-end machine learning and model management tool that speeds up the experiment cycle exponentially and makes you more productive.
In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes experiments exponentially fast and efficient. PyCaret is essentially a Python wrapper around several machine learning libraries and frameworks such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and a few more.
The design and simplicity of PyCaret are inspired by the emerging role of citizen data scientists, a term first used by Gartner. Citizen Data Scientists are power users who can perform both simple and moderately sophisticated analytical tasks that would previously have required more technical expertise.
To learn more about PyCaret, you can check the official website or GitHub.
In this tutorial we will learn:
Getting Data: How to import data from the PyCaret repository.
Set up Environment: How to set up an experiment in PyCaret’s unsupervised clustering module.
Create Model: How to train unsupervised clustering models and assign cluster labels to the training dataset for further analysis.
Plot Model: How to analyze model performance using various plots (Elbow, Silhouette, Distribution, etc.).
Predict Model: How to assign cluster labels to new and unseen datasets based on a trained model.
Save/Load Model: How to save/load model for future use.
Installation is easy and will only take a few minutes. PyCaret’s default installation from pip only installs hard dependencies as listed in the requirements.txt file.
pip install pycaret
To install the full version:
pip install pycaret[full]
Clustering is the task of grouping a set of objects in such a way that those in the same group (called a cluster) are more similar to each other than to those in other groups. It is an exploratory data mining activity, and a common technique for statistical data analysis used in many fields including machine learning, pattern recognition, image analysis, information retrieval, bioinformatics, data compression, and computer graphics. Some common real-life use cases of clustering are:
Customer segmentation based on purchase history or interests to design targeted marketing campaigns.
Cluster documents into multiple categories based on tags, topics, and the content of the document.
Analysis of outcome in social / life science experiments to find natural groupings and patterns in the data.
PyCaret’s clustering module (pycaret.clustering) is an unsupervised machine learning module that performs the task of grouping a set of objects in such a way that those in the same group (called a cluster) are more similar to each other than to those in other groups.
PyCaret’s clustering module provides several pre-processing features that can be configured when initializing the setup through the setup function. It has over 8 algorithms and several plots to analyze the results. PyCaret's clustering module also implements a unique function called tune_model that allows you to tune the hyperparameters of a clustering model to optimize a supervised learning objective such as AUC for classification or R2 for regression.
In this tutorial, we will use a dataset from UCI called Mice Protein Expression. The data set consists of the expression levels of 77 proteins that produced detectable signals in the nuclear fraction of the cortex. The dataset contains a total of 1080 measurements per protein. Each measurement can be considered as an independent sample (mouse).
Higuera C, Gardiner KJ, Cios KJ (2015) Self-Organizing Feature Maps Identify Proteins Critical to Learning in a Mouse Model of Down Syndrome. PLoS ONE 10(6): e0129126. [Web Link] journal.pone.0129126
You can download the data from the original source found here and load it using pandas (Learn How) or you can use PyCaret’s data repository to load the data using the get_data() function (This will require an internet connection).
from pycaret.datasets import get_datadataset = get_data('mice')
# check the shape of datadataset.shape>>> (1080, 82)
In order to demonstrate the use of the predict_model function on unseen data, a sample of 5% (54 records) has been withheld from the original dataset to be used for predictions at the end of the experiment.
data = dataset.sample(frac=0.95, random_state=786)data_unseen = dataset.drop(data.index)data.reset_index(drop=True, inplace=True)data_unseen.reset_index(drop=True, inplace=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))>>> Data for Modeling: (1026, 82)>>> Unseen Data For Predictions: (54, 82)
The setup function in PyCaret initializes the environment and creates the transformation pipeline for modeling and deployment. setup must be called before executing any other function in pycaret. It takes only one mandatory parameter: a pandas dataframe. All other parameters are optional can be used to customize the preprocessing pipeline.
When setup is executed, PyCaret's inference algorithm will automatically infer the data types for all features based on certain properties. The data type should be inferred correctly but this is not always the case. To handle this, PyCaret displays a prompt, asking for data types confirmation, once you execute the setup. You can press enter if all data types are correct or type quit to exit the setup.
Ensuring that the data types are correct is really important in PyCaret as it automatically performs multiple type-specific preprocessing tasks which are imperative for machine learning models.
Alternatively, you can also use numeric_features and categorical_features parameters in the setup to pre-define the data types.
from pycaret.clustering import *exp_clu101 = setup(data, normalize = True, ignore_features = ['MouseID'], session_id = 123)
Once the setup has been successfully executed it displays the information grid which contains some important information about the experiment. Most of the information is related to the pre-processing pipeline which is constructed when setup is executed. The majority of these features are out of scope for this tutorial, however, a few important things to note are:
session_id: A pseduo-random number distributed as a seed in all functions for later reproducibility. If no session_id is passed, a random number is automatically generated that is distributed to all functions. In this experiment, the session_id is set as 123 for later reproducibility.
Missing Values: When there are missing values in original data this will show as True. Notice that Missing Values in the information grid above is Trueas the data contains missing values which are automatically imputed using mean for the numeric features and constant for the categorical features in the dataset. The method of imputation can be changed using the numeric_imputation and categorical_imputation parameters in the setup function.
Original Data: Displays the original shape of the dataset. In this experiment (1026, 82) means 1026 samples and 82 features.
Transformed Data: Displays the shape of the transformed dataset. Notice that the shape of the original dataset (1026, 82) is transformed into (1026, 91). The number of features has increased due to the encoding of categorical features in the dataset.
Numeric Features: The number of features inferred as numeric. In this dataset, 77 out of 82 features are inferred as numeric.
Categorical Features: The number of features inferred as categorical. In this dataset, 5 out of 82 features are inferred as categorical. Also notice that we have ignored one categorical feature MouseID using the ignore_feature parameter since it's a unique identifier for each sample and we don’t want it to be considered during model training.
Notice how a few tasks that are imperative to perform modeling are automatically handled such as missing value imputation, categorical encoding, etc. Most of the parameters in the setup function are optional and used for customizing the pre-processing pipeline. These parameters are out of scope for this tutorial but I will write more about them later.
Training a clustering model in PyCaret is simple and similar to how you would create a model in the supervised learning modules of PyCaret. A clustering model is created using the create_model function. This function returns a trained model object and a few unsupervised metrics. See an example below:
kmeans = create_model('kmeans')
print(kmeans)>>> OUTPUTKMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300, n_clusters=4, n_init=10, n_jobs=-1, precompute_distances='deprecated', random_state=123, tol=0.0001, verbose=0)
We have trained an unsupervised K-Means model using the create_model. Notice the n_clusters parameter is set to 4 which is the default when you do not pass a value to the num_clusters parameter. In the below example we will create a kmodes model with 6 clusters.
kmodes = create_model('kmodes', num_clusters = 6)
print(kmodes)>>> OUTPUTKModes(cat_dissim=<function matching_dissim at 0x00000168B0B403A0>, init='Cao', max_iter=100, n_clusters=6, n_init=1, n_jobs=-1, random_state=123, verbose=0)
To see the complete list of models available in the model library, please check the documentation or use the models function.
models()
Now that we have trained a model, we can assign the cluster labels to our training dataset (1026 samples) by using the assign_model function.
kmean_results = assign_model(kmeans)kmean_results.head()
Notice that a new column called Cluster has been added to the original dataset.
Note that the results also include the MouseID column that we actually dropped during the setup. Don’t worry, it is not used for the model training, rather is only appended to the dataset only when assign_model is called.
The plot_model function is used to analyze clustering models. This function takes a trained model object and returns a plot.
plot_model(kmeans)
The cluster labels are automatically colored and shown in a legend. When you hover over the data points you will see additional features which by default use the first column of the dataset (in this case MouseID). You can change this by passing the feature parameter and you may also set label to True if you want labels to be printed on the plot.
plot_model(kmeans, plot = 'elbow')
The elbow method is a heuristic method of interpretation and validation of consistency within-cluster analysis designed to help find the appropriate number of clusters in a dataset. In this example, the Elbow plot above suggests that 5 is the optimal number of clusters.
Learn More about Elbow Plot
plot_model(kmeans, plot = 'silhouette')
Silhouette is a method of interpretation and validation of consistency within clusters of data. The technique provides a succinct graphical representation of how well each object has been classified. In other words, the silhouette value is a measure of how similar an object is to its own cluster (cohesion) compared to other clusters (separation).
Learn More about Silhouette Plot
plot_model(kmeans, plot = 'distribution')
The distribution plot shows the size of each cluster. When hovering over the bars you will see the number of samples assigned to each cluster. From the example above, we can observe that cluster 3 has the highest number of samples. We can also use the distribution plot to see the distribution of cluster labels in association with any other numeric or categorical feature.
plot_model(kmeans, plot = 'distribution', feature = 'class')
In the above example, we have used the class as a feature so each bar represents a class which is colored with a cluster label (legend on right). We can observe that class t-SC-m and c-SC-m are mostly dominated by Cluster 3. We can also use the same plot to see the distribution of any continuous feature.
plot_model(kmeans, plot = 'distribution', feature = 'CaNA_N')
The predict_model function is used to assign cluster labels to a new unseen dataset. We will now use our trained kmeans model to predict the data stored in data_unseen. This variable was created at the beginning of the tutorial and contains 54 samples from the original dataset that were never exposed to PyCaret.
unseen_predictions = predict_model(kmeans, data=data_unseen)unseen_predictions.head()
We have now finished the experiment by using our kmeans model to predict labels on unseen data.
This brings us to the end of our experiment, but one question is still to be asked: What happens when you have more new data to predict? Do you have to go through the entire experiment again? The answer is no, PyCaret’s inbuilt function save_model allows you to save the model along with the entire transformation pipeline for later use.
save_model(kmeans,’Final KMeans Model 25Nov2020')
To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model function and then easily apply the saved model on new unseen data for prediction.
saved_kmeans = load_model('Final KMeans Model 25Nov2020')new_prediction = predict_model(saved_kmeans, data=data_unseen)new_prediction.head()
We have only covered the basics of PyCaret’s clustering module. In the following tutorials, we will go deeper into advanced pre-processing techniques that allow you to fully customize your machine learning pipeline and are a must-know for any data scientist.
Thank you for reading 🙏
⭐ Tutorials New to PyCaret? Check out our official notebooks!📋 Example Notebooks created by the community.📙 Blog Tutorials and articles by contributors.📚 Documentation The detailed API docs of PyCaret📺 Video Tutorials Our video tutorial from various events.📢 Discussions Have questions? Engage with community and contributors.🛠️ Changelog Changes and version history.🌳 Roadmap PyCaret’s software and community development plan.
I write about PyCaret and its use-cases in the real world, If you would like to be notified automatically, you can follow me on Medium, LinkedIn, and Twitter.
|
[
{
"code": null,
"e": 430,
"s": 172,
"text": "PyCaret is an open-source, low-code machine learning library in Python that automates machine learning workflows. It is an end-to-end machine learning and model management tool that speeds up the experiment cycle exponentially and makes you more productive."
},
{
"code": null,
"e": 866,
"s": 430,
"text": "In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes experiments exponentially fast and efficient. PyCaret is essentially a Python wrapper around several machine learning libraries and frameworks such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and a few more."
},
{
"code": null,
"e": 1171,
"s": 866,
"text": "The design and simplicity of PyCaret are inspired by the emerging role of citizen data scientists, a term first used by Gartner. Citizen Data Scientists are power users who can perform both simple and moderately sophisticated analytical tasks that would previously have required more technical expertise."
},
{
"code": null,
"e": 1246,
"s": 1171,
"text": "To learn more about PyCaret, you can check the official website or GitHub."
},
{
"code": null,
"e": 1278,
"s": 1246,
"text": "In this tutorial we will learn:"
},
{
"code": null,
"e": 1340,
"s": 1278,
"text": "Getting Data: How to import data from the PyCaret repository."
},
{
"code": null,
"e": 1433,
"s": 1340,
"text": "Set up Environment: How to set up an experiment in PyCaret’s unsupervised clustering module."
},
{
"code": null,
"e": 1563,
"s": 1433,
"text": "Create Model: How to train unsupervised clustering models and assign cluster labels to the training dataset for further analysis."
},
{
"code": null,
"e": 1669,
"s": 1563,
"text": "Plot Model: How to analyze model performance using various plots (Elbow, Silhouette, Distribution, etc.)."
},
{
"code": null,
"e": 1766,
"s": 1669,
"text": "Predict Model: How to assign cluster labels to new and unseen datasets based on a trained model."
},
{
"code": null,
"e": 1822,
"s": 1766,
"text": "Save/Load Model: How to save/load model for future use."
},
{
"code": null,
"e": 1989,
"s": 1822,
"text": "Installation is easy and will only take a few minutes. PyCaret’s default installation from pip only installs hard dependencies as listed in the requirements.txt file."
},
{
"code": null,
"e": 2009,
"s": 1989,
"text": "pip install pycaret"
},
{
"code": null,
"e": 2038,
"s": 2009,
"text": "To install the full version:"
},
{
"code": null,
"e": 2064,
"s": 2038,
"text": "pip install pycaret[full]"
},
{
"code": null,
"e": 2552,
"s": 2064,
"text": "Clustering is the task of grouping a set of objects in such a way that those in the same group (called a cluster) are more similar to each other than to those in other groups. It is an exploratory data mining activity, and a common technique for statistical data analysis used in many fields including machine learning, pattern recognition, image analysis, information retrieval, bioinformatics, data compression, and computer graphics. Some common real-life use cases of clustering are:"
},
{
"code": null,
"e": 2653,
"s": 2552,
"text": "Customer segmentation based on purchase history or interests to design targeted marketing campaigns."
},
{
"code": null,
"e": 2752,
"s": 2653,
"text": "Cluster documents into multiple categories based on tags, topics, and the content of the document."
},
{
"code": null,
"e": 2861,
"s": 2752,
"text": "Analysis of outcome in social / life science experiments to find natural groupings and patterns in the data."
},
{
"code": null,
"e": 3129,
"s": 2861,
"text": "PyCaret’s clustering module (pycaret.clustering) is an unsupervised machine learning module that performs the task of grouping a set of objects in such a way that those in the same group (called a cluster) are more similar to each other than to those in other groups."
},
{
"code": null,
"e": 3587,
"s": 3129,
"text": "PyCaret’s clustering module provides several pre-processing features that can be configured when initializing the setup through the setup function. It has over 8 algorithms and several plots to analyze the results. PyCaret's clustering module also implements a unique function called tune_model that allows you to tune the hyperparameters of a clustering model to optimize a supervised learning objective such as AUC for classification or R2 for regression."
},
{
"code": null,
"e": 3934,
"s": 3587,
"text": "In this tutorial, we will use a dataset from UCI called Mice Protein Expression. The data set consists of the expression levels of 77 proteins that produced detectable signals in the nuclear fraction of the cortex. The dataset contains a total of 1080 measurements per protein. Each measurement can be considered as an independent sample (mouse)."
},
{
"code": null,
"e": 4134,
"s": 3934,
"text": "Higuera C, Gardiner KJ, Cios KJ (2015) Self-Organizing Feature Maps Identify Proteins Critical to Learning in a Mouse Model of Down Syndrome. PLoS ONE 10(6): e0129126. [Web Link] journal.pone.0129126"
},
{
"code": null,
"e": 4365,
"s": 4134,
"text": "You can download the data from the original source found here and load it using pandas (Learn How) or you can use PyCaret’s data repository to load the data using the get_data() function (This will require an internet connection)."
},
{
"code": null,
"e": 4429,
"s": 4365,
"text": "from pycaret.datasets import get_datadataset = get_data('mice')"
},
{
"code": null,
"e": 4482,
"s": 4429,
"text": "# check the shape of datadataset.shape>>> (1080, 82)"
},
{
"code": null,
"e": 4689,
"s": 4482,
"text": "In order to demonstrate the use of the predict_model function on unseen data, a sample of 5% (54 records) has been withheld from the original dataset to be used for predictions at the end of the experiment."
},
{
"code": null,
"e": 5050,
"s": 4689,
"text": "data = dataset.sample(frac=0.95, random_state=786)data_unseen = dataset.drop(data.index)data.reset_index(drop=True, inplace=True)data_unseen.reset_index(drop=True, inplace=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))>>> Data for Modeling: (1026, 82)>>> Unseen Data For Predictions: (54, 82)"
},
{
"code": null,
"e": 5392,
"s": 5050,
"text": "The setup function in PyCaret initializes the environment and creates the transformation pipeline for modeling and deployment. setup must be called before executing any other function in pycaret. It takes only one mandatory parameter: a pandas dataframe. All other parameters are optional can be used to customize the preprocessing pipeline."
},
{
"code": null,
"e": 5797,
"s": 5392,
"text": "When setup is executed, PyCaret's inference algorithm will automatically infer the data types for all features based on certain properties. The data type should be inferred correctly but this is not always the case. To handle this, PyCaret displays a prompt, asking for data types confirmation, once you execute the setup. You can press enter if all data types are correct or type quit to exit the setup."
},
{
"code": null,
"e": 5991,
"s": 5797,
"text": "Ensuring that the data types are correct is really important in PyCaret as it automatically performs multiple type-specific preprocessing tasks which are imperative for machine learning models."
},
{
"code": null,
"e": 6119,
"s": 5991,
"text": "Alternatively, you can also use numeric_features and categorical_features parameters in the setup to pre-define the data types."
},
{
"code": null,
"e": 6280,
"s": 6119,
"text": "from pycaret.clustering import *exp_clu101 = setup(data, normalize = True, ignore_features = ['MouseID'], session_id = 123)"
},
{
"code": null,
"e": 6646,
"s": 6280,
"text": "Once the setup has been successfully executed it displays the information grid which contains some important information about the experiment. Most of the information is related to the pre-processing pipeline which is constructed when setup is executed. The majority of these features are out of scope for this tutorial, however, a few important things to note are:"
},
{
"code": null,
"e": 6932,
"s": 6646,
"text": "session_id: A pseduo-random number distributed as a seed in all functions for later reproducibility. If no session_id is passed, a random number is automatically generated that is distributed to all functions. In this experiment, the session_id is set as 123 for later reproducibility."
},
{
"code": null,
"e": 7375,
"s": 6932,
"text": "Missing Values: When there are missing values in original data this will show as True. Notice that Missing Values in the information grid above is Trueas the data contains missing values which are automatically imputed using mean for the numeric features and constant for the categorical features in the dataset. The method of imputation can be changed using the numeric_imputation and categorical_imputation parameters in the setup function."
},
{
"code": null,
"e": 7500,
"s": 7375,
"text": "Original Data: Displays the original shape of the dataset. In this experiment (1026, 82) means 1026 samples and 82 features."
},
{
"code": null,
"e": 7751,
"s": 7500,
"text": "Transformed Data: Displays the shape of the transformed dataset. Notice that the shape of the original dataset (1026, 82) is transformed into (1026, 91). The number of features has increased due to the encoding of categorical features in the dataset."
},
{
"code": null,
"e": 7877,
"s": 7751,
"text": "Numeric Features: The number of features inferred as numeric. In this dataset, 77 out of 82 features are inferred as numeric."
},
{
"code": null,
"e": 8222,
"s": 7877,
"text": "Categorical Features: The number of features inferred as categorical. In this dataset, 5 out of 82 features are inferred as categorical. Also notice that we have ignored one categorical feature MouseID using the ignore_feature parameter since it's a unique identifier for each sample and we don’t want it to be considered during model training."
},
{
"code": null,
"e": 8576,
"s": 8222,
"text": "Notice how a few tasks that are imperative to perform modeling are automatically handled such as missing value imputation, categorical encoding, etc. Most of the parameters in the setup function are optional and used for customizing the pre-processing pipeline. These parameters are out of scope for this tutorial but I will write more about them later."
},
{
"code": null,
"e": 8878,
"s": 8576,
"text": "Training a clustering model in PyCaret is simple and similar to how you would create a model in the supervised learning modules of PyCaret. A clustering model is created using the create_model function. This function returns a trained model object and a few unsupervised metrics. See an example below:"
},
{
"code": null,
"e": 8910,
"s": 8878,
"text": "kmeans = create_model('kmeans')"
},
{
"code": null,
"e": 9127,
"s": 8910,
"text": "print(kmeans)>>> OUTPUTKMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300, n_clusters=4, n_init=10, n_jobs=-1, precompute_distances='deprecated', random_state=123, tol=0.0001, verbose=0)"
},
{
"code": null,
"e": 9390,
"s": 9127,
"text": "We have trained an unsupervised K-Means model using the create_model. Notice the n_clusters parameter is set to 4 which is the default when you do not pass a value to the num_clusters parameter. In the below example we will create a kmodes model with 6 clusters."
},
{
"code": null,
"e": 9440,
"s": 9390,
"text": "kmodes = create_model('kmodes', num_clusters = 6)"
},
{
"code": null,
"e": 9633,
"s": 9440,
"text": "print(kmodes)>>> OUTPUTKModes(cat_dissim=<function matching_dissim at 0x00000168B0B403A0>, init='Cao', max_iter=100, n_clusters=6, n_init=1, n_jobs=-1, random_state=123, verbose=0)"
},
{
"code": null,
"e": 9759,
"s": 9633,
"text": "To see the complete list of models available in the model library, please check the documentation or use the models function."
},
{
"code": null,
"e": 9768,
"s": 9759,
"text": "models()"
},
{
"code": null,
"e": 9910,
"s": 9768,
"text": "Now that we have trained a model, we can assign the cluster labels to our training dataset (1026 samples) by using the assign_model function."
},
{
"code": null,
"e": 9967,
"s": 9910,
"text": "kmean_results = assign_model(kmeans)kmean_results.head()"
},
{
"code": null,
"e": 10047,
"s": 9967,
"text": "Notice that a new column called Cluster has been added to the original dataset."
},
{
"code": null,
"e": 10269,
"s": 10047,
"text": "Note that the results also include the MouseID column that we actually dropped during the setup. Don’t worry, it is not used for the model training, rather is only appended to the dataset only when assign_model is called."
},
{
"code": null,
"e": 10394,
"s": 10269,
"text": "The plot_model function is used to analyze clustering models. This function takes a trained model object and returns a plot."
},
{
"code": null,
"e": 10413,
"s": 10394,
"text": "plot_model(kmeans)"
},
{
"code": null,
"e": 10761,
"s": 10413,
"text": "The cluster labels are automatically colored and shown in a legend. When you hover over the data points you will see additional features which by default use the first column of the dataset (in this case MouseID). You can change this by passing the feature parameter and you may also set label to True if you want labels to be printed on the plot."
},
{
"code": null,
"e": 10796,
"s": 10761,
"text": "plot_model(kmeans, plot = 'elbow')"
},
{
"code": null,
"e": 11067,
"s": 10796,
"text": "The elbow method is a heuristic method of interpretation and validation of consistency within-cluster analysis designed to help find the appropriate number of clusters in a dataset. In this example, the Elbow plot above suggests that 5 is the optimal number of clusters."
},
{
"code": null,
"e": 11095,
"s": 11067,
"text": "Learn More about Elbow Plot"
},
{
"code": null,
"e": 11135,
"s": 11095,
"text": "plot_model(kmeans, plot = 'silhouette')"
},
{
"code": null,
"e": 11484,
"s": 11135,
"text": "Silhouette is a method of interpretation and validation of consistency within clusters of data. The technique provides a succinct graphical representation of how well each object has been classified. In other words, the silhouette value is a measure of how similar an object is to its own cluster (cohesion) compared to other clusters (separation)."
},
{
"code": null,
"e": 11517,
"s": 11484,
"text": "Learn More about Silhouette Plot"
},
{
"code": null,
"e": 11559,
"s": 11517,
"text": "plot_model(kmeans, plot = 'distribution')"
},
{
"code": null,
"e": 11933,
"s": 11559,
"text": "The distribution plot shows the size of each cluster. When hovering over the bars you will see the number of samples assigned to each cluster. From the example above, we can observe that cluster 3 has the highest number of samples. We can also use the distribution plot to see the distribution of cluster labels in association with any other numeric or categorical feature."
},
{
"code": null,
"e": 11994,
"s": 11933,
"text": "plot_model(kmeans, plot = 'distribution', feature = 'class')"
},
{
"code": null,
"e": 12300,
"s": 11994,
"text": "In the above example, we have used the class as a feature so each bar represents a class which is colored with a cluster label (legend on right). We can observe that class t-SC-m and c-SC-m are mostly dominated by Cluster 3. We can also use the same plot to see the distribution of any continuous feature."
},
{
"code": null,
"e": 12362,
"s": 12300,
"text": "plot_model(kmeans, plot = 'distribution', feature = 'CaNA_N')"
},
{
"code": null,
"e": 12676,
"s": 12362,
"text": "The predict_model function is used to assign cluster labels to a new unseen dataset. We will now use our trained kmeans model to predict the data stored in data_unseen. This variable was created at the beginning of the tutorial and contains 54 samples from the original dataset that were never exposed to PyCaret."
},
{
"code": null,
"e": 12762,
"s": 12676,
"text": "unseen_predictions = predict_model(kmeans, data=data_unseen)unseen_predictions.head()"
},
{
"code": null,
"e": 12858,
"s": 12762,
"text": "We have now finished the experiment by using our kmeans model to predict labels on unseen data."
},
{
"code": null,
"e": 13196,
"s": 12858,
"text": "This brings us to the end of our experiment, but one question is still to be asked: What happens when you have more new data to predict? Do you have to go through the entire experiment again? The answer is no, PyCaret’s inbuilt function save_model allows you to save the model along with the entire transformation pipeline for later use."
},
{
"code": null,
"e": 13246,
"s": 13196,
"text": "save_model(kmeans,’Final KMeans Model 25Nov2020')"
},
{
"code": null,
"e": 13444,
"s": 13246,
"text": "To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model function and then easily apply the saved model on new unseen data for prediction."
},
{
"code": null,
"e": 13585,
"s": 13444,
"text": "saved_kmeans = load_model('Final KMeans Model 25Nov2020')new_prediction = predict_model(saved_kmeans, data=data_unseen)new_prediction.head()"
},
{
"code": null,
"e": 13844,
"s": 13585,
"text": "We have only covered the basics of PyCaret’s clustering module. In the following tutorials, we will go deeper into advanced pre-processing techniques that allow you to fully customize your machine learning pipeline and are a must-know for any data scientist."
},
{
"code": null,
"e": 13868,
"s": 13844,
"text": "Thank you for reading 🙏"
},
{
"code": null,
"e": 14296,
"s": 13868,
"text": "⭐ Tutorials New to PyCaret? Check out our official notebooks!📋 Example Notebooks created by the community.📙 Blog Tutorials and articles by contributors.📚 Documentation The detailed API docs of PyCaret📺 Video Tutorials Our video tutorial from various events.📢 Discussions Have questions? Engage with community and contributors.🛠️ Changelog Changes and version history.🌳 Roadmap PyCaret’s software and community development plan."
}
] |
C++ Program to Find Factorial of a Number using Recursion
|
Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n.
For example: The factorial of 4 is 24.
4! = 4 * 3 * 2 *1
4! = 24
The factorial of an integer can be found using a recursive program or an iterative program.
The following program demonstrates a recursive program to find the factorial of a number −
Live Demo
#include <iostream>
using namespace std;
int fact(int n) {
if ((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}
int main() {
int n = 4;
cout<<"Factorial of "<<n<<" is "<<fact(n);
return 0;
}
Factorial of 4 is 24
In the above program, the function fact() is a recursive function. The main() function calls fact() using the number whose factorial is required. This is demonstrated by the following code snippet.
cout<<"Factorial of "<<n<<" is "<<fact(n);
If the number is 0 or 1, then fact() returns 1. If the number is any other, then fact() recursively calls itself with the value n-1.
This is demonstrated using the following code snippet.
int fact(int n) {
if ((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n."
},
{
"code": null,
"e": 1217,
"s": 1178,
"text": "For example: The factorial of 4 is 24."
},
{
"code": null,
"e": 1243,
"s": 1217,
"text": "4! = 4 * 3 * 2 *1\n4! = 24"
},
{
"code": null,
"e": 1335,
"s": 1243,
"text": "The factorial of an integer can be found using a recursive program or an iterative program."
},
{
"code": null,
"e": 1426,
"s": 1335,
"text": "The following program demonstrates a recursive program to find the factorial of a number −"
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": " Live Demo"
},
{
"code": null,
"e": 1653,
"s": 1437,
"text": "#include <iostream>\nusing namespace std;\nint fact(int n) {\n if ((n==0)||(n==1))\n return 1;\n else\n return n*fact(n-1);\n}\nint main() {\n int n = 4;\n cout<<\"Factorial of \"<<n<<\" is \"<<fact(n);\n return 0;\n}"
},
{
"code": null,
"e": 1674,
"s": 1653,
"text": "Factorial of 4 is 24"
},
{
"code": null,
"e": 1872,
"s": 1674,
"text": "In the above program, the function fact() is a recursive function. The main() function calls fact() using the number whose factorial is required. This is demonstrated by the following code snippet."
},
{
"code": null,
"e": 1915,
"s": 1872,
"text": "cout<<\"Factorial of \"<<n<<\" is \"<<fact(n);"
},
{
"code": null,
"e": 2048,
"s": 1915,
"text": "If the number is 0 or 1, then fact() returns 1. If the number is any other, then fact() recursively calls itself with the value n-1."
},
{
"code": null,
"e": 2103,
"s": 2048,
"text": "This is demonstrated using the following code snippet."
},
{
"code": null,
"e": 2190,
"s": 2103,
"text": "int fact(int n) {\n if ((n==0)||(n==1))\n return 1;\n else\n return n*fact(n-1);\n}"
}
] |
Get minimum element from stack | Practice | GeeksforGeeks
|
You are given N elements and your task is to Implement a Stack in which you can get minimum element in O(1) time.
Example 1:
Input:
push(2)
push(3)
pop()
getMin()
push(1)
getMin()
Output: 3 2 1
Explanation: In the first test case for
query
push(2) Insert 2 into the stack.
The stack will be {2}
push(3) Insert 3 into the stack.
The stack will be {2 3}
pop() Remove top element from stack
Poped element will be 3 the
stack will be {2}
getMin() Return the minimum element
min element will be 2
push(1) Insert 1 into the stack.
The stack will be {2 1}
getMin() Return the minimum element
min element will be 1
Your Task:
You are required to complete the three methods push() which take one argument an integer 'x' to be pushed into the stack, pop() which returns a integer poped out from the stack and getMin() which returns the min element from the stack. (-1 will be returned if for pop() and getMin() the stack is empty.)
Expected Time Complexity : O(1) for all the 3 methods.
Expected Auixilliary Space : O(1) for all the 3 methods.
Constraints:
1 <= Number of queries <= 100
1 <= values of the stack <= 100
0
harshitnjin 9 hours
Python Solution of O(1) time complexity for all functions
class stack:
def __init__(self):
self.s=[]
def push(self,x):
#CODE HERE
if self.s:
self.s.append([x,min(x,self.s[-1][1])])
else:
self.s.append([x,x])
def pop(self):
#CODE HERE
if self.s:
return self.s.pop()[0]
return -1
def getMin(self):
#CODE HERE
if self.s:
return self.s[-1][1]
return -1
0
naveenmnka1556 minutes ago
Python
def push(self,x):
self.s.append(x)
def pop(self):
if len(self.s)>0:
return self.s.pop()
return -1
def getMin(self):
if len(self.s)>0:
return min(self.s)
return -1
0
arjundevmishra62 weeks ago
C++ solution :
class Solution{
int minEle;
multiset<int> st;
stack<int> s;
public:
/*returns min element from stack*/
int getMin(){
if(s.size()==0)
{
return -1;
}
auto it = st.begin();
return *it;
}
/*returns poped element from stack*/
int pop(){
if(s.size()==0)
{
return -1;
}
else{
int a = s.top();
s.pop();
st.erase(st.lower_bound(a));
return a;
}
//Write your code here
}
/*push element x into the stack*/
void push(int x){
s.push(x);
st.insert(x);
}
0
amit09
This comment was deleted.
-1
amit093 weeks ago
class Solution{
int minEle = INT_MAX;
stack<pair<int, int>> s;
public:
/*returns min element from stack*/
int getMin(){
if(s.empty()) return -1;
return minEle;
}
/*returns poped element from stack*/
int pop(){
if(s.empty()) return -1;
int val = s.top().first;
s.pop();
if(!s.empty()) minEle = s.top().second;
return val;
}
/*push element x into the stack*/
void push(int x){
if(s.empty()) minEle = x;
else
minEle = std::min(x,minEle);
s.push({x,minEle});
}
};
0
amruthack11013 weeks ago
JAVA Solution
class GfG
{
int min=Integer.MAX_VALUE;
Stack<Integer> st=new Stack<>();
boolean k=false;
/*returns min element from stack*/
int getMin()
{
if(st.isEmpty()){
return -1;
}
if(k){
for(int v:st){
min=Math.min(min,v);
}
return min;
}
return min;
}
/*returns poped element from stack*/
int pop()
{
if(st.isEmpty()){
return -1;
}
if(st.peek()==min){
k=true;
min=Integer.MAX_VALUE;
}
return st.pop();
}
/*push element x into the stack*/
void push(int x)
{
st.push(x);
min=Math.min(min,x);
}
}
+1
himanshukug19cs1 month ago
int minEle; Stack<Integer> s= new Stack<>();
/*returns min element from stack*/ int getMin() {// Your code here
return s.empty() ? -1:minEle ; } /*returns poped element from stack*/ int pop() {// Your code here if(s.empty()) return -1;if(s.peek()<minEle){ int min=minEle; minEle=2*minEle-s.pop(); return min;}else return s.pop(); }
/*push element x into the stack*/ void push(int x) {// Your code hereif(s.empty()){ s.push(x); minEle=x;}else{ if(x>=minEle){ s.push(x); } else{ s.push(2*x-minEle); minEle=x; } } }
+2
0aryabhatt1 month ago
class GfG {
int minEle;
Stack<Integer> s = new Stack<>();
Stack<Integer> min = new Stack<>();
int getMin() {
if (s.isEmpty())
return -1;
return min.peek();
}
int pop() {
if (s.isEmpty()) {
return -1;
}
int x = s.pop();
if (min.peek() == x) {
min.pop();
}
return x;
}
void push(int x) {
s.push(x);
if (min.isEmpty())
min.push(x);
else {
if (x <= min.peek()) {
min.push(x);
}
}
}
}
0
anshumankumar11 month ago
Simplest c++ solution
class Solution{ stack<int> st,s2; public: int getMin(){ if (st.empty()) return -1; return s2.top(); } int pop(){ if(st.empty()) return -1; if(st.top()==s2.top()) s2.pop(); int x=st.top(); st.pop(); return x; } void push(int x){ if(s2.empty()|| x<=s2.top()) s2.push(x); st.push(x); }};
-1
karmakaranupam111 month ago
java solution using extra stack :
class GfG
{
int minEle;
Stack<Integer> st = new Stack<>();
Stack<Integer> min = new Stack<>();
/*returns min element from stack*/
int getMin()
{
// Your code here
if(min.size() == 0) return -1;
return min.peek();
}
/*returns poped element from stack*/
int pop()
{
// Your code here
if(st.size() == 0 ) return -1;
int e = st.pop();
if(e == min.peek()) min.pop();
return e;
}
/*push element x into the stack*/
void push(int x)
{
// Your code here
st.push(x);
if(min.size() == 0 || min.peek() >= x) min.push(x);
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 352,
"s": 238,
"text": "You are given N elements and your task is to Implement a Stack in which you can get minimum element in O(1) time."
},
{
"code": null,
"e": 363,
"s": 352,
"text": "Example 1:"
},
{
"code": null,
"e": 918,
"s": 363,
"text": "Input:\npush(2)\npush(3)\npop()\ngetMin()\npush(1)\ngetMin()\nOutput: 3 2 1\nExplanation: In the first test case for\nquery \npush(2) Insert 2 into the stack.\n The stack will be {2}\npush(3) Insert 3 into the stack.\n The stack will be {2 3}\npop() Remove top element from stack \n Poped element will be 3 the\n stack will be {2}\ngetMin() Return the minimum element\n min element will be 2 \npush(1) Insert 1 into the stack.\n The stack will be {2 1}\ngetMin() Return the minimum element\n min element will be 1\n"
},
{
"code": null,
"e": 1233,
"s": 918,
"text": "Your Task:\nYou are required to complete the three methods push() which take one argument an integer 'x' to be pushed into the stack, pop() which returns a integer poped out from the stack and getMin() which returns the min element from the stack. (-1 will be returned if for pop() and getMin() the stack is empty.)"
},
{
"code": null,
"e": 1345,
"s": 1233,
"text": "Expected Time Complexity : O(1) for all the 3 methods.\nExpected Auixilliary Space : O(1) for all the 3 methods."
},
{
"code": null,
"e": 1420,
"s": 1345,
"text": "Constraints:\n1 <= Number of queries <= 100\n1 <= values of the stack <= 100"
},
{
"code": null,
"e": 1422,
"s": 1420,
"text": "0"
},
{
"code": null,
"e": 1442,
"s": 1422,
"text": "harshitnjin 9 hours"
},
{
"code": null,
"e": 1500,
"s": 1442,
"text": "Python Solution of O(1) time complexity for all functions"
},
{
"code": null,
"e": 1956,
"s": 1500,
"text": "class stack:\n def __init__(self):\n self.s=[]\n \n\n def push(self,x):\n #CODE HERE\n if self.s:\n self.s.append([x,min(x,self.s[-1][1])])\n else:\n self.s.append([x,x])\n\n def pop(self):\n #CODE HERE\n if self.s:\n return self.s.pop()[0]\n return -1\n \n\n def getMin(self):\n #CODE HERE\n if self.s:\n return self.s[-1][1]\n return -1"
},
{
"code": null,
"e": 1958,
"s": 1956,
"text": "0"
},
{
"code": null,
"e": 1985,
"s": 1958,
"text": "naveenmnka1556 minutes ago"
},
{
"code": null,
"e": 1992,
"s": 1985,
"text": "Python"
},
{
"code": null,
"e": 2194,
"s": 1992,
"text": "def push(self,x):\n self.s.append(x)\n\ndef pop(self):\n if len(self.s)>0:\n return self.s.pop()\n return -1\n \ndef getMin(self):\n\tif len(self.s)>0:\n return min(self.s)\n return -1"
},
{
"code": null,
"e": 2196,
"s": 2194,
"text": "0"
},
{
"code": null,
"e": 2223,
"s": 2196,
"text": "arjundevmishra62 weeks ago"
},
{
"code": null,
"e": 2238,
"s": 2223,
"text": "C++ solution :"
},
{
"code": null,
"e": 3011,
"s": 2238,
"text": "class Solution{\n int minEle;\n multiset<int> st;\n stack<int> s;\n public:\n \n /*returns min element from stack*/\n int getMin(){\n if(s.size()==0)\n {\n return -1;\n }\n auto it = st.begin();\n return *it;\n }\n \n /*returns poped element from stack*/\n int pop(){\n if(s.size()==0)\n {\n return -1;\n }\n else{\n int a = s.top();\n s.pop();\n st.erase(st.lower_bound(a));\n return a;\n }\n //Write your code here\n }\n \n /*push element x into the stack*/\n void push(int x){\n s.push(x);\n st.insert(x);\n }"
},
{
"code": null,
"e": 3013,
"s": 3011,
"text": "0"
},
{
"code": null,
"e": 3020,
"s": 3013,
"text": "amit09"
},
{
"code": null,
"e": 3046,
"s": 3020,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3049,
"s": 3046,
"text": "-1"
},
{
"code": null,
"e": 3067,
"s": 3049,
"text": "amit093 weeks ago"
},
{
"code": null,
"e": 3720,
"s": 3067,
"text": "class Solution{\n int minEle = INT_MAX;\n stack<pair<int, int>> s;\n public:\n \n /*returns min element from stack*/\n int getMin(){\n if(s.empty()) return -1;\n return minEle;\n }\n \n /*returns poped element from stack*/\n int pop(){\n if(s.empty()) return -1;\n int val = s.top().first;\n s.pop();\n if(!s.empty()) minEle = s.top().second;\n return val;\n }\n \n /*push element x into the stack*/\n void push(int x){\n if(s.empty()) minEle = x;\n else \n minEle = std::min(x,minEle);\n s.push({x,minEle});\n }\n};"
},
{
"code": null,
"e": 3722,
"s": 3720,
"text": "0"
},
{
"code": null,
"e": 3747,
"s": 3722,
"text": "amruthack11013 weeks ago"
},
{
"code": null,
"e": 3761,
"s": 3747,
"text": "JAVA Solution"
},
{
"code": null,
"e": 4473,
"s": 3761,
"text": "class GfG\n{\n int min=Integer.MAX_VALUE;\n Stack<Integer> st=new Stack<>();\n boolean k=false;\n /*returns min element from stack*/\n int getMin()\n {\n if(st.isEmpty()){\n return -1;\n }\n if(k){\n for(int v:st){\n min=Math.min(min,v);\n }\n return min;\n }\n return min;\n }\n \n /*returns poped element from stack*/\n int pop()\n {\n if(st.isEmpty()){\n return -1;\n }\n\t\tif(st.peek()==min){\n\t\t k=true;\n\t\t min=Integer.MAX_VALUE;\n\t\t}\n\t\treturn st.pop();\n }\n\n /*push element x into the stack*/\n void push(int x)\n {\n\t st.push(x);\n\t min=Math.min(min,x);\n }\t\n}"
},
{
"code": null,
"e": 4476,
"s": 4473,
"text": "+1"
},
{
"code": null,
"e": 4503,
"s": 4476,
"text": "himanshukug19cs1 month ago"
},
{
"code": null,
"e": 4551,
"s": 4503,
"text": " int minEle; Stack<Integer> s= new Stack<>();"
},
{
"code": null,
"e": 4625,
"s": 4551,
"text": " /*returns min element from stack*/ int getMin() {// Your code here"
},
{
"code": null,
"e": 4885,
"s": 4625,
"text": "return s.empty() ? -1:minEle ; } /*returns poped element from stack*/ int pop() {// Your code here if(s.empty()) return -1;if(s.peek()<minEle){ int min=minEle; minEle=2*minEle-s.pop(); return min;}else return s.pop(); }"
},
{
"code": null,
"e": 5134,
"s": 4885,
"text": " /*push element x into the stack*/ void push(int x) {// Your code hereif(s.empty()){ s.push(x); minEle=x;}else{ if(x>=minEle){ s.push(x); } else{ s.push(2*x-minEle); minEle=x; } } } "
},
{
"code": null,
"e": 5137,
"s": 5134,
"text": "+2"
},
{
"code": null,
"e": 5159,
"s": 5137,
"text": "0aryabhatt1 month ago"
},
{
"code": null,
"e": 5764,
"s": 5159,
"text": "class GfG {\n int minEle;\n Stack<Integer> s = new Stack<>();\n Stack<Integer> min = new Stack<>();\n\n int getMin() {\n if (s.isEmpty())\n return -1;\n return min.peek();\n }\n\n int pop() {\n if (s.isEmpty()) {\n return -1;\n }\n int x = s.pop();\n\n if (min.peek() == x) {\n min.pop();\n }\n return x;\n }\n\n void push(int x) {\n s.push(x);\n\n if (min.isEmpty())\n min.push(x);\n else {\n if (x <= min.peek()) {\n min.push(x);\n }\n }\n }\n}"
},
{
"code": null,
"e": 5766,
"s": 5764,
"text": "0"
},
{
"code": null,
"e": 5792,
"s": 5766,
"text": "anshumankumar11 month ago"
},
{
"code": null,
"e": 5814,
"s": 5792,
"text": "Simplest c++ solution"
},
{
"code": null,
"e": 6282,
"s": 5814,
"text": "class Solution{ stack<int> st,s2; public: int getMin(){ if (st.empty()) return -1; return s2.top(); } int pop(){ if(st.empty()) return -1; if(st.top()==s2.top()) s2.pop(); int x=st.top(); st.pop(); return x; } void push(int x){ if(s2.empty()|| x<=s2.top()) s2.push(x); st.push(x); }};"
},
{
"code": null,
"e": 6285,
"s": 6282,
"text": "-1"
},
{
"code": null,
"e": 6313,
"s": 6285,
"text": "karmakaranupam111 month ago"
},
{
"code": null,
"e": 6347,
"s": 6313,
"text": "java solution using extra stack :"
},
{
"code": null,
"e": 6943,
"s": 6347,
"text": "class GfG\n{\n int minEle;\n Stack<Integer> st = new Stack<>();\n Stack<Integer> min = new Stack<>();\n /*returns min element from stack*/\n int getMin()\n {\n\t// Your code here\n\tif(min.size() == 0) return -1;\n\t return min.peek();\n }\n \n /*returns poped element from stack*/\n int pop()\n {\n\t// Your code here\t\n\tif(st.size() == 0 ) return -1;\n\tint e = st.pop();\n\tif(e == min.peek()) min.pop();\n\treturn e;\n }\n\n /*push element x into the stack*/\n void push(int x)\n {\n\t// Your code here\n\tst.push(x);\n\tif(min.size() == 0 || min.peek() >= x) min.push(x);\n\n }\t\n}"
},
{
"code": null,
"e": 7089,
"s": 6943,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7125,
"s": 7089,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7135,
"s": 7125,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7145,
"s": 7135,
"text": "\nContest\n"
},
{
"code": null,
"e": 7208,
"s": 7145,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7356,
"s": 7208,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7564,
"s": 7356,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7670,
"s": 7564,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C# - Inheritance
|
One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on.
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.
The syntax used in C# for creating derived classes is as follows −
<acess-specifier> class <base_class> {
...
}
class <derived_class> : <base_class> {
...
}
Consider a base class Shape and its derived class Rectangle −
using System;
namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape {
public int getArea() {
return (width * height);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list.
The following program demonstrates this −
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle {
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
public double GetCost() {
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display() {
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program demonstrates this −
using System;
namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
// Base class PaintCost
public interface PaintCost {
int getCost(int area);
}
// Derived class
class Rectangle : Shape, PaintCost {
public int getArea() {
return (width * height);
}
public int getCost(int area) {
return area * 70;
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2581,
"s": 2270,
"text": "One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time."
},
{
"code": null,
"e": 2871,
"s": 2581,
"text": "When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class."
},
{
"code": null,
"e": 3020,
"s": 2871,
"text": "The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on."
},
{
"code": null,
"e": 3175,
"s": 3020,
"text": "A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces."
},
{
"code": null,
"e": 3242,
"s": 3175,
"text": "The syntax used in C# for creating derived classes is as follows −"
},
{
"code": null,
"e": 3340,
"s": 3242,
"text": "<acess-specifier> class <base_class> {\n ...\n}\n\nclass <derived_class> : <base_class> {\n ...\n}\n"
},
{
"code": null,
"e": 3402,
"s": 3340,
"text": "Consider a base class Shape and its derived class Rectangle −"
},
{
"code": null,
"e": 4102,
"s": 3402,
"text": "using System;\n\nnamespace InheritanceApplication {\n class Shape {\n public void setWidth(int w) {\n width = w;\n }\n public void setHeight(int h) {\n height = h;\n }\n protected int width;\n protected int height;\n }\n\n // Derived class\n class Rectangle: Shape {\n public int getArea() { \n return (width * height); \n }\n }\n class RectangleTester {\n static void Main(string[] args) {\n Rectangle Rect = new Rectangle();\n\n Rect.setWidth(5);\n Rect.setHeight(7);\n\n // Print the area of the object.\n Console.WriteLine(\"Total area: {0}\", Rect.getArea());\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4183,
"s": 4102,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4199,
"s": 4183,
"text": "Total area: 35\n"
},
{
"code": null,
"e": 4452,
"s": 4199,
"text": "The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list."
},
{
"code": null,
"e": 4494,
"s": 4452,
"text": "The following program demonstrates this −"
},
{
"code": null,
"e": 5588,
"s": 4494,
"text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n \n //member variables\n protected double length;\n protected double width;\n \n public Rectangle(double l, double w) {\n length = l;\n width = w;\n }\n public double GetArea() {\n return length * width;\n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }//end class Rectangle \n class Tabletop : Rectangle {\n private double cost;\n public Tabletop(double l, double w) : base(l, w) { }\n \n public double GetCost() {\n double cost;\n cost = GetArea() * 70;\n return cost;\n }\n public void Display() {\n base.Display();\n Console.WriteLine(\"Cost: {0}\", GetCost());\n }\n }\n class ExecuteRectangle {\n static void Main(string[] args) {\n Tabletop t = new Tabletop(4.5, 7.5);\n t.Display();\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 5669,
"s": 5588,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5718,
"s": 5669,
"text": "Length: 4.5\nWidth: 7.5\nArea: 33.75\nCost: 2362.5\n"
},
{
"code": null,
"e": 5869,
"s": 5718,
"text": "C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program demonstrates this −"
},
{
"code": null,
"e": 6892,
"s": 5869,
"text": "using System;\n\nnamespace InheritanceApplication {\n class Shape {\n public void setWidth(int w) {\n width = w;\n }\n public void setHeight(int h) {\n height = h;\n }\n protected int width;\n protected int height;\n }\n\n // Base class PaintCost\n public interface PaintCost {\n int getCost(int area);\n }\n \n // Derived class\n class Rectangle : Shape, PaintCost {\n public int getArea() {\n return (width * height);\n }\n public int getCost(int area) {\n return area * 70;\n }\n }\n class RectangleTester {\n static void Main(string[] args) {\n Rectangle Rect = new Rectangle();\n int area;\n \n Rect.setWidth(5);\n Rect.setHeight(7);\n area = Rect.getArea();\n \n // Print the area of the object.\n Console.WriteLine(\"Total area: {0}\", Rect.getArea());\n Console.WriteLine(\"Total paint cost: ${0}\" , Rect.getCost(area));\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 6973,
"s": 6892,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7013,
"s": 6973,
"text": "Total area: 35\nTotal paint cost: $2450\n"
},
{
"code": null,
"e": 7050,
"s": 7013,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 7063,
"s": 7050,
"text": " Raja Biswas"
},
{
"code": null,
"e": 7097,
"s": 7063,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7115,
"s": 7097,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 7148,
"s": 7115,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7162,
"s": 7148,
"text": " Peter Jepson"
},
{
"code": null,
"e": 7199,
"s": 7162,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 7214,
"s": 7199,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 7249,
"s": 7214,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 7264,
"s": 7249,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 7299,
"s": 7264,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7311,
"s": 7299,
"text": " Eric Frick"
},
{
"code": null,
"e": 7318,
"s": 7311,
"text": " Print"
},
{
"code": null,
"e": 7329,
"s": 7318,
"text": " Add Notes"
}
] |
Use MySQL concat() and lower() effectively
|
The contact() method is used to concatenate. However, lower() is used to change the case to lowercase. For our example, let us create a table.
The query to create a table is as follows
mysql> create table concatAndLowerDemo
-> (
-> FirstValue varchar(10),
-> SecondValue varchar(10),
-> ThirdValue varchar(10),
-> FourthValue varchar(10)
-> );
Query OK, 0 rows affected (0.55 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into concatAndLowerDemo values('John','12345','Java','MySQL');
Query OK, 1 row affected (0.21 sec)
mysql> insert into concatAndLowerDemo values('Hi','12345','98764','MongoDB');
Query OK, 1 row affected (0.24 sec)
mysql> insert into concatAndLowerDemo values('9485','746464','903940','cpp');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from concatAndLowerDemo;
The following is the output
+------------+-------------+------------+-------------+
| FirstValue | SecondValue | ThirdValue | FourthValue |
+------------+-------------+------------+-------------+
| John | 12345 | Java | MySQL |
| Hi | 12345 | 98764 | MongoDB |
| 9485 | 746464 | 903940 | cpp |
+------------+-------------+------------+-------------+
3 rows in set (0.00 sec)
Here is the query to use concat() and lower() in the same query
mysql> select lower(concat(FirstValue,SecondValue,ThirdValue,FourthValue)) AS lowerDemo from concatAndLowerDemo;
The following is the output
+---------------------+
| lowerDemo |
+---------------------+
| john12345javamysql |
| hi1234598764mongodb |
| 9485746464903940cpp |
+---------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "The contact() method is used to concatenate. However, lower() is used to change the case to lowercase. For our example, let us create a table."
},
{
"code": null,
"e": 1247,
"s": 1205,
"text": "The query to create a table is as follows"
},
{
"code": null,
"e": 1461,
"s": 1247,
"text": "mysql> create table concatAndLowerDemo\n -> (\n -> FirstValue varchar(10),\n -> SecondValue varchar(10),\n -> ThirdValue varchar(10),\n -> FourthValue varchar(10)\n -> );\nQuery OK, 0 rows affected (0.55 sec)"
},
{
"code": null,
"e": 1528,
"s": 1461,
"text": "Now you can insert some records in the table using insert command."
},
{
"code": null,
"e": 1552,
"s": 1528,
"text": "The query is as follows"
},
{
"code": null,
"e": 1893,
"s": 1552,
"text": "mysql> insert into concatAndLowerDemo values('John','12345','Java','MySQL');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into concatAndLowerDemo values('Hi','12345','98764','MongoDB');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into concatAndLowerDemo values('9485','746464','903940','cpp');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 1952,
"s": 1893,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 1976,
"s": 1952,
"text": "The query is as follows"
},
{
"code": null,
"e": 2016,
"s": 1976,
"text": "mysql> select *from concatAndLowerDemo;"
},
{
"code": null,
"e": 2044,
"s": 2016,
"text": "The following is the output"
},
{
"code": null,
"e": 2461,
"s": 2044,
"text": "+------------+-------------+------------+-------------+\n| FirstValue | SecondValue | ThirdValue | FourthValue |\n+------------+-------------+------------+-------------+\n| John | 12345 | Java | MySQL |\n| Hi | 12345 | 98764 | MongoDB |\n| 9485 | 746464 | 903940 | cpp |\n+------------+-------------+------------+-------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2525,
"s": 2461,
"text": "Here is the query to use concat() and lower() in the same query"
},
{
"code": null,
"e": 2638,
"s": 2525,
"text": "mysql> select lower(concat(FirstValue,SecondValue,ThirdValue,FourthValue)) AS lowerDemo from concatAndLowerDemo;"
},
{
"code": null,
"e": 2666,
"s": 2638,
"text": "The following is the output"
},
{
"code": null,
"e": 2859,
"s": 2666,
"text": "+---------------------+\n| lowerDemo |\n+---------------------+\n| john12345javamysql |\n| hi1234598764mongodb |\n| 9485746464903940cpp |\n+---------------------+\n3 rows in set (0.00 sec)"
}
] |
How to validate email using jQuery?
|
To validate email using jQuery, use the regex pattern. You can try to run the following code to learn how to validate email using jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.error').hide();
$('#submit').click(function(){
var name = $('#name').val();
var email = $('#email').val();
if(name== ''){
$('#name').next().show();
return false;
}
if(email== ''){
$('#email').next().show();
return false;
}
if(IsEmail(email)==false){
$('#invalid_email').show();
return false;
}
$.post("", $("#myform").serialize(), function(response) {
$('#myform').fadeOut('slow',function(){
$('#correct').html(response);
$('#correct').fadeIn('slow');
});
});
return false;
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form action="" method="post" id="contactform">
<table class="mytable">
<tr>
<td><label for="name">Name :</label></td>
<td class="name"> <input name="name" id="name" type="text" placeholder="Please enter your name" class="contact-input"><span class="error">Enter your name here</span></td>
</tr>
<tr>
<td><label for="email">Email :</label></td>
<td class="email"><input name="email" id="email" type="text" placeholder="Please enter your email" class="contact-input"><span class="error">Enter your email-id here</span>
<span class="error" id="invalid_email">Email-id is invalid</span>
</td>
</td>
</tr>
<tr>
<input type="submit" class="contactform-buttons" id="submit"value="Send" />
<input type="reset" class="contactform-buttons" id="" value="Clear" />
</tr>
</tr>
</table>
</form>
<div id="correct" style="color:gray;"></div>
</body>
</html>
|
[
{
"code": null,
"e": 1201,
"s": 1062,
"text": "To validate email using jQuery, use the regex pattern. You can try to run the following code to learn how to validate email using jQuery −"
},
{
"code": null,
"e": 1211,
"s": 1201,
"text": "Live Demo"
},
{
"code": null,
"e": 3205,
"s": 1211,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script> \n $(document).ready(function() {\n $('.error').hide();\n $('#submit').click(function(){\n var name = $('#name').val();\n var email = $('#email').val();\n\n if(name== ''){\n $('#name').next().show();\n return false;\n }\n if(email== ''){\n $('#email').next().show();\n return false;\n }\n if(IsEmail(email)==false){\n $('#invalid_email').show();\n return false;\n }\n $.post(\"\", $(\"#myform\").serialize(), function(response) {\n $('#myform').fadeOut('slow',function(){\n $('#correct').html(response);\n $('#correct').fadeIn('slow');\n });\n });\n return false;\n });\n });\n function IsEmail(email) {\n var regex = /^([a-zA-Z0-9_\\.\\-\\+])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\n if(!regex.test(email)) {\n return false;\n }else{\n return true;\n }\n}\n</script>\n</head>\n<body>\n <form action=\"\" method=\"post\" id=\"contactform\">\n <table class=\"mytable\">\n <tr>\n <td><label for=\"name\">Name :</label></td>\n <td class=\"name\"> <input name=\"name\" id=\"name\" type=\"text\" placeholder=\"Please enter your name\" class=\"contact-input\"><span class=\"error\">Enter your name here</span></td>\n </tr>\n <tr>\n <td><label for=\"email\">Email :</label></td>\n <td class=\"email\"><input name=\"email\" id=\"email\" type=\"text\" placeholder=\"Please enter your email\" class=\"contact-input\"><span class=\"error\">Enter your email-id here</span>\n <span class=\"error\" id=\"invalid_email\">Email-id is invalid</span>\n </td>\n </td>\n </tr>\n <tr>\n <input type=\"submit\" class=\"contactform-buttons\" id=\"submit\"value=\"Send\" />\n <input type=\"reset\" class=\"contactform-buttons\" id=\"\" value=\"Clear\" />\n </tr>\n </tr>\n</table>\n</form>\n <div id=\"correct\" style=\"color:gray;\"></div>\n</body>\n</html>"
}
] |
C - Categories of Functions - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to learn about categories of functions.
All the C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Depending on the arguments and return values functions are classified into 4 categories:
Function without arguments and without a return value.
Function with arguments and without a return value.
Function without arguments and with a return value.
Function with arguments and with a return value.
Function without arguments and without a return value.
Function with arguments and without a return value.
Function without arguments and with a return value.
Function with arguments and with a return value.
When a function has no arguments, it does not receive any data from the calling function. similarly, when a function does not return a value, the calling function does not receive any data from the called function.
In effect, there is no data transfer between the calling function and the called function in the category function without arguments and without a return value.
Let’s consider an example of a function without arguments and without a return value:
#include <stdio.h>
void country_capital(void);
void main() {
country_capital();
}
void country_capital() {
printf("New Delhi is the capital of India\n");
}
Output:
New Delhi is the capital of India
In the above sample code the function
void country_capital(void);
specifies that the function does not receive any arguments and does not return any value to the main() function.
When a function definition has arguments, it receives data from the calling function.
The actual arguments in the function call must correspond to the formal parameters in the function definition, i.e. the number of actual arguments must be the same as the number of formal parameters, and each actual argument must be of the same data type as its corresponding formal parameter.
The formal parameters must be valid variable names in the function definition and the actual arguments may be variable names, expressions, or constants in the function call.
The variables used in actual arguments must be assigned values before the function call is made. When a function call is made, copies of the values of actual arguments are passed to the called function.
What occurs inside the function will have no effect on the variables used in the actual argument list. There may be several different calls to the same function from various places with a program.
Let’s consider an example of a function with arguments and without return value:
#include <stdio.h>
void largest(int, int);
void main() {
int p, q;
printf("Enter two numbers : ");
scanf("%d%d" , &p, &q);
largest(p, q);
}
void largest(int x, int y) {
if (x > y) {
printf("Largest element = %d\n", x);
} else {
printf("Largest element = %d\n", y);
}
}
Output:
Enter two numbers : 1
10
Largest element = 10
In the above sample code the function
void largest(int, int);
specifies that the function receives two integer arguments from the calling function and does not return any value to the called function.
When the function call largest(p, q) is made in the main() function, the values of actual arguments p and q are copied into the formal parameters x and y.
After completion of execution of largest(int x, int y) function, it does not return any value to the main() function. Simply the control is transferred to the main() function.
When a function has no arguments, it does not receive any data from the calling function. When a function returns a value, the calling function receives data from the called function.
Let’s consider an example of a function without arguments and with a return value:
#include <stdio.h>
int sum(void);
void main() {
printf("\nSum of two given values = %d\n", sum());
}
int sum() {
int a, b, total;
printf("Enter two numbers : ");
scanf("%d%d", &a, &b);
total = a + b;
return total;
}
Output:
Enter two numbers : 1
2
Sum of two given values = 3
In the above sample code the function
int sum(void);
specifies that the function does not receive any arguments but returns a value to the calling function.
When a function definition has arguments, it receives data from the calling function.
After taking some desired action, only one value will be returned from called function to the calling a function through the return statement.
If a function returns a value, the function call may appear in any expression, and the returned value used as an operand in the evaluation of the expression.
Let us consider an example of a function with arguments and with return value:
#include <stdio.h>
int largest(int, int, int);
void main() {
int a, b, c;
printf("Enter three numbers : ");
scanf("%d%d%d" , &a, &b, &c);
printf(" Largest of the given three numbers = %d\n", largest(a, b, c));
}
int largest(int x, int y, int z) {
if ((x > y) && (x > z)) {
return x;
} else if (y > z) {
return y;
} else {
return z;
}
}
Output:
Enter three numbers : 1
4
7
Largest of the given three numbers = 7
In the above sample code the function
int largest(int, int, int);
specifies that the function receives three values and returns a value to the calling function.
crasseux – Functions
C Functions
User defined functions in C
Happy Learning 🙂
C How to Pass Arrays to Functions
Functions in C
User defined Functions in C
PHP Functions Example Tutorials
Python Decorators – Classes and Functions
Dynamic Memory Allocation in C
JQuery Callback Functions Example Tutorial
PHP String functions Example Tutorials
C Program – Find Largest and Smallest number in an Array
Understanding the structure of a C Program
C – Derived and User Defined Data Types
Java Program To Find Largest and Smallest Number in Array
Java Program to find Smallest and Largest element in Array
C – Header Files & Preprocessor Directives
Understanding Scope & Lifetime of Variables
C How to Pass Arrays to Functions
Functions in C
User defined Functions in C
PHP Functions Example Tutorials
Python Decorators – Classes and Functions
Dynamic Memory Allocation in C
JQuery Callback Functions Example Tutorial
PHP String functions Example Tutorials
C Program – Find Largest and Smallest number in an Array
Understanding the structure of a C Program
C – Derived and User Defined Data Types
Java Program To Find Largest and Smallest Number in Array
Java Program to find Smallest and Largest element in Array
C – Header Files & Preprocessor Directives
Understanding Scope & Lifetime of Variables
Δ
C – Introduction
C – Features
C – Variables & Keywords
C – Program Structure
C – Comment Lines & Tokens
C – Number System
C – Local and Global Variables
C – Scope & Lifetime of Variables
C – Data Types
C – Integer Data Types
C – Floating Data Types
C – Derived, Defined Data Types
C – Type Conversions
C – Arithmetic Operators
C – Bitwise Operators
C – Logical Operators
C – Comma and sizeof Operators
C – Operator Precedence and Associativity
C – Relational Operators
C Flow Control – if, if-else, nested if-else, if-else-if
C – Switch Case
C Iterative – for, while, dowhile loops
C Unconditional – break, continue, goto statements
C – Expressions and Statements
C – Header Files & Preprocessor Directives
C – One Dimensional Arrays
C – Multi Dimensional Arrays
C – Pointers Basics
C – Pointers with Arrays
C – Functions
C – How to Pass Arrays to Functions
C – Categories of Functions
C – User defined Functions
C – Formal and Actual Arguments
C – Recursion functions
C – Structures Part -1
C – Structures Part -2
C – Unions
C – File Handling
C – File Operations
C – Dynamic Memory Allocation
C Program – Fibonacci Series
C Program – Prime or Not
C Program – Factorial of Number
C Program – Even or Odd
C Program – Sum of digits till Single Digit
C Program – Sum of digits
C Program – Reverse of a number
C Program – Armstrong Numbers
C Program – Print prime Numbers
C Program – GCD of two Numbers
C Program – Number Palindrome or Not
C Program – Find Largest and Smallest number in an Array
C Program – Add elements of an Array
C Program – Addition of Matrices
C Program – Multiplication of Matrices
C Program – Reverse of an Array
C Program – Bubble Sort
C Program – Add and Sub without using + –
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 469,
"s": 398,
"text": "In this tutorial, we are going to learn about categories of functions."
},
{
"code": null,
"e": 721,
"s": 469,
"text": "All the C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Depending on the arguments and return values functions are classified into 4 categories:"
},
{
"code": null,
"e": 931,
"s": 721,
"text": "\nFunction without arguments and without a return value.\nFunction with arguments and without a return value.\nFunction without arguments and with a return value.\nFunction with arguments and with a return value.\n"
},
{
"code": null,
"e": 986,
"s": 931,
"text": "Function without arguments and without a return value."
},
{
"code": null,
"e": 1038,
"s": 986,
"text": "Function with arguments and without a return value."
},
{
"code": null,
"e": 1090,
"s": 1038,
"text": "Function without arguments and with a return value."
},
{
"code": null,
"e": 1139,
"s": 1090,
"text": "Function with arguments and with a return value."
},
{
"code": null,
"e": 1354,
"s": 1139,
"text": "When a function has no arguments, it does not receive any data from the calling function. similarly, when a function does not return a value, the calling function does not receive any data from the called function."
},
{
"code": null,
"e": 1515,
"s": 1354,
"text": "In effect, there is no data transfer between the calling function and the called function in the category function without arguments and without a return value."
},
{
"code": null,
"e": 1601,
"s": 1515,
"text": "Let’s consider an example of a function without arguments and without a return value:"
},
{
"code": null,
"e": 1761,
"s": 1601,
"text": "#include <stdio.h>\nvoid country_capital(void);\nvoid main() {\n country_capital();\n}\nvoid country_capital() {\n printf(\"New Delhi is the capital of India\\n\");\n}"
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "Output:"
},
{
"code": null,
"e": 1803,
"s": 1769,
"text": "New Delhi is the capital of India"
},
{
"code": null,
"e": 1841,
"s": 1803,
"text": "In the above sample code the function"
},
{
"code": null,
"e": 1870,
"s": 1841,
"text": "void country_capital(void); "
},
{
"code": null,
"e": 1983,
"s": 1870,
"text": "specifies that the function does not receive any arguments and does not return any value to the main() function."
},
{
"code": null,
"e": 2069,
"s": 1983,
"text": "When a function definition has arguments, it receives data from the calling function."
},
{
"code": null,
"e": 2363,
"s": 2069,
"text": "The actual arguments in the function call must correspond to the formal parameters in the function definition, i.e. the number of actual arguments must be the same as the number of formal parameters, and each actual argument must be of the same data type as its corresponding formal parameter."
},
{
"code": null,
"e": 2537,
"s": 2363,
"text": "The formal parameters must be valid variable names in the function definition and the actual arguments may be variable names, expressions, or constants in the function call."
},
{
"code": null,
"e": 2740,
"s": 2537,
"text": "The variables used in actual arguments must be assigned values before the function call is made. When a function call is made, copies of the values of actual arguments are passed to the called function."
},
{
"code": null,
"e": 2937,
"s": 2740,
"text": "What occurs inside the function will have no effect on the variables used in the actual argument list. There may be several different calls to the same function from various places with a program."
},
{
"code": null,
"e": 3018,
"s": 2937,
"text": "Let’s consider an example of a function with arguments and without return value:"
},
{
"code": null,
"e": 3309,
"s": 3018,
"text": "#include <stdio.h>\nvoid largest(int, int);\nvoid main() {\n int p, q;\n printf(\"Enter two numbers : \");\n scanf(\"%d%d\" , &p, &q);\n largest(p, q);\n}\nvoid largest(int x, int y) {\n if (x > y) {\n printf(\"Largest element = %d\\n\", x);\n } else {\n printf(\"Largest element = %d\\n\", y);\n }\n}"
},
{
"code": null,
"e": 3317,
"s": 3309,
"text": "Output:"
},
{
"code": null,
"e": 3363,
"s": 3317,
"text": "Enter two numbers : 1\n10\nLargest element = 10"
},
{
"code": null,
"e": 3401,
"s": 3363,
"text": "In the above sample code the function"
},
{
"code": null,
"e": 3425,
"s": 3401,
"text": "void largest(int, int);"
},
{
"code": null,
"e": 3564,
"s": 3425,
"text": "specifies that the function receives two integer arguments from the calling function and does not return any value to the called function."
},
{
"code": null,
"e": 3719,
"s": 3564,
"text": "When the function call largest(p, q) is made in the main() function, the values of actual arguments p and q are copied into the formal parameters x and y."
},
{
"code": null,
"e": 3895,
"s": 3719,
"text": "After completion of execution of largest(int x, int y) function, it does not return any value to the main() function. Simply the control is transferred to the main() function."
},
{
"code": null,
"e": 4079,
"s": 3895,
"text": "When a function has no arguments, it does not receive any data from the calling function. When a function returns a value, the calling function receives data from the called function."
},
{
"code": null,
"e": 4162,
"s": 4079,
"text": "Let’s consider an example of a function without arguments and with a return value:"
},
{
"code": null,
"e": 4410,
"s": 4162,
"text": "#include <stdio.h>\nint sum(void); \nvoid main() {\n printf(\"\\nSum of two given values = %d\\n\", sum());\n}\nint sum() {\n int a, b, total; \n printf(\"Enter two numbers : \");\n scanf(\"%d%d\", &a, &b);\n total = a + b;\n return total; \n}"
},
{
"code": null,
"e": 4418,
"s": 4410,
"text": "Output:"
},
{
"code": null,
"e": 4470,
"s": 4418,
"text": "Enter two numbers : 1\n2\nSum of two given values = 3"
},
{
"code": null,
"e": 4510,
"s": 4472,
"text": "In the above sample code the function"
},
{
"code": null,
"e": 4525,
"s": 4510,
"text": "int sum(void);"
},
{
"code": null,
"e": 4629,
"s": 4525,
"text": "specifies that the function does not receive any arguments but returns a value to the calling function."
},
{
"code": null,
"e": 4715,
"s": 4629,
"text": "When a function definition has arguments, it receives data from the calling function."
},
{
"code": null,
"e": 4858,
"s": 4715,
"text": "After taking some desired action, only one value will be returned from called function to the calling a function through the return statement."
},
{
"code": null,
"e": 5016,
"s": 4858,
"text": "If a function returns a value, the function call may appear in any expression, and the returned value used as an operand in the evaluation of the expression."
},
{
"code": null,
"e": 5095,
"s": 5016,
"text": "Let us consider an example of a function with arguments and with return value:"
},
{
"code": null,
"e": 5460,
"s": 5095,
"text": "#include <stdio.h>\nint largest(int, int, int);\nvoid main() {\n int a, b, c;\n printf(\"Enter three numbers : \");\n scanf(\"%d%d%d\" , &a, &b, &c);\n printf(\" Largest of the given three numbers = %d\\n\", largest(a, b, c));\n}\nint largest(int x, int y, int z) {\n if ((x > y) && (x > z)) {\n return x; \n } else if (y > z) {\n return y;\n } else {\n return z;\n }\n}"
},
{
"code": null,
"e": 5468,
"s": 5460,
"text": "Output:"
},
{
"code": null,
"e": 5536,
"s": 5468,
"text": "Enter three numbers : 1\n4\n7\nLargest of the given three numbers = 7\n"
},
{
"code": null,
"e": 5574,
"s": 5536,
"text": "In the above sample code the function"
},
{
"code": null,
"e": 5602,
"s": 5574,
"text": "int largest(int, int, int);"
},
{
"code": null,
"e": 5697,
"s": 5602,
"text": "specifies that the function receives three values and returns a value to the calling function."
},
{
"code": null,
"e": 5718,
"s": 5697,
"text": "crasseux – Functions"
},
{
"code": null,
"e": 5730,
"s": 5718,
"text": "C Functions"
},
{
"code": null,
"e": 5758,
"s": 5730,
"text": "User defined functions in C"
},
{
"code": null,
"e": 5775,
"s": 5758,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 6385,
"s": 5775,
"text": "\nC How to Pass Arrays to Functions\nFunctions in C\nUser defined Functions in C\nPHP Functions Example Tutorials\nPython Decorators – Classes and Functions\nDynamic Memory Allocation in C\nJQuery Callback Functions Example Tutorial\nPHP String functions Example Tutorials\nC Program – Find Largest and Smallest number in an Array\nUnderstanding the structure of a C Program\nC – Derived and User Defined Data Types\nJava Program To Find Largest and Smallest Number in Array\nJava Program to find Smallest and Largest element in Array\nC – Header Files & Preprocessor Directives\nUnderstanding Scope & Lifetime of Variables\n"
},
{
"code": null,
"e": 6419,
"s": 6385,
"text": "C How to Pass Arrays to Functions"
},
{
"code": null,
"e": 6434,
"s": 6419,
"text": "Functions in C"
},
{
"code": null,
"e": 6462,
"s": 6434,
"text": "User defined Functions in C"
},
{
"code": null,
"e": 6494,
"s": 6462,
"text": "PHP Functions Example Tutorials"
},
{
"code": null,
"e": 6536,
"s": 6494,
"text": "Python Decorators – Classes and Functions"
},
{
"code": null,
"e": 6567,
"s": 6536,
"text": "Dynamic Memory Allocation in C"
},
{
"code": null,
"e": 6610,
"s": 6567,
"text": "JQuery Callback Functions Example Tutorial"
},
{
"code": null,
"e": 6649,
"s": 6610,
"text": "PHP String functions Example Tutorials"
},
{
"code": null,
"e": 6706,
"s": 6649,
"text": "C Program – Find Largest and Smallest number in an Array"
},
{
"code": null,
"e": 6749,
"s": 6706,
"text": "Understanding the structure of a C Program"
},
{
"code": null,
"e": 6789,
"s": 6749,
"text": "C – Derived and User Defined Data Types"
},
{
"code": null,
"e": 6847,
"s": 6789,
"text": "Java Program To Find Largest and Smallest Number in Array"
},
{
"code": null,
"e": 6906,
"s": 6847,
"text": "Java Program to find Smallest and Largest element in Array"
},
{
"code": null,
"e": 6949,
"s": 6906,
"text": "C – Header Files & Preprocessor Directives"
},
{
"code": null,
"e": 6993,
"s": 6949,
"text": "Understanding Scope & Lifetime of Variables"
},
{
"code": null,
"e": 6999,
"s": 6997,
"text": "Δ"
},
{
"code": null,
"e": 7017,
"s": 6999,
"text": " C – Introduction"
},
{
"code": null,
"e": 7031,
"s": 7017,
"text": " C – Features"
},
{
"code": null,
"e": 7057,
"s": 7031,
"text": " C – Variables & Keywords"
},
{
"code": null,
"e": 7080,
"s": 7057,
"text": " C – Program Structure"
},
{
"code": null,
"e": 7109,
"s": 7080,
"text": " C – Comment Lines & Tokens"
},
{
"code": null,
"e": 7128,
"s": 7109,
"text": " C – Number System"
},
{
"code": null,
"e": 7160,
"s": 7128,
"text": " C – Local and Global Variables"
},
{
"code": null,
"e": 7195,
"s": 7160,
"text": " C – Scope & Lifetime of Variables"
},
{
"code": null,
"e": 7211,
"s": 7195,
"text": " C – Data Types"
},
{
"code": null,
"e": 7235,
"s": 7211,
"text": " C – Integer Data Types"
},
{
"code": null,
"e": 7260,
"s": 7235,
"text": " C – Floating Data Types"
},
{
"code": null,
"e": 7293,
"s": 7260,
"text": " C – Derived, Defined Data Types"
},
{
"code": null,
"e": 7315,
"s": 7293,
"text": " C – Type Conversions"
},
{
"code": null,
"e": 7341,
"s": 7315,
"text": " C – Arithmetic Operators"
},
{
"code": null,
"e": 7364,
"s": 7341,
"text": " C – Bitwise Operators"
},
{
"code": null,
"e": 7387,
"s": 7364,
"text": " C – Logical Operators"
},
{
"code": null,
"e": 7420,
"s": 7387,
"text": " C – Comma and sizeof Operators"
},
{
"code": null,
"e": 7463,
"s": 7420,
"text": " C – Operator Precedence and Associativity"
},
{
"code": null,
"e": 7489,
"s": 7463,
"text": " C – Relational Operators"
},
{
"code": null,
"e": 7547,
"s": 7489,
"text": " C Flow Control – if, if-else, nested if-else, if-else-if"
},
{
"code": null,
"e": 7564,
"s": 7547,
"text": " C – Switch Case"
},
{
"code": null,
"e": 7605,
"s": 7564,
"text": " C Iterative – for, while, dowhile loops"
},
{
"code": null,
"e": 7657,
"s": 7605,
"text": " C Unconditional – break, continue, goto statements"
},
{
"code": null,
"e": 7689,
"s": 7657,
"text": " C – Expressions and Statements"
},
{
"code": null,
"e": 7733,
"s": 7689,
"text": " C – Header Files & Preprocessor Directives"
},
{
"code": null,
"e": 7761,
"s": 7733,
"text": " C – One Dimensional Arrays"
},
{
"code": null,
"e": 7791,
"s": 7761,
"text": " C – Multi Dimensional Arrays"
},
{
"code": null,
"e": 7812,
"s": 7791,
"text": " C – Pointers Basics"
},
{
"code": null,
"e": 7838,
"s": 7812,
"text": " C – Pointers with Arrays"
},
{
"code": null,
"e": 7853,
"s": 7838,
"text": " C – Functions"
},
{
"code": null,
"e": 7890,
"s": 7853,
"text": " C – How to Pass Arrays to Functions"
},
{
"code": null,
"e": 7919,
"s": 7890,
"text": " C – Categories of Functions"
},
{
"code": null,
"e": 7947,
"s": 7919,
"text": " C – User defined Functions"
},
{
"code": null,
"e": 7980,
"s": 7947,
"text": " C – Formal and Actual Arguments"
},
{
"code": null,
"e": 8005,
"s": 7980,
"text": " C – Recursion functions"
},
{
"code": null,
"e": 8029,
"s": 8005,
"text": " C – Structures Part -1"
},
{
"code": null,
"e": 8053,
"s": 8029,
"text": " C – Structures Part -2"
},
{
"code": null,
"e": 8065,
"s": 8053,
"text": " C – Unions"
},
{
"code": null,
"e": 8084,
"s": 8065,
"text": " C – File Handling"
},
{
"code": null,
"e": 8105,
"s": 8084,
"text": " C – File Operations"
},
{
"code": null,
"e": 8136,
"s": 8105,
"text": " C – Dynamic Memory Allocation"
},
{
"code": null,
"e": 8166,
"s": 8136,
"text": " C Program – Fibonacci Series"
},
{
"code": null,
"e": 8192,
"s": 8166,
"text": " C Program – Prime or Not"
},
{
"code": null,
"e": 8225,
"s": 8192,
"text": " C Program – Factorial of Number"
},
{
"code": null,
"e": 8250,
"s": 8225,
"text": " C Program – Even or Odd"
},
{
"code": null,
"e": 8295,
"s": 8250,
"text": " C Program – Sum of digits till Single Digit"
},
{
"code": null,
"e": 8322,
"s": 8295,
"text": " C Program – Sum of digits"
},
{
"code": null,
"e": 8355,
"s": 8322,
"text": " C Program – Reverse of a number"
},
{
"code": null,
"e": 8386,
"s": 8355,
"text": " C Program – Armstrong Numbers"
},
{
"code": null,
"e": 8419,
"s": 8386,
"text": " C Program – Print prime Numbers"
},
{
"code": null,
"e": 8451,
"s": 8419,
"text": " C Program – GCD of two Numbers"
},
{
"code": null,
"e": 8489,
"s": 8451,
"text": " C Program – Number Palindrome or Not"
},
{
"code": null,
"e": 8547,
"s": 8489,
"text": " C Program – Find Largest and Smallest number in an Array"
},
{
"code": null,
"e": 8585,
"s": 8547,
"text": " C Program – Add elements of an Array"
},
{
"code": null,
"e": 8619,
"s": 8585,
"text": " C Program – Addition of Matrices"
},
{
"code": null,
"e": 8659,
"s": 8619,
"text": " C Program – Multiplication of Matrices"
},
{
"code": null,
"e": 8692,
"s": 8659,
"text": " C Program – Reverse of an Array"
},
{
"code": null,
"e": 8717,
"s": 8692,
"text": " C Program – Bubble Sort"
}
] |
2 Key keyboard problem in JavaScript
|
Suppose the following situation −
Initially on a notepad only one character 'A' is present. We can perform two operations on this notepad for each step −
Copy All − We can copy all the characters present on the notepad (partial copy is not allowed).
Copy All − We can copy all the characters present on the notepad (partial copy is not allowed).
Paste − We can paste the characters which were copied last time.
Paste − We can paste the characters which were copied last time.
We are required to write a JavaScript function that takes in a number, let's call it num as the only argument. Our function is required to compute and return the minimum number of steps (copy all or paste) required to print 'A' num times.
For example −
If the input number is −
const num = 3;
Then the output should be −
const output = 3;
because, the steps are −
copy all (result: 'A')
copy all (result: 'A')
paste all (result: 'AA')
paste all (result: 'AA')
paste all (result: 'AAA')
paste all (result: 'AAA')
The code for this will be −
Live Demo
const num = 3;
const minimumSteps = (num = 1) => {
let [curr, copy, steps] = [1, 0, 0];
while(curr != num){
if((copy < curr) && ((num - curr) % curr) == 0) {
copy = curr;
}else{
curr += copy;
};
steps += 1;
};
return steps;
};
console.log(minimumSteps(num));
And the output in the console will be −
3
|
[
{
"code": null,
"e": 1096,
"s": 1062,
"text": "Suppose the following situation −"
},
{
"code": null,
"e": 1216,
"s": 1096,
"text": "Initially on a notepad only one character 'A' is present. We can perform two operations on this notepad for each step −"
},
{
"code": null,
"e": 1312,
"s": 1216,
"text": "Copy All − We can copy all the characters present on the notepad (partial copy is not allowed)."
},
{
"code": null,
"e": 1408,
"s": 1312,
"text": "Copy All − We can copy all the characters present on the notepad (partial copy is not allowed)."
},
{
"code": null,
"e": 1473,
"s": 1408,
"text": "Paste − We can paste the characters which were copied last time."
},
{
"code": null,
"e": 1538,
"s": 1473,
"text": "Paste − We can paste the characters which were copied last time."
},
{
"code": null,
"e": 1777,
"s": 1538,
"text": "We are required to write a JavaScript function that takes in a number, let's call it num as the only argument. Our function is required to compute and return the minimum number of steps (copy all or paste) required to print 'A' num times."
},
{
"code": null,
"e": 1791,
"s": 1777,
"text": "For example −"
},
{
"code": null,
"e": 1816,
"s": 1791,
"text": "If the input number is −"
},
{
"code": null,
"e": 1831,
"s": 1816,
"text": "const num = 3;"
},
{
"code": null,
"e": 1859,
"s": 1831,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1877,
"s": 1859,
"text": "const output = 3;"
},
{
"code": null,
"e": 1902,
"s": 1877,
"text": "because, the steps are −"
},
{
"code": null,
"e": 1925,
"s": 1902,
"text": "copy all (result: 'A')"
},
{
"code": null,
"e": 1948,
"s": 1925,
"text": "copy all (result: 'A')"
},
{
"code": null,
"e": 1973,
"s": 1948,
"text": "paste all (result: 'AA')"
},
{
"code": null,
"e": 1998,
"s": 1973,
"text": "paste all (result: 'AA')"
},
{
"code": null,
"e": 2024,
"s": 1998,
"text": "paste all (result: 'AAA')"
},
{
"code": null,
"e": 2050,
"s": 2024,
"text": "paste all (result: 'AAA')"
},
{
"code": null,
"e": 2078,
"s": 2050,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2089,
"s": 2078,
"text": " Live Demo"
},
{
"code": null,
"e": 2402,
"s": 2089,
"text": "const num = 3;\nconst minimumSteps = (num = 1) => {\n let [curr, copy, steps] = [1, 0, 0];\n while(curr != num){\n if((copy < curr) && ((num - curr) % curr) == 0) {\n copy = curr;\n }else{\n curr += copy;\n };\n steps += 1;\n };\n return steps;\n};\nconsole.log(minimumSteps(num));"
},
{
"code": null,
"e": 2442,
"s": 2402,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2444,
"s": 2442,
"text": "3"
}
] |
C Program to print all permutations of a given string
|
In this problem, we are given a string. Our task is to create a c program to print all permutations of a given string.
This program will find all possible combinations of the given string and print them.
Permutation is the arrangement of all parts of an object, in all possible orders of arrangement.
Let’s take an example to understand the problem,
xyz
xyz, xzy, yxz, yzx, zxy, zyx
These are all permutations take in order.
To solve this problem, we will use backtracking i.e. taking each character of the string as the first character of the permutation and then sequentially choosing all remaining characters of the string one by one. And thus, printing all the permutations of the string.
//Program to print all permutations of a given string −
Live Demo
#include <iostream>
using namespace std;
void findPermutations(string str, int l, int r){
if (l == r)
cout<<str<<" ";
else{
for (int i = l; i <= r; i++){
swap(str[l], str[i]);
findPermutations(str, l+1, r);
swap(str[l], str[i]);
}
}
}
int main(){
string str = "WXYZ";
int n = str.size();
findPermutations(str, 0, n-1);
return 0;
}
WXYZ WXZY WYXZ WYZX WZYX WZXY XWYZ XWZY XYWZ XYZW XZYW XZWY YXWZ YXZW YWXZ
YWZX YZWX YZXW ZXYW ZXWY ZYXW ZYWX ZWYX ZWXY
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "In this problem, we are given a string. Our task is to create a c program to print all permutations of a given string."
},
{
"code": null,
"e": 1266,
"s": 1181,
"text": "This program will find all possible combinations of the given string and print them."
},
{
"code": null,
"e": 1363,
"s": 1266,
"text": "Permutation is the arrangement of all parts of an object, in all possible orders of arrangement."
},
{
"code": null,
"e": 1412,
"s": 1363,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1416,
"s": 1412,
"text": "xyz"
},
{
"code": null,
"e": 1445,
"s": 1416,
"text": "xyz, xzy, yxz, yzx, zxy, zyx"
},
{
"code": null,
"e": 1487,
"s": 1445,
"text": "These are all permutations take in order."
},
{
"code": null,
"e": 1755,
"s": 1487,
"text": "To solve this problem, we will use backtracking i.e. taking each character of the string as the first character of the permutation and then sequentially choosing all remaining characters of the string one by one. And thus, printing all the permutations of the string."
},
{
"code": null,
"e": 1811,
"s": 1755,
"text": "//Program to print all permutations of a given string −"
},
{
"code": null,
"e": 1822,
"s": 1811,
"text": " Live Demo"
},
{
"code": null,
"e": 2216,
"s": 1822,
"text": "#include <iostream>\nusing namespace std;\nvoid findPermutations(string str, int l, int r){\n if (l == r)\n cout<<str<<\" \";\n else{\n for (int i = l; i <= r; i++){\n swap(str[l], str[i]);\n findPermutations(str, l+1, r);\n swap(str[l], str[i]);\n }\n }\n}\nint main(){\n string str = \"WXYZ\";\n int n = str.size();\n findPermutations(str, 0, n-1);\n return 0;\n}"
},
{
"code": null,
"e": 2337,
"s": 2216,
"text": "WXYZ WXZY WYXZ WYZX WZYX WZXY XWYZ XWZY XYWZ XYZW XZYW XZWY YXWZ YXZW YWXZ \nYWZX YZWX YZXW ZXYW ZXWY ZYXW ZYWX ZWYX ZWXY"
}
] |
AI with Python â Heuristic Search
|
Heuristic search plays a key role in artificial intelligence. In this chapter, you will learn in detail about it.
Heuristic is a rule of thumb which leads us to the probable solution. Most problems in artificial intelligence are of exponential nature and have many possible solutions. You do not know exactly which solutions are correct and checking all the solutions would be very expensive.
Thus, the use of heuristic narrows down the search for solution and eliminates the wrong options. The method of using heuristic to lead the search in search space is called Heuristic Search. Heuristic techniques are very useful because the search can be boosted when you use them.
There are two types of control strategies or search techniques: uninformed and informed. They are explained in detail as given here −
It is also called blind search or blind control strategy. It is named so because there is information only about the problem definition, and no other extra information is available about the states. This kind of search techniques would search the whole state space for getting the solution. Breadth First Search (BFS) and Depth First Search (DFS) are the examples of uninformed search.
It is also called heuristic search or heuristic control strategy. It is named so because there is some extra information about the states. This extra information is useful to compute the preference among the child nodes to explore and expand. There would be a heuristic function associated with each node. Best First Search (BFS), A*, Mean and Analysis are the examples of informed search.
Constraint means restriction or limitation. In AI, constraint satisfaction problems are the problems which must be solved under some constraints. The focus must be on not to violate the constraint while solving such problems. Finally, when we reach the final solution, CSP must obey the restriction.
The previous sections dealt with creating constraint satisfaction problems. Now, let us apply this to real world problems too. Some examples of real world problems solved by constraint satisfaction are as follows −
With the help of constraint satisfaction problem, we can solve algebraic relations. In this example, we will try to solve a simple algebraic relation a*2 = b. It will return the value of a and b within the range that we would define.
After completing this Python program, you would be able to understand the basics of solving problems with constraint satisfaction.
Note that before writing the program, we need to install Python package called python-constraint. You can install it with the help of the following command −
pip install python-constraint
The following steps show you a Python program for solving algebraic relation using constraint satisfaction −
Import the constraint package using the following command −
from constraint import *
Now, create an object of module named problem() as shown below −
problem = Problem()
Now, define variables. Note that here we have two variables a and b, and we are defining 10 as their range, which means we got the solution within first 10 numbers.
problem.addVariable('a', range(10))
problem.addVariable('b', range(10))
Next, define the particular constraint that we want to apply on this problem. Observe that here we are using the constraint a*2 = b.
problem.addConstraint(lambda a, b: a * 2 == b)
Now, create the object of getSolution() module using the following command −
solutions = problem.getSolutions()
Lastly, print the output using the following command −
print (solutions)
You can observe the output of the above program as follows −
[{'a': 4, 'b': 8}, {'a': 3, 'b': 6}, {'a': 2, 'b': 4}, {'a': 1, 'b': 2}, {'a': 0, 'b': 0}]
A magic square is an arrangement of distinct numbers, generally integers, in a square grid, where the numbers in each row , and in each column , and the numbers in the diagonal, all add up to the same number called the “magic constant”.
The following is a stepwise execution of simple Python code for generating magic squares −
Define a function named magic_square, as shown below −
def magic_square(matrix_ms):
iSize = len(matrix_ms[0])
sum_list = []
The following code shows the code for vertical of squares −
for col in range(iSize):
sum_list.append(sum(row[col] for row in matrix_ms))
The following code shows the code for horizantal of squares −
sum_list.extend([sum (lines) for lines in matrix_ms])
The following code shows the code for horizontal of squares −
dlResult = 0
for i in range(0,iSize):
dlResult +=matrix_ms[i][i]
sum_list.append(dlResult)
drResult = 0
for i in range(iSize-1,-1,-1):
drResult +=matrix_ms[i][i]
sum_list.append(drResult)
if len(set(sum_list))>1:
return False
return True
Now, give the value of the matrix and check the output −
print(magic_square([[1,2,3], [4,5,6], [7,8,9]]))
You can observe that the output would be False as the sum is not up to the same number.
print(magic_square([[3,9,2], [3,5,7], [9,1,6]]))
You can observe that the output would be True as the sum is the same number, that is 15 here.
78 Lectures
7 hours
Arnab Chakraborty
87 Lectures
9.5 hours
DigiFisk (Programming Is Fun)
10 Lectures
1 hours
Nikoloz Sanakoevi
15 Lectures
54 mins
Mukund Kumar Mishra
11 Lectures
1 hours
Gilad James, PhD
20 Lectures
2 hours
Gilad James, PhD
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2319,
"s": 2205,
"text": "Heuristic search plays a key role in artificial intelligence. In this chapter, you will learn in detail about it."
},
{
"code": null,
"e": 2598,
"s": 2319,
"text": "Heuristic is a rule of thumb which leads us to the probable solution. Most problems in artificial intelligence are of exponential nature and have many possible solutions. You do not know exactly which solutions are correct and checking all the solutions would be very expensive."
},
{
"code": null,
"e": 2879,
"s": 2598,
"text": "Thus, the use of heuristic narrows down the search for solution and eliminates the wrong options. The method of using heuristic to lead the search in search space is called Heuristic Search. Heuristic techniques are very useful because the search can be boosted when you use them."
},
{
"code": null,
"e": 3013,
"s": 2879,
"text": "There are two types of control strategies or search techniques: uninformed and informed. They are explained in detail as given here −"
},
{
"code": null,
"e": 3399,
"s": 3013,
"text": "It is also called blind search or blind control strategy. It is named so because there is information only about the problem definition, and no other extra information is available about the states. This kind of search techniques would search the whole state space for getting the solution. Breadth First Search (BFS) and Depth First Search (DFS) are the examples of uninformed search."
},
{
"code": null,
"e": 3789,
"s": 3399,
"text": "It is also called heuristic search or heuristic control strategy. It is named so because there is some extra information about the states. This extra information is useful to compute the preference among the child nodes to explore and expand. There would be a heuristic function associated with each node. Best First Search (BFS), A*, Mean and Analysis are the examples of informed search."
},
{
"code": null,
"e": 4089,
"s": 3789,
"text": "Constraint means restriction or limitation. In AI, constraint satisfaction problems are the problems which must be solved under some constraints. The focus must be on not to violate the constraint while solving such problems. Finally, when we reach the final solution, CSP must obey the restriction."
},
{
"code": null,
"e": 4304,
"s": 4089,
"text": "The previous sections dealt with creating constraint satisfaction problems. Now, let us apply this to real world problems too. Some examples of real world problems solved by constraint satisfaction are as follows −"
},
{
"code": null,
"e": 4538,
"s": 4304,
"text": "With the help of constraint satisfaction problem, we can solve algebraic relations. In this example, we will try to solve a simple algebraic relation a*2 = b. It will return the value of a and b within the range that we would define."
},
{
"code": null,
"e": 4669,
"s": 4538,
"text": "After completing this Python program, you would be able to understand the basics of solving problems with constraint satisfaction."
},
{
"code": null,
"e": 4827,
"s": 4669,
"text": "Note that before writing the program, we need to install Python package called python-constraint. You can install it with the help of the following command −"
},
{
"code": null,
"e": 4858,
"s": 4827,
"text": "pip install python-constraint\n"
},
{
"code": null,
"e": 4967,
"s": 4858,
"text": "The following steps show you a Python program for solving algebraic relation using constraint satisfaction −"
},
{
"code": null,
"e": 5027,
"s": 4967,
"text": "Import the constraint package using the following command −"
},
{
"code": null,
"e": 5053,
"s": 5027,
"text": "from constraint import *\n"
},
{
"code": null,
"e": 5118,
"s": 5053,
"text": "Now, create an object of module named problem() as shown below −"
},
{
"code": null,
"e": 5138,
"s": 5118,
"text": "problem = Problem()"
},
{
"code": null,
"e": 5303,
"s": 5138,
"text": "Now, define variables. Note that here we have two variables a and b, and we are defining 10 as their range, which means we got the solution within first 10 numbers."
},
{
"code": null,
"e": 5375,
"s": 5303,
"text": "problem.addVariable('a', range(10))\nproblem.addVariable('b', range(10))"
},
{
"code": null,
"e": 5508,
"s": 5375,
"text": "Next, define the particular constraint that we want to apply on this problem. Observe that here we are using the constraint a*2 = b."
},
{
"code": null,
"e": 5555,
"s": 5508,
"text": "problem.addConstraint(lambda a, b: a * 2 == b)"
},
{
"code": null,
"e": 5632,
"s": 5555,
"text": "Now, create the object of getSolution() module using the following command −"
},
{
"code": null,
"e": 5668,
"s": 5632,
"text": "solutions = problem.getSolutions()\n"
},
{
"code": null,
"e": 5723,
"s": 5668,
"text": "Lastly, print the output using the following command −"
},
{
"code": null,
"e": 5742,
"s": 5723,
"text": "print (solutions)\n"
},
{
"code": null,
"e": 5803,
"s": 5742,
"text": "You can observe the output of the above program as follows −"
},
{
"code": null,
"e": 5895,
"s": 5803,
"text": "[{'a': 4, 'b': 8}, {'a': 3, 'b': 6}, {'a': 2, 'b': 4}, {'a': 1, 'b': 2}, {'a': 0, 'b': 0}]\n"
},
{
"code": null,
"e": 6132,
"s": 5895,
"text": "A magic square is an arrangement of distinct numbers, generally integers, in a square grid, where the numbers in each row , and in each column , and the numbers in the diagonal, all add up to the same number called the “magic constant”."
},
{
"code": null,
"e": 6223,
"s": 6132,
"text": "The following is a stepwise execution of simple Python code for generating magic squares −"
},
{
"code": null,
"e": 6278,
"s": 6223,
"text": "Define a function named magic_square, as shown below −"
},
{
"code": null,
"e": 6353,
"s": 6278,
"text": "def magic_square(matrix_ms):\n iSize = len(matrix_ms[0])\n sum_list = []"
},
{
"code": null,
"e": 6413,
"s": 6353,
"text": "The following code shows the code for vertical of squares −"
},
{
"code": null,
"e": 6493,
"s": 6413,
"text": "for col in range(iSize):\n sum_list.append(sum(row[col] for row in matrix_ms))"
},
{
"code": null,
"e": 6555,
"s": 6493,
"text": "The following code shows the code for horizantal of squares −"
},
{
"code": null,
"e": 6609,
"s": 6555,
"text": "sum_list.extend([sum (lines) for lines in matrix_ms])"
},
{
"code": null,
"e": 6671,
"s": 6609,
"text": "The following code shows the code for horizontal of squares −"
},
{
"code": null,
"e": 6919,
"s": 6671,
"text": "dlResult = 0\nfor i in range(0,iSize):\n dlResult +=matrix_ms[i][i]\nsum_list.append(dlResult)\ndrResult = 0\nfor i in range(iSize-1,-1,-1):\n drResult +=matrix_ms[i][i]\nsum_list.append(drResult)\n\nif len(set(sum_list))>1:\n return False\nreturn True"
},
{
"code": null,
"e": 6976,
"s": 6919,
"text": "Now, give the value of the matrix and check the output −"
},
{
"code": null,
"e": 7026,
"s": 6976,
"text": "print(magic_square([[1,2,3], [4,5,6], [7,8,9]]))\n"
},
{
"code": null,
"e": 7114,
"s": 7026,
"text": "You can observe that the output would be False as the sum is not up to the same number."
},
{
"code": null,
"e": 7164,
"s": 7114,
"text": "print(magic_square([[3,9,2], [3,5,7], [9,1,6]]))\n"
},
{
"code": null,
"e": 7258,
"s": 7164,
"text": "You can observe that the output would be True as the sum is the same number, that is 15 here."
},
{
"code": null,
"e": 7291,
"s": 7258,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7310,
"s": 7291,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7345,
"s": 7310,
"text": "\n 87 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 7376,
"s": 7345,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7409,
"s": 7376,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7428,
"s": 7409,
"text": " Nikoloz Sanakoevi"
},
{
"code": null,
"e": 7460,
"s": 7428,
"text": "\n 15 Lectures \n 54 mins\n"
},
{
"code": null,
"e": 7481,
"s": 7460,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 7514,
"s": 7481,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7532,
"s": 7514,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 7565,
"s": 7532,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7583,
"s": 7565,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 7590,
"s": 7583,
"text": " Print"
},
{
"code": null,
"e": 7601,
"s": 7590,
"text": " Add Notes"
}
] |
Difference between Constructors and Methods in Java
|
Constructors are special methods used to initialize objects whereas methods are used to execute certain statements. Following are the important differences between Constructors and Methods.
public class JavaTester {
int num;
JavaTester(){
num = 3;
System.out.println("Constructor invoked. num: " + num);
}
public void init(){
num = 5;
System.out.println("Method invoked. num: " + num);
}
public static void main(String args[]) {
JavaTester tester = new JavaTester();
tester.init();
}
}
Constructor invoked. num: 3
Method invoked. num: 5
|
[
{
"code": null,
"e": 1252,
"s": 1062,
"text": "Constructors are special methods used to initialize objects whereas methods are used to execute certain statements. Following are the important differences between Constructors and Methods."
},
{
"code": null,
"e": 1605,
"s": 1252,
"text": "public class JavaTester {\n int num;\n JavaTester(){\n num = 3;\n System.out.println(\"Constructor invoked. num: \" + num);\n }\n public void init(){\n num = 5;\n System.out.println(\"Method invoked. num: \" + num);\n }\n public static void main(String args[]) {\n JavaTester tester = new JavaTester();\n tester.init();\n }\n}"
},
{
"code": null,
"e": 1656,
"s": 1605,
"text": "Constructor invoked. num: 3\nMethod invoked. num: 5"
}
] |
Style input type reset with CSS
|
The input type button can be a submit button or reset button. With CSS, we can style any button on a web page.
You can try to run the following code to style input type button:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
input[type = submit], input[type = reset] {
background-color: orange;
border: none;
text-decoration: none;
color: white;
padding: 20px 20px;
margin: 20px 20px;
cursor: pointer;
}
</style>
</head>
<body>
<p>Fill the below form,</p>
<form>
<label for = "subject">Subject</label>
<input type = "text" id = "subject" name = "sub"><br><br>
<label for = "student">Student</label>
<input type = "text" id = "student" name = "stu"><br>
<input type = "reset" value = "Reset">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "The input type button can be a submit button or reset button. With CSS, we can style any button on a web page."
},
{
"code": null,
"e": 1239,
"s": 1173,
"text": "You can try to run the following code to style input type button:"
},
{
"code": null,
"e": 1249,
"s": 1239,
"text": "Live Demo"
},
{
"code": null,
"e": 2017,
"s": 1249,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n input[type = submit], input[type = reset] {\n background-color: orange;\n border: none;\n text-decoration: none;\n color: white;\n padding: 20px 20px;\n margin: 20px 20px;\n cursor: pointer;\n }\n </style>\n </head>\n <body>\n <p>Fill the below form,</p>\n <form>\n <label for = \"subject\">Subject</label>\n <input type = \"text\" id = \"subject\" name = \"sub\"><br><br>\n <label for = \"student\">Student</label>\n <input type = \"text\" id = \"student\" name = \"stu\"><br>\n <input type = \"reset\" value = \"Reset\">\n <input type = \"submit\" value = \"Submit\">\n </form>\n </body>\n</html>"
}
] |
Access Links and Control Links - GeeksforGeeks
|
30 Jun, 2021
In this article, we are going to explain Access Links and Control Links. Well, both are in the field of Activation Records.
Activation Record : An activation record is a contiguous block of storage that manages information required by a single execution of a procedure. When you enter a procedure, you allocate an activation record, and when you exit that procedure, you de-allocate it. Basically, it stores the status of the current activation function. So, whenever a function call occurs, then a new activation record is created and it will be pushed onto the top of the stack. It will be in function till the execution of that function. So, once the procedure is completed and it is returned to the calling function, this activation function will be popped out of the stack.If a procedure is called, an activation record is pushed into the stack, and it is popped when the control returns to the calling function.
Activation Record includes some fields which are – Return values, parameter list, control links, access links, saved machine status, local data and temporaries.
Activation Record
Access Link : It refers to information stored in other activation records that is non-local. The access link is a static link and the main purpose of the access link is to access the data which is not present in the local scope of the activation record. It is a static link. Let’s take an example to understand this –
C
#include <stdio.h>int g=12;void Geeks(){ printf("%d", g);}void main(){ Geeks();}
Now, In this example, when Geeks() is called in a main(), the task of Geeks() in main() is to print(g), but g is not defined within its scope(local scope of Geeks()); in this case, Geeks() would use the access link to access ‘g’ from Global Scope and then print its value (g=12).
As a chain of access links (think of scopes), the program traces its static structure.Now, let’s take another example to understand the concept of access link in detail –
C
#include <stdio.h> int main (int argc, char *argv[]) { int a = 100; int geeks(int b) { int c = a+b; return c; } int geek1(int b) { return geeks(2*b); } (void) printf("The answer is %d\n", geek1(a)); return 0; }
There are no errors detected while compiling the program, and the correct answer is displayed, which is 300. Now, let’s discuss the nesting paths. Nested procedures include an AR(Activation Record) access link that enables users to access the AR of the most recent action taken by their immediately outer procedure. So, in this example, the access link for geeks and access link for geeks1 would each point to the AR of the activation of the main. Each activation record gets a pointer called the access link that facilitates the direct implementation of the normal static scope rule.
Control Links : In this case, it refers to an activation record of the caller. They are generally used for links and saved status. It is a dynamic link in nature. When a function calls another function, then the control link points to the activation record of the caller.Record A contains a control link pointing to the previous record on the stack. Dynamically executed programs are traced by the chain of control links.Example –
C
#include<stdio.h>int geeks(int x){ printf("value of x is: %d", x);}int main(){ geeks(10);}
Let’s take another example –
C
#include <stdio.h>int geeks();int main() { int x, y; //Calling a function geeks(); return 0;} int geeks() { //Function called from main() printf("Function called from main()"); return 0;}
When the function geeks() is called, it uses the access link method to access x and y (statically scoped) in its calling function main().
Picked
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
S - attributed and L - attributed SDTs in Syntax directed translation
Directed Acyclic graph in Compiler Design (with examples)
Difference between Top down parsing and Bottom up parsing
Compiler construction tools
Why FIRST and FOLLOW in Compiler Design?
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
|
[
{
"code": null,
"e": 24053,
"s": 24025,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 24177,
"s": 24053,
"text": "In this article, we are going to explain Access Links and Control Links. Well, both are in the field of Activation Records."
},
{
"code": null,
"e": 24971,
"s": 24177,
"text": "Activation Record : An activation record is a contiguous block of storage that manages information required by a single execution of a procedure. When you enter a procedure, you allocate an activation record, and when you exit that procedure, you de-allocate it. Basically, it stores the status of the current activation function. So, whenever a function call occurs, then a new activation record is created and it will be pushed onto the top of the stack. It will be in function till the execution of that function. So, once the procedure is completed and it is returned to the calling function, this activation function will be popped out of the stack.If a procedure is called, an activation record is pushed into the stack, and it is popped when the control returns to the calling function."
},
{
"code": null,
"e": 25132,
"s": 24971,
"text": "Activation Record includes some fields which are – Return values, parameter list, control links, access links, saved machine status, local data and temporaries."
},
{
"code": null,
"e": 25150,
"s": 25132,
"text": "Activation Record"
},
{
"code": null,
"e": 25468,
"s": 25150,
"text": "Access Link : It refers to information stored in other activation records that is non-local. The access link is a static link and the main purpose of the access link is to access the data which is not present in the local scope of the activation record. It is a static link. Let’s take an example to understand this –"
},
{
"code": null,
"e": 25470,
"s": 25468,
"text": "C"
},
{
"code": "#include <stdio.h>int g=12;void Geeks(){ printf(\"%d\", g);}void main(){ Geeks();}",
"e": 25552,
"s": 25470,
"text": null
},
{
"code": null,
"e": 25832,
"s": 25552,
"text": "Now, In this example, when Geeks() is called in a main(), the task of Geeks() in main() is to print(g), but g is not defined within its scope(local scope of Geeks()); in this case, Geeks() would use the access link to access ‘g’ from Global Scope and then print its value (g=12)."
},
{
"code": null,
"e": 26003,
"s": 25832,
"text": "As a chain of access links (think of scopes), the program traces its static structure.Now, let’s take another example to understand the concept of access link in detail –"
},
{
"code": null,
"e": 26005,
"s": 26003,
"text": "C"
},
{
"code": "#include <stdio.h> int main (int argc, char *argv[]) { int a = 100; int geeks(int b) { int c = a+b; return c; } int geek1(int b) { return geeks(2*b); } (void) printf(\"The answer is %d\\n\", geek1(a)); return 0; }",
"e": 26250,
"s": 26005,
"text": null
},
{
"code": null,
"e": 26837,
"s": 26250,
"text": "There are no errors detected while compiling the program, and the correct answer is displayed, which is 300. Now, let’s discuss the nesting paths. Nested procedures include an AR(Activation Record) access link that enables users to access the AR of the most recent action taken by their immediately outer procedure. So, in this example, the access link for geeks and access link for geeks1 would each point to the AR of the activation of the main. Each activation record gets a pointer called the access link that facilitates the direct implementation of the normal static scope rule. "
},
{
"code": null,
"e": 27269,
"s": 26837,
"text": "Control Links : In this case, it refers to an activation record of the caller. They are generally used for links and saved status. It is a dynamic link in nature. When a function calls another function, then the control link points to the activation record of the caller.Record A contains a control link pointing to the previous record on the stack. Dynamically executed programs are traced by the chain of control links.Example –"
},
{
"code": null,
"e": 27271,
"s": 27269,
"text": "C"
},
{
"code": "#include<stdio.h>int geeks(int x){ printf(\"value of x is: %d\", x);}int main(){ geeks(10);}",
"e": 27364,
"s": 27271,
"text": null
},
{
"code": null,
"e": 27393,
"s": 27364,
"text": "Let’s take another example –"
},
{
"code": null,
"e": 27395,
"s": 27393,
"text": "C"
},
{
"code": "#include <stdio.h>int geeks();int main() { int x, y; //Calling a function geeks(); return 0;} int geeks() { //Function called from main() printf(\"Function called from main()\"); return 0;}",
"e": 27603,
"s": 27395,
"text": null
},
{
"code": null,
"e": 27741,
"s": 27603,
"text": "When the function geeks() is called, it uses the access link method to access x and y (statically scoped) in its calling function main()."
},
{
"code": null,
"e": 27748,
"s": 27741,
"text": "Picked"
},
{
"code": null,
"e": 27764,
"s": 27748,
"text": "Compiler Design"
},
{
"code": null,
"e": 27772,
"s": 27764,
"text": "GATE CS"
},
{
"code": null,
"e": 27870,
"s": 27772,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27879,
"s": 27870,
"text": "Comments"
},
{
"code": null,
"e": 27892,
"s": 27879,
"text": "Old Comments"
},
{
"code": null,
"e": 27962,
"s": 27892,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 28020,
"s": 27962,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 28078,
"s": 28020,
"text": "Difference between Top down parsing and Bottom up parsing"
},
{
"code": null,
"e": 28106,
"s": 28078,
"text": "Compiler construction tools"
},
{
"code": null,
"e": 28147,
"s": 28106,
"text": "Why FIRST and FOLLOW in Compiler Design?"
},
{
"code": null,
"e": 28167,
"s": 28147,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 28191,
"s": 28167,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28218,
"s": 28191,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 28231,
"s": 28218,
"text": "TCP/IP Model"
}
] |
SQL Challenge: Case Study. Step-by-step walkthrough of a SQL... | by Chloe Lubin | Towards Data Science
|
In a previous post, I talked about how to use a framework to solve a SQL challenge. Today, I’m going to do a walkthrough of this challenge, asked by Microsoft in February 2021. Before you continue reading this article, I highly encourage you to try solving this question on your own. The more you practice solving SQL questions, the better you’ll get at them. Alright, let’s get into it!
The question asks us to:
select the most popular client_id based on a count of the number of users who have at least 50% of their events from the following list: ‘video call received’, ‘video call sent’, ‘voice call received’, ‘voice call sent’.
Before I start working on this question, I like to visualize how the information appears in the dataset. Let’s run a simple SELECT statement to check the data stored in the table fact_events.
SELECT *FROM fact_eventsLIMIT 10
The query returns the following output:
Out of curiosity, I wonder if all the values in the list provided appear in the dataset:
SELECT event_typeFROM fact_eventsWHERE event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent')GROUP BY event_type
It looks like only 2 of the 4 values are included. Even though the 2 other values don’t appear in the current dataset, they may appear later as data gets appended to the table. You can’t assume that the data will remain static. As a result, let’s keep all 4 values in our filter.
Great! I now have a better idea of what I’m working with. The next step is to analyze the prompt so we can come up with a strategy to tackle this challenge.
For this step, I like to scribble my thoughts on a piece of paper 📝 However, feel free to use your computer, iPad, or other device that works best for you. Here, we need to analyze the prompt to understand exactly what is being asked of us.
In this case, the prompt seems to be broken down into 3 parts:
Find the users with 50% of events from the list aboveCount the number of users found in step (1)Select the client_id with the most number of users based on step (2)
Find the users with 50% of events from the list above
Count the number of users found in step (1)
Select the client_id with the most number of users based on step (2)
I’m also going to make the following assumptions:
I don’t need to use the customer_id and event_id columns
timing doesn’t matter
I’m calculating the 50% by dividing the number of events in the given list by the number of all events.
I’m counting the total number of users, even if they appear multiple times in the column. The prompt doesn’t specify to select the most popular client_id by identifying the distinct number of times a user appears in the dataset.
At this point in the interview, you would have taken the time to understand the challenge and communicated initial thoughts to the interviewer. In addition, feel free to ask the interviewer for clarification if you have any questions. Without the presence of an interviewer, let’s move onto the next step!
First, let’s get the users with 50% or more events in the following list: ‘video call received’, ‘video call sent’, ‘voice call received’, and ‘voice call sent.’ To get the percentage, we’ll use one-hot encoding in a CASE statement to return the values in the list as 1 and everything else as 0. The sum of that CASE statement will be the numerator. The denominator will be a COUNT of all elements in the event_type column.
CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type)
Next, we’ll wrap the conditional in a GROUP BY/HAVING clause. Remember that we need to filter on the user_id with at least 50% of events in the list. For that, we need to perform the aggregation, filter on the conditional, and finally, group by user_id.
SELECT user_idFROM fact_eventsGROUP BY user_idHAVING CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type) >= 0.5
After completing the first step, we get the following output:
Now that we know that only 2 users have at least 50% of events in the list, let’s find out the number of users by client_id and user_id.
SELECT client_id, user_id, COUNT(user_id)FROM fact_eventsWHERE user_id in (SELECT user_id FROM fact_events GROUP BY user_id HAVING CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type) >= 0.5)GROUP BY client_id, user_idORDER BY COUNT (user_id) DESC
The output already points to our answer. Note that the client_id ‘desktop’ has 7 + 4 = 11 users while ‘mobile’ only has 3.
In our final step, we’ll clean up the output above to only return the client_id with the most number of users. Not too many changes to the SQL script are warranted here. Instead of grouping by client_id and user_id, I only group by client_id. I also make sure to limit the number of rows to return the client_id with the most number of users. If you don’t limit the selection, you’d also return “mobile” in the final output.
--final querySELECT client_idFROM fact_eventsWHERE user_id in (SELECT user_id FROM fact_events GROUP BY user_id HAVING CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type) >= 0.5)GROUP BY client_idORDER BY COUNT(user_id) DESCLIMIT 1
Final output:
I hope you enjoyed this walkthrough exercise! There are plenty of resources for you to practice interview questions. Some of the most popular websites are Leetcode, StrataScratch, and InterviewQuery but I’m sure you can find many others that would give you the preparation you need to ace the DA interview. Don’t forget to share feedback or post a question in the comments below!
This post was last edited on October 30, 2021. The opinions expressed here belong solely to myself, and do not reflect the views of my employer.
|
[
{
"code": null,
"e": 560,
"s": 172,
"text": "In a previous post, I talked about how to use a framework to solve a SQL challenge. Today, I’m going to do a walkthrough of this challenge, asked by Microsoft in February 2021. Before you continue reading this article, I highly encourage you to try solving this question on your own. The more you practice solving SQL questions, the better you’ll get at them. Alright, let’s get into it!"
},
{
"code": null,
"e": 585,
"s": 560,
"text": "The question asks us to:"
},
{
"code": null,
"e": 806,
"s": 585,
"text": "select the most popular client_id based on a count of the number of users who have at least 50% of their events from the following list: ‘video call received’, ‘video call sent’, ‘voice call received’, ‘voice call sent’."
},
{
"code": null,
"e": 998,
"s": 806,
"text": "Before I start working on this question, I like to visualize how the information appears in the dataset. Let’s run a simple SELECT statement to check the data stored in the table fact_events."
},
{
"code": null,
"e": 1031,
"s": 998,
"text": "SELECT *FROM fact_eventsLIMIT 10"
},
{
"code": null,
"e": 1071,
"s": 1031,
"text": "The query returns the following output:"
},
{
"code": null,
"e": 1160,
"s": 1071,
"text": "Out of curiosity, I wonder if all the values in the list provided appear in the dataset:"
},
{
"code": null,
"e": 1359,
"s": 1160,
"text": "SELECT event_typeFROM fact_eventsWHERE event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent')GROUP BY event_type"
},
{
"code": null,
"e": 1639,
"s": 1359,
"text": "It looks like only 2 of the 4 values are included. Even though the 2 other values don’t appear in the current dataset, they may appear later as data gets appended to the table. You can’t assume that the data will remain static. As a result, let’s keep all 4 values in our filter."
},
{
"code": null,
"e": 1796,
"s": 1639,
"text": "Great! I now have a better idea of what I’m working with. The next step is to analyze the prompt so we can come up with a strategy to tackle this challenge."
},
{
"code": null,
"e": 2037,
"s": 1796,
"text": "For this step, I like to scribble my thoughts on a piece of paper 📝 However, feel free to use your computer, iPad, or other device that works best for you. Here, we need to analyze the prompt to understand exactly what is being asked of us."
},
{
"code": null,
"e": 2100,
"s": 2037,
"text": "In this case, the prompt seems to be broken down into 3 parts:"
},
{
"code": null,
"e": 2265,
"s": 2100,
"text": "Find the users with 50% of events from the list aboveCount the number of users found in step (1)Select the client_id with the most number of users based on step (2)"
},
{
"code": null,
"e": 2319,
"s": 2265,
"text": "Find the users with 50% of events from the list above"
},
{
"code": null,
"e": 2363,
"s": 2319,
"text": "Count the number of users found in step (1)"
},
{
"code": null,
"e": 2432,
"s": 2363,
"text": "Select the client_id with the most number of users based on step (2)"
},
{
"code": null,
"e": 2482,
"s": 2432,
"text": "I’m also going to make the following assumptions:"
},
{
"code": null,
"e": 2539,
"s": 2482,
"text": "I don’t need to use the customer_id and event_id columns"
},
{
"code": null,
"e": 2561,
"s": 2539,
"text": "timing doesn’t matter"
},
{
"code": null,
"e": 2665,
"s": 2561,
"text": "I’m calculating the 50% by dividing the number of events in the given list by the number of all events."
},
{
"code": null,
"e": 2894,
"s": 2665,
"text": "I’m counting the total number of users, even if they appear multiple times in the column. The prompt doesn’t specify to select the most popular client_id by identifying the distinct number of times a user appears in the dataset."
},
{
"code": null,
"e": 3200,
"s": 2894,
"text": "At this point in the interview, you would have taken the time to understand the challenge and communicated initial thoughts to the interviewer. In addition, feel free to ask the interviewer for clarification if you have any questions. Without the presence of an interviewer, let’s move onto the next step!"
},
{
"code": null,
"e": 3624,
"s": 3200,
"text": "First, let’s get the users with 50% or more events in the following list: ‘video call received’, ‘video call sent’, ‘voice call received’, and ‘voice call sent.’ To get the percentage, we’ll use one-hot encoding in a CASE statement to return the values in the list as 1 and everything else as 0. The sum of that CASE statement will be the numerator. The denominator will be a COUNT of all elements in the event_type column."
},
{
"code": null,
"e": 3902,
"s": 3624,
"text": "CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type)"
},
{
"code": null,
"e": 4156,
"s": 3902,
"text": "Next, we’ll wrap the conditional in a GROUP BY/HAVING clause. Remember that we need to filter on the user_id with at least 50% of events in the list. For that, we need to perform the aggregation, filter on the conditional, and finally, group by user_id."
},
{
"code": null,
"e": 4499,
"s": 4156,
"text": "SELECT user_idFROM fact_eventsGROUP BY user_idHAVING CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type) >= 0.5"
},
{
"code": null,
"e": 4561,
"s": 4499,
"text": "After completing the first step, we get the following output:"
},
{
"code": null,
"e": 4698,
"s": 4561,
"text": "Now that we know that only 2 users have at least 50% of events in the list, let’s find out the number of users by client_id and user_id."
},
{
"code": null,
"e": 5233,
"s": 4698,
"text": "SELECT client_id, user_id, COUNT(user_id)FROM fact_eventsWHERE user_id in (SELECT user_id FROM fact_events GROUP BY user_id HAVING CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type) >= 0.5)GROUP BY client_id, user_idORDER BY COUNT (user_id) DESC"
},
{
"code": null,
"e": 5356,
"s": 5233,
"text": "The output already points to our answer. Note that the client_id ‘desktop’ has 7 + 4 = 11 users while ‘mobile’ only has 3."
},
{
"code": null,
"e": 5781,
"s": 5356,
"text": "In our final step, we’ll clean up the output above to only return the client_id with the most number of users. Not too many changes to the SQL script are warranted here. Instead of grouping by client_id and user_id, I only group by client_id. I also make sure to limit the number of rows to return the client_id with the most number of users. If you don’t limit the selection, you’d also return “mobile” in the final output."
},
{
"code": null,
"e": 6289,
"s": 5781,
"text": "--final querySELECT client_idFROM fact_eventsWHERE user_id in (SELECT user_id FROM fact_events GROUP BY user_id HAVING CAST(SUM( CASE WHEN event_type IN ('video call received', 'video call sent', 'voice call received', 'voice call sent') THEN 1 ELSE 0 END) AS FLOAT) / COUNT(event_type) >= 0.5)GROUP BY client_idORDER BY COUNT(user_id) DESCLIMIT 1"
},
{
"code": null,
"e": 6303,
"s": 6289,
"text": "Final output:"
},
{
"code": null,
"e": 6683,
"s": 6303,
"text": "I hope you enjoyed this walkthrough exercise! There are plenty of resources for you to practice interview questions. Some of the most popular websites are Leetcode, StrataScratch, and InterviewQuery but I’m sure you can find many others that would give you the preparation you need to ace the DA interview. Don’t forget to share feedback or post a question in the comments below!"
}
] |
Tryit Editor v3.7
|
Tryit: HTML font-family
|
[] |
Codenation Interview Experience | Online Test - GeeksforGeeks
|
28 Sep, 2020
Recently, on-campus drive was held for Codenation for Software Development Engineer Intern.
The process was:
1. Online Test
2. Telephonic Interview
3. Skype Interview
Online test for on-campus was held on September 15th 2020. The off-campus coding challenge known as CodeAgon for the hiring of same position is going to be held on 28th of September. So, I just wanted to share questions asked in online test.
There were three questions:
First Question:
Alice has got a Random Number Generator. The generator generates a random number from 1 to N.
Now Alice wants to know the expected number of turns until K distinct elements are generated.
Help Alice find this value modulo 109+7.
Problem Constraints:
1<=K<=N<=105
Input format:
Input consists of 2 arguments, N=A and K=B in this order.
Output format:
Return a single integer , the expected value modulo 109+7.
Second Question:
Given a grid A of size N*M, 2 players are playing a game on it taking alternate turns.
In each turn, a player chooses a subset of elements from any row and replaces each one of them with their proper divisor.
A proper divisor of a number N is any divisor of N, not equal to N.
The player who is unable to move, loses. Determine the winner of the game.
Problem Constraints:
1<=N, M<=103
1<=A[i][j]<=106
Input format:
The only line of argument contains the grid A.
Output format:
Return a single integer, 1 or 2 , depending upon which player wins.
Third Question:
Given a tree of N nodes numbers 0 to N-1. Each node have binary value i.e 0 or 1 denoted by integer array A.
The beauty of a ith node is 2i*A[i]. The total beauty of the Tree is sum of beauty of each node.
Aman is superstitious and will accept the tree only its total beauty is 2N -1 or 0.
He asked you to make the tree acceptable but you can only use the following operation.
In each operation, select any node X and call flip(X).
Python
flip(X): for (v: 0 to N-1): if(all nodes in path from X to node v have same value) A[v] = 1 - A[v]
Find the minimum number of operation required to make the tree acceptable.
Problem Constraints:
1<=N<=105
0<=A[i] <=1
0<=B[i][0], B[i][1]<=N-1
Input format:
First argument is an integer array A of size N denoting the node value.
Second argument is a 2D array B of size (N-1)*2 where ith edge is between B[i][0] and B[i][1] node
Output format:
Return an integer denoting the minimum number of operations required.
Codenation
Marketing
Interview Experiences
Codenation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Amazon Interview Experience for SDE-1
Oracle Interview Experience | Set 69 (Application Engineer)
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1
Infosys DSE Interview Experience 2021
|
[
{
"code": null,
"e": 25421,
"s": 25393,
"text": "\n28 Sep, 2020"
},
{
"code": null,
"e": 25513,
"s": 25421,
"text": "Recently, on-campus drive was held for Codenation for Software Development Engineer Intern."
},
{
"code": null,
"e": 25530,
"s": 25513,
"text": "The process was:"
},
{
"code": null,
"e": 25545,
"s": 25530,
"text": "1. Online Test"
},
{
"code": null,
"e": 25569,
"s": 25545,
"text": "2. Telephonic Interview"
},
{
"code": null,
"e": 25588,
"s": 25569,
"text": "3. Skype Interview"
},
{
"code": null,
"e": 25830,
"s": 25588,
"text": "Online test for on-campus was held on September 15th 2020. The off-campus coding challenge known as CodeAgon for the hiring of same position is going to be held on 28th of September. So, I just wanted to share questions asked in online test."
},
{
"code": null,
"e": 25858,
"s": 25830,
"text": "There were three questions:"
},
{
"code": null,
"e": 25874,
"s": 25858,
"text": "First Question:"
},
{
"code": null,
"e": 25969,
"s": 25874,
"text": "Alice has got a Random Number Generator. The generator generates a random number from 1 to N. "
},
{
"code": null,
"e": 26064,
"s": 25969,
"text": "Now Alice wants to know the expected number of turns until K distinct elements are generated. "
},
{
"code": null,
"e": 26106,
"s": 26064,
"text": "Help Alice find this value modulo 109+7. "
},
{
"code": null,
"e": 26127,
"s": 26106,
"text": "Problem Constraints:"
},
{
"code": null,
"e": 26140,
"s": 26127,
"text": "1<=K<=N<=105"
},
{
"code": null,
"e": 26154,
"s": 26140,
"text": "Input format:"
},
{
"code": null,
"e": 26212,
"s": 26154,
"text": "Input consists of 2 arguments, N=A and K=B in this order."
},
{
"code": null,
"e": 26227,
"s": 26212,
"text": "Output format:"
},
{
"code": null,
"e": 26286,
"s": 26227,
"text": "Return a single integer , the expected value modulo 109+7."
},
{
"code": null,
"e": 26303,
"s": 26286,
"text": "Second Question:"
},
{
"code": null,
"e": 26391,
"s": 26303,
"text": "Given a grid A of size N*M, 2 players are playing a game on it taking alternate turns. "
},
{
"code": null,
"e": 26514,
"s": 26391,
"text": "In each turn, a player chooses a subset of elements from any row and replaces each one of them with their proper divisor. "
},
{
"code": null,
"e": 26583,
"s": 26514,
"text": "A proper divisor of a number N is any divisor of N, not equal to N. "
},
{
"code": null,
"e": 26658,
"s": 26583,
"text": "The player who is unable to move, loses. Determine the winner of the game."
},
{
"code": null,
"e": 26679,
"s": 26658,
"text": "Problem Constraints:"
},
{
"code": null,
"e": 26692,
"s": 26679,
"text": "1<=N, M<=103"
},
{
"code": null,
"e": 26708,
"s": 26692,
"text": "1<=A[i][j]<=106"
},
{
"code": null,
"e": 26722,
"s": 26708,
"text": "Input format:"
},
{
"code": null,
"e": 26769,
"s": 26722,
"text": "The only line of argument contains the grid A."
},
{
"code": null,
"e": 26784,
"s": 26769,
"text": "Output format:"
},
{
"code": null,
"e": 26852,
"s": 26784,
"text": "Return a single integer, 1 or 2 , depending upon which player wins."
},
{
"code": null,
"e": 26868,
"s": 26852,
"text": "Third Question:"
},
{
"code": null,
"e": 26978,
"s": 26868,
"text": "Given a tree of N nodes numbers 0 to N-1. Each node have binary value i.e 0 or 1 denoted by integer array A. "
},
{
"code": null,
"e": 27075,
"s": 26978,
"text": "The beauty of a ith node is 2i*A[i]. The total beauty of the Tree is sum of beauty of each node."
},
{
"code": null,
"e": 27160,
"s": 27075,
"text": "Aman is superstitious and will accept the tree only its total beauty is 2N -1 or 0. "
},
{
"code": null,
"e": 27247,
"s": 27160,
"text": "He asked you to make the tree acceptable but you can only use the following operation."
},
{
"code": null,
"e": 27302,
"s": 27247,
"text": "In each operation, select any node X and call flip(X)."
},
{
"code": null,
"e": 27309,
"s": 27302,
"text": "Python"
},
{
"code": "flip(X): for (v: 0 to N-1): if(all nodes in path from X to node v have same value) A[v] = 1 - A[v]",
"e": 27419,
"s": 27309,
"text": null
},
{
"code": null,
"e": 27494,
"s": 27419,
"text": "Find the minimum number of operation required to make the tree acceptable."
},
{
"code": null,
"e": 27515,
"s": 27494,
"text": "Problem Constraints:"
},
{
"code": null,
"e": 27525,
"s": 27515,
"text": "1<=N<=105"
},
{
"code": null,
"e": 27537,
"s": 27525,
"text": "0<=A[i] <=1"
},
{
"code": null,
"e": 27562,
"s": 27537,
"text": "0<=B[i][0], B[i][1]<=N-1"
},
{
"code": null,
"e": 27576,
"s": 27562,
"text": "Input format:"
},
{
"code": null,
"e": 27648,
"s": 27576,
"text": "First argument is an integer array A of size N denoting the node value."
},
{
"code": null,
"e": 27747,
"s": 27648,
"text": "Second argument is a 2D array B of size (N-1)*2 where ith edge is between B[i][0] and B[i][1] node"
},
{
"code": null,
"e": 27762,
"s": 27747,
"text": "Output format:"
},
{
"code": null,
"e": 27832,
"s": 27762,
"text": "Return an integer denoting the minimum number of operations required."
},
{
"code": null,
"e": 27843,
"s": 27832,
"text": "Codenation"
},
{
"code": null,
"e": 27853,
"s": 27843,
"text": "Marketing"
},
{
"code": null,
"e": 27875,
"s": 27853,
"text": "Interview Experiences"
},
{
"code": null,
"e": 27886,
"s": 27875,
"text": "Codenation"
},
{
"code": null,
"e": 27984,
"s": 27886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27993,
"s": 27984,
"text": "Comments"
},
{
"code": null,
"e": 28006,
"s": 27993,
"text": "Old Comments"
},
{
"code": null,
"e": 28065,
"s": 28006,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 28115,
"s": 28065,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 28187,
"s": 28115,
"text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022"
},
{
"code": null,
"e": 28225,
"s": 28187,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 28285,
"s": 28225,
"text": "Oracle Interview Experience | Set 69 (Application Engineer)"
},
{
"code": null,
"e": 28350,
"s": 28285,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 28400,
"s": 28350,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
},
{
"code": null,
"e": 28446,
"s": 28400,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 28484,
"s": 28446,
"text": "Amazon Interview Experience for SDE-1"
}
] |
Create a striped Bootstrap progress bar
|
Follow the below given steps to create a striped progress bar in Bootstrap −
Add a <div> with a class of .progress and .progress-striped.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger.
Add a style attribute with the width expressed as a percentage. Say, for example, style = "60%"; indicates that the progress bar was at 60%.
You can try to run the following code to form a striped progress bar −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h2>Striped Progress Bars</h2>
<h3>Warning Progress Bar</h3>
<div class = "progress progress-striped">
<div class = "progress-bar progress-bar-warning" role = "progressbar"
aria-valuenow = "45" aria-valuemin = "0" aria-valuemax = "100" style="width: 45%;">
<span class = "sr-only">45%Complete (warning)</span>
</div>
</div>
<h3>Danger Progress Bar</h3>
<div class = "progress progress-striped">
<div class = "progress-bar progress-bar-danger" role = "progressbar"
aria-valuenow = "80" aria-valuemin = "0" aria-valuemax = "100" style = "width: 80%;">
<span class = "sr-only">80% Complete (danger)</span>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "Follow the below given steps to create a striped progress bar in Bootstrap −"
},
{
"code": null,
"e": 1200,
"s": 1139,
"text": "Add a <div> with a class of .progress and .progress-striped."
},
{
"code": null,
"e": 1353,
"s": 1200,
"text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger."
},
{
"code": null,
"e": 1494,
"s": 1353,
"text": "Add a style attribute with the width expressed as a percentage. Say, for example, style = \"60%\"; indicates that the progress bar was at 60%."
},
{
"code": null,
"e": 1565,
"s": 1494,
"text": "You can try to run the following code to form a striped progress bar −"
},
{
"code": null,
"e": 1575,
"s": 1565,
"text": "Live Demo"
},
{
"code": null,
"e": 2619,
"s": 1575,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h2>Striped Progress Bars</h2>\n <h3>Warning Progress Bar</h3>\n <div class = \"progress progress-striped\">\n <div class = \"progress-bar progress-bar-warning\" role = \"progressbar\"\n aria-valuenow = \"45\" aria-valuemin = \"0\" aria-valuemax = \"100\" style=\"width: 45%;\">\n <span class = \"sr-only\">45%Complete (warning)</span>\n </div>\n </div>\n <h3>Danger Progress Bar</h3>\n <div class = \"progress progress-striped\">\n <div class = \"progress-bar progress-bar-danger\" role = \"progressbar\"\n aria-valuenow = \"80\" aria-valuemin = \"0\" aria-valuemax = \"100\" style = \"width: 80%;\">\n <span class = \"sr-only\">80% Complete (danger)</span>\n </div>\n </div>\n </body>\n</html>"
}
] |
sympy.stats.Reciprocal() in Python - GeeksforGeeks
|
08 Jun, 2020
With the help of sympy.stats.Reciprocal() method, we can get the continuous random variable which represents the Reciprocal distribution.
Syntax : sympy.stats.Reciprocal(name, a, b)Where, a and b are real number and a, b > 0.
Return : Return the continuous random variable.
Example #1 :In this example we can see that by using sympy.stats.Reciprocal() method, we are able to get the continuous random variable representing reciprocal distribution by using this method.
# Import sympy and Reciprocalfrom sympy.stats import Reciprocal, densityfrom sympy import Symbol, pprint z = Symbol("z")a = Symbol("a", positive = True)b = Symbol("b", positive = True) # Using sympy.stats.Reciprocal() methodX = Reciprocal("x", a, b)gfg = density(X)(z) print(gfg)
Output :
1/(x*(-log(a) + log(b)))
Example #2 :
# Import sympy and Reciprocalfrom sympy.stats import Reciprocal, densityfrom sympy import Symbol, pprint z = 0.35a = 1b = 2 # Using sympy.stats.Reciprocal() methodX = Reciprocal("x", a, b)gfg = density(X)(z) print(gfg)
Output :
0.0861703622690834
Python SymPy-Stats
SymPy
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 24350,
"s": 24212,
"text": "With the help of sympy.stats.Reciprocal() method, we can get the continuous random variable which represents the Reciprocal distribution."
},
{
"code": null,
"e": 24438,
"s": 24350,
"text": "Syntax : sympy.stats.Reciprocal(name, a, b)Where, a and b are real number and a, b > 0."
},
{
"code": null,
"e": 24486,
"s": 24438,
"text": "Return : Return the continuous random variable."
},
{
"code": null,
"e": 24681,
"s": 24486,
"text": "Example #1 :In this example we can see that by using sympy.stats.Reciprocal() method, we are able to get the continuous random variable representing reciprocal distribution by using this method."
},
{
"code": "# Import sympy and Reciprocalfrom sympy.stats import Reciprocal, densityfrom sympy import Symbol, pprint z = Symbol(\"z\")a = Symbol(\"a\", positive = True)b = Symbol(\"b\", positive = True) # Using sympy.stats.Reciprocal() methodX = Reciprocal(\"x\", a, b)gfg = density(X)(z) print(gfg)",
"e": 24964,
"s": 24681,
"text": null
},
{
"code": null,
"e": 24973,
"s": 24964,
"text": "Output :"
},
{
"code": null,
"e": 24998,
"s": 24973,
"text": "1/(x*(-log(a) + log(b)))"
},
{
"code": null,
"e": 25011,
"s": 24998,
"text": "Example #2 :"
},
{
"code": "# Import sympy and Reciprocalfrom sympy.stats import Reciprocal, densityfrom sympy import Symbol, pprint z = 0.35a = 1b = 2 # Using sympy.stats.Reciprocal() methodX = Reciprocal(\"x\", a, b)gfg = density(X)(z) print(gfg)",
"e": 25233,
"s": 25011,
"text": null
},
{
"code": null,
"e": 25242,
"s": 25233,
"text": "Output :"
},
{
"code": null,
"e": 25261,
"s": 25242,
"text": "0.0861703622690834"
},
{
"code": null,
"e": 25280,
"s": 25261,
"text": "Python SymPy-Stats"
},
{
"code": null,
"e": 25286,
"s": 25280,
"text": "SymPy"
},
{
"code": null,
"e": 25293,
"s": 25286,
"text": "Python"
},
{
"code": null,
"e": 25391,
"s": 25293,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25400,
"s": 25391,
"text": "Comments"
},
{
"code": null,
"e": 25413,
"s": 25400,
"text": "Old Comments"
},
{
"code": null,
"e": 25445,
"s": 25413,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25501,
"s": 25445,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25522,
"s": 25501,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 25561,
"s": 25522,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25603,
"s": 25561,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25630,
"s": 25603,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25661,
"s": 25630,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25703,
"s": 25661,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25739,
"s": 25703,
"text": "Python | Pandas dataframe.groupby()"
}
] |
SQLite - ALTER TABLE Command
|
SQLite ALTER TABLE command modifies an existing table without performing a full dump and reload of the data. You can rename a table using ALTER TABLE statement and additional columns can be added in an existing table using ALTER TABLE statement.
There is no other operation supported by ALTER TABLE command in SQLite except renaming a table and adding a column in an existing table.
Following is the basic syntax of ALTER TABLE to RENAME an existing table.
ALTER TABLE database_name.table_name RENAME TO new_table_name;
Following is the basic syntax of ALTER TABLE to add a new column in an existing table.
ALTER TABLE database_name.table_name ADD COLUMN column_def...;
Consider the COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Now, let's try to rename this table using ALTER TABLE statement as follows −
sqlite> ALTER TABLE COMPANY RENAME TO OLD_COMPANY;
The above SQLite statement will rename COMPANY table to OLD_COMPANY. Now, let's try to add a new column in OLD_COMPANY table as follows −
sqlite> ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1);
COMPANY table is now changed and following will be the output from SELECT statement.
ID NAME AGE ADDRESS SALARY SEX
---------- ---------- ---------- ---------- ---------- ---
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
It should be noted that newly added column is filled with NULL values.
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2884,
"s": 2638,
"text": "SQLite ALTER TABLE command modifies an existing table without performing a full dump and reload of the data. You can rename a table using ALTER TABLE statement and additional columns can be added in an existing table using ALTER TABLE statement."
},
{
"code": null,
"e": 3021,
"s": 2884,
"text": "There is no other operation supported by ALTER TABLE command in SQLite except renaming a table and adding a column in an existing table."
},
{
"code": null,
"e": 3095,
"s": 3021,
"text": "Following is the basic syntax of ALTER TABLE to RENAME an existing table."
},
{
"code": null,
"e": 3159,
"s": 3095,
"text": "ALTER TABLE database_name.table_name RENAME TO new_table_name;\n"
},
{
"code": null,
"e": 3246,
"s": 3159,
"text": "Following is the basic syntax of ALTER TABLE to add a new column in an existing table."
},
{
"code": null,
"e": 3310,
"s": 3246,
"text": "ALTER TABLE database_name.table_name ADD COLUMN column_def...;\n"
},
{
"code": null,
"e": 3366,
"s": 3310,
"text": "Consider the COMPANY table with the following records −"
},
{
"code": null,
"e": 3872,
"s": 3366,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 3949,
"s": 3872,
"text": "Now, let's try to rename this table using ALTER TABLE statement as follows −"
},
{
"code": null,
"e": 4000,
"s": 3949,
"text": "sqlite> ALTER TABLE COMPANY RENAME TO OLD_COMPANY;"
},
{
"code": null,
"e": 4138,
"s": 4000,
"text": "The above SQLite statement will rename COMPANY table to OLD_COMPANY. Now, let's try to add a new column in OLD_COMPANY table as follows −"
},
{
"code": null,
"e": 4194,
"s": 4138,
"text": "sqlite> ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1);"
},
{
"code": null,
"e": 4279,
"s": 4194,
"text": "COMPANY table is now changed and following will be the output from SELECT statement."
},
{
"code": null,
"e": 4799,
"s": 4279,
"text": "ID NAME AGE ADDRESS SALARY SEX\n---------- ---------- ---------- ---------- ---------- ---\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 4870,
"s": 4799,
"text": "It should be noted that newly added column is filled with NULL values."
},
{
"code": null,
"e": 4905,
"s": 4870,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4926,
"s": 4905,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4959,
"s": 4926,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4976,
"s": 4959,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5007,
"s": 4976,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 5020,
"s": 5007,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 5027,
"s": 5020,
"text": " Print"
},
{
"code": null,
"e": 5038,
"s": 5027,
"text": " Add Notes"
}
] |
Matplotlib vs. Seaborn vs. Plotly | by Clare Blessen | Towards Data Science
|
Clear, effective data visualization is key to optimizing your ability to convey findings. With various packages in use such as Matplotlib, Seaborn, and Plotly, knowing the capabilities of each and the syntax behind them can become bewildering. I’m going to walk you through creating some common graphs in Python using each of these packages using a csv file of the 2017 Spotify top tracks.
First, i’ll import the pandas package to read my csv into an easily readable dataframe.
import pandas as pddf = pd.DataFrame(pd.read_csv('featuresdf.csv'))
I’ll need to import the matplotlib package:
import matplotlib.pyplot as plt%matplotlib inline
To plot a histogram of the danceability and energy scores overlaid, I can use the following code:
#set figuref, ax = plt.subplots(1,1)#graph histogramplt.hist(df['danceability'], bins=10, alpha=0.5, color='purple', label='Danceability')plt.hist(df['energy'], bins=10, alpha = 0.5, color='blue', label='Energy')#set legendplt.legend(loc='upper right')#set title & axis titlesax.set_title('Danceability Histogram', fontsize=20)ax.set_xlabel('Danceability')ax.set_ylabel('Frequency')#set x & y rangesplt.xlim(0,1)plt.ylim(0, 30)plt.show()
Notice the sparse nature of this graph. However, once I run the following code, you can see how my graph improves:
import seaborn as snssns.set(style='darkgrid')
Seaborn allows us to add a nice backdrop to our plots and improves the font. You can set style = darkgrid, whitegrid, dark, white, and ticks. We can also plot the same graph using what seaborn calls the distplot:
f, ax = plt.subplots(1,1)sns.distplot(df['danceability'], bins=10, label='Danceability', color='purple')sns.distplot(df['energy'], bins=10, label='Energy', color='blue')ax.set_title('Danceability & Energy Histogram', fontsize=20)ax.set(xlabel='Rating', ylabel='Frequency')ax.set_xlim([0, 1])ax.legend()
Almost exactly the same, right? Seaborn is built on matplotlib, so you can use them concurrently. Seaborn simply has its own library of graphs, and has pleasant formatting built in. However, it does not have all of the same capabilities of matplotlib. For instance, if you want to create the same histogram, but with the two variables stacked next to each other as opposed to overlaid, you would need to fall back to matplotlib:
#set figuref, ax = plt.subplots(1,1)#next to each otherplt.hist([df['danceability'], df['energy']], bins=10, alpha=0.5, color=['red', 'blue'], label = ['Danceability', 'Energy'])#set legendplt.legend(loc='upper right')#set title & axis titlesax.set_title('Danceability & Energy Histogram', fontsize=20)ax.set_xlabel('Rating')ax.set_ylabel('Frequency')#set x & y rangesplt.xlim(0,1)plt.ylim(0, 30)plt.show()
Seaborn’s built in features for its graphs can be helpful, but they can be limiting if you want to further customize your graph.
Matplotlib and Seaborn may be the most commonly used data visualization packages, but there is a simpler method that produces superior graphs than either of these: Plotly. To get started in a jupyter notebook, run the code below:
pip install chart-studioconda install -c plotly chart-studio# Standard plotly importsfrom chart_studio.plotly import plot, iplot as pyimport plotly.graph_objects as gofrom plotly.offline import iplot, init_notebook_mode# Using plotly + cufflinks in offline modeimport cufflinkscufflinks.go_offline(connected=True)init_notebook_mode(connected=True)
To plot the same overlaid histogram as above using default Plotly settings:
fig = df[['danceability', 'energy']].iplot(kind='hist', color=['purple', 'blue'], xTitle='Danceability', yTitle='Frequency', title='Danceability Histogram')
Plotly graphs are automatically outfitted with hover tool capabilities — hovering your mouse over any of the bars of data will display the numerical values.
To plot the bars side by side or otherwise further customize the graph, the code is lengthier, but fairly intuitive. You can specify your desired theme from a growing list of available default themes, including one modeled after seaborn (used below).
#install themes & view availableimport plotly.io as piopio.templates
You can also specify your colors using the default color codes below:
And finally, plot your graph:
#plottrace1 = go.Histogram( x=df['danceability'], name='danceability', #name used in legend and hover labels xbins=dict( #bins used for histogram start=0, end=10, size=0.1 ), marker=dict( color='#1f77b4', ), opacity=0.75)trace2 = go.Histogram( x=df['energy'], name='energy', #name used in legend and hover labels xbins=dict( #bins used for histogram start=0, end=10, size=0.1 ), marker=dict( color='#9467bd' ), opacity=0.75)data = [trace1, trace2]layout = go.Layout(template='seaborn', #set theme title='Danceability & Energy Histogram', xaxis=dict( title='Danceability & Energy' ), yaxis=dict( title='Frequency' ), bargap=0.2, bargroupgap=0.1)fig = go.Figure(data=data, layout=layout)iplot(fig, filename='styled histogram')
To plot the loudness score vs. valence in matplotlib:
#set figuref, ax = plt.subplots(1,1)#plotplt.scatter(df['loudness'], df['valence'], s=df['energy']*100)#set title & labelsplt.title('Scatterplot: Loudness vs. Valence', fontsize=20)plt.xlabel('Loudness')plt.ylabel('Positivity')#set x rangeax.set_xlim([0, -10])plt.show()
In seaborn:
fig = sns.scatterplot(x=df['loudness'], y=df['valence'], size = df['energy'],sizes = (40,200))fig.figure.suptitle("Scatterplot: Loudness vs. Valence", fontsize = 25)fig.set(xlabel='Loudness', ylabel='Positivity')fig.set_xlim([0,-10])
If you want to add a regression line to the graph, seaborn makes this infinitely easier with its regplot graph:
fig = sns.regplot(df['loudness'], y=df['valence'], data=df)fig.figure.suptitle("Scatterplot: Loudness vs. Valence", fontsize = 25)fig.set(xlabel='Loudness', ylabel='Positivity')fig.set_xlim([0,-10])
To add the correlation coefficient to this, import the pearson.r package from scipy and follow the steps below:
import numpy as npfrom scipy.stats import pearsonr#calculate correlation coefficientcorr = pearsonr(df['loudness'], df['valence'])corr = [np.round(c, 2) for c in corr]#add the coefficient to your graphtext = 'r=%s, p=%s' % (corr[0], corr[1])ax = sns.regplot(x="loudness", y="valence", data=df)ax.text(-7.5, 0.9, text, fontsize=12)
Lastly, with Plotly, we can again create a scatterplot using the default settings:
fig = go.Figure(data=go.Scatter(x=df[‘loudness’], y=df[‘valence’],mode=’markers’))fig.update_layout(title=’Loudness vs. Valence (Positivity)’)fig.layout.template = ‘seaborn’fig.show()
By adding another trace called ‘lineOfBestFit’ and calculating the regression using numpy, we can plot the regression line:
dataPoints = go.Scattergl( x=df.loudness, y=df.valence, mode='markers', marker=dict( opacity=1, line=dict( color='white' ) ), name='Data points')data=[dataPoints]layout.update( yaxis=dict( title='Energy'), xaxis=dict( title='Danceability' ))figure.update( data=data, layout=layout)m,b = np.polyfit(df.loudness, df.valence, 1)bestfit_y = (df.loudness * m + b)lineOfBestFit=go.Scattergl( x=df.loudness, y=bestfit_y, name='Line of best fit', line=dict( color='blue', ))data=[dataPoints, lineOfBestFit]figure = go.Figure(data=data, layout=layout)figure.update_xaxes(autorange="reversed")figure.layout.template = 'plotly_dark'iplot(figure)
These are you just two of the multitude of graphs available through seaborn and plotly libraries. Both seaborn and plotly create visually appealing graphs, but plotly allows for endless customization and interactivity with fairly intuitive syntax, making it a popular tool among data scientists.
|
[
{
"code": null,
"e": 562,
"s": 172,
"text": "Clear, effective data visualization is key to optimizing your ability to convey findings. With various packages in use such as Matplotlib, Seaborn, and Plotly, knowing the capabilities of each and the syntax behind them can become bewildering. I’m going to walk you through creating some common graphs in Python using each of these packages using a csv file of the 2017 Spotify top tracks."
},
{
"code": null,
"e": 650,
"s": 562,
"text": "First, i’ll import the pandas package to read my csv into an easily readable dataframe."
},
{
"code": null,
"e": 718,
"s": 650,
"text": "import pandas as pddf = pd.DataFrame(pd.read_csv('featuresdf.csv'))"
},
{
"code": null,
"e": 762,
"s": 718,
"text": "I’ll need to import the matplotlib package:"
},
{
"code": null,
"e": 812,
"s": 762,
"text": "import matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 910,
"s": 812,
"text": "To plot a histogram of the danceability and energy scores overlaid, I can use the following code:"
},
{
"code": null,
"e": 1348,
"s": 910,
"text": "#set figuref, ax = plt.subplots(1,1)#graph histogramplt.hist(df['danceability'], bins=10, alpha=0.5, color='purple', label='Danceability')plt.hist(df['energy'], bins=10, alpha = 0.5, color='blue', label='Energy')#set legendplt.legend(loc='upper right')#set title & axis titlesax.set_title('Danceability Histogram', fontsize=20)ax.set_xlabel('Danceability')ax.set_ylabel('Frequency')#set x & y rangesplt.xlim(0,1)plt.ylim(0, 30)plt.show()"
},
{
"code": null,
"e": 1463,
"s": 1348,
"text": "Notice the sparse nature of this graph. However, once I run the following code, you can see how my graph improves:"
},
{
"code": null,
"e": 1510,
"s": 1463,
"text": "import seaborn as snssns.set(style='darkgrid')"
},
{
"code": null,
"e": 1723,
"s": 1510,
"text": "Seaborn allows us to add a nice backdrop to our plots and improves the font. You can set style = darkgrid, whitegrid, dark, white, and ticks. We can also plot the same graph using what seaborn calls the distplot:"
},
{
"code": null,
"e": 2026,
"s": 1723,
"text": "f, ax = plt.subplots(1,1)sns.distplot(df['danceability'], bins=10, label='Danceability', color='purple')sns.distplot(df['energy'], bins=10, label='Energy', color='blue')ax.set_title('Danceability & Energy Histogram', fontsize=20)ax.set(xlabel='Rating', ylabel='Frequency')ax.set_xlim([0, 1])ax.legend()"
},
{
"code": null,
"e": 2455,
"s": 2026,
"text": "Almost exactly the same, right? Seaborn is built on matplotlib, so you can use them concurrently. Seaborn simply has its own library of graphs, and has pleasant formatting built in. However, it does not have all of the same capabilities of matplotlib. For instance, if you want to create the same histogram, but with the two variables stacked next to each other as opposed to overlaid, you would need to fall back to matplotlib:"
},
{
"code": null,
"e": 2862,
"s": 2455,
"text": "#set figuref, ax = plt.subplots(1,1)#next to each otherplt.hist([df['danceability'], df['energy']], bins=10, alpha=0.5, color=['red', 'blue'], label = ['Danceability', 'Energy'])#set legendplt.legend(loc='upper right')#set title & axis titlesax.set_title('Danceability & Energy Histogram', fontsize=20)ax.set_xlabel('Rating')ax.set_ylabel('Frequency')#set x & y rangesplt.xlim(0,1)plt.ylim(0, 30)plt.show()"
},
{
"code": null,
"e": 2991,
"s": 2862,
"text": "Seaborn’s built in features for its graphs can be helpful, but they can be limiting if you want to further customize your graph."
},
{
"code": null,
"e": 3221,
"s": 2991,
"text": "Matplotlib and Seaborn may be the most commonly used data visualization packages, but there is a simpler method that produces superior graphs than either of these: Plotly. To get started in a jupyter notebook, run the code below:"
},
{
"code": null,
"e": 3569,
"s": 3221,
"text": "pip install chart-studioconda install -c plotly chart-studio# Standard plotly importsfrom chart_studio.plotly import plot, iplot as pyimport plotly.graph_objects as gofrom plotly.offline import iplot, init_notebook_mode# Using plotly + cufflinks in offline modeimport cufflinkscufflinks.go_offline(connected=True)init_notebook_mode(connected=True)"
},
{
"code": null,
"e": 3645,
"s": 3569,
"text": "To plot the same overlaid histogram as above using default Plotly settings:"
},
{
"code": null,
"e": 3819,
"s": 3645,
"text": "fig = df[['danceability', 'energy']].iplot(kind='hist', color=['purple', 'blue'], xTitle='Danceability', yTitle='Frequency', title='Danceability Histogram')"
},
{
"code": null,
"e": 3976,
"s": 3819,
"text": "Plotly graphs are automatically outfitted with hover tool capabilities — hovering your mouse over any of the bars of data will display the numerical values."
},
{
"code": null,
"e": 4227,
"s": 3976,
"text": "To plot the bars side by side or otherwise further customize the graph, the code is lengthier, but fairly intuitive. You can specify your desired theme from a growing list of available default themes, including one modeled after seaborn (used below)."
},
{
"code": null,
"e": 4296,
"s": 4227,
"text": "#install themes & view availableimport plotly.io as piopio.templates"
},
{
"code": null,
"e": 4366,
"s": 4296,
"text": "You can also specify your colors using the default color codes below:"
},
{
"code": null,
"e": 4396,
"s": 4366,
"text": "And finally, plot your graph:"
},
{
"code": null,
"e": 5254,
"s": 4396,
"text": "#plottrace1 = go.Histogram( x=df['danceability'], name='danceability', #name used in legend and hover labels xbins=dict( #bins used for histogram start=0, end=10, size=0.1 ), marker=dict( color='#1f77b4', ), opacity=0.75)trace2 = go.Histogram( x=df['energy'], name='energy', #name used in legend and hover labels xbins=dict( #bins used for histogram start=0, end=10, size=0.1 ), marker=dict( color='#9467bd' ), opacity=0.75)data = [trace1, trace2]layout = go.Layout(template='seaborn', #set theme title='Danceability & Energy Histogram', xaxis=dict( title='Danceability & Energy' ), yaxis=dict( title='Frequency' ), bargap=0.2, bargroupgap=0.1)fig = go.Figure(data=data, layout=layout)iplot(fig, filename='styled histogram')"
},
{
"code": null,
"e": 5308,
"s": 5254,
"text": "To plot the loudness score vs. valence in matplotlib:"
},
{
"code": null,
"e": 5579,
"s": 5308,
"text": "#set figuref, ax = plt.subplots(1,1)#plotplt.scatter(df['loudness'], df['valence'], s=df['energy']*100)#set title & labelsplt.title('Scatterplot: Loudness vs. Valence', fontsize=20)plt.xlabel('Loudness')plt.ylabel('Positivity')#set x rangeax.set_xlim([0, -10])plt.show()"
},
{
"code": null,
"e": 5591,
"s": 5579,
"text": "In seaborn:"
},
{
"code": null,
"e": 5825,
"s": 5591,
"text": "fig = sns.scatterplot(x=df['loudness'], y=df['valence'], size = df['energy'],sizes = (40,200))fig.figure.suptitle(\"Scatterplot: Loudness vs. Valence\", fontsize = 25)fig.set(xlabel='Loudness', ylabel='Positivity')fig.set_xlim([0,-10])"
},
{
"code": null,
"e": 5937,
"s": 5825,
"text": "If you want to add a regression line to the graph, seaborn makes this infinitely easier with its regplot graph:"
},
{
"code": null,
"e": 6136,
"s": 5937,
"text": "fig = sns.regplot(df['loudness'], y=df['valence'], data=df)fig.figure.suptitle(\"Scatterplot: Loudness vs. Valence\", fontsize = 25)fig.set(xlabel='Loudness', ylabel='Positivity')fig.set_xlim([0,-10])"
},
{
"code": null,
"e": 6248,
"s": 6136,
"text": "To add the correlation coefficient to this, import the pearson.r package from scipy and follow the steps below:"
},
{
"code": null,
"e": 6579,
"s": 6248,
"text": "import numpy as npfrom scipy.stats import pearsonr#calculate correlation coefficientcorr = pearsonr(df['loudness'], df['valence'])corr = [np.round(c, 2) for c in corr]#add the coefficient to your graphtext = 'r=%s, p=%s' % (corr[0], corr[1])ax = sns.regplot(x=\"loudness\", y=\"valence\", data=df)ax.text(-7.5, 0.9, text, fontsize=12)"
},
{
"code": null,
"e": 6662,
"s": 6579,
"text": "Lastly, with Plotly, we can again create a scatterplot using the default settings:"
},
{
"code": null,
"e": 6846,
"s": 6662,
"text": "fig = go.Figure(data=go.Scatter(x=df[‘loudness’], y=df[‘valence’],mode=’markers’))fig.update_layout(title=’Loudness vs. Valence (Positivity)’)fig.layout.template = ‘seaborn’fig.show()"
},
{
"code": null,
"e": 6970,
"s": 6846,
"text": "By adding another trace called ‘lineOfBestFit’ and calculating the regression using numpy, we can plot the regression line:"
},
{
"code": null,
"e": 7706,
"s": 6970,
"text": "dataPoints = go.Scattergl( x=df.loudness, y=df.valence, mode='markers', marker=dict( opacity=1, line=dict( color='white' ) ), name='Data points')data=[dataPoints]layout.update( yaxis=dict( title='Energy'), xaxis=dict( title='Danceability' ))figure.update( data=data, layout=layout)m,b = np.polyfit(df.loudness, df.valence, 1)bestfit_y = (df.loudness * m + b)lineOfBestFit=go.Scattergl( x=df.loudness, y=bestfit_y, name='Line of best fit', line=dict( color='blue', ))data=[dataPoints, lineOfBestFit]figure = go.Figure(data=data, layout=layout)figure.update_xaxes(autorange=\"reversed\")figure.layout.template = 'plotly_dark'iplot(figure)"
}
] |
How to read a line from the console in C#?
|
The ReadLine() method is used to read a line from the console in C#.
str = Console.ReadLine();
The above will set the line in the variable str.
Live Demo
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string str;
// use ReadLine() to read the entered line
str = Console.ReadLine();
// display the line
Console.WriteLine("Input = {0}", str);
}
}
Input =
Above, we displayed a line using the Console.ReadLine() method. The string is entered by the user from the command line.
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "The ReadLine() method is used to read a line from the console in C#."
},
{
"code": null,
"e": 1157,
"s": 1131,
"text": "str = Console.ReadLine();"
},
{
"code": null,
"e": 1206,
"s": 1157,
"text": "The above will set the line in the variable str."
},
{
"code": null,
"e": 1217,
"s": 1206,
"text": " Live Demo"
},
{
"code": null,
"e": 1482,
"s": 1217,
"text": "using System;\nusing System.Collections.Generic;\n\nclass Demo {\n static void Main() {\n string str;\n\n // use ReadLine() to read the entered line\n str = Console.ReadLine();\n\n // display the line\n Console.WriteLine(\"Input = {0}\", str);\n }\n}"
},
{
"code": null,
"e": 1490,
"s": 1482,
"text": "Input ="
},
{
"code": null,
"e": 1611,
"s": 1490,
"text": "Above, we displayed a line using the Console.ReadLine() method. The string is entered by the user from the command line."
}
] |
How to use handleChange() function in react component? - GeeksforGeeks
|
14 Jan, 2021
An onChange event is triggered when values are entered in the input. This fires a function handleChange(), that is used to set a new state for the input.
First, we have to set up the input field as a controlled component so that we have a controlled component that senses changes and updates the state accordingly.
We will learn handleChange() function with the help of a project in which we’re going to use handleChange() function to display the entered input.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app handlechangedemo
Step 2: After creating your project folder i.e. handlechangedemo, move to it using the following command:
cd handlechangedemo
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from "react"; const App = () => { /* Initial State */ let [Name, setname] = useState(''); /* The handleChange() function to set a new state for input */ const handleChange = (event) => { setname(event.target.value); } return ( /* Short-form of React.Fragement*/ <> <form> { /* The handleChange() is triggered when text is entered */} <div> <h1>My Name is <span style={{ color: 'red' }} > {Name}</span></h1> <input type="text" value={Name} onChange={handleChange} placeholder="Enter a text" /> </div> </form> </> )} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below:
In the above project write down the following code in the App.js file for handling multiple inputs.
Javascript
import React, { useState } from 'react'; const App = () => { let [Fullname, setFullname] = useState({ fname: '', lname: '' }) const handleChange = (event) => { let value = event.target.value; let name = event.target.name; setFullname((prevalue) => { return { ...prevalue, // Spread Operator [name]: value } }) } return ( <> <form> <div> <h1>Hello <span style={{ color: 'red' }}>{Fullname.fname}</span> <span style={{ color: 'green' }}>{Fullname.lname}</span></h1> <input type='text' placeholder='Enter Your FirstName' onChange={handleChange} name='fname' /> <input type='text' placeholder='Enter Your LastName' onChange={handleChange} name='lname' /> </div> </form> </> )} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below:
Explanation: We have added name property in case of multiple inputs so that we can identify which input field fired the handleChange() function. We have used the spread operator because when the handleChange() function has been fired, we need the current value of fname and lname (because only then we can add(or assign) the entered input to the state variables(fname and lname)) which are stored in the state object, so we used spread operator to take an existing state object.
How this [name]: value statement works?
This statement assigns the value to that input field whose name (Property) matches the value.
Picked
react-js
Technical Scripter 2020
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Lodash _.debounce() Method
Angular File Upload
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
|
[
{
"code": null,
"e": 26568,
"s": 26540,
"text": "\n14 Jan, 2021"
},
{
"code": null,
"e": 26722,
"s": 26568,
"text": "An onChange event is triggered when values are entered in the input. This fires a function handleChange(), that is used to set a new state for the input."
},
{
"code": null,
"e": 26883,
"s": 26722,
"text": "First, we have to set up the input field as a controlled component so that we have a controlled component that senses changes and updates the state accordingly."
},
{
"code": null,
"e": 27030,
"s": 26883,
"text": "We will learn handleChange() function with the help of a project in which we’re going to use handleChange() function to display the entered input."
},
{
"code": null,
"e": 27058,
"s": 27030,
"text": "Creating React Application:"
},
{
"code": null,
"e": 27122,
"s": 27058,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27160,
"s": 27122,
"text": "npx create-react-app handlechangedemo"
},
{
"code": null,
"e": 27266,
"s": 27160,
"text": "Step 2: After creating your project folder i.e. handlechangedemo, move to it using the following command:"
},
{
"code": null,
"e": 27286,
"s": 27266,
"text": "cd handlechangedemo"
},
{
"code": null,
"e": 27338,
"s": 27286,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27356,
"s": 27338,
"text": "Project Structure"
},
{
"code": null,
"e": 27485,
"s": 27356,
"text": "App.js: 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": 27496,
"s": 27485,
"text": "Javascript"
},
{
"code": "import React, { useState } from \"react\"; const App = () => { /* Initial State */ let [Name, setname] = useState(''); /* The handleChange() function to set a new state for input */ const handleChange = (event) => { setname(event.target.value); } return ( /* Short-form of React.Fragement*/ <> <form> { /* The handleChange() is triggered when text is entered */} <div> <h1>My Name is <span style={{ color: 'red' }} > {Name}</span></h1> <input type=\"text\" value={Name} onChange={handleChange} placeholder=\"Enter a text\" /> </div> </form> </> )} export default App;",
"e": 28197,
"s": 27496,
"text": null
},
{
"code": null,
"e": 28310,
"s": 28197,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28320,
"s": 28310,
"text": "npm start"
},
{
"code": null,
"e": 28328,
"s": 28320,
"text": "Output:"
},
{
"code": null,
"e": 28459,
"s": 28328,
"text": "The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below:"
},
{
"code": null,
"e": 28559,
"s": 28459,
"text": "In the above project write down the following code in the App.js file for handling multiple inputs."
},
{
"code": null,
"e": 28570,
"s": 28559,
"text": "Javascript"
},
{
"code": "import React, { useState } from 'react'; const App = () => { let [Fullname, setFullname] = useState({ fname: '', lname: '' }) const handleChange = (event) => { let value = event.target.value; let name = event.target.name; setFullname((prevalue) => { return { ...prevalue, // Spread Operator [name]: value } }) } return ( <> <form> <div> <h1>Hello <span style={{ color: 'red' }}>{Fullname.fname}</span> <span style={{ color: 'green' }}>{Fullname.lname}</span></h1> <input type='text' placeholder='Enter Your FirstName' onChange={handleChange} name='fname' /> <input type='text' placeholder='Enter Your LastName' onChange={handleChange} name='lname' /> </div> </form> </> )} export default App;",
"e": 29426,
"s": 28570,
"text": null
},
{
"code": null,
"e": 29539,
"s": 29426,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29549,
"s": 29539,
"text": "npm start"
},
{
"code": null,
"e": 29557,
"s": 29549,
"text": "Output:"
},
{
"code": null,
"e": 29689,
"s": 29557,
"text": "The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below: "
},
{
"code": null,
"e": 30168,
"s": 29689,
"text": "Explanation: We have added name property in case of multiple inputs so that we can identify which input field fired the handleChange() function. We have used the spread operator because when the handleChange() function has been fired, we need the current value of fname and lname (because only then we can add(or assign) the entered input to the state variables(fname and lname)) which are stored in the state object, so we used spread operator to take an existing state object."
},
{
"code": null,
"e": 30208,
"s": 30168,
"text": "How this [name]: value statement works?"
},
{
"code": null,
"e": 30302,
"s": 30208,
"text": "This statement assigns the value to that input field whose name (Property) matches the value."
},
{
"code": null,
"e": 30309,
"s": 30302,
"text": "Picked"
},
{
"code": null,
"e": 30318,
"s": 30309,
"text": "react-js"
},
{
"code": null,
"e": 30342,
"s": 30318,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30353,
"s": 30342,
"text": "JavaScript"
},
{
"code": null,
"e": 30372,
"s": 30353,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30470,
"s": 30372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30510,
"s": 30470,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30571,
"s": 30510,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30612,
"s": 30571,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30634,
"s": 30612,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30688,
"s": 30634,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30736,
"s": 30688,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 30763,
"s": 30736,
"text": "Lodash _.debounce() Method"
},
{
"code": null,
"e": 30783,
"s": 30763,
"text": "Angular File Upload"
},
{
"code": null,
"e": 30840,
"s": 30783,
"text": "How to remove duplicate elements from JavaScript Array ?"
}
] |
Highcharts - Basic Column Chart
|
Following is an example of a basic column chart.
We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. An example of a basic column chart is given below.
Let us now see the additional configurations/steps taken.
Configure the chart type to be column based. chart.type decides the series type for the chart. Here, the default value is "line".
var chart = {
type: 'column'
};
highcharts_column_basic.htm
<html>
<head>
<title>Highcharts Tutorial</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src = "https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div>
<script language = "JavaScript">
$(document).ready(function() {
var chart = {
type: 'column'
};
var title = {
text: 'Monthly Average Rainfall'
};
var subtitle = {
text: 'Source: WorldClimate.com'
};
var xAxis = {
categories: ['Jan','Feb','Mar','Apr','May','Jun','Jul',
'Aug','Sep','Oct','Nov','Dec'],
crosshair: true
};
var yAxis = {
min: 0,
title: {
text: 'Rainfall (mm)'
}
};
var tooltip = {
headerFormat: '<span style = "font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style = "color:{series.color};padding:0">{series.name}: </td>' +
'<td style = "padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
};
var plotOptions = {
column: {
pointPadding: 0.2,
borderWidth: 0
}
};
var credits = {
enabled: false
};
var series= [
{
name: 'Tokyo',
data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6,
148.5, 216.4, 194.1, 95.6, 54.4]
},
{
name: 'New York',
data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3,
91.2, 83.5, 106.6, 92.3]
},
{
name: 'London',
data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6,
52.4, 65.2, 59.3, 51.2]
},
{
name: 'Berlin',
data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4,
47.6, 39.1, 46.8, 51.1]
}
];
var json = {};
json.chart = chart;
json.title = title;
json.subtitle = subtitle;
json.tooltip = tooltip;
json.xAxis = xAxis;
json.yAxis = yAxis;
json.series = series;
json.plotOptions = plotOptions;
json.credits = credits;
$('#container').highcharts(json);
});
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2066,
"s": 2017,
"text": "Following is an example of a basic column chart."
},
{
"code": null,
"e": 2221,
"s": 2066,
"text": "We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. An example of a basic column chart is given below."
},
{
"code": null,
"e": 2279,
"s": 2221,
"text": "Let us now see the additional configurations/steps taken."
},
{
"code": null,
"e": 2409,
"s": 2279,
"text": "Configure the chart type to be column based. chart.type decides the series type for the chart. Here, the default value is \"line\"."
},
{
"code": null,
"e": 2444,
"s": 2409,
"text": "var chart = {\n type: 'column'\n};"
},
{
"code": null,
"e": 2472,
"s": 2444,
"text": "highcharts_column_basic.htm"
},
{
"code": null,
"e": 5432,
"s": 2472,
"text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script> \n </head>\n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n <script language = \"JavaScript\">\n $(document).ready(function() { \n var chart = {\n type: 'column'\n };\n var title = {\n text: 'Monthly Average Rainfall' \n };\n var subtitle = {\n text: 'Source: WorldClimate.com' \n };\n var xAxis = {\n categories: ['Jan','Feb','Mar','Apr','May','Jun','Jul',\n 'Aug','Sep','Oct','Nov','Dec'],\n crosshair: true\n };\n var yAxis = {\n min: 0,\n title: {\n text: 'Rainfall (mm)' \n } \n };\n var tooltip = {\n headerFormat: '<span style = \"font-size:10px\">{point.key}</span><table>',\n pointFormat: '<tr><td style = \"color:{series.color};padding:0\">{series.name}: </td>' +\n '<td style = \"padding:0\"><b>{point.y:.1f} mm</b></td></tr>',\n footerFormat: '</table>',\n shared: true,\n useHTML: true\n };\n var plotOptions = {\n column: {\n pointPadding: 0.2,\n borderWidth: 0\n }\n }; \n var credits = {\n enabled: false\n };\n var series= [\n {\n name: 'Tokyo',\n data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6,\n 148.5, 216.4, 194.1, 95.6, 54.4]\n }, \n {\n name: 'New York',\n data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3,\n 91.2, 83.5, 106.6, 92.3]\n }, \n {\n name: 'London',\n data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6,\n 52.4, 65.2, 59.3, 51.2]\n }, \n {\n name: 'Berlin',\n data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4,\n 47.6, 39.1, 46.8, 51.1]\n }\n ]; \n \n var json = {}; \n json.chart = chart; \n json.title = title; \n json.subtitle = subtitle; \n json.tooltip = tooltip;\n json.xAxis = xAxis;\n json.yAxis = yAxis; \n json.series = series;\n json.plotOptions = plotOptions; \n json.credits = credits;\n $('#container').highcharts(json);\n \n });\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 5451,
"s": 5432,
"text": "Verify the result."
},
{
"code": null,
"e": 5458,
"s": 5451,
"text": " Print"
},
{
"code": null,
"e": 5469,
"s": 5458,
"text": " Add Notes"
}
] |
p5.js | randomSeed() Function - GeeksforGeeks
|
22 Apr, 2019
The randomSeed() function in p5.js is used to return a random number each time when run the program. The difference between the random() and randomSeed() function is that random() function produces distinct values each time the program is run but when randomSeed() function is used then it gives a constant random number each time the program is run.
Syntax:
randomSeed( Seed )
Parameters: This function accepts single parameter Seed which is any integer value.
Return Value: It returns a constant random number.
Below programs illustrate the randomSeed() function in p5.js:
Example 1: This example uses randomSeed() function to return a random number each time when run the program.
function setup() { // Creating Canvas size createCanvas(550, 140); // Set the background color background(220); // Calling to randomSeed() function randomSeed(9) // Calling to random() function with // min and max parameters let A = random(1, 2); let B = random(0, 1); let C = random(2); let D = random(2, 10); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting random number text("Random number between 1 and 2 is: " + A, 50, 30); text("Random number between 0 and 1 is: " + B, 50, 60); text("Random number between 0 and 2 is: " + C, 50, 90); text("Random number between 2 and 10 is: " + D, 50, 110);}
Output:
Note: In the above example, in variable “C” only one parameter is passed then it returns a random number from lower bound 0 to upper bound of that number.
Example 2: This example uses randomSeed() function to return a random number each time when run the program.
function setup() { // Creating Canvas size createCanvas(550, 140); // Set the background color background(220); // Calling to randomSeed() function randomSeed(9) // Calling to random() function with // parameter array of some elements let A = random([1, 2, 3, 4]); let B = random([0, 1]); let C = random([2, 6, 7, 9]); let D = random([2, 10]); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting random number text("Random number is: " + A, 50, 30); text("Random number is: " + B, 50, 60); text("Random number is: " + C, 50, 90); text("Random number is: " + D, 50, 110);}
Output:
Reference: https://p5js.org/reference/#/p5/randomSeed
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25382,
"s": 25354,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 25733,
"s": 25382,
"text": "The randomSeed() function in p5.js is used to return a random number each time when run the program. The difference between the random() and randomSeed() function is that random() function produces distinct values each time the program is run but when randomSeed() function is used then it gives a constant random number each time the program is run."
},
{
"code": null,
"e": 25741,
"s": 25733,
"text": "Syntax:"
},
{
"code": null,
"e": 25760,
"s": 25741,
"text": "randomSeed( Seed )"
},
{
"code": null,
"e": 25844,
"s": 25760,
"text": "Parameters: This function accepts single parameter Seed which is any integer value."
},
{
"code": null,
"e": 25895,
"s": 25844,
"text": "Return Value: It returns a constant random number."
},
{
"code": null,
"e": 25957,
"s": 25895,
"text": "Below programs illustrate the randomSeed() function in p5.js:"
},
{
"code": null,
"e": 26066,
"s": 25957,
"text": "Example 1: This example uses randomSeed() function to return a random number each time when run the program."
},
{
"code": "function setup() { // Creating Canvas size createCanvas(550, 140); // Set the background color background(220); // Calling to randomSeed() function randomSeed(9) // Calling to random() function with // min and max parameters let A = random(1, 2); let B = random(0, 1); let C = random(2); let D = random(2, 10); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting random number text(\"Random number between 1 and 2 is: \" + A, 50, 30); text(\"Random number between 0 and 1 is: \" + B, 50, 60); text(\"Random number between 0 and 2 is: \" + C, 50, 90); text(\"Random number between 2 and 10 is: \" + D, 50, 110);} ",
"e": 26819,
"s": 26066,
"text": null
},
{
"code": null,
"e": 26827,
"s": 26819,
"text": "Output:"
},
{
"code": null,
"e": 26982,
"s": 26827,
"text": "Note: In the above example, in variable “C” only one parameter is passed then it returns a random number from lower bound 0 to upper bound of that number."
},
{
"code": null,
"e": 27091,
"s": 26982,
"text": "Example 2: This example uses randomSeed() function to return a random number each time when run the program."
},
{
"code": "function setup() { // Creating Canvas size createCanvas(550, 140); // Set the background color background(220); // Calling to randomSeed() function randomSeed(9) // Calling to random() function with // parameter array of some elements let A = random([1, 2, 3, 4]); let B = random([0, 1]); let C = random([2, 6, 7, 9]); let D = random([2, 10]); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting random number text(\"Random number is: \" + A, 50, 30); text(\"Random number is: \" + B, 50, 60); text(\"Random number is: \" + C, 50, 90); text(\"Random number is: \" + D, 50, 110);} ",
"e": 27816,
"s": 27091,
"text": null
},
{
"code": null,
"e": 27824,
"s": 27816,
"text": "Output:"
},
{
"code": null,
"e": 27878,
"s": 27824,
"text": "Reference: https://p5js.org/reference/#/p5/randomSeed"
},
{
"code": null,
"e": 27895,
"s": 27878,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 27906,
"s": 27895,
"text": "JavaScript"
},
{
"code": null,
"e": 27923,
"s": 27906,
"text": "Web Technologies"
},
{
"code": null,
"e": 28021,
"s": 27923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28030,
"s": 28021,
"text": "Comments"
},
{
"code": null,
"e": 28043,
"s": 28030,
"text": "Old Comments"
},
{
"code": null,
"e": 28104,
"s": 28043,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28145,
"s": 28104,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28199,
"s": 28145,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28252,
"s": 28199,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 28314,
"s": 28252,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28356,
"s": 28314,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28389,
"s": 28356,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28451,
"s": 28389,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28494,
"s": 28451,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Adjust the width of box in boxplot in Python Matplotlib
|
To adjust the width of box in boxplot in Python matplotlib, we can use width in the boxplot()
method.
Set the figure size and adjust the padding between and around the subplots.
Make a Pandas dataframe, i.e., two-dimensional, size-mutable, potentially heterogeneous tabular data.
Make a box and whisker plot, using boxplot() method with width tuple to adjust the box in boxplot.
To display the figure, use show() method.
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = pd.DataFrame({"Box1": np.random.rand(10), "Box2": np.random.rand(10)})
ax = plt.boxplot(data, widths=(0.25, 0.5))
plt.show()
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To adjust the width of box in boxplot in Python matplotlib, we can use width in the boxplot()\nmethod."
},
{
"code": null,
"e": 1240,
"s": 1164,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1342,
"s": 1240,
"text": "Make a Pandas dataframe, i.e., two-dimensional, size-mutable, potentially heterogeneous tabular data."
},
{
"code": null,
"e": 1441,
"s": 1342,
"text": "Make a box and whisker plot, using boxplot() method with width tuple to adjust the box in boxplot."
},
{
"code": null,
"e": 1483,
"s": 1441,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1781,
"s": 1483,
"text": "import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = pd.DataFrame({\"Box1\": np.random.rand(10), \"Box2\": np.random.rand(10)})\nax = plt.boxplot(data, widths=(0.25, 0.5))\n\nplt.show()"
}
] |
Move To Front Data Transform Algorithm - GeeksforGeeks
|
29 Nov, 2017
What is the MTF transform?The MTF (Move to Front) is a data transformation algorithm that restructures data in such a way that the transformed message is more compressible and therefore used as an extra step in compression. Technically, it is an invertible transform of a sequence of input characters to an array of output numbers.
Why MTF?1. In many cases, the output array gives frequently repeated characters’ lower indexes which is useful in data compression algorithms.
2. It is first of the three steps to be performed in succession while implementing Burrows – Wheeler Data Compression algorithm that forms the basis of the Unix compression utility bzip2.
The main idea behind MTF:
1. The primary idea behind MTF is to maintain an ordered list of legal symbols (a to z, in our example).
2. Read one character at a time from input string .
3. Print out the position at which that character appears in the list.
4. Move that character to front of the list and repeat the process until indexes for all input characters are obtained.
Illustration for "panama".
List initially contains English alphabets in order.
We one by one characters of input to front.
input_str chars output_arr list
p 15 abcdefghijklmnopqrstuvwxyz
a 15 1 pabcdefghijklmnoqrstuvwxyz
n 15 1 14 apbcdefghijklmnoqrstuvwxyz
a 15 1 14 1 napbcdefghijklmoqrstuvwxyz
m 15 1 14 1 14 anpbcdefghijklmoqrstuvwxyz
a 15 1 14 1 14 manpbcdefghijkloqrstuvwxyz
Inference:1. If the letters occur many times in the input, then many of the output values will be small integers such as 0, 1, 2 etc.
2. Thus, encoding extremely high frequency of these letters makes an ideal scenario for Huffman Coding.
Examples:
Input : panama
Output : 15 1 14 1 14 1
Input : geeksforgeeks
Output : 6 5 0 10 18 8 15 18 6 6 0 6 6
Following is the code for idea explained above:
// C program to find move to front transform of// a given string#include <stdio.h>#include <stdlib.h>#include <string.h> // Returns index at which character of the input text// exists in the listint search(char input_char, char* list){ int i; for (i = 0; i < strlen(list); i++) { if (list[i] == input_char) { return i; break; } }} // Takes curr_index of input_char as argument// to bring that character to the front of the listvoid moveToFront(int curr_index, char* list){ char* record = (char*)malloc(sizeof(char) * 26); strcpy(record, list); // Characters pushed one position right // in the list up until curr_index strncpy(list + 1, record, curr_index); // Character at curr_index stored at 0th position list[0] = record[curr_index];} // Move to Front Encodingvoid mtfEncode(char* input_text, int len_text, char* list){ int i; int* output_arr = (int*)malloc(len_text * sizeof(int)); for (i = 0; i < len_text; i++) { // Linear Searches the characters of input_text // in list output_arr[i] = search(input_text[i], list); // Printing the Move to Front Transform printf("%d ", output_arr[i]); // Moves the searched character to the front // of the list moveToFront(output_arr[i], list); }} // Driver program to test functions aboveint main(){ char* input_text = "panama"; int len_text = strlen(input_text); // Maintains an ordered list of legal symbols char* list = (char*)malloc(sizeof(char) * 26); strcpy(list, "abcdefghijklmnopqrstuvwxyz"); printf("Input text: %s", input_text); printf("\nMove to Front Transform: "); // Computes Move to Front transform of given text mtfEncode(input_text, len_text, list); return 0;}
Output:
Input text: panama
Move to Front Transform: 15 1 14 1 14 1
Time Complexity: O(n^2)
Exercise: Implement Inverse of Move to Front Transform.
encoding-decoding
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different methods to reverse a string in C/C++
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Reverse words in a given string
Length of the longest substring without repeating characters
|
[
{
"code": null,
"e": 24856,
"s": 24828,
"text": "\n29 Nov, 2017"
},
{
"code": null,
"e": 25188,
"s": 24856,
"text": "What is the MTF transform?The MTF (Move to Front) is a data transformation algorithm that restructures data in such a way that the transformed message is more compressible and therefore used as an extra step in compression. Technically, it is an invertible transform of a sequence of input characters to an array of output numbers."
},
{
"code": null,
"e": 25331,
"s": 25188,
"text": "Why MTF?1. In many cases, the output array gives frequently repeated characters’ lower indexes which is useful in data compression algorithms."
},
{
"code": null,
"e": 25519,
"s": 25331,
"text": "2. It is first of the three steps to be performed in succession while implementing Burrows – Wheeler Data Compression algorithm that forms the basis of the Unix compression utility bzip2."
},
{
"code": null,
"e": 25545,
"s": 25519,
"text": "The main idea behind MTF:"
},
{
"code": null,
"e": 25650,
"s": 25545,
"text": "1. The primary idea behind MTF is to maintain an ordered list of legal symbols (a to z, in our example)."
},
{
"code": null,
"e": 25702,
"s": 25650,
"text": "2. Read one character at a time from input string ."
},
{
"code": null,
"e": 25773,
"s": 25702,
"text": "3. Print out the position at which that character appears in the list."
},
{
"code": null,
"e": 25893,
"s": 25773,
"text": "4. Move that character to front of the list and repeat the process until indexes for all input characters are obtained."
},
{
"code": null,
"e": 26427,
"s": 25893,
"text": "Illustration for \"panama\". \nList initially contains English alphabets in order. \nWe one by one characters of input to front.\n\ninput_str chars output_arr list\n p 15 abcdefghijklmnopqrstuvwxyz\n a 15 1 pabcdefghijklmnoqrstuvwxyz\n n 15 1 14 apbcdefghijklmnoqrstuvwxyz\n a 15 1 14 1 napbcdefghijklmoqrstuvwxyz\n m 15 1 14 1 14 anpbcdefghijklmoqrstuvwxyz\n a 15 1 14 1 14 manpbcdefghijkloqrstuvwxyz\n"
},
{
"code": null,
"e": 26561,
"s": 26427,
"text": "Inference:1. If the letters occur many times in the input, then many of the output values will be small integers such as 0, 1, 2 etc."
},
{
"code": null,
"e": 26665,
"s": 26561,
"text": "2. Thus, encoding extremely high frequency of these letters makes an ideal scenario for Huffman Coding."
},
{
"code": null,
"e": 26675,
"s": 26665,
"text": "Examples:"
},
{
"code": null,
"e": 26778,
"s": 26675,
"text": "Input : panama\nOutput : 15 1 14 1 14 1\n\nInput : geeksforgeeks\nOutput : 6 5 0 10 18 8 15 18 6 6 0 6 6 \n"
},
{
"code": null,
"e": 26826,
"s": 26778,
"text": "Following is the code for idea explained above:"
},
{
"code": "// C program to find move to front transform of// a given string#include <stdio.h>#include <stdlib.h>#include <string.h> // Returns index at which character of the input text// exists in the listint search(char input_char, char* list){ int i; for (i = 0; i < strlen(list); i++) { if (list[i] == input_char) { return i; break; } }} // Takes curr_index of input_char as argument// to bring that character to the front of the listvoid moveToFront(int curr_index, char* list){ char* record = (char*)malloc(sizeof(char) * 26); strcpy(record, list); // Characters pushed one position right // in the list up until curr_index strncpy(list + 1, record, curr_index); // Character at curr_index stored at 0th position list[0] = record[curr_index];} // Move to Front Encodingvoid mtfEncode(char* input_text, int len_text, char* list){ int i; int* output_arr = (int*)malloc(len_text * sizeof(int)); for (i = 0; i < len_text; i++) { // Linear Searches the characters of input_text // in list output_arr[i] = search(input_text[i], list); // Printing the Move to Front Transform printf(\"%d \", output_arr[i]); // Moves the searched character to the front // of the list moveToFront(output_arr[i], list); }} // Driver program to test functions aboveint main(){ char* input_text = \"panama\"; int len_text = strlen(input_text); // Maintains an ordered list of legal symbols char* list = (char*)malloc(sizeof(char) * 26); strcpy(list, \"abcdefghijklmnopqrstuvwxyz\"); printf(\"Input text: %s\", input_text); printf(\"\\nMove to Front Transform: \"); // Computes Move to Front transform of given text mtfEncode(input_text, len_text, list); return 0;}",
"e": 28640,
"s": 26826,
"text": null
},
{
"code": null,
"e": 28648,
"s": 28640,
"text": "Output:"
},
{
"code": null,
"e": 28708,
"s": 28648,
"text": "Input text: panama\nMove to Front Transform: 15 1 14 1 14 1\n"
},
{
"code": null,
"e": 28732,
"s": 28708,
"text": "Time Complexity: O(n^2)"
},
{
"code": null,
"e": 28788,
"s": 28732,
"text": "Exercise: Implement Inverse of Move to Front Transform."
},
{
"code": null,
"e": 28806,
"s": 28788,
"text": "encoding-decoding"
},
{
"code": null,
"e": 28814,
"s": 28806,
"text": "Strings"
},
{
"code": null,
"e": 28833,
"s": 28814,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28841,
"s": 28833,
"text": "Strings"
},
{
"code": null,
"e": 28939,
"s": 28841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28948,
"s": 28939,
"text": "Comments"
},
{
"code": null,
"e": 28961,
"s": 28948,
"text": "Old Comments"
},
{
"code": null,
"e": 29036,
"s": 28961,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 29083,
"s": 29036,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 29140,
"s": 29083,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 29176,
"s": 29140,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 29212,
"s": 29176,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 29250,
"s": 29212,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 29303,
"s": 29250,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 29333,
"s": 29303,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 29365,
"s": 29333,
"text": "Reverse words in a given string"
}
] |
What is Explainable AI (XAI)?. An introduction to building trust in... | by Nicklas Ankarstad | Towards Data Science
|
There is a lot of buzz around AI these days. Almost every company either has plans to incorporate AI, is actively using it, or is rebranding their old rule-based engines as AI-enabled technologies. As more and more companies embed AI and advanced analytics within a business process and automate decisions, there needs to have transparency into how these models make decisions grows larger and larger.
How do we achieve this transparency while harnessing the efficiencies AI brings. This is where the field of Explainable AI (XAI) can help.
Explainable AI refers to methods and techniques in the application of artificial intelligence technology (AI) such that the results of the solution can be understood by human experts.
It contrasts with the concept of the “black box” in machine learning where even their designers cannot explain why the AI arrived at a specific decision. XAI is an implementation of the social right to explanation [1]
In it’s simplest form, AI takes some inputs to produce an output. When we talk about Explainable AI, we are really talking about the input variables impact on the output.
AI has the power to automate decisions and those decisions have business impacts, both positive and negative. Much like hiring decision-makers in the organization, it's important to understand how AI makes decisions. A lot of organizations want to leverage AI but are not comfortable letting the model or AI make more impactful decisions because they do not yet trust the model. Explainability helps with this as it provides insights into how models make decisions.
One of the biggest challenges I’ve found in my experience isn’t building the right model, it’s getting stakeholder buy-in that the model makes a better decision than a human. A better decision is not the same as higher accuracy scores or lower RMSE. It’s using the right inputs to derive a good answer. Often times the decision-maker needs to understand the decision. They need see how the model reasoned to be comfortable handing it off to the model to make the decision.
We build trust in AI and models the same way we do as humans. We show our work. Let’s dive into a practical example of explainability.
What if we were to try and predict the mpg on the number of cylinders a car has using a linear regression model.
This can be easily done in any programming tool or even excel these days. We find the coefficient and the intercept and plot it. The nice thing here is that we can simply see how the overall model makes decisions (global level). At the same time, the individual predictions are consistent with the global level predictions.
import requestsimport pandas as pdfrom io import StringIOimport matplotlib.pyplot as pltimport numpy as npfrom sklearn import linear_model## The URL for the dataseturl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data' r = requests.get(url)## Read the file in and store as dffile = r.text.replace("\t"," ") # list_labels written manually: list_labels = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin','car name']df = pd.read_csv(StringIO(file),sep="\s+",header = None,names=list_labels)## Modelingregr = linear_model.LinearRegression()train_x = np.asanyarray(df[['cylinders']])train_y = np.asanyarray(df[['mpg']])regr.fit (train_x, train_y)## Plotting the modelplt.scatter(df.cylinders, df.mpg, color='blue')plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')plt.xlabel("Cylinders")plt.ylabel("MPG")
There is a negative linear relationship, but as the plot shows our predictions are way off. For example, in the 4 cylinder category, our estimate is about 28–29ish, but the values seem to range from 45+ to 19.
We may need to add more features or try a more complex model to achieve the desired model performance.
Increasing Performance through Complexity
We may want to try a more complex model such as Gradient Boosted Decision Trees. GBMs such as XGBoost, H20, LightGBM, AdaBoost, and Catboost consistently win data science competitions for tabular data.
GBM’s converts weak learners (decision trees) into strong learners. They have lower bias and lower variance by using a sampling technique called boosting.
On the spectrum of complexity, they are not as black-box as neural networks nor as transparent as logistic regression.
When we talk about impact, we differentiate between global and local importance:
Global importance can be thought of as overall how is the model making decisions.
Local importance is how is the model making decisions for this one person.
These distinctions may seem small, but they have a significant impact as the right to explanation legislation becomes more prevalent.
Increased Complexity Example
Let’s load up a new data set. In this case, we will use the credit card default prediction dataset from UCI. The dataset is from a Taiwanese bank and includes information
The columns include information on each borrower:
Demographics
Historical repayment history
Historical bill amount
Historical previous payment amount
We can use this dataset to predict payment defaults using XGBoost. Once we have built the model, we need to evaluate its performance and since this is credit decision, we are interested in how it makes decisions.
import requestsimport pandas as pdfrom io import StringIOimport matplotlib.pyplot as pltimport numpy as npfrom sklearn import linear_modelimport shapimport xgboost as xgbfrom xgboost import XGBClassifierfrom sklearn.model_selection import train_test_splitshap.initjs()import limeimport lime.lime_tabularimport matplotlib.pylab as plfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import roc_auc_scorefrom sklearn.metrics import accuracy_score## Read in the filedf = pd.read_excel('https://archive.ics.uci.edu/ml/machine-learning-databases/00350/default%20of%20credit%20card%20clients.xls',header = 1)## Store target in y variable and split to train testy = df['default payment next month'] df = df.drop(['default payment next month','ID'], axis =1) X_train, X_test, y_train, y_test = train_test_split(df, y, test_size=0.20, random_state=42)## Train XGBoost Modelxgb_model = XGBClassifier(learning_rate = 0.05, verbosity = 1, n_estimators = 200 ,scale_pos_weight =4, random_state = 2456 )xgb_model.fit(X_train, y_train)## Predicty_pred = xgb_model.predict(X_test) roc_auc_score(y_test,y_pred)
Feature importance plots are what many data scientist use to evaluate the impact the input variables have on the output variable. Notice that depending on which metric (cover or gain), different feature come to the top. How do you explain to a customer that you declined their application due to their marital status? Is that really how the model made its decision?
## Plot importance (cover)xgb.plot_importance(xgb_model, importance_type="cover")pl.title('xgboost.plot_importance(model, importance_type="cover")')pl.show()## Plot importance (gain)xgb.plot_importance(xgb_model, importance_type="gain")pl.title('xgboost.plot_importance(model, importance_type="gain")')pl.show()
The truth is that while these feature importance plots show the overall impact of the features, they are not able to explain how the model makes decisions for individual people.
Global interpretability of models entails seeking to understand the overall structure of the model. What if I want to understand how a model made a prediction for a specific person?
Local interpretability of models consists of providing detailed explanations for why an individual prediction was made.
Let’s talk about the first local interpretability framework, often referred to as LIME.
LIME randomly samples from the prediction and uses simpler models to explain the prediction. Since it is not tied to a specific model, it is considered model agnostic.
xgb_model.fit(X_train.as_matrix(), y_train)predict_fn_xgb = lambda x: xgb_model.predict_proba(x).astype(float)explainer = lime.lime_tabular.LimeTabularExplainer(X_train.to_numpy(), feature_names = X_train.columns)exp = explainer.explain_instance(X_test.to_numpy()[observation_1], predict_fn_xgb, num_features = 9)exp.show_in_notebook()
If you look closely you can see that the top feature is Pay > 0 meaning that the person is behind on their payments.
LIME uses a decision tree to explain the more complex models. Because LIME estimates the prediction using local approximations it can sometimes be risky to use as a ground truth explanation.
SHAP is another novel approach to explainability developed by Scott Lundberg at Microsoft and eventually opened sourced.
SHAP has a strong mathematical foundation based on Shapley values in game theory where each player in the cooperation is rewarded based on how important they are to cooperation.
Here we see the same most likely defaulting borrower and the impact each variable has on the output. These local explanations are accurate and can be used to explain how XGBoost makes its decision.
## Calculate SHAP Valuesexplainer = shap.TreeExplainer(xgb_model)expected_value = explainer.expected_value## Generate forceplotshap.force_plot(expected_value,shap_values[observation_1],features_display.iloc[observation_1] ,X_test.columns,link='logit', matplotlib=True)
SHAP can illustrate local importance and the really nice thing about SHAP is that it is globally consistent. Several model frameworks can spit out SHAP values (XGBoost for example) directly from the code.
shap.summary_plot(shap_values, X_test)
The last framework I’ll mention t is Explainable Boosting Machines.
Explainable Boosting Machines or EBMs is another Microsoft open source library. Instead of being a post-hoc explanation framework, they are considered more white-box than XGBoost, while reaching similar performance.
EBM uses a framework called GA2M, which is a generalized additive model with an interaction function added to it.
The models have been proven to be as accurate as XGBoost and a GA2M won a data science contest hosted by FICO a year or so ago.
from interpret.glassbox import ExplainableBoostingClassifierfrom interpret import show## Train Modelebm = ExplainableBoostingClassifier(scoring = 'auc')ebm.fit(X_train, y_train)## Calculate Global Explainationebm_global = ebm.explain_global()## Plot Global Variable Importanceshow(ebm_global)
InterpretML is still in alpha release right now, but for tabular data GA2M models they are starting to become the de-facto standard for white-box models.
There is a very nice user interface with a dashboard that explains the predictions from the global level down to the local level, much like SHAP.
## Local explainationsebm_local = ebm.explain_local(X_test, y_test)show(ebm_local)
You should use explainability techniques such as LIME and SHAP when you need to build trust with your stakeholders by being transparent in modeling. If you are a decision-maker, always ask your data scientist or vendor for explanations of how the model makes decisions. As with almost everything in life, the best model and explanation option usually depends on the situation.
[1] Explainable Artificial Intelligence, Wikipedia
[2] Lundberg, Scott M and Lee, Su-In, A Unified Approach to Interpreting Model Predictions (2017), Advances in Neural Information Processing Systems 30
[3] H. Nori, S. Jenkins, P. Koch, and R. Caruana, InterpretML: A Unified Framework for Machine Learning Interpretability (2019)
|
[
{
"code": null,
"e": 574,
"s": 172,
"text": "There is a lot of buzz around AI these days. Almost every company either has plans to incorporate AI, is actively using it, or is rebranding their old rule-based engines as AI-enabled technologies. As more and more companies embed AI and advanced analytics within a business process and automate decisions, there needs to have transparency into how these models make decisions grows larger and larger."
},
{
"code": null,
"e": 713,
"s": 574,
"text": "How do we achieve this transparency while harnessing the efficiencies AI brings. This is where the field of Explainable AI (XAI) can help."
},
{
"code": null,
"e": 897,
"s": 713,
"text": "Explainable AI refers to methods and techniques in the application of artificial intelligence technology (AI) such that the results of the solution can be understood by human experts."
},
{
"code": null,
"e": 1115,
"s": 897,
"text": "It contrasts with the concept of the “black box” in machine learning where even their designers cannot explain why the AI arrived at a specific decision. XAI is an implementation of the social right to explanation [1]"
},
{
"code": null,
"e": 1286,
"s": 1115,
"text": "In it’s simplest form, AI takes some inputs to produce an output. When we talk about Explainable AI, we are really talking about the input variables impact on the output."
},
{
"code": null,
"e": 1752,
"s": 1286,
"text": "AI has the power to automate decisions and those decisions have business impacts, both positive and negative. Much like hiring decision-makers in the organization, it's important to understand how AI makes decisions. A lot of organizations want to leverage AI but are not comfortable letting the model or AI make more impactful decisions because they do not yet trust the model. Explainability helps with this as it provides insights into how models make decisions."
},
{
"code": null,
"e": 2225,
"s": 1752,
"text": "One of the biggest challenges I’ve found in my experience isn’t building the right model, it’s getting stakeholder buy-in that the model makes a better decision than a human. A better decision is not the same as higher accuracy scores or lower RMSE. It’s using the right inputs to derive a good answer. Often times the decision-maker needs to understand the decision. They need see how the model reasoned to be comfortable handing it off to the model to make the decision."
},
{
"code": null,
"e": 2360,
"s": 2225,
"text": "We build trust in AI and models the same way we do as humans. We show our work. Let’s dive into a practical example of explainability."
},
{
"code": null,
"e": 2473,
"s": 2360,
"text": "What if we were to try and predict the mpg on the number of cylinders a car has using a linear regression model."
},
{
"code": null,
"e": 2797,
"s": 2473,
"text": "This can be easily done in any programming tool or even excel these days. We find the coefficient and the intercept and plot it. The nice thing here is that we can simply see how the overall model makes decisions (global level). At the same time, the individual predictions are consistent with the global level predictions."
},
{
"code": null,
"e": 3704,
"s": 2797,
"text": "import requestsimport pandas as pdfrom io import StringIOimport matplotlib.pyplot as pltimport numpy as npfrom sklearn import linear_model## The URL for the dataseturl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data' r = requests.get(url)## Read the file in and store as dffile = r.text.replace(\"\\t\",\" \") # list_labels written manually: list_labels = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin','car name']df = pd.read_csv(StringIO(file),sep=\"\\s+\",header = None,names=list_labels)## Modelingregr = linear_model.LinearRegression()train_x = np.asanyarray(df[['cylinders']])train_y = np.asanyarray(df[['mpg']])regr.fit (train_x, train_y)## Plotting the modelplt.scatter(df.cylinders, df.mpg, color='blue')plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')plt.xlabel(\"Cylinders\")plt.ylabel(\"MPG\")"
},
{
"code": null,
"e": 3914,
"s": 3704,
"text": "There is a negative linear relationship, but as the plot shows our predictions are way off. For example, in the 4 cylinder category, our estimate is about 28–29ish, but the values seem to range from 45+ to 19."
},
{
"code": null,
"e": 4017,
"s": 3914,
"text": "We may need to add more features or try a more complex model to achieve the desired model performance."
},
{
"code": null,
"e": 4059,
"s": 4017,
"text": "Increasing Performance through Complexity"
},
{
"code": null,
"e": 4261,
"s": 4059,
"text": "We may want to try a more complex model such as Gradient Boosted Decision Trees. GBMs such as XGBoost, H20, LightGBM, AdaBoost, and Catboost consistently win data science competitions for tabular data."
},
{
"code": null,
"e": 4416,
"s": 4261,
"text": "GBM’s converts weak learners (decision trees) into strong learners. They have lower bias and lower variance by using a sampling technique called boosting."
},
{
"code": null,
"e": 4535,
"s": 4416,
"text": "On the spectrum of complexity, they are not as black-box as neural networks nor as transparent as logistic regression."
},
{
"code": null,
"e": 4616,
"s": 4535,
"text": "When we talk about impact, we differentiate between global and local importance:"
},
{
"code": null,
"e": 4698,
"s": 4616,
"text": "Global importance can be thought of as overall how is the model making decisions."
},
{
"code": null,
"e": 4773,
"s": 4698,
"text": "Local importance is how is the model making decisions for this one person."
},
{
"code": null,
"e": 4907,
"s": 4773,
"text": "These distinctions may seem small, but they have a significant impact as the right to explanation legislation becomes more prevalent."
},
{
"code": null,
"e": 4936,
"s": 4907,
"text": "Increased Complexity Example"
},
{
"code": null,
"e": 5107,
"s": 4936,
"text": "Let’s load up a new data set. In this case, we will use the credit card default prediction dataset from UCI. The dataset is from a Taiwanese bank and includes information"
},
{
"code": null,
"e": 5157,
"s": 5107,
"text": "The columns include information on each borrower:"
},
{
"code": null,
"e": 5170,
"s": 5157,
"text": "Demographics"
},
{
"code": null,
"e": 5199,
"s": 5170,
"text": "Historical repayment history"
},
{
"code": null,
"e": 5222,
"s": 5199,
"text": "Historical bill amount"
},
{
"code": null,
"e": 5257,
"s": 5222,
"text": "Historical previous payment amount"
},
{
"code": null,
"e": 5470,
"s": 5257,
"text": "We can use this dataset to predict payment defaults using XGBoost. Once we have built the model, we need to evaluate its performance and since this is credit decision, we are interested in how it makes decisions."
},
{
"code": null,
"e": 6579,
"s": 5470,
"text": "import requestsimport pandas as pdfrom io import StringIOimport matplotlib.pyplot as pltimport numpy as npfrom sklearn import linear_modelimport shapimport xgboost as xgbfrom xgboost import XGBClassifierfrom sklearn.model_selection import train_test_splitshap.initjs()import limeimport lime.lime_tabularimport matplotlib.pylab as plfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import roc_auc_scorefrom sklearn.metrics import accuracy_score## Read in the filedf = pd.read_excel('https://archive.ics.uci.edu/ml/machine-learning-databases/00350/default%20of%20credit%20card%20clients.xls',header = 1)## Store target in y variable and split to train testy = df['default payment next month'] df = df.drop(['default payment next month','ID'], axis =1) X_train, X_test, y_train, y_test = train_test_split(df, y, test_size=0.20, random_state=42)## Train XGBoost Modelxgb_model = XGBClassifier(learning_rate = 0.05, verbosity = 1, n_estimators = 200 ,scale_pos_weight =4, random_state = 2456 )xgb_model.fit(X_train, y_train)## Predicty_pred = xgb_model.predict(X_test) roc_auc_score(y_test,y_pred)"
},
{
"code": null,
"e": 6945,
"s": 6579,
"text": "Feature importance plots are what many data scientist use to evaluate the impact the input variables have on the output variable. Notice that depending on which metric (cover or gain), different feature come to the top. How do you explain to a customer that you declined their application due to their marital status? Is that really how the model made its decision?"
},
{
"code": null,
"e": 7257,
"s": 6945,
"text": "## Plot importance (cover)xgb.plot_importance(xgb_model, importance_type=\"cover\")pl.title('xgboost.plot_importance(model, importance_type=\"cover\")')pl.show()## Plot importance (gain)xgb.plot_importance(xgb_model, importance_type=\"gain\")pl.title('xgboost.plot_importance(model, importance_type=\"gain\")')pl.show()"
},
{
"code": null,
"e": 7435,
"s": 7257,
"text": "The truth is that while these feature importance plots show the overall impact of the features, they are not able to explain how the model makes decisions for individual people."
},
{
"code": null,
"e": 7617,
"s": 7435,
"text": "Global interpretability of models entails seeking to understand the overall structure of the model. What if I want to understand how a model made a prediction for a specific person?"
},
{
"code": null,
"e": 7737,
"s": 7617,
"text": "Local interpretability of models consists of providing detailed explanations for why an individual prediction was made."
},
{
"code": null,
"e": 7825,
"s": 7737,
"text": "Let’s talk about the first local interpretability framework, often referred to as LIME."
},
{
"code": null,
"e": 7993,
"s": 7825,
"text": "LIME randomly samples from the prediction and uses simpler models to explain the prediction. Since it is not tied to a specific model, it is considered model agnostic."
},
{
"code": null,
"e": 8329,
"s": 7993,
"text": "xgb_model.fit(X_train.as_matrix(), y_train)predict_fn_xgb = lambda x: xgb_model.predict_proba(x).astype(float)explainer = lime.lime_tabular.LimeTabularExplainer(X_train.to_numpy(), feature_names = X_train.columns)exp = explainer.explain_instance(X_test.to_numpy()[observation_1], predict_fn_xgb, num_features = 9)exp.show_in_notebook()"
},
{
"code": null,
"e": 8446,
"s": 8329,
"text": "If you look closely you can see that the top feature is Pay > 0 meaning that the person is behind on their payments."
},
{
"code": null,
"e": 8637,
"s": 8446,
"text": "LIME uses a decision tree to explain the more complex models. Because LIME estimates the prediction using local approximations it can sometimes be risky to use as a ground truth explanation."
},
{
"code": null,
"e": 8758,
"s": 8637,
"text": "SHAP is another novel approach to explainability developed by Scott Lundberg at Microsoft and eventually opened sourced."
},
{
"code": null,
"e": 8936,
"s": 8758,
"text": "SHAP has a strong mathematical foundation based on Shapley values in game theory where each player in the cooperation is rewarded based on how important they are to cooperation."
},
{
"code": null,
"e": 9134,
"s": 8936,
"text": "Here we see the same most likely defaulting borrower and the impact each variable has on the output. These local explanations are accurate and can be used to explain how XGBoost makes its decision."
},
{
"code": null,
"e": 9403,
"s": 9134,
"text": "## Calculate SHAP Valuesexplainer = shap.TreeExplainer(xgb_model)expected_value = explainer.expected_value## Generate forceplotshap.force_plot(expected_value,shap_values[observation_1],features_display.iloc[observation_1] ,X_test.columns,link='logit', matplotlib=True)"
},
{
"code": null,
"e": 9608,
"s": 9403,
"text": "SHAP can illustrate local importance and the really nice thing about SHAP is that it is globally consistent. Several model frameworks can spit out SHAP values (XGBoost for example) directly from the code."
},
{
"code": null,
"e": 9647,
"s": 9608,
"text": "shap.summary_plot(shap_values, X_test)"
},
{
"code": null,
"e": 9715,
"s": 9647,
"text": "The last framework I’ll mention t is Explainable Boosting Machines."
},
{
"code": null,
"e": 9931,
"s": 9715,
"text": "Explainable Boosting Machines or EBMs is another Microsoft open source library. Instead of being a post-hoc explanation framework, they are considered more white-box than XGBoost, while reaching similar performance."
},
{
"code": null,
"e": 10045,
"s": 9931,
"text": "EBM uses a framework called GA2M, which is a generalized additive model with an interaction function added to it."
},
{
"code": null,
"e": 10173,
"s": 10045,
"text": "The models have been proven to be as accurate as XGBoost and a GA2M won a data science contest hosted by FICO a year or so ago."
},
{
"code": null,
"e": 10466,
"s": 10173,
"text": "from interpret.glassbox import ExplainableBoostingClassifierfrom interpret import show## Train Modelebm = ExplainableBoostingClassifier(scoring = 'auc')ebm.fit(X_train, y_train)## Calculate Global Explainationebm_global = ebm.explain_global()## Plot Global Variable Importanceshow(ebm_global)"
},
{
"code": null,
"e": 10620,
"s": 10466,
"text": "InterpretML is still in alpha release right now, but for tabular data GA2M models they are starting to become the de-facto standard for white-box models."
},
{
"code": null,
"e": 10766,
"s": 10620,
"text": "There is a very nice user interface with a dashboard that explains the predictions from the global level down to the local level, much like SHAP."
},
{
"code": null,
"e": 10849,
"s": 10766,
"text": "## Local explainationsebm_local = ebm.explain_local(X_test, y_test)show(ebm_local)"
},
{
"code": null,
"e": 11226,
"s": 10849,
"text": "You should use explainability techniques such as LIME and SHAP when you need to build trust with your stakeholders by being transparent in modeling. If you are a decision-maker, always ask your data scientist or vendor for explanations of how the model makes decisions. As with almost everything in life, the best model and explanation option usually depends on the situation."
},
{
"code": null,
"e": 11277,
"s": 11226,
"text": "[1] Explainable Artificial Intelligence, Wikipedia"
},
{
"code": null,
"e": 11429,
"s": 11277,
"text": "[2] Lundberg, Scott M and Lee, Su-In, A Unified Approach to Interpreting Model Predictions (2017), Advances in Neural Information Processing Systems 30"
}
] |
Python - Odd Frequency Characters - GeeksforGeeks
|
10 May, 2020
Sometimes, while working with Python strings, we can have a problem in which we need to extract all the string characters which have odd number of occurrences. This problem can have applications in domains such as data domain and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_str = ‘geekforgeeks’Output : [‘r’, ‘o’, ‘f’, ‘s’]
Input : test_str = ‘g’Output : [‘g’]
Method #1 : Using defaultdict() + list comprehension + loopThe combination of above functions can be used to solve this problem. In this, we initialize the defaultdict() with integer and then perform frequency count. List comprehension is used to extract all the odd frequencies.
# Python3 code to demonstrate working of # Odd Frequency Characters# Using list comprehension + defaultdict()from collections import defaultdict # helper_functiondef hlper_fnc(test_str): cntr = defaultdict(int) for ele in test_str: cntr[ele] += 1 return [val for val, chr in cntr.items() if chr % 2 != 0] # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # Odd Frequency Characters# Using list comprehension + defaultdict()res = hlper_fnc(test_str) # printing result print("The Odd Frequency Characters are : " + str(res))
The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']
Method #2 : Using list comprehension + Counter()The combination of above functionalities can be used to solve this problem. In this, we use Counter() to count the frequency.
# Python3 code to demonstrate working of # Odd Frequency Characters# Using list comprehension + Counter()from collections import Counter # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # Odd Frequency Characters# Using list comprehension + Counter()res = [ chr for chr, count in Counter(test_str).items() if count & 1 ] # printing result print("The Odd Frequency Characters are : " + str(res))
The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']
Python string-programs
Python
Python Programs
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24242,
"s": 23927,
"text": "Sometimes, while working with Python strings, we can have a problem in which we need to extract all the string characters which have odd number of occurrences. This problem can have applications in domains such as data domain and day-day programming. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24305,
"s": 24242,
"text": "Input : test_str = ‘geekforgeeks’Output : [‘r’, ‘o’, ‘f’, ‘s’]"
},
{
"code": null,
"e": 24342,
"s": 24305,
"text": "Input : test_str = ‘g’Output : [‘g’]"
},
{
"code": null,
"e": 24622,
"s": 24342,
"text": "Method #1 : Using defaultdict() + list comprehension + loopThe combination of above functions can be used to solve this problem. In this, we initialize the defaultdict() with integer and then perform frequency count. List comprehension is used to extract all the odd frequencies."
},
{
"code": "# Python3 code to demonstrate working of # Odd Frequency Characters# Using list comprehension + defaultdict()from collections import defaultdict # helper_functiondef hlper_fnc(test_str): cntr = defaultdict(int) for ele in test_str: cntr[ele] += 1 return [val for val, chr in cntr.items() if chr % 2 != 0] # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Odd Frequency Characters# Using list comprehension + defaultdict()res = hlper_fnc(test_str) # printing result print(\"The Odd Frequency Characters are : \" + str(res))",
"e": 25258,
"s": 24622,
"text": null
},
{
"code": null,
"e": 25381,
"s": 25258,
"text": "The original string is : geekforgeeks is best for geeks\nThe Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']\n"
},
{
"code": null,
"e": 25557,
"s": 25383,
"text": "Method #2 : Using list comprehension + Counter()The combination of above functionalities can be used to solve this problem. In this, we use Counter() to count the frequency."
},
{
"code": "# Python3 code to demonstrate working of # Odd Frequency Characters# Using list comprehension + Counter()from collections import Counter # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Odd Frequency Characters# Using list comprehension + Counter()res = [ chr for chr, count in Counter(test_str).items() if count & 1 ] # printing result print(\"The Odd Frequency Characters are : \" + str(res))",
"e": 26050,
"s": 25557,
"text": null
},
{
"code": null,
"e": 26173,
"s": 26050,
"text": "The original string is : geekforgeeks is best for geeks\nThe Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']\n"
},
{
"code": null,
"e": 26196,
"s": 26173,
"text": "Python string-programs"
},
{
"code": null,
"e": 26203,
"s": 26196,
"text": "Python"
},
{
"code": null,
"e": 26219,
"s": 26203,
"text": "Python Programs"
},
{
"code": null,
"e": 26317,
"s": 26219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26326,
"s": 26317,
"text": "Comments"
},
{
"code": null,
"e": 26339,
"s": 26326,
"text": "Old Comments"
},
{
"code": null,
"e": 26371,
"s": 26339,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26427,
"s": 26371,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26469,
"s": 26427,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26511,
"s": 26469,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26547,
"s": 26511,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26569,
"s": 26547,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26608,
"s": 26569,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26654,
"s": 26608,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26692,
"s": 26654,
"text": "Python | Convert a list to dictionary"
}
] |
Ionic - Forms
|
Ionic forms are mostly used for interaction with users and collecting needed info. This chapter will cover various text input forms and in our subsequent chapters, we will explain how to use other form elements using the Ionic framework.
The best way to use forms is to use list and item as your main classes. Your app will usually consist more than one-form element, so it makes sense to organize it as a list. In the following example, you can notice that the item element is a label tag.
You can use any other element, but a label will provide the ability to tap on any part of the element to focus your text input. You can set a placeholder that will look different from the input text and it will be hidden as soon as you start typing. You can see this in the example below.
<div class = "list">
<label class = "item item-input">
<input type = "text" placeholder = "Placeholder 1" />
</label>
<label class = "item item-input">
<input type = "text" placeholder = "Placeholder 2" />
</label>
</div>
The above code will produce the following screen −
Ionic offers some other options for your label. You can use the input-label class, if you want your placeholder to be on the left side when you type the text.
<div class = "list">
<label class = "item item-input">
<input type = "text" placeholder = "Placeholder 1" />
</label>
<label class = "item item-input">
<input type = "text" placeholder = "Placeholder 2" />
</label>
</div>
The above code will produce the following screen −
Stacked label is the other option that allows moving your label on top or the bottom of the input. To achieve this, we will add the item-stacked-label class to our label element and we need to create a new element and assign the input-label class to it. If we want it to be on top, we just need to add this element before the input tag. This is shown in the following example.
Notice that the span tag is before the input tag. If we changed their places, it would appear below it on the screen.
<div class = "list">
<label class = "item item-input item-stacked-label">
<span class = "input-label">Label 1</span>
<input type = "text" placeholder = "Placeholder 1" />
</label>
<label class = "item item-input item-stacked-label">
<span class = "input-label">Label 2</span>
<input type = "text" placeholder = "Placeholder 2" />
</label>
</div>
The above code will produce the following screen −
Floating labels are the third option we can use. These labels will be hidden before we start typing. As soon the typing starts, they will appear on top of the element with nice floating animation. We can use floating labels the same way as we used stacked labels. The only difference is that this time we will use item-floating-label class.
<div class = "list">
<label class = "item item-input item-floating-label">
<span class = "input-label"t>Label 1</span>
<input type = "text" placeholder = "Placeholder 1" />
</label>
<label class = "item item-input item-floating-label">
<span class = "input-label">Label 2</span>
<input type = "text" placeholder = "Placeholder 2" />
</label>
</div>
The above code will produce the following screen −
In our last chapter, we discussed how to inset Ionic elements. You can also inset an input by adding the item-input-inset class to your item and the item-input-wrapper to your label. A Wrapper will add additional styling to your label.
If you add some other elements next to your label, the label size will adjust to accommodate the new element. You can also add elements inside your label (usually icons).
The following example shows two inset inputs. The first one has a button next to the label, and the second one has an icon inside it. We used the placeholder-icon class to make the icon with the same color as the placeholder text. Without it, the icon would use the color of the label.
<div class = "list">
<div class = "item item-input-inset">
<label class = "item item-input-wrapper">
<input type = "text" placeholder = "Placeholder 1" />
</label>
<button class = "button">button</button>
</div>
<div class = "item item-input-inset">
<label class = "item item-input-wrapper">
<i class = "icon ion-edit placeholder-icon"></i>
<input type = "text" placeholder = "Placeholder 2" />
</label>
</div>
</div>
The above code will produce the following screen −
16 Lectures
2.5 hours
Frahaan Hussain
185 Lectures
46.5 hours
Nikhil Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2701,
"s": 2463,
"text": "Ionic forms are mostly used for interaction with users and collecting needed info. This chapter will cover various text input forms and in our subsequent chapters, we will explain how to use other form elements using the Ionic framework."
},
{
"code": null,
"e": 2954,
"s": 2701,
"text": "The best way to use forms is to use list and item as your main classes. Your app will usually consist more than one-form element, so it makes sense to organize it as a list. In the following example, you can notice that the item element is a label tag."
},
{
"code": null,
"e": 3243,
"s": 2954,
"text": "You can use any other element, but a label will provide the ability to tap on any part of the element to focus your text input. You can set a placeholder that will look different from the input text and it will be hidden as soon as you start typing. You can see this in the example below."
},
{
"code": null,
"e": 3490,
"s": 3243,
"text": "<div class = \"list\">\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>"
},
{
"code": null,
"e": 3541,
"s": 3490,
"text": "The above code will produce the following screen −"
},
{
"code": null,
"e": 3700,
"s": 3541,
"text": "Ionic offers some other options for your label. You can use the input-label class, if you want your placeholder to be on the left side when you type the text."
},
{
"code": null,
"e": 3947,
"s": 3700,
"text": "<div class = \"list\">\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>"
},
{
"code": null,
"e": 3998,
"s": 3947,
"text": "The above code will produce the following screen −"
},
{
"code": null,
"e": 4375,
"s": 3998,
"text": "Stacked label is the other option that allows moving your label on top or the bottom of the input. To achieve this, we will add the item-stacked-label class to our label element and we need to create a new element and assign the input-label class to it. If we want it to be on top, we just need to add this element before the input tag. This is shown in the following example."
},
{
"code": null,
"e": 4493,
"s": 4375,
"text": "Notice that the span tag is before the input tag. If we changed their places, it would appear below it on the screen."
},
{
"code": null,
"e": 4876,
"s": 4493,
"text": "<div class = \"list\">\n <label class = \"item item-input item-stacked-label\">\n <span class = \"input-label\">Label 1</span>\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input item-stacked-label\">\n <span class = \"input-label\">Label 2</span>\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>"
},
{
"code": null,
"e": 4927,
"s": 4876,
"text": "The above code will produce the following screen −"
},
{
"code": null,
"e": 5268,
"s": 4927,
"text": "Floating labels are the third option we can use. These labels will be hidden before we start typing. As soon the typing starts, they will appear on top of the element with nice floating animation. We can use floating labels the same way as we used stacked labels. The only difference is that this time we will use item-floating-label class."
},
{
"code": null,
"e": 5654,
"s": 5268,
"text": "<div class = \"list\">\n <label class = \"item item-input item-floating-label\">\n <span class = \"input-label\"t>Label 1</span>\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input item-floating-label\">\n <span class = \"input-label\">Label 2</span>\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>"
},
{
"code": null,
"e": 5705,
"s": 5654,
"text": "The above code will produce the following screen −"
},
{
"code": null,
"e": 5941,
"s": 5705,
"text": "In our last chapter, we discussed how to inset Ionic elements. You can also inset an input by adding the item-input-inset class to your item and the item-input-wrapper to your label. A Wrapper will add additional styling to your label."
},
{
"code": null,
"e": 6112,
"s": 5941,
"text": "If you add some other elements next to your label, the label size will adjust to accommodate the new element. You can also add elements inside your label (usually icons)."
},
{
"code": null,
"e": 6398,
"s": 6112,
"text": "The following example shows two inset inputs. The first one has a button next to the label, and the second one has an icon inside it. We used the placeholder-icon class to make the icon with the same color as the placeholder text. Without it, the icon would use the color of the label."
},
{
"code": null,
"e": 6888,
"s": 6398,
"text": "<div class = \"list\">\n <div class = \"item item-input-inset\">\n <label class = \"item item-input-wrapper\">\t\t\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n <button class = \"button\">button</button>\n </div>\n\n <div class = \"item item-input-inset\">\n <label class = \"item item-input-wrapper\">\n <i class = \"icon ion-edit placeholder-icon\"></i>\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n </div>\n</div>"
},
{
"code": null,
"e": 6939,
"s": 6888,
"text": "The above code will produce the following screen −"
},
{
"code": null,
"e": 6974,
"s": 6939,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6991,
"s": 6974,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7028,
"s": 6991,
"text": "\n 185 Lectures \n 46.5 hours \n"
},
{
"code": null,
"e": 7044,
"s": 7028,
"text": " Nikhil Agarwal"
},
{
"code": null,
"e": 7051,
"s": 7044,
"text": " Print"
},
{
"code": null,
"e": 7062,
"s": 7051,
"text": " Add Notes"
}
] |
Angular 6 - Project Setup
|
AngularJS is based on the model view controller, whereas Angular 4 is based on the components structure. Angular 6 works on the same structure as Angular4 but is faster when compared to Angular4.
Angular6 uses TypeScript 2.9 version whereas Angular 4 uses TypeScript version 2.2. This brings a lot of difference in the performance.
To install Angular 6, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 6.
Go to this site https://cli.angular.io to install Angular CLI.
To get started with the installation, we first need to make sure we have nodejs and npm installed with the latest version. The npm package gets installed along with nodejs.
Go to the nodejs site https://nodejs.org/en/.
The latest version of Nodejs v8.11.3 is recommended for users. Users who already have nodejs greater than 8.11 can skip the above process. Once nodejs is installed, you can check the version of node in the command line using the command, node -v, as shown below −
node -v
v8.11.3
The command prompt shows v8.11.3. Once nodejs is installed, npm will also get installed along with it.
To check the version of npm, type command npm -v in the terminal. It will display the version of npm as shown below.
npm -v
v5.6.0
The version of npm is 5.6.0. Now that we have nodejs and npm installed, let us run the angular cli commands to install Angular 6. You will see the following commands on the webpage −
npm install -g @angular/cli //command to install angular 6
ng new Angular 6-app // name of the project
cd my-dream-app
ng serve
Let us start with the first command in the command line and see how it works.
To start with, we will create an empty directory wherein, we will run the Angular CLI command.
npm install -g @angular/cli //command to install angular 6
We have created an empty folder ProjectA4 and installed the Angular CLI command. We have also used -g to install Angular CLI globally. Now, you can create your Angular 4 project in any directory or folder and you don�t have to install Angular CLI project wise, as it is installed on your system globally and you can make use of it from any directory.
Let us now check whether Angular CLI is installed or not. To check the installation, run the following command in the terminal −
ng -v
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 6.1.3
Node: 8.11.3
OS: win32 x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.7.3
@angular-devkit/core 0.7.3
@angular-devkit/schematics 0.7.3
@schematics/angular 0.7.3
@schematics/update 0.7.3
rxjs 6.2.2
typescript 2.9.2
We get the @angular/cli version, which is at present 6.1.3. The node version running is 8.11.3 and also the OS details. The above details tell us that we have installed angular cli successfully and now we are ready to commence with our project.
We have now installed Angular 6. Let us now create our first project in Angular 6. To create a project in Angular 6, we will use the following command −
ng new projectname
We will name the project ng new Angular6App.
Let us now run the above command in the command line.
ng new Angular6App
CREATE Angular6App/angular.json (3593 bytes)
CREATE Angular6App/package.json (1317 bytes)
CREATE Angular6App/README.md (1028 bytes)
CREATE Angular6App/tsconfig.json (408 bytes)
CREATE Angular6App/tslint.json (2805 bytes)
CREATE Angular6App/.editorconfig (245 bytes)
CREATE Angular6App/.gitignore (503 bytes)
CREATE Angular6App/src/favicon.ico (5430 bytes)
CREATE Angular6App/src/index.html (298 bytes)
CREATE Angular6App/src/main.ts (370 bytes)
CREATE Angular6App/src/polyfills.ts (3194 bytes)
CREATE Angular6App/src/test.ts (642 bytes)
CREATE Angular6App/src/styles.css (80 bytes)
CREATE Angular6App/src/browserslist (375 bytes)
CREATE Angular6App/src/karma.conf.js (964 bytes)
CREATE Angular6App/src/tsconfig.app.json (170 bytes)
CREATE Angular6App/src/tsconfig.spec.json (256 bytes)
CREATE Angular6App/src/tslint.json (314 bytes)
CREATE Angular6App/src/assets/.gitkeep (0 bytes)
CREATE Angular6App/src/environments/environment.prod.ts (51 bytes)
CREATE Angular6App/src/environments/environment.ts (642 bytes)
CREATE Angular6App/src/app/app.module.ts (314 bytes)
CREATE Angular6App/src/app/app.component.html (1141 bytes)
CREATE Angular6App/src/app/app.component.spec.ts (1010 bytes)
CREATE Angular6App/src/app/app.component.ts (215 bytes)
CREATE Angular6App/src/app/app.component.css (0 bytes)
CREATE Angular6App/e2e/protractor.conf.js (752 bytes)
CREATE Angular6App/e2e/tsconfig.e2e.json (213 bytes)
CREATE Angular6App/e2e/src/app.e2e-spec.ts (307 bytes)
CREATE Angular6App/e2e/src/app.po.ts (208 bytes)
The project Angular6App is created successfully. It installs all the required packages necessary for our project to run in Angular 6. Let us now switch to the project created, which is in the directory Angular6App. Change the directory in the command line - cd Angular 6-app.
We will use Visual Studio Code IDE for working with Angular 6; you can use any IDE, i.e., Atom, WebStorm, etc.
To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows.
Click Download for Windows for installing the IDE and run the setup to start using IDE.
The Editor looks as follows −
We have not started any project in it. Let us now take the project we have created using angular-cli.
Now that we have the file structure for our project, let us compile our project with the following command −
ng serve
The ng serve command builds the application and starts the web server.
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
...
Date: 2018-08-18T11:17:54.745Z
Hash: 0ace6c8a055c58d1734c
Time: 20490ms
chunk {main} main.js, main.js.map (main) 10.7 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 227 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 15.6 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.27 MB [initial] [rendered]
i ?wdm?: Compiled successfully.
The web server starts on port 4200. Type the url http://localhost:4200/ in the browser and see the output. You will be directed to the following screen −
Let us now make some changes to display the following content −
"Welcome to Angular 6 project"
We have made changes in the files - app.component.html and app.component.ts. We will discuss more about this in our subsequent chapters.
Let us complete the project setup. If you see we have used port 4200, which is the default port that angular-cli makes use of while compiling. You can change the port if you wish using the following command −
ng serve --host 0.0.0.0 -port 4205
The Angular 6 app folder has the following folder structure −
e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine.
e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine.
node_modules − The npm package installed is node_modules. You can open the folder and see the packages available.
node_modules − The npm package installed is node_modules. You can open the folder and see the packages available.
src − This folder is where we will work on the project using Angular 4.
src − This folder is where we will work on the project using Angular 4.
The Angular 6 app folder has the following file structure −
.angular-cli.json − It basically holds the project name, version of cli, etc.
.angular-cli.json − It basically holds the project name, version of cli, etc.
.editorconfig − This is the config file for the editor.
.editorconfig − This is the config file for the editor.
.gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository.
.gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository.
karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file.
karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file.
package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install.
package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install.
At present, if you open the file in the editor, you will get the following modules added in it.
"@angular/animations": "^6.1.0",
"@angular/common": "^6.1.0",
"@angular/compiler": "^6.1.0",
"@angular/core": "^6.1.0",
"@angular/forms": "^6.1.0",
"@angular/http": "^6.1.0",
"@angular/platform-browser": "^6.1.0",
"@angular/platform-browser-dynamic": "^6.1.0",
"@angular/router": "^6.1.0",
"core-js": "^2.5.4",
"rxjs": "^6.0.0",
"zone.js": "~0.8.26"
In case you need to add more libraries, you can add those over here and run the npm install command.
protractor.conf.js − This is the testing configuration required for the application.
protractor.conf.js − This is the testing configuration required for the application.
tsconfig.json − This basically contains the compiler options required during compilation.
tsconfig.json − This basically contains the compiler options required during compilation.
tslint.json − This is the config file with rules to be considered while compiling.
tslint.json − This is the config file with rules to be considered while compiling.
The src folder is the main folder, which internally has a different file structure.
It contains the files described below. These files are installed by angular-cli by default.
app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import - angular/core, platform-browser. The names itself explain the usage of the libraries.
app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import - angular/core, platform-browser. The names itself explain the usage of the libraries.
They are imported and saved into variables such as declarations, imports, providers, and bootstrap.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
declarations − In declarations, the reference to the components is stored. The Appcomponent is the default component that is created whenever a new project is initiated. We will learn about creating new components in a different section.
imports − This will have the modules imported as shown above. At present, BrowserModule is part of the imports which is imported from @angular/platform-browser.
providers − This will have reference to the services created. The service will be discussed in a subsequent chapter.
bootstrap − This has reference to the default component created, i.e., AppComponent.
app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below.
app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below.
.divdetails{
background-color: #ccc;
}
app.component.html − The html code will be available in this file.
app.component.html − The html code will be available in this file.
<!--The content below is only a placeholder and can be replaced.-->
<div class = "divdetails">
<div style = "text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<img width = "300" src = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNv
ZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3Ry
YXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9
uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0i
TGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4b
Wxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB
4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hY
mxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmV
zZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojR
EQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZ
GRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBva
W50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjM
gMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMi
AJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1L
DUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwy
MzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGN
sYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLj
ctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuM
UwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4b
DE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
<li>
<h2>
<a target = "_blank" href="https://angular.io/tutorial">Tour of Heroes</a>
</h2>
</li>
<li>
<h2>
<a target = "_blank" href = "https://github.com/angular/angular-cli/wiki">
CLI Documentation
</a>
</h2>
</li>
<li>
<h2>
<a target = "_blank" href="http://angularjs.blogspot.ca/">Angular blog</a>
</h2>
</li>
</ul>
</div>
This is the default html code currently available with the project creation.
app.component.spec.ts − These are automatically generated files which contain unit tests for source component.
app.component.spec.ts − These are automatically generated files which contain unit tests for source component.
app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc.
app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc.
The structure of the file is as follows −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
}
You can save your images, js files in this folder.
This folder has the details for the production or the dev environment. The folder contains two files.
environment.prod.ts
environment.ts
Both the files have details of whether the final file should be compiled in the production environment or the dev environment.
The additional file structure of Angular 4 app folder includes the following −
This is a file that is usually found in the root directory of a website.
This is the file which is displayed in the browser.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>HTTP Search Param</title>
<base href = "/">
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
<link href = "https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono" rel = "stylesheet">
<link href = "styles.c7c7b8bf22964ff954d3.bundle.css" rel = "stylesheet">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "icon" type = "image/x-icon" href = "favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
The body has <app-root></app-root>. This is the selector which is used in app.component.ts file and will display the details from app.component.html file.
main.ts is the file from where we start our project development. It starts with importing the basic module which we need. Right now if you see angular/core, angular/platform-browser-dynamic, app.module and environment is imported by default during angular-cli installation and project setup.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
The platformBrowserDynamic().bootstrapModule(AppModule) has the parent module reference AppModule. Hence, when it executes in the browser, the file that is called is index.html. Index.html internally refers to main.ts which calls the parent module, i.e., AppModule when the following code executes −
platformBrowserDynamic().bootstrapModule(AppModule);
When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the boostrap as follows −
bootstrap: [AppComponent]
In app.component.ts, there is a selector: app-root which is used in the index.html file. This will display the contents present in app.component.html.
The following will be displayed in the browser −
This is mainly used for backward compatibility.
This is the style file required for the project.
Here, the unit test cases for testing the project will be handled.
This is used during compilation, it has the config details that need to be used to run the application.
This helps maintain the details for testing.
It is used to manage the TypeScript definition.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2191,
"s": 1995,
"text": "AngularJS is based on the model view controller, whereas Angular 4 is based on the components structure. Angular 6 works on the same structure as Angular4 but is faster when compared to Angular4."
},
{
"code": null,
"e": 2327,
"s": 2191,
"text": "Angular6 uses TypeScript 2.9 version whereas Angular 4 uses TypeScript version 2.2. This brings a lot of difference in the performance."
},
{
"code": null,
"e": 2482,
"s": 2327,
"text": "To install Angular 6, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 6."
},
{
"code": null,
"e": 2545,
"s": 2482,
"text": "Go to this site https://cli.angular.io to install Angular CLI."
},
{
"code": null,
"e": 2718,
"s": 2545,
"text": "To get started with the installation, we first need to make sure we have nodejs and npm installed with the latest version. The npm package gets installed along with nodejs."
},
{
"code": null,
"e": 2764,
"s": 2718,
"text": "Go to the nodejs site https://nodejs.org/en/."
},
{
"code": null,
"e": 3028,
"s": 2764,
"text": "The latest version of Nodejs v8.11.3 is recommended for users. Users who already have nodejs greater than 8.11 can skip the above process. Once nodejs is installed, you can check the version of node in the command line using the command, node -v, as shown below −"
},
{
"code": null,
"e": 3045,
"s": 3028,
"text": "node -v\nv8.11.3\n"
},
{
"code": null,
"e": 3148,
"s": 3045,
"text": "The command prompt shows v8.11.3. Once nodejs is installed, npm will also get installed along with it."
},
{
"code": null,
"e": 3265,
"s": 3148,
"text": "To check the version of npm, type command npm -v in the terminal. It will display the version of npm as shown below."
},
{
"code": null,
"e": 3280,
"s": 3265,
"text": "npm -v\nv5.6.0\n"
},
{
"code": null,
"e": 3463,
"s": 3280,
"text": "The version of npm is 5.6.0. Now that we have nodejs and npm installed, let us run the angular cli commands to install Angular 6. You will see the following commands on the webpage −"
},
{
"code": null,
"e": 3592,
"s": 3463,
"text": "npm install -g @angular/cli //command to install angular 6\nng new Angular 6-app // name of the project\ncd my-dream-app\nng serve\n"
},
{
"code": null,
"e": 3670,
"s": 3592,
"text": "Let us start with the first command in the command line and see how it works."
},
{
"code": null,
"e": 3765,
"s": 3670,
"text": "To start with, we will create an empty directory wherein, we will run the Angular CLI command."
},
{
"code": null,
"e": 3825,
"s": 3765,
"text": "npm install -g @angular/cli //command to install angular 6\n"
},
{
"code": null,
"e": 4176,
"s": 3825,
"text": "We have created an empty folder ProjectA4 and installed the Angular CLI command. We have also used -g to install Angular CLI globally. Now, you can create your Angular 4 project in any directory or folder and you don�t have to install Angular CLI project wise, as it is installed on your system globally and you can make use of it from any directory."
},
{
"code": null,
"e": 4305,
"s": 4176,
"text": "Let us now check whether Angular CLI is installed or not. To check the installation, run the following command in the terminal −"
},
{
"code": null,
"e": 5040,
"s": 4305,
"text": "ng -v\n _ _ ____ _ ___\n / \\ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|\n / ? \\ | '_ \\ / _` | | | | |/ _` | '__| | | | | | |\n / ___ \\| | | | (_| | |_| | | (_| | | | |___| |___ | |\n /_/ \\_\\_| |_|\\__, |\\__,_|_|\\__,_|_| \\____|_____|___|\n |___/\n\n\nAngular CLI: 6.1.3\nNode: 8.11.3\nOS: win32 x64\nAngular:\n...\n\nPackage Version\n------------------------------------------------------\n@angular-devkit/architect 0.7.3\n@angular-devkit/core 0.7.3\n@angular-devkit/schematics 0.7.3\n@schematics/angular 0.7.3\n@schematics/update 0.7.3\nrxjs 6.2.2\ntypescript 2.9.2\n"
},
{
"code": null,
"e": 5285,
"s": 5040,
"text": "We get the @angular/cli version, which is at present 6.1.3. The node version running is 8.11.3 and also the OS details. The above details tell us that we have installed angular cli successfully and now we are ready to commence with our project."
},
{
"code": null,
"e": 5438,
"s": 5285,
"text": "We have now installed Angular 6. Let us now create our first project in Angular 6. To create a project in Angular 6, we will use the following command −"
},
{
"code": null,
"e": 5458,
"s": 5438,
"text": "ng new projectname\n"
},
{
"code": null,
"e": 5503,
"s": 5458,
"text": "We will name the project ng new Angular6App."
},
{
"code": null,
"e": 5557,
"s": 5503,
"text": "Let us now run the above command in the command line."
},
{
"code": null,
"e": 7085,
"s": 5557,
"text": "ng new Angular6App\nCREATE Angular6App/angular.json (3593 bytes)\nCREATE Angular6App/package.json (1317 bytes)\nCREATE Angular6App/README.md (1028 bytes)\nCREATE Angular6App/tsconfig.json (408 bytes)\nCREATE Angular6App/tslint.json (2805 bytes)\nCREATE Angular6App/.editorconfig (245 bytes)\nCREATE Angular6App/.gitignore (503 bytes)\nCREATE Angular6App/src/favicon.ico (5430 bytes)\nCREATE Angular6App/src/index.html (298 bytes)\nCREATE Angular6App/src/main.ts (370 bytes)\nCREATE Angular6App/src/polyfills.ts (3194 bytes)\nCREATE Angular6App/src/test.ts (642 bytes)\nCREATE Angular6App/src/styles.css (80 bytes)\nCREATE Angular6App/src/browserslist (375 bytes)\nCREATE Angular6App/src/karma.conf.js (964 bytes)\nCREATE Angular6App/src/tsconfig.app.json (170 bytes)\nCREATE Angular6App/src/tsconfig.spec.json (256 bytes)\nCREATE Angular6App/src/tslint.json (314 bytes)\nCREATE Angular6App/src/assets/.gitkeep (0 bytes)\nCREATE Angular6App/src/environments/environment.prod.ts (51 bytes)\nCREATE Angular6App/src/environments/environment.ts (642 bytes)\nCREATE Angular6App/src/app/app.module.ts (314 bytes)\nCREATE Angular6App/src/app/app.component.html (1141 bytes)\nCREATE Angular6App/src/app/app.component.spec.ts (1010 bytes)\nCREATE Angular6App/src/app/app.component.ts (215 bytes)\nCREATE Angular6App/src/app/app.component.css (0 bytes)\nCREATE Angular6App/e2e/protractor.conf.js (752 bytes)\nCREATE Angular6App/e2e/tsconfig.e2e.json (213 bytes)\nCREATE Angular6App/e2e/src/app.e2e-spec.ts (307 bytes)\nCREATE Angular6App/e2e/src/app.po.ts (208 bytes)\n"
},
{
"code": null,
"e": 7361,
"s": 7085,
"text": "The project Angular6App is created successfully. It installs all the required packages necessary for our project to run in Angular 6. Let us now switch to the project created, which is in the directory Angular6App. Change the directory in the command line - cd Angular 6-app."
},
{
"code": null,
"e": 7472,
"s": 7361,
"text": "We will use Visual Studio Code IDE for working with Angular 6; you can use any IDE, i.e., Atom, WebStorm, etc."
},
{
"code": null,
"e": 7573,
"s": 7472,
"text": "To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows."
},
{
"code": null,
"e": 7661,
"s": 7573,
"text": "Click Download for Windows for installing the IDE and run the setup to start using IDE."
},
{
"code": null,
"e": 7691,
"s": 7661,
"text": "The Editor looks as follows −"
},
{
"code": null,
"e": 7793,
"s": 7691,
"text": "We have not started any project in it. Let us now take the project we have created using angular-cli."
},
{
"code": null,
"e": 7902,
"s": 7793,
"text": "Now that we have the file structure for our project, let us compile our project with the following command −"
},
{
"code": null,
"e": 7912,
"s": 7902,
"text": "ng serve\n"
},
{
"code": null,
"e": 7983,
"s": 7912,
"text": "The ng serve command builds the application and starts the web server."
},
{
"code": null,
"e": 8601,
"s": 7983,
"text": "** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **\n...\nDate: 2018-08-18T11:17:54.745Z\nHash: 0ace6c8a055c58d1734c\nTime: 20490ms\nchunk {main} main.js, main.js.map (main) 10.7 kB [initial] [rendered]\nchunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 227 kB [initial] [rendered]\nchunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]\nchunk {styles} styles.js, styles.js.map (styles) 15.6 kB [initial] [rendered]\nchunk {vendor} vendor.js, vendor.js.map (vendor) 3.27 MB [initial] [rendered]\ni ?wdm?: Compiled successfully.\n"
},
{
"code": null,
"e": 8755,
"s": 8601,
"text": "The web server starts on port 4200. Type the url http://localhost:4200/ in the browser and see the output. You will be directed to the following screen −"
},
{
"code": null,
"e": 8819,
"s": 8755,
"text": "Let us now make some changes to display the following content −"
},
{
"code": null,
"e": 8850,
"s": 8819,
"text": "\"Welcome to Angular 6 project\""
},
{
"code": null,
"e": 8987,
"s": 8850,
"text": "We have made changes in the files - app.component.html and app.component.ts. We will discuss more about this in our subsequent chapters."
},
{
"code": null,
"e": 9196,
"s": 8987,
"text": "Let us complete the project setup. If you see we have used port 4200, which is the default port that angular-cli makes use of while compiling. You can change the port if you wish using the following command −"
},
{
"code": null,
"e": 9232,
"s": 9196,
"text": "ng serve --host 0.0.0.0 -port 4205\n"
},
{
"code": null,
"e": 9294,
"s": 9232,
"text": "The Angular 6 app folder has the following folder structure −"
},
{
"code": null,
"e": 9412,
"s": 9294,
"text": "e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine."
},
{
"code": null,
"e": 9530,
"s": 9412,
"text": "e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine."
},
{
"code": null,
"e": 9644,
"s": 9530,
"text": "node_modules − The npm package installed is node_modules. You can open the folder and see the packages available."
},
{
"code": null,
"e": 9758,
"s": 9644,
"text": "node_modules − The npm package installed is node_modules. You can open the folder and see the packages available."
},
{
"code": null,
"e": 9830,
"s": 9758,
"text": "src − This folder is where we will work on the project using Angular 4."
},
{
"code": null,
"e": 9902,
"s": 9830,
"text": "src − This folder is where we will work on the project using Angular 4."
},
{
"code": null,
"e": 9962,
"s": 9902,
"text": "The Angular 6 app folder has the following file structure −"
},
{
"code": null,
"e": 10040,
"s": 9962,
"text": ".angular-cli.json − It basically holds the project name, version of cli, etc."
},
{
"code": null,
"e": 10118,
"s": 10040,
"text": ".angular-cli.json − It basically holds the project name, version of cli, etc."
},
{
"code": null,
"e": 10174,
"s": 10118,
"text": ".editorconfig − This is the config file for the editor."
},
{
"code": null,
"e": 10230,
"s": 10174,
"text": ".editorconfig − This is the config file for the editor."
},
{
"code": null,
"e": 10385,
"s": 10230,
"text": ".gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository."
},
{
"code": null,
"e": 10540,
"s": 10385,
"text": ".gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository."
},
{
"code": null,
"e": 10686,
"s": 10540,
"text": "karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file."
},
{
"code": null,
"e": 10832,
"s": 10686,
"text": "karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file."
},
{
"code": null,
"e": 10953,
"s": 10832,
"text": "package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install."
},
{
"code": null,
"e": 11074,
"s": 10953,
"text": "package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install."
},
{
"code": null,
"e": 11170,
"s": 11074,
"text": "At present, if you open the file in the editor, you will get the following modules added in it."
},
{
"code": null,
"e": 11521,
"s": 11170,
"text": "\"@angular/animations\": \"^6.1.0\",\n\"@angular/common\": \"^6.1.0\",\n\"@angular/compiler\": \"^6.1.0\",\n\"@angular/core\": \"^6.1.0\",\n\"@angular/forms\": \"^6.1.0\",\n\"@angular/http\": \"^6.1.0\",\n\"@angular/platform-browser\": \"^6.1.0\",\n\"@angular/platform-browser-dynamic\": \"^6.1.0\",\n\"@angular/router\": \"^6.1.0\",\n\"core-js\": \"^2.5.4\",\n\"rxjs\": \"^6.0.0\",\n\"zone.js\": \"~0.8.26\"\n"
},
{
"code": null,
"e": 11622,
"s": 11521,
"text": "In case you need to add more libraries, you can add those over here and run the npm install command."
},
{
"code": null,
"e": 11707,
"s": 11622,
"text": "protractor.conf.js − This is the testing configuration required for the application."
},
{
"code": null,
"e": 11792,
"s": 11707,
"text": "protractor.conf.js − This is the testing configuration required for the application."
},
{
"code": null,
"e": 11882,
"s": 11792,
"text": "tsconfig.json − This basically contains the compiler options required during compilation."
},
{
"code": null,
"e": 11972,
"s": 11882,
"text": "tsconfig.json − This basically contains the compiler options required during compilation."
},
{
"code": null,
"e": 12055,
"s": 11972,
"text": "tslint.json − This is the config file with rules to be considered while compiling."
},
{
"code": null,
"e": 12138,
"s": 12055,
"text": "tslint.json − This is the config file with rules to be considered while compiling."
},
{
"code": null,
"e": 12222,
"s": 12138,
"text": "The src folder is the main folder, which internally has a different file structure."
},
{
"code": null,
"e": 12314,
"s": 12222,
"text": "It contains the files described below. These files are installed by angular-cli by default."
},
{
"code": null,
"e": 12584,
"s": 12314,
"text": "app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import - angular/core, platform-browser. The names itself explain the usage of the libraries."
},
{
"code": null,
"e": 12854,
"s": 12584,
"text": "app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import - angular/core, platform-browser. The names itself explain the usage of the libraries."
},
{
"code": null,
"e": 12954,
"s": 12854,
"text": "They are imported and saved into variables such as declarations, imports, providers, and bootstrap."
},
{
"code": null,
"e": 13276,
"s": 12954,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 13514,
"s": 13276,
"text": "declarations − In declarations, the reference to the components is stored. The Appcomponent is the default component that is created whenever a new project is initiated. We will learn about creating new components in a different section."
},
{
"code": null,
"e": 13675,
"s": 13514,
"text": "imports − This will have the modules imported as shown above. At present, BrowserModule is part of the imports which is imported from @angular/platform-browser."
},
{
"code": null,
"e": 13792,
"s": 13675,
"text": "providers − This will have reference to the services created. The service will be discussed in a subsequent chapter."
},
{
"code": null,
"e": 13877,
"s": 13792,
"text": "bootstrap − This has reference to the default component created, i.e., AppComponent."
},
{
"code": null,
"e": 14014,
"s": 13877,
"text": "app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below."
},
{
"code": null,
"e": 14151,
"s": 14014,
"text": "app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below."
},
{
"code": null,
"e": 14194,
"s": 14151,
"text": ".divdetails{\n background-color: #ccc;\n}\n"
},
{
"code": null,
"e": 14261,
"s": 14194,
"text": "app.component.html − The html code will be available in this file."
},
{
"code": null,
"e": 14328,
"s": 14261,
"text": "app.component.html − The html code will be available in this file."
},
{
"code": null,
"e": 16521,
"s": 14328,
"text": "<!--The content below is only a placeholder and can be replaced.-->\n<div class = \"divdetails\">\n <div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}!\n </h1>\n <img width = \"300\" src = \"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNv\n ZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3Ry\n YXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9\n uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0i\n TGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4b\n Wxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB\n 4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hY\n mxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmV\n zZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojR\n EQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZ\n GRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBva\n W50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjM\n gMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMi\n AJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1L\n DUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwy\n MzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGN\n sYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLj\n ctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuM\n UwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4b\n DE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=\">\n </div>\n <h2>Here are some links to help you start: </h2>\n <ul>\n <li>\n <h2>\n <a target = \"_blank\" href=\"https://angular.io/tutorial\">Tour of Heroes</a>\n </h2>\n </li>\n <li>\n <h2>\n <a target = \"_blank\" href = \"https://github.com/angular/angular-cli/wiki\">\n CLI Documentation\n </a>\n </h2>\n </li>\n <li>\n <h2>\n <a target = \"_blank\" href=\"http://angularjs.blogspot.ca/\">Angular blog</a>\n </h2>\n </li>\n </ul>\n</div>"
},
{
"code": null,
"e": 16598,
"s": 16521,
"text": "This is the default html code currently available with the project creation."
},
{
"code": null,
"e": 16709,
"s": 16598,
"text": "app.component.spec.ts − These are automatically generated files which contain unit tests for source component."
},
{
"code": null,
"e": 16820,
"s": 16709,
"text": "app.component.spec.ts − These are automatically generated files which contain unit tests for source component."
},
{
"code": null,
"e": 17088,
"s": 16820,
"text": "app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc."
},
{
"code": null,
"e": 17356,
"s": 17088,
"text": "app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc."
},
{
"code": null,
"e": 17398,
"s": 17356,
"text": "The structure of the file is as follows −"
},
{
"code": null,
"e": 17608,
"s": 17398,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'app';\n}"
},
{
"code": null,
"e": 17659,
"s": 17608,
"text": "You can save your images, js files in this folder."
},
{
"code": null,
"e": 17761,
"s": 17659,
"text": "This folder has the details for the production or the dev environment. The folder contains two files."
},
{
"code": null,
"e": 17781,
"s": 17761,
"text": "environment.prod.ts"
},
{
"code": null,
"e": 17796,
"s": 17781,
"text": "environment.ts"
},
{
"code": null,
"e": 17923,
"s": 17796,
"text": "Both the files have details of whether the final file should be compiled in the production environment or the dev environment."
},
{
"code": null,
"e": 18002,
"s": 17923,
"text": "The additional file structure of Angular 4 app folder includes the following −"
},
{
"code": null,
"e": 18075,
"s": 18002,
"text": "This is a file that is usually found in the root directory of a website."
},
{
"code": null,
"e": 18127,
"s": 18075,
"text": "This is the file which is displayed in the browser."
},
{
"code": null,
"e": 18763,
"s": 18127,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>HTTP Search Param</title>\n <base href = \"/\">\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n <link href = \"https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono\" rel = \"stylesheet\">\n <link href = \"styles.c7c7b8bf22964ff954d3.bundle.css\" rel = \"stylesheet\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"icon\" type = \"image/x-icon\" href = \"favicon.ico\">\n </head>\n <body>\n <app-root></app-root>\n </body>\n</html>"
},
{
"code": null,
"e": 18918,
"s": 18763,
"text": "The body has <app-root></app-root>. This is the selector which is used in app.component.ts file and will display the details from app.component.html file."
},
{
"code": null,
"e": 19210,
"s": 18918,
"text": "main.ts is the file from where we start our project development. It starts with importing the basic module which we need. Right now if you see angular/core, angular/platform-browser-dynamic, app.module and environment is imported by default during angular-cli installation and project setup."
},
{
"code": null,
"e": 19544,
"s": 19210,
"text": "import { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\nimport { AppModule } from './app/app.module';\nimport { environment } from './environments/environment';\nif (environment.production) {\n enableProdMode();\n}\nplatformBrowserDynamic().bootstrapModule(AppModule);"
},
{
"code": null,
"e": 19844,
"s": 19544,
"text": "The platformBrowserDynamic().bootstrapModule(AppModule) has the parent module reference AppModule. Hence, when it executes in the browser, the file that is called is index.html. Index.html internally refers to main.ts which calls the parent module, i.e., AppModule when the following code executes −"
},
{
"code": null,
"e": 19898,
"s": 19844,
"text": "platformBrowserDynamic().bootstrapModule(AppModule);\n"
},
{
"code": null,
"e": 20019,
"s": 19898,
"text": "When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the boostrap as follows −"
},
{
"code": null,
"e": 20046,
"s": 20019,
"text": "bootstrap: [AppComponent]\n"
},
{
"code": null,
"e": 20197,
"s": 20046,
"text": "In app.component.ts, there is a selector: app-root which is used in the index.html file. This will display the contents present in app.component.html."
},
{
"code": null,
"e": 20246,
"s": 20197,
"text": "The following will be displayed in the browser −"
},
{
"code": null,
"e": 20294,
"s": 20246,
"text": "This is mainly used for backward compatibility."
},
{
"code": null,
"e": 20343,
"s": 20294,
"text": "This is the style file required for the project."
},
{
"code": null,
"e": 20410,
"s": 20343,
"text": "Here, the unit test cases for testing the project will be handled."
},
{
"code": null,
"e": 20514,
"s": 20410,
"text": "This is used during compilation, it has the config details that need to be used to run the application."
},
{
"code": null,
"e": 20559,
"s": 20514,
"text": "This helps maintain the details for testing."
},
{
"code": null,
"e": 20607,
"s": 20559,
"text": "It is used to manage the TypeScript definition."
},
{
"code": null,
"e": 20642,
"s": 20607,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 20656,
"s": 20642,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 20691,
"s": 20656,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 20705,
"s": 20691,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 20740,
"s": 20705,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 20760,
"s": 20740,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 20795,
"s": 20760,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 20812,
"s": 20795,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 20845,
"s": 20812,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 20857,
"s": 20845,
"text": " Senol Atac"
},
{
"code": null,
"e": 20892,
"s": 20857,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 20904,
"s": 20892,
"text": " Senol Atac"
},
{
"code": null,
"e": 20911,
"s": 20904,
"text": " Print"
},
{
"code": null,
"e": 20922,
"s": 20911,
"text": " Add Notes"
}
] |
Sum of Exponential Random Variables | by Aerin Kim | Towards Data Science
|
X1 and X2 are independent exponential random variables with the rate λ.
X1~EXP(λ)X2~EXP(λ)
Let Y=X1+X2.
Question : What is the PDF of Y? Where do we use the distribution of Y?
👉 We find the CDF and differentiate it. (We have already used this technique many times in previous posts.)
Ok, then let’s find the CDF of (X1 + X2).
But we don’t know the PDF of (X1+X2). In fact, that’s the very thing we want to calculate.
Ummm... can we say...
∫ PDF(X1+ X2) = ∫ PDF(X1) + ∫ PDF(X2) ???!?!?
No, of course not.
If you do that, the PDF of (X1+X2) will sum to 2. (The integral of any PDF should always sum to 1.)
How do I find a CDF of any distribution, without knowing the PDF?
There are two main tricks used in the above CDF derivation.One is marginalizing X1 out (so that we can integrate it over x1) and the other is utilizing the definition of independence, which is P(X1+X2 ≤ x|X1) = P(X1+X2 ≤ x). These tricks simplify the derivation and reach the result in terms of x.
These are mathematical conventions. X is stochastic and x is deterministic. For example, let’s say X is the number we get from a die roll. So X can take any number in {1,2,3,4,5,6}. But once we roll the die, the value of X is determined. The notation X = x means that the random variable X takes the particular value x.
X is a random variable and capital letters are used.
x is a certain (fixed) value that the random variable can take. For example, x1, x2, ..., xn could be a sample corresponding to the random variable X.
Therefore, a cumulative probability P(X ≤ x) means the probability that the range of the function X is less than a certain value x. x can be any scalar, e.g., X ≤ 1, X ≤ 2.5, X ≤ 888, etc.
A tilde (~) means “has the probability distribution of,” e.g., X1~EXP(λ).
This is an Erlang (2, λ) distribution.
In the Poisson Process with rate λ, X1+X2 would represent the time at which the 2nd event happens.
In our blog clapping 👏 example, if you get claps at a rate of λ per unit time, the time you wait until you see your first clapping fan is distributed exponentially with the rate λ.
If you wait for other fans to clap for many more units of time, then you could see 0, 1, 2, ... fans.
An Erlang distribution is then used to answer the question:
“How long do I have to wait before I see n fans applauding for me?”
The answer is a sum of independent exponentially distributed random variables, which is an Erlang(n, λ) distribution. The Erlang distribution is a special case of the Gamma distribution. The difference between Erlang and Gamma is that in a Gamma distribution, n can be a non-integer.
a) What distribution is equivalent to Erlang(1, λ)?
Easy. Exponential.
b) [Queuing Theory] You went to Chipotle and joined a line with two people ahead of you. One is being served and the other is waiting. Their service times S1 and S2 are independent, exponential random variables with mean of 2 minutes. (Thus the mean service rate is .5/minute. If this “rate vs. time” concept confuses you, read this to clarify.)
Your conditional time in the queue is T = S1 + S2, given the system state N = 2.T is Erlang distributed.
What is the probability that you wait more than 5 minutes in the queue?
Let’s plug λ = 0.5 into the CDF that we have already derived.
A less-than-30% chance that I’ll wait for more than 5 minutes at Chipotle sounds good to me!
Dr. Bognar at the University of Iowa built this Erlang (Gamma) distribution calculator, which I found useful and beautiful:
|
[
{
"code": null,
"e": 244,
"s": 172,
"text": "X1 and X2 are independent exponential random variables with the rate λ."
},
{
"code": null,
"e": 263,
"s": 244,
"text": "X1~EXP(λ)X2~EXP(λ)"
},
{
"code": null,
"e": 276,
"s": 263,
"text": "Let Y=X1+X2."
},
{
"code": null,
"e": 348,
"s": 276,
"text": "Question : What is the PDF of Y? Where do we use the distribution of Y?"
},
{
"code": null,
"e": 456,
"s": 348,
"text": "👉 We find the CDF and differentiate it. (We have already used this technique many times in previous posts.)"
},
{
"code": null,
"e": 498,
"s": 456,
"text": "Ok, then let’s find the CDF of (X1 + X2)."
},
{
"code": null,
"e": 589,
"s": 498,
"text": "But we don’t know the PDF of (X1+X2). In fact, that’s the very thing we want to calculate."
},
{
"code": null,
"e": 611,
"s": 589,
"text": "Ummm... can we say..."
},
{
"code": null,
"e": 657,
"s": 611,
"text": "∫ PDF(X1+ X2) = ∫ PDF(X1) + ∫ PDF(X2) ???!?!?"
},
{
"code": null,
"e": 676,
"s": 657,
"text": "No, of course not."
},
{
"code": null,
"e": 776,
"s": 676,
"text": "If you do that, the PDF of (X1+X2) will sum to 2. (The integral of any PDF should always sum to 1.)"
},
{
"code": null,
"e": 842,
"s": 776,
"text": "How do I find a CDF of any distribution, without knowing the PDF?"
},
{
"code": null,
"e": 1140,
"s": 842,
"text": "There are two main tricks used in the above CDF derivation.One is marginalizing X1 out (so that we can integrate it over x1) and the other is utilizing the definition of independence, which is P(X1+X2 ≤ x|X1) = P(X1+X2 ≤ x). These tricks simplify the derivation and reach the result in terms of x."
},
{
"code": null,
"e": 1460,
"s": 1140,
"text": "These are mathematical conventions. X is stochastic and x is deterministic. For example, let’s say X is the number we get from a die roll. So X can take any number in {1,2,3,4,5,6}. But once we roll the die, the value of X is determined. The notation X = x means that the random variable X takes the particular value x."
},
{
"code": null,
"e": 1513,
"s": 1460,
"text": "X is a random variable and capital letters are used."
},
{
"code": null,
"e": 1664,
"s": 1513,
"text": "x is a certain (fixed) value that the random variable can take. For example, x1, x2, ..., xn could be a sample corresponding to the random variable X."
},
{
"code": null,
"e": 1853,
"s": 1664,
"text": "Therefore, a cumulative probability P(X ≤ x) means the probability that the range of the function X is less than a certain value x. x can be any scalar, e.g., X ≤ 1, X ≤ 2.5, X ≤ 888, etc."
},
{
"code": null,
"e": 1927,
"s": 1853,
"text": "A tilde (~) means “has the probability distribution of,” e.g., X1~EXP(λ)."
},
{
"code": null,
"e": 1966,
"s": 1927,
"text": "This is an Erlang (2, λ) distribution."
},
{
"code": null,
"e": 2065,
"s": 1966,
"text": "In the Poisson Process with rate λ, X1+X2 would represent the time at which the 2nd event happens."
},
{
"code": null,
"e": 2246,
"s": 2065,
"text": "In our blog clapping 👏 example, if you get claps at a rate of λ per unit time, the time you wait until you see your first clapping fan is distributed exponentially with the rate λ."
},
{
"code": null,
"e": 2348,
"s": 2246,
"text": "If you wait for other fans to clap for many more units of time, then you could see 0, 1, 2, ... fans."
},
{
"code": null,
"e": 2408,
"s": 2348,
"text": "An Erlang distribution is then used to answer the question:"
},
{
"code": null,
"e": 2476,
"s": 2408,
"text": "“How long do I have to wait before I see n fans applauding for me?”"
},
{
"code": null,
"e": 2760,
"s": 2476,
"text": "The answer is a sum of independent exponentially distributed random variables, which is an Erlang(n, λ) distribution. The Erlang distribution is a special case of the Gamma distribution. The difference between Erlang and Gamma is that in a Gamma distribution, n can be a non-integer."
},
{
"code": null,
"e": 2812,
"s": 2760,
"text": "a) What distribution is equivalent to Erlang(1, λ)?"
},
{
"code": null,
"e": 2831,
"s": 2812,
"text": "Easy. Exponential."
},
{
"code": null,
"e": 3177,
"s": 2831,
"text": "b) [Queuing Theory] You went to Chipotle and joined a line with two people ahead of you. One is being served and the other is waiting. Their service times S1 and S2 are independent, exponential random variables with mean of 2 minutes. (Thus the mean service rate is .5/minute. If this “rate vs. time” concept confuses you, read this to clarify.)"
},
{
"code": null,
"e": 3282,
"s": 3177,
"text": "Your conditional time in the queue is T = S1 + S2, given the system state N = 2.T is Erlang distributed."
},
{
"code": null,
"e": 3354,
"s": 3282,
"text": "What is the probability that you wait more than 5 minutes in the queue?"
},
{
"code": null,
"e": 3416,
"s": 3354,
"text": "Let’s plug λ = 0.5 into the CDF that we have already derived."
},
{
"code": null,
"e": 3509,
"s": 3416,
"text": "A less-than-30% chance that I’ll wait for more than 5 minutes at Chipotle sounds good to me!"
}
] |
Python - Legendre polynomials using Recursion relation - GeeksforGeeks
|
11 Dec, 2019
Legendre polynomials are a type of orthogonal polynomials which occur often in science and engineering. Hence, their generation is crucial to those fields. There are different ways to evaluate a Legendre polynomial, using generating functions, Rodrigues formula, recurrence relation, Gram-Schmidt orthogonalization etc. One of the easiest and alsoone of the most accurate, method is using recurrence relation.
Here we use Bonnet’s recurrence relation of legendre polynomials, i.e, –
It can be implemented using Python by proceeding as follows-
We define Legendre polynomials as a function named P(n, x), where n is called the order of the polynomial and x is the point of evaluation. The base cases are if n is 0, then The value of the polynomial is always 1, and it is x when order is 1. These are the seed values required for the recurrence relation.For other values of n, the function is recursively defined, directly from the Bonnet’s recurrence. Thus, P(n, x) returns values of the Legendre polynomial, by recursion method (A function effectively defined with other base cases of the same function itself.)
Below is the Python implementation –
# Legendre polynomialdef P(n, x): if(n == 0): return 1 # P0 = 1 elif(n == 1): return x # P1 = x else: return (((2 * n)-1)*x * P(n-1, x)-(n-1)*P(n-2, x))/float(n) # Suppose, we want to find the value of # 3rd order legendre polynomial at x = 5# We can display the value by-- # Driver programn = 3X = 5print("The value of the polynomial at given point is:", P(n, X))
The value of the polynomial at given point is: 305.0
We can now also plot the Legendre polynomials (say from 1st order to 4th order) using matplotlib.
import matplotlib # This is for use in webbrowser, can be ignored.matplotlib.use('Agg') import matplotlib.pyplot as pltimport numpy as np # Creating an array of x valuesx = np.linspace(-1, 1, 200) # for which polynomial values are evaluated and plottedfor i in range(1, 5): # Labelling according to order plt.plot(x, P(i, x), label ="P"+str(i)) plt.legend(loc ="best")plt.xlabel("X")plt.ylabel("Pn")plt.show()
Engineering Mathematics
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Activation Functions
Difference between Propositional Logic and Predicate Logic
Proof that vertex cover is NP complete
Mathematics | Matrix Introduction
Logic Notations in LaTeX
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24501,
"s": 24473,
"text": "\n11 Dec, 2019"
},
{
"code": null,
"e": 24911,
"s": 24501,
"text": "Legendre polynomials are a type of orthogonal polynomials which occur often in science and engineering. Hence, their generation is crucial to those fields. There are different ways to evaluate a Legendre polynomial, using generating functions, Rodrigues formula, recurrence relation, Gram-Schmidt orthogonalization etc. One of the easiest and alsoone of the most accurate, method is using recurrence relation."
},
{
"code": null,
"e": 24984,
"s": 24911,
"text": "Here we use Bonnet’s recurrence relation of legendre polynomials, i.e, –"
},
{
"code": null,
"e": 25050,
"s": 24989,
"text": "It can be implemented using Python by proceeding as follows-"
},
{
"code": null,
"e": 25618,
"s": 25050,
"text": "We define Legendre polynomials as a function named P(n, x), where n is called the order of the polynomial and x is the point of evaluation. The base cases are if n is 0, then The value of the polynomial is always 1, and it is x when order is 1. These are the seed values required for the recurrence relation.For other values of n, the function is recursively defined, directly from the Bonnet’s recurrence. Thus, P(n, x) returns values of the Legendre polynomial, by recursion method (A function effectively defined with other base cases of the same function itself.)"
},
{
"code": null,
"e": 25655,
"s": 25618,
"text": "Below is the Python implementation –"
},
{
"code": "# Legendre polynomialdef P(n, x): if(n == 0): return 1 # P0 = 1 elif(n == 1): return x # P1 = x else: return (((2 * n)-1)*x * P(n-1, x)-(n-1)*P(n-2, x))/float(n) # Suppose, we want to find the value of # 3rd order legendre polynomial at x = 5# We can display the value by-- # Driver programn = 3X = 5print(\"The value of the polynomial at given point is:\", P(n, X))",
"e": 26053,
"s": 25655,
"text": null
},
{
"code": null,
"e": 26107,
"s": 26053,
"text": "The value of the polynomial at given point is: 305.0\n"
},
{
"code": null,
"e": 26205,
"s": 26107,
"text": "We can now also plot the Legendre polynomials (say from 1st order to 4th order) using matplotlib."
},
{
"code": "import matplotlib # This is for use in webbrowser, can be ignored.matplotlib.use('Agg') import matplotlib.pyplot as pltimport numpy as np # Creating an array of x valuesx = np.linspace(-1, 1, 200) # for which polynomial values are evaluated and plottedfor i in range(1, 5): # Labelling according to order plt.plot(x, P(i, x), label =\"P\"+str(i)) plt.legend(loc =\"best\")plt.xlabel(\"X\")plt.ylabel(\"Pn\")plt.show()",
"e": 26631,
"s": 26205,
"text": null
},
{
"code": null,
"e": 26655,
"s": 26631,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 26662,
"s": 26655,
"text": "Python"
},
{
"code": null,
"e": 26678,
"s": 26662,
"text": "Python Programs"
},
{
"code": null,
"e": 26776,
"s": 26678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26785,
"s": 26776,
"text": "Comments"
},
{
"code": null,
"e": 26798,
"s": 26785,
"text": "Old Comments"
},
{
"code": null,
"e": 26819,
"s": 26798,
"text": "Activation Functions"
},
{
"code": null,
"e": 26878,
"s": 26819,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 26917,
"s": 26878,
"text": "Proof that vertex cover is NP complete"
},
{
"code": null,
"e": 26951,
"s": 26917,
"text": "Mathematics | Matrix Introduction"
},
{
"code": null,
"e": 26976,
"s": 26951,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 27004,
"s": 26976,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27054,
"s": 27004,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27076,
"s": 27054,
"text": "Python map() function"
}
] |
HTML5 - Attributes
|
As explained in the previous chapter, elements may contain attributes that are used to set various properties of an element.
Some attributes are defined globally and can be used on any element, while others are defined for specific elements only. All attributes have a name and a value and look like as shown below in the example.
Following is the example of an HTML5 attributes which illustrates how to mark up a div element with an attribute named class using a value of "example" −
<div class = "example">...</div>
Attributes may only be specified within start tags and must never be used in end tags.
HTML5 attributes are case insensitive and may be written in all uppercase or mixed case, although the most common convention is to stick with lowercase.
The attributes listed below are supported by almost all the HTML 5 tags.
For a complete list of HTML5 Tags and related attributes, please check our reference to HTML5 Tags.
A new feature being introduced in HTML 5 is the addition of custom data attributes.
A custom data attribute starts with data- and would be named based on your requirement. Here is a simple example −
<div class = "example" data-subject = "physics" data-level = "complex">
...
</div>
The above code will be perfectly valid HTML5 with two custom attributes called datasubject and data-level. You would be able to get the values of these attributes using JavaScript APIs or CSS in similar way as you get for standard attributes.
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2733,
"s": 2608,
"text": "As explained in the previous chapter, elements may contain attributes that are used to set various properties of an element."
},
{
"code": null,
"e": 2939,
"s": 2733,
"text": "Some attributes are defined globally and can be used on any element, while others are defined for specific elements only. All attributes have a name and a value and look like as shown below in the example."
},
{
"code": null,
"e": 3093,
"s": 2939,
"text": "Following is the example of an HTML5 attributes which illustrates how to mark up a div element with an attribute named class using a value of \"example\" −"
},
{
"code": null,
"e": 3127,
"s": 3093,
"text": "<div class = \"example\">...</div>\n"
},
{
"code": null,
"e": 3214,
"s": 3127,
"text": "Attributes may only be specified within start tags and must never be used in end tags."
},
{
"code": null,
"e": 3367,
"s": 3214,
"text": "HTML5 attributes are case insensitive and may be written in all uppercase or mixed case, although the most common convention is to stick with lowercase."
},
{
"code": null,
"e": 3440,
"s": 3367,
"text": "The attributes listed below are supported by almost all the HTML 5 tags."
},
{
"code": null,
"e": 3540,
"s": 3440,
"text": "For a complete list of HTML5 Tags and related attributes, please check our reference to HTML5 Tags."
},
{
"code": null,
"e": 3624,
"s": 3540,
"text": "A new feature being introduced in HTML 5 is the addition of custom data attributes."
},
{
"code": null,
"e": 3739,
"s": 3624,
"text": "A custom data attribute starts with data- and would be named based on your requirement. Here is a simple example −"
},
{
"code": null,
"e": 3825,
"s": 3739,
"text": "<div class = \"example\" data-subject = \"physics\" data-level = \"complex\">\n ...\n</div>"
},
{
"code": null,
"e": 4068,
"s": 3825,
"text": "The above code will be perfectly valid HTML5 with two custom attributes called datasubject and data-level. You would be able to get the values of these attributes using JavaScript APIs or CSS in similar way as you get for standard attributes."
},
{
"code": null,
"e": 4101,
"s": 4068,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4115,
"s": 4101,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4150,
"s": 4115,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4164,
"s": 4150,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4199,
"s": 4164,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4216,
"s": 4199,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4251,
"s": 4216,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4282,
"s": 4251,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4315,
"s": 4282,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4346,
"s": 4315,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4381,
"s": 4346,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4412,
"s": 4381,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4419,
"s": 4412,
"text": " Print"
},
{
"code": null,
"e": 4430,
"s": 4419,
"text": " Add Notes"
}
] |
Spark MLlib Python Example — Machine Learning At Scale | by Cory Maklin | Towards Data Science
|
For most of their history, computer processors became faster every year. Unfortunately, this trend in hardware stopped around 2005. Due to limits in heat dissipation, hardware developers stopped increasing the clock frequency of individual processors and opted for parallel CPU cores. This is fine for playing video games on a desktop computer. However, when it involves processing petabytes of data, we have to go a step further and pool the processing power from multiple computers together in order to complete tasks in any reasonable amount of time. The need for horizontal scaling led to the Apache Hadoop project. Apache Hadoop provides a way of breaking up a given task, concurrently executing it across multiple nodes inside of a cluster and aggregating the result.
Apache Spark began at UC Berkeley AMPlab in 2009. At the time, Hadoop MapReduce was the dominant parallel programming engine for clusters. The AMPlab created Apache Spark to address some of the drawbacks to using Apache Hadoop. One of the most notable limitations of Apache Hadoop is the fact that it writes intermediate results to disk. In contrast, Spark keeps everything in memory and in consequence tends to be much faster. In 2013, the project had grown to widespread use, with more than 100 contributors from more than 30 organizations outside UC Berkeley. The AMPlab contributed Spark to the Apache Software Foundation. The early AMPlab team also launched a company, Databricks, to improve the project.
Although Python libraries such as scikit-learn are great for Kaggle competitions and the like, they are rarely used, if ever, at scale. In my own personal experience, I’ve run in to situations where I could only load a portion of the data since it would otherwise fill my computer’s RAM up completely and crash the program. Spark has the ability to perform machine learning at scale with a built-in library called MLlib. The MLlib API, although not as inclusive as scikit-learn, can be used for classification, regression and clustering problems. In the proceeding article, we’ll train a machine learning model using the traditional scikit-learn/pandas stack and then repeat the process using Spark.
import pandas as pd
In the proceeding example, we’ll attempt to predict whether an adult’s income exceeds $50K/year based on census data. The data can be downloaded from the UC Irvine Machine Learning Repository.
The dataset we’re working with contains 14 features and 1 label. A header isn’t included in the csv file by default, therefore, we must define the column names ourselves.
column_names = [ 'age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'salary']train_df = pd.read_csv('adult.data', names=column_names)test_df = pd.read_csv('adult.test', names=column_names)
You’ll notice that every feature is separated by a comma and a space. Although Pandas can handle this under the hood, Spark cannot. Therefore, we remove the spaces. In addition, we remove any rows with a native country of Holand-Neitherlands from our training set because there aren’t any instances in our testing set and it will cause issues when we go to encode our categorical variables. We save the resulting dataframe to a csv file so that we can use it at a later point.
train_df = train_df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)train_df_cp = train_df.copy()train_df_cp = train_df_cp.loc[train_df_cp['native-country'] != 'Holand-Netherlands']train_df_cp.to_csv('train.csv', index=False, header=False)test_df = test_df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)test_df.to_csv('test.csv', index=False, header=False)
Next, let’s take a look to see what we’re working with. The training set contains a little over 30 thousand rows.
print('Training data shape: ', train_df.shape)train_df.head()
On the other hand, the testing set contains a little over 15 thousand rows.
print('Testing data shape: ', test_df.shape)test_df.head()
Often times, we’ll have to handle missing data prior to training our model. The following line returns the number of missing values for each feature. Fortunately, the dataset is complete.
train_df.isnull().sum()
Categorical variables will have a type of object. Categorical variables must be encoded in order to be interpreted by machine learning models (other than decision trees).
train_df.dtypes.value_counts()
The following code prints the distinct number of categories for each categorical variable.
train_df.select_dtypes('object').apply(pd.Series.nunique, axis=0)
test_df.select_dtypes('object').apply(pd.Series.nunique, axis=0)
We manually encode salary to avoid having it create two columns when we perform one hot encoding. After transforming our data, every string is replaced with an array of 1s and 0s where the location of the 1 corresponds to a given category.
train_df['salary'] = train_df['salary'].apply(lambda x: 0 if x == ' <=50K' else 1)test_df['salary'] = test_df['salary'].apply(lambda x: 0 if x == ' <=50K' else 1)train_df = pd.get_dummies(train_df)test_df = pd.get_dummies(test_df)print('Training Features shape: ', train_df.shape)print('Testing Features shape: ', test_df.shape)
There is a discrepancy between the distinct number of native-country categories in the testing and training sets (the testing set doesn’t have a person whose native country is Holand). As a result, when we applied one hot encoding, we ended up with a different number of features. Before we can use logistic regression, we must ensure that the number of features in our training and testing sets match. We can do so by performing an inner join.
# Align the training and testing data, keep only columns present in both dataframestrain_df, test_df = train_df.align(test_df, join = 'inner', axis = 1)print('Training Features shape: ', train_df.shape)print('Testing Features shape: ', test_df.shape)
train_df.head()
Next, we break up the dataframes into dependent and independent variables.
X_train = train_df.drop('salary', axis=1)y_train = train_df['salary']X_test = test_df.drop('salary', axis=1)y_test = test_df['salary']
We don’t need to scale variables for normal logistic regression as long as we keep units in mind when interpreting the coefficients. However, by default, the scikit-learn implementation of logistic regression uses L2 regularization. L2 regularization penalizes large values of all parameters equally. Hence, a feature for height in metres would be penalized much more than another feature in millimetres. Therefore, we scale our data, prior to sending it through our model.
from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler(feature_range = (0, 1))scaler.fit(X_train)X_train = scaler.transform(X_train)X_test = scaler.transform(X_test)
Finally, we can train our model and measure its performance on the testing set.
from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train, y_train)lr_pred = lr.predict(X_test)from sklearn.metrics import accuracy_scoreaccuracy_score(y_test, lr_pred)
Let’s see how we could go about accomplishing the same thing using Spark. Depending on your preference, you can write Spark code in Java, Scala or Python. Given that most data scientist are used to working with Python, we’ll use that.
All of the code in the proceeding section will be running on our local machine. However, if we were to setup a Spark clusters with multiple nodes, the operations would run concurrently on every computer inside the cluster without any modifications to the code.
The easiest way to start using Spark is to use the Docker container provided by Jupyter. For simplicity, we create a docker-compose.yml file with the following content. Make sure to modify the path to match the directory that contains the data downloaded from the UCI Machine Learning Repository.
version: '2'services: spark: image: jupyter/pyspark-notebook:latest ports: - 8888:8888 volumes: - /home/cory/kaggle/adult:/home/jovyan/work
Then, run the proceeding command.
docker-compose up
To access the Jupyter Notebook, open a browser and go to localhost:8888.
Go ahead and import the following libraries.
from pyspark import SparkConf, SparkContextfrom pyspark.sql import SparkSessionfrom pyspark.ml.classification import LogisticRegressionfrom pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer, VectorAssemblerfrom pyspark.ml import Pipelinefrom pyspark.sql.types import StructType, StructField, IntegerType, StringType
Prior, to doing anything else, we need to initialize a Spark session.
spark = SparkSession.builder.appName("Predict Adult Salary").getOrCreate()
Just like before, we define the column names which we’ll use when reading in the data.
schema = StructType([ StructField("age", IntegerType(), True), StructField("workclass", StringType(), True), StructField("fnlwgt", IntegerType(), True), StructField("education", StringType(), True), StructField("education-num", IntegerType(), True), StructField("marital-status", StringType(), True), StructField("occupation", StringType(), True), StructField("relationship", StringType(), True), StructField("race", StringType(), True), StructField("sex", StringType(), True), StructField("capital-gain", IntegerType(), True), StructField("capital-loss", IntegerType(), True), StructField("hours-per-week", IntegerType(), True), StructField("native-country", StringType(), True), StructField("salary", StringType(), True)])
Like Pandas, Spark provides an API for loading the contents of a csv file into our program. We use the files that we created in the beginning.
train_df = spark.read.csv('train.csv', header=False, schema=schema)test_df = spark.read.csv('test.csv', header=False, schema=schema)
We can run the following line to view the first 5 rows.
train_df.head(5)
If, for whatever reason, you’d like to convert the Spark dataframe into a Pandas dataframe, you can do so. Personally, I find the output cleaner and easier to read.
train_df.limit(5).toPandas()
There are a couple of important dinstinction between Spark and Scikit-learn/Pandas which must be understood before moving forward.
Spark DataFrames are immutable. Thus, whenever we want to apply transformations, we must do so by creating new columns.
MLlib expects all features to be contained within a single column.
The proceeding code block is where we apply all of the necessary transformations to the categorical variables.
The StringIndexer class performs label encoding and must be applied before the OneHotEncoderEstimator which in turn performs one hot encoding. The VectorAssembler class takes multiple columns as input and outputs a single column whose contents is an array containing the values for all of the input columns.
categorical_variables = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country']indexers = [StringIndexer(inputCol=column, outputCol=column+"-index") for column in categorical_variables]encoder = OneHotEncoderEstimator( inputCols=[indexer.getOutputCol() for indexer in indexers], outputCols=["{0}-encoded".format(indexer.getOutputCol()) for indexer in indexers])assembler = VectorAssembler( inputCols=encoder.getOutputCols(), outputCol="categorical-features")pipeline = Pipeline(stages=indexers + [encoder, assembler])train_df = pipeline.fit(train_df).transform(train_df)test_df = pipeline.fit(test_df).transform(test_df)
Let’s view all the different columns that were created in the previous step.
train_df.printSchema()
After applying the transformations, we end up with a single column that contains an array with every encoded categorical variable.
df = train_df.limit(5).toPandas()df['scaled-categorical-features'][1]
We combine our continuous variables with our categorical variables into a single column.
continuous_variables = ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']assembler = VectorAssembler( inputCols=['categorical-features', *continuous_variables], outputCol='features')train_df = assembler.transform(train_df)test_df = assembler.transform(test_df)
Let’s take a look at the final column which we’ll use to train our model. As you can see it outputs a SparseVector. To save space, sparse vectors do not contain the 0s from one hot encoding.
train_df.limit(5).toPandas()['features'][0]
Finally, we encode our target label.
indexer = StringIndexer(inputCol='salary', outputCol='label')train_df = indexer.fit(train_df).transform(train_df)test_df = indexer.fit(test_df).transform(test_df)train_df.limit(10).toPandas()['label']
We fit and train our model.
lr = LogisticRegression(featuresCol='features', labelCol='label')model = lr.fit(train_df)
The transform method is used to make predictions for the testing set.
pred = model.transform(test_df)pred.limit(10).toPandas()[['label', 'prediction']]
Spark is a distributed computing platform which can be used to perform operations on dataframes and train machine learning models at scale.
|
[
{
"code": null,
"e": 946,
"s": 172,
"text": "For most of their history, computer processors became faster every year. Unfortunately, this trend in hardware stopped around 2005. Due to limits in heat dissipation, hardware developers stopped increasing the clock frequency of individual processors and opted for parallel CPU cores. This is fine for playing video games on a desktop computer. However, when it involves processing petabytes of data, we have to go a step further and pool the processing power from multiple computers together in order to complete tasks in any reasonable amount of time. The need for horizontal scaling led to the Apache Hadoop project. Apache Hadoop provides a way of breaking up a given task, concurrently executing it across multiple nodes inside of a cluster and aggregating the result."
},
{
"code": null,
"e": 1656,
"s": 946,
"text": "Apache Spark began at UC Berkeley AMPlab in 2009. At the time, Hadoop MapReduce was the dominant parallel programming engine for clusters. The AMPlab created Apache Spark to address some of the drawbacks to using Apache Hadoop. One of the most notable limitations of Apache Hadoop is the fact that it writes intermediate results to disk. In contrast, Spark keeps everything in memory and in consequence tends to be much faster. In 2013, the project had grown to widespread use, with more than 100 contributors from more than 30 organizations outside UC Berkeley. The AMPlab contributed Spark to the Apache Software Foundation. The early AMPlab team also launched a company, Databricks, to improve the project."
},
{
"code": null,
"e": 2356,
"s": 1656,
"text": "Although Python libraries such as scikit-learn are great for Kaggle competitions and the like, they are rarely used, if ever, at scale. In my own personal experience, I’ve run in to situations where I could only load a portion of the data since it would otherwise fill my computer’s RAM up completely and crash the program. Spark has the ability to perform machine learning at scale with a built-in library called MLlib. The MLlib API, although not as inclusive as scikit-learn, can be used for classification, regression and clustering problems. In the proceeding article, we’ll train a machine learning model using the traditional scikit-learn/pandas stack and then repeat the process using Spark."
},
{
"code": null,
"e": 2376,
"s": 2356,
"text": "import pandas as pd"
},
{
"code": null,
"e": 2569,
"s": 2376,
"text": "In the proceeding example, we’ll attempt to predict whether an adult’s income exceeds $50K/year based on census data. The data can be downloaded from the UC Irvine Machine Learning Repository."
},
{
"code": null,
"e": 2740,
"s": 2569,
"text": "The dataset we’re working with contains 14 features and 1 label. A header isn’t included in the csv file by default, therefore, we must define the column names ourselves."
},
{
"code": null,
"e": 3114,
"s": 2740,
"text": "column_names = [ 'age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'salary']train_df = pd.read_csv('adult.data', names=column_names)test_df = pd.read_csv('adult.test', names=column_names)"
},
{
"code": null,
"e": 3591,
"s": 3114,
"text": "You’ll notice that every feature is separated by a comma and a space. Although Pandas can handle this under the hood, Spark cannot. Therefore, we remove the spaces. In addition, we remove any rows with a native country of Holand-Neitherlands from our training set because there aren’t any instances in our testing set and it will cause issues when we go to encode our categorical variables. We save the resulting dataframe to a csv file so that we can use it at a later point."
},
{
"code": null,
"e": 3974,
"s": 3591,
"text": "train_df = train_df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)train_df_cp = train_df.copy()train_df_cp = train_df_cp.loc[train_df_cp['native-country'] != 'Holand-Netherlands']train_df_cp.to_csv('train.csv', index=False, header=False)test_df = test_df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)test_df.to_csv('test.csv', index=False, header=False)"
},
{
"code": null,
"e": 4088,
"s": 3974,
"text": "Next, let’s take a look to see what we’re working with. The training set contains a little over 30 thousand rows."
},
{
"code": null,
"e": 4150,
"s": 4088,
"text": "print('Training data shape: ', train_df.shape)train_df.head()"
},
{
"code": null,
"e": 4226,
"s": 4150,
"text": "On the other hand, the testing set contains a little over 15 thousand rows."
},
{
"code": null,
"e": 4285,
"s": 4226,
"text": "print('Testing data shape: ', test_df.shape)test_df.head()"
},
{
"code": null,
"e": 4473,
"s": 4285,
"text": "Often times, we’ll have to handle missing data prior to training our model. The following line returns the number of missing values for each feature. Fortunately, the dataset is complete."
},
{
"code": null,
"e": 4497,
"s": 4473,
"text": "train_df.isnull().sum()"
},
{
"code": null,
"e": 4668,
"s": 4497,
"text": "Categorical variables will have a type of object. Categorical variables must be encoded in order to be interpreted by machine learning models (other than decision trees)."
},
{
"code": null,
"e": 4699,
"s": 4668,
"text": "train_df.dtypes.value_counts()"
},
{
"code": null,
"e": 4790,
"s": 4699,
"text": "The following code prints the distinct number of categories for each categorical variable."
},
{
"code": null,
"e": 4856,
"s": 4790,
"text": "train_df.select_dtypes('object').apply(pd.Series.nunique, axis=0)"
},
{
"code": null,
"e": 4921,
"s": 4856,
"text": "test_df.select_dtypes('object').apply(pd.Series.nunique, axis=0)"
},
{
"code": null,
"e": 5161,
"s": 4921,
"text": "We manually encode salary to avoid having it create two columns when we perform one hot encoding. After transforming our data, every string is replaced with an array of 1s and 0s where the location of the 1 corresponds to a given category."
},
{
"code": null,
"e": 5490,
"s": 5161,
"text": "train_df['salary'] = train_df['salary'].apply(lambda x: 0 if x == ' <=50K' else 1)test_df['salary'] = test_df['salary'].apply(lambda x: 0 if x == ' <=50K' else 1)train_df = pd.get_dummies(train_df)test_df = pd.get_dummies(test_df)print('Training Features shape: ', train_df.shape)print('Testing Features shape: ', test_df.shape)"
},
{
"code": null,
"e": 5935,
"s": 5490,
"text": "There is a discrepancy between the distinct number of native-country categories in the testing and training sets (the testing set doesn’t have a person whose native country is Holand). As a result, when we applied one hot encoding, we ended up with a different number of features. Before we can use logistic regression, we must ensure that the number of features in our training and testing sets match. We can do so by performing an inner join."
},
{
"code": null,
"e": 6186,
"s": 5935,
"text": "# Align the training and testing data, keep only columns present in both dataframestrain_df, test_df = train_df.align(test_df, join = 'inner', axis = 1)print('Training Features shape: ', train_df.shape)print('Testing Features shape: ', test_df.shape)"
},
{
"code": null,
"e": 6202,
"s": 6186,
"text": "train_df.head()"
},
{
"code": null,
"e": 6277,
"s": 6202,
"text": "Next, we break up the dataframes into dependent and independent variables."
},
{
"code": null,
"e": 6412,
"s": 6277,
"text": "X_train = train_df.drop('salary', axis=1)y_train = train_df['salary']X_test = test_df.drop('salary', axis=1)y_test = test_df['salary']"
},
{
"code": null,
"e": 6886,
"s": 6412,
"text": "We don’t need to scale variables for normal logistic regression as long as we keep units in mind when interpreting the coefficients. However, by default, the scikit-learn implementation of logistic regression uses L2 regularization. L2 regularization penalizes large values of all parameters equally. Hence, a feature for height in metres would be penalized much more than another feature in millimetres. Therefore, we scale our data, prior to sending it through our model."
},
{
"code": null,
"e": 7065,
"s": 6886,
"text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler(feature_range = (0, 1))scaler.fit(X_train)X_train = scaler.transform(X_train)X_test = scaler.transform(X_test)"
},
{
"code": null,
"e": 7145,
"s": 7065,
"text": "Finally, we can train our model and measure its performance on the testing set."
},
{
"code": null,
"e": 7347,
"s": 7145,
"text": "from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train, y_train)lr_pred = lr.predict(X_test)from sklearn.metrics import accuracy_scoreaccuracy_score(y_test, lr_pred)"
},
{
"code": null,
"e": 7582,
"s": 7347,
"text": "Let’s see how we could go about accomplishing the same thing using Spark. Depending on your preference, you can write Spark code in Java, Scala or Python. Given that most data scientist are used to working with Python, we’ll use that."
},
{
"code": null,
"e": 7843,
"s": 7582,
"text": "All of the code in the proceeding section will be running on our local machine. However, if we were to setup a Spark clusters with multiple nodes, the operations would run concurrently on every computer inside the cluster without any modifications to the code."
},
{
"code": null,
"e": 8140,
"s": 7843,
"text": "The easiest way to start using Spark is to use the Docker container provided by Jupyter. For simplicity, we create a docker-compose.yml file with the following content. Make sure to modify the path to match the directory that contains the data downloaded from the UCI Machine Learning Repository."
},
{
"code": null,
"e": 8300,
"s": 8140,
"text": "version: '2'services: spark: image: jupyter/pyspark-notebook:latest ports: - 8888:8888 volumes: - /home/cory/kaggle/adult:/home/jovyan/work"
},
{
"code": null,
"e": 8334,
"s": 8300,
"text": "Then, run the proceeding command."
},
{
"code": null,
"e": 8352,
"s": 8334,
"text": "docker-compose up"
},
{
"code": null,
"e": 8425,
"s": 8352,
"text": "To access the Jupyter Notebook, open a browser and go to localhost:8888."
},
{
"code": null,
"e": 8470,
"s": 8425,
"text": "Go ahead and import the following libraries."
},
{
"code": null,
"e": 8800,
"s": 8470,
"text": "from pyspark import SparkConf, SparkContextfrom pyspark.sql import SparkSessionfrom pyspark.ml.classification import LogisticRegressionfrom pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer, VectorAssemblerfrom pyspark.ml import Pipelinefrom pyspark.sql.types import StructType, StructField, IntegerType, StringType"
},
{
"code": null,
"e": 8870,
"s": 8800,
"text": "Prior, to doing anything else, we need to initialize a Spark session."
},
{
"code": null,
"e": 8945,
"s": 8870,
"text": "spark = SparkSession.builder.appName(\"Predict Adult Salary\").getOrCreate()"
},
{
"code": null,
"e": 9032,
"s": 8945,
"text": "Just like before, we define the column names which we’ll use when reading in the data."
},
{
"code": null,
"e": 9802,
"s": 9032,
"text": "schema = StructType([ StructField(\"age\", IntegerType(), True), StructField(\"workclass\", StringType(), True), StructField(\"fnlwgt\", IntegerType(), True), StructField(\"education\", StringType(), True), StructField(\"education-num\", IntegerType(), True), StructField(\"marital-status\", StringType(), True), StructField(\"occupation\", StringType(), True), StructField(\"relationship\", StringType(), True), StructField(\"race\", StringType(), True), StructField(\"sex\", StringType(), True), StructField(\"capital-gain\", IntegerType(), True), StructField(\"capital-loss\", IntegerType(), True), StructField(\"hours-per-week\", IntegerType(), True), StructField(\"native-country\", StringType(), True), StructField(\"salary\", StringType(), True)])"
},
{
"code": null,
"e": 9945,
"s": 9802,
"text": "Like Pandas, Spark provides an API for loading the contents of a csv file into our program. We use the files that we created in the beginning."
},
{
"code": null,
"e": 10078,
"s": 9945,
"text": "train_df = spark.read.csv('train.csv', header=False, schema=schema)test_df = spark.read.csv('test.csv', header=False, schema=schema)"
},
{
"code": null,
"e": 10134,
"s": 10078,
"text": "We can run the following line to view the first 5 rows."
},
{
"code": null,
"e": 10151,
"s": 10134,
"text": "train_df.head(5)"
},
{
"code": null,
"e": 10316,
"s": 10151,
"text": "If, for whatever reason, you’d like to convert the Spark dataframe into a Pandas dataframe, you can do so. Personally, I find the output cleaner and easier to read."
},
{
"code": null,
"e": 10345,
"s": 10316,
"text": "train_df.limit(5).toPandas()"
},
{
"code": null,
"e": 10476,
"s": 10345,
"text": "There are a couple of important dinstinction between Spark and Scikit-learn/Pandas which must be understood before moving forward."
},
{
"code": null,
"e": 10596,
"s": 10476,
"text": "Spark DataFrames are immutable. Thus, whenever we want to apply transformations, we must do so by creating new columns."
},
{
"code": null,
"e": 10663,
"s": 10596,
"text": "MLlib expects all features to be contained within a single column."
},
{
"code": null,
"e": 10774,
"s": 10663,
"text": "The proceeding code block is where we apply all of the necessary transformations to the categorical variables."
},
{
"code": null,
"e": 11082,
"s": 10774,
"text": "The StringIndexer class performs label encoding and must be applied before the OneHotEncoderEstimator which in turn performs one hot encoding. The VectorAssembler class takes multiple columns as input and outputs a single column whose contents is an array containing the values for all of the input columns."
},
{
"code": null,
"e": 11767,
"s": 11082,
"text": "categorical_variables = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country']indexers = [StringIndexer(inputCol=column, outputCol=column+\"-index\") for column in categorical_variables]encoder = OneHotEncoderEstimator( inputCols=[indexer.getOutputCol() for indexer in indexers], outputCols=[\"{0}-encoded\".format(indexer.getOutputCol()) for indexer in indexers])assembler = VectorAssembler( inputCols=encoder.getOutputCols(), outputCol=\"categorical-features\")pipeline = Pipeline(stages=indexers + [encoder, assembler])train_df = pipeline.fit(train_df).transform(train_df)test_df = pipeline.fit(test_df).transform(test_df)"
},
{
"code": null,
"e": 11844,
"s": 11767,
"text": "Let’s view all the different columns that were created in the previous step."
},
{
"code": null,
"e": 11867,
"s": 11844,
"text": "train_df.printSchema()"
},
{
"code": null,
"e": 11998,
"s": 11867,
"text": "After applying the transformations, we end up with a single column that contains an array with every encoded categorical variable."
},
{
"code": null,
"e": 12068,
"s": 11998,
"text": "df = train_df.limit(5).toPandas()df['scaled-categorical-features'][1]"
},
{
"code": null,
"e": 12157,
"s": 12068,
"text": "We combine our continuous variables with our categorical variables into a single column."
},
{
"code": null,
"e": 12458,
"s": 12157,
"text": "continuous_variables = ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']assembler = VectorAssembler( inputCols=['categorical-features', *continuous_variables], outputCol='features')train_df = assembler.transform(train_df)test_df = assembler.transform(test_df)"
},
{
"code": null,
"e": 12649,
"s": 12458,
"text": "Let’s take a look at the final column which we’ll use to train our model. As you can see it outputs a SparseVector. To save space, sparse vectors do not contain the 0s from one hot encoding."
},
{
"code": null,
"e": 12693,
"s": 12649,
"text": "train_df.limit(5).toPandas()['features'][0]"
},
{
"code": null,
"e": 12730,
"s": 12693,
"text": "Finally, we encode our target label."
},
{
"code": null,
"e": 12931,
"s": 12730,
"text": "indexer = StringIndexer(inputCol='salary', outputCol='label')train_df = indexer.fit(train_df).transform(train_df)test_df = indexer.fit(test_df).transform(test_df)train_df.limit(10).toPandas()['label']"
},
{
"code": null,
"e": 12959,
"s": 12931,
"text": "We fit and train our model."
},
{
"code": null,
"e": 13049,
"s": 12959,
"text": "lr = LogisticRegression(featuresCol='features', labelCol='label')model = lr.fit(train_df)"
},
{
"code": null,
"e": 13119,
"s": 13049,
"text": "The transform method is used to make predictions for the testing set."
},
{
"code": null,
"e": 13201,
"s": 13119,
"text": "pred = model.transform(test_df)pred.limit(10).toPandas()[['label', 'prediction']]"
}
] |
Calculate Volume, Curved Surface Area and Total Surface Area Of Cylinder - GeeksforGeeks
|
17 Mar, 2021
Given radius and height of Cylinder, calculate the volume, total surface area and curved surface area of cylinder.
Volume of Cylinder: The volume of cylinder is defined as the amount of three dimensional space occupied by the cylinder or the storage capacity of a cylinder. We can calculate volume of cylinder by using formula:
where ‘ r ‘is radius of the base and ‘ h ‘ is height of cylinder.
Total Surface Area of Cylinder: Surface area of cylinder is the number of square units that will exactly cover outer surface of a cone. There are three surfaces in a cylinder, one curved and two circular bases. Total surface area of cylinder is the sum of the area of both circular bases and area of curved surface. The total surface area includes the area of the circular top and base, as well as the Curved Surface Area (CSA).We can calculate curved surface area and total surface area by using formula:
Examples:
Input : Enter Radius Of Cylinder 5
Enter Height Of Cylinder 8
Output : Volume Of Cylinder = 628.3185307179587
Total Surface Area Of Cylinder = 408.4070449666731
Curved Surface Area Of Cylinder = 251.32741228718345
Input :Enter Radius Of Cylinder 15
Enter Height Of Cylinder 10
Output :Volume Of Cylinder = 7068.583470577034
Total Surface Area Of Cylinder = 2356.194490192345
Curved Surface Area Of Cylinder = 942.4777960769379
C
C++
Java
Python
C#
PHP
Javascript
#include <stdio.h>#define PI 3.14159 // Function To Calculate Volume OF Cylinderfloat volume(float r, float h){ float vol = PI * r * r * h; printf("Volume of Cylinder = %f \n" , vol);} // Function To Calculate Total Surface Area OF Cylinderfloat totalsurfacearea(float r, float h){ float tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); printf("Total Surface Area Of Cylinder = %f \n" , tsurf_ar);} // Function To Calculate Curved Surface Area OF Cylinderfloat curvedsurfacearea(float r, float h){ float cursurf_ar = (2 * PI * r * h); printf("Curved Surface Area Of Cylinder = %f \n" , cursurf_ar);} // Driver Codeint main(){ float r = 5; float h = 8; // Function Call And Printing Volume, TSA, CSA Of Cylinder volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); return 0;}// This code is contributed by Abhishek Agrawal.
#include <bits/stdc++.h>#define PI 3.14159using namespace std; // Function To Calculate Volume OF Cylindervoid volume(float r, float h){ float vol = PI * r * r * h; cout << "Volume of Cylinder = " << vol << "\n" ;} // Function To Calculate Total Surface Area OF Cylindervoid totalsurfacearea(float r, float h){ float tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); cout << "Total Surface Area Of Cylinder = " << tsurf_ar << "\n";} // Function To Calculate Curved Surface Area OF Cylindervoid curvedsurfacearea(float r, float h){ float cursurf_ar = (2 * PI * r * h); cout << "Curved Surface Area Of Cylinder = " << cursurf_ar << "\n";} // Driver codeint main(){ float r = 5; float h = 8; volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h);}// This code is contributed by Abhishek Agrawal.
// java code for illustion....import java.io.*; class GFG{ static double PI = 3.14159; // Function To Calculate Volume OF Cylinder static void volume(double r, double h) { double vol = PI * r * r * h; System.out.println( "Volume of Cylinder = " + vol ); } // Function To Calculate Total Surface Area OF Cylinder static void totalsurfacearea(double r, double h) { double tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); System.out.println( "Total Surface Area Of Cylinder = " + tsurf_ar ); } // Function To Calculate Curved Surface Area OF Cylinder static void curvedsurfacearea(double r, double h) { double cursurf_ar = (2 * PI * r * h); System.out.println( "Curved Surface Area Of Cylinder = " + cursurf_ar ); } // Driver code public static void main (String[] args) { double r = 7; double h = 6; volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); }} // This code is contributed by Sunnysingh
# Importing Math Library For The Value Of PIimport mathpi = math.pi # Function To Calculate Volume OF Cylinderdef volume(r, h): vol = pi * r * r * h return vol # Function To Calculate Total Surface Area# of Cylinderdef totalsurfacearea(r, h): tsurf_ar = (2 * pi * r * h) + (2 * pi * r * r) return tsurf_ar # Function To Calculate Curved Surface Area# of Cylinderdef curvedsurfacearea(r, h): cursurf_ar = (2 * pi * r * h) return cursurf_ar # Driver Coder = 5h = 8# Function Call And Printing Volume, TSA, CSA Of Cylinderprint("Volume Of Cylinder = ",volume(r, h))print("Total Surface Area Of Cylinder = ",totalsurfacearea(r,h))print("Curved Surface Area Of Cylinder = ",curvedsurfacearea(r,h))
// C# code for illustion....using System; class GFG { static double PI = 3.14159; // Function To Calculate Volume OF Cylinder static void volume(double r, double h) { double vol = PI * r * r * h; Console.WriteLine( "Volume of Cylinder = " + vol ); } // Function To Calculate Total Surface Area // OF Cylinder static void totalsurfacearea(double r, double h) { double tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); Console.WriteLine( "Total Surface Area Of " + "Cylinder = " + tsurf_ar ); } // Function To Calculate Curved Surface Area // OF Cylinder static void curvedsurfacearea(double r, double h) { double cursurf_ar = (2 * PI * r * h); Console.WriteLine( "Curved Surface Area Of" + " Cylinder = " + cursurf_ar ); } // Driver code public static void Main () { double r = 5; double h = 8; volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); }} // This code is contributed by vt_m.
<?php // Function To Calculate Volume OF Cylinderfunction volume( $r, $h){ $PI = 3.14159; $vol = $PI * $r * $r * $h; echo("Volume of Cylinder ="); echo($vol); echo("\n");} // Function To Calculate Total Surface// Area OF Cylinderfunction totalsurfacearea( $r, $h){ $PI = 3.14159; $tsurf_ar = (2 * $PI * $r * $h) + (2 * $PI * $r * $r); echo("Total Surface Area Of Cylinder = "); echo($tsurf_ar); echo("\n");} // Function To Calculate Curved Surface// Area OF Cylinderfunction curvedsurfacearea($r, $h){ $PI =3.14159; $cursurf_ar = (2 * $PI * $r * $h); echo("Curved Surface Area Of Cylinder = "); echo($cursurf_ar);} // Driver Code$r = 5;$h = 8; // Function Call And Printing Volume,// TSA, CSA Of Cylindervolume($r, $h);totalsurfacearea($r, $h);curvedsurfacearea($r, $h); // This code is contributed by vt_m.?>
<script>let PI = 3.141592653589793238; // Function To Calculate Volume OF Cylinderfunction volume( r, h){ let vol = PI * r * r * h; document.write("Volume of Cylinder = " + vol + "<br/>");} // Function To Calculate Total Surface Area OF Cylinderfunction totalsurfacearea( r, h){ let tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); document.write("Total Surface Area Of Cylinder = " + tsurf_ar+ "<br/>");} // Function To Calculate Curved Surface Area OF Cylinderfunction curvedsurfacearea( r, h){ let cursurf_ar = (2 * PI * r * h); document.write("Curved Surface Area Of Cylinder = " + cursurf_ar+ "<br/>");} // Driver Code let r = 5; let h = 8; // Function Call And Printing Volume, TSA, CSA Of Cylinder volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); // This code is contributed by Rajput-Ji</script>
Output:
Volume Of Cylinder = 628.3185307179587
Total Surface Area Of Cylinder = 408.4070449666731
Total Surface Area Of Cylinder = 251.32741228718345
vt_m
gowtham_yuvaraj
Rajput-Ji
area-volume-programs
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Program to multiply two matrices
Program to print prime numbers from 1 to N.
Count ways to reach the n'th stair
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
|
[
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 24832,
"s": 24716,
"text": "Given radius and height of Cylinder, calculate the volume, total surface area and curved surface area of cylinder. "
},
{
"code": null,
"e": 25046,
"s": 24832,
"text": "Volume of Cylinder: The volume of cylinder is defined as the amount of three dimensional space occupied by the cylinder or the storage capacity of a cylinder. We can calculate volume of cylinder by using formula: "
},
{
"code": null,
"e": 25112,
"s": 25046,
"text": "where ‘ r ‘is radius of the base and ‘ h ‘ is height of cylinder."
},
{
"code": null,
"e": 25620,
"s": 25114,
"text": "Total Surface Area of Cylinder: Surface area of cylinder is the number of square units that will exactly cover outer surface of a cone. There are three surfaces in a cylinder, one curved and two circular bases. Total surface area of cylinder is the sum of the area of both circular bases and area of curved surface. The total surface area includes the area of the circular top and base, as well as the Curved Surface Area (CSA).We can calculate curved surface area and total surface area by using formula:"
},
{
"code": null,
"e": 25634,
"s": 25622,
"text": "Examples: "
},
{
"code": null,
"e": 26173,
"s": 25634,
"text": "Input : Enter Radius Of Cylinder 5\n Enter Height Of Cylinder 8\nOutput : Volume Of Cylinder = 628.3185307179587\n Total Surface Area Of Cylinder = 408.4070449666731\n Curved Surface Area Of Cylinder = 251.32741228718345\n\n\nInput :Enter Radius Of Cylinder 15\n Enter Height Of Cylinder 10\nOutput :Volume Of Cylinder = 7068.583470577034\n Total Surface Area Of Cylinder = 2356.194490192345\n Curved Surface Area Of Cylinder = 942.4777960769379"
},
{
"code": null,
"e": 26179,
"s": 26177,
"text": "C"
},
{
"code": null,
"e": 26183,
"s": 26179,
"text": "C++"
},
{
"code": null,
"e": 26188,
"s": 26183,
"text": "Java"
},
{
"code": null,
"e": 26195,
"s": 26188,
"text": "Python"
},
{
"code": null,
"e": 26198,
"s": 26195,
"text": "C#"
},
{
"code": null,
"e": 26202,
"s": 26198,
"text": "PHP"
},
{
"code": null,
"e": 26213,
"s": 26202,
"text": "Javascript"
},
{
"code": "#include <stdio.h>#define PI 3.14159 // Function To Calculate Volume OF Cylinderfloat volume(float r, float h){ float vol = PI * r * r * h; printf(\"Volume of Cylinder = %f \\n\" , vol);} // Function To Calculate Total Surface Area OF Cylinderfloat totalsurfacearea(float r, float h){ float tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); printf(\"Total Surface Area Of Cylinder = %f \\n\" , tsurf_ar);} // Function To Calculate Curved Surface Area OF Cylinderfloat curvedsurfacearea(float r, float h){ float cursurf_ar = (2 * PI * r * h); printf(\"Curved Surface Area Of Cylinder = %f \\n\" , cursurf_ar);} // Driver Codeint main(){ float r = 5; float h = 8; // Function Call And Printing Volume, TSA, CSA Of Cylinder volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); return 0;}// This code is contributed by Abhishek Agrawal.",
"e": 27088,
"s": 26213,
"text": null
},
{
"code": "#include <bits/stdc++.h>#define PI 3.14159using namespace std; // Function To Calculate Volume OF Cylindervoid volume(float r, float h){ float vol = PI * r * r * h; cout << \"Volume of Cylinder = \" << vol << \"\\n\" ;} // Function To Calculate Total Surface Area OF Cylindervoid totalsurfacearea(float r, float h){ float tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); cout << \"Total Surface Area Of Cylinder = \" << tsurf_ar << \"\\n\";} // Function To Calculate Curved Surface Area OF Cylindervoid curvedsurfacearea(float r, float h){ float cursurf_ar = (2 * PI * r * h); cout << \"Curved Surface Area Of Cylinder = \" << cursurf_ar << \"\\n\";} // Driver codeint main(){ float r = 5; float h = 8; volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h);}// This code is contributed by Abhishek Agrawal.",
"e": 27934,
"s": 27088,
"text": null
},
{
"code": "// java code for illustion....import java.io.*; class GFG{ static double PI = 3.14159; // Function To Calculate Volume OF Cylinder static void volume(double r, double h) { double vol = PI * r * r * h; System.out.println( \"Volume of Cylinder = \" + vol ); } // Function To Calculate Total Surface Area OF Cylinder static void totalsurfacearea(double r, double h) { double tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); System.out.println( \"Total Surface Area Of Cylinder = \" + tsurf_ar ); } // Function To Calculate Curved Surface Area OF Cylinder static void curvedsurfacearea(double r, double h) { double cursurf_ar = (2 * PI * r * h); System.out.println( \"Curved Surface Area Of Cylinder = \" + cursurf_ar ); } // Driver code public static void main (String[] args) { double r = 7; double h = 6; volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); }} // This code is contributed by Sunnysingh",
"e": 29072,
"s": 27934,
"text": null
},
{
"code": "# Importing Math Library For The Value Of PIimport mathpi = math.pi # Function To Calculate Volume OF Cylinderdef volume(r, h): vol = pi * r * r * h return vol # Function To Calculate Total Surface Area# of Cylinderdef totalsurfacearea(r, h): tsurf_ar = (2 * pi * r * h) + (2 * pi * r * r) return tsurf_ar # Function To Calculate Curved Surface Area# of Cylinderdef curvedsurfacearea(r, h): cursurf_ar = (2 * pi * r * h) return cursurf_ar # Driver Coder = 5h = 8# Function Call And Printing Volume, TSA, CSA Of Cylinderprint(\"Volume Of Cylinder = \",volume(r, h))print(\"Total Surface Area Of Cylinder = \",totalsurfacearea(r,h))print(\"Curved Surface Area Of Cylinder = \",curvedsurfacearea(r,h))",
"e": 29803,
"s": 29072,
"text": null
},
{
"code": "// C# code for illustion....using System; class GFG { static double PI = 3.14159; // Function To Calculate Volume OF Cylinder static void volume(double r, double h) { double vol = PI * r * r * h; Console.WriteLine( \"Volume of Cylinder = \" + vol ); } // Function To Calculate Total Surface Area // OF Cylinder static void totalsurfacearea(double r, double h) { double tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); Console.WriteLine( \"Total Surface Area Of \" + \"Cylinder = \" + tsurf_ar ); } // Function To Calculate Curved Surface Area // OF Cylinder static void curvedsurfacearea(double r, double h) { double cursurf_ar = (2 * PI * r * h); Console.WriteLine( \"Curved Surface Area Of\" + \" Cylinder = \" + cursurf_ar ); } // Driver code public static void Main () { double r = 5; double h = 8; volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); }} // This code is contributed by vt_m.",
"e": 30972,
"s": 29803,
"text": null
},
{
"code": "<?php // Function To Calculate Volume OF Cylinderfunction volume( $r, $h){ $PI = 3.14159; $vol = $PI * $r * $r * $h; echo(\"Volume of Cylinder =\"); echo($vol); echo(\"\\n\");} // Function To Calculate Total Surface// Area OF Cylinderfunction totalsurfacearea( $r, $h){ $PI = 3.14159; $tsurf_ar = (2 * $PI * $r * $h) + (2 * $PI * $r * $r); echo(\"Total Surface Area Of Cylinder = \"); echo($tsurf_ar); echo(\"\\n\");} // Function To Calculate Curved Surface// Area OF Cylinderfunction curvedsurfacearea($r, $h){ $PI =3.14159; $cursurf_ar = (2 * $PI * $r * $h); echo(\"Curved Surface Area Of Cylinder = \"); echo($cursurf_ar);} // Driver Code$r = 5;$h = 8; // Function Call And Printing Volume,// TSA, CSA Of Cylindervolume($r, $h);totalsurfacearea($r, $h);curvedsurfacearea($r, $h); // This code is contributed by vt_m.?>",
"e": 31843,
"s": 30972,
"text": null
},
{
"code": "<script>let PI = 3.141592653589793238; // Function To Calculate Volume OF Cylinderfunction volume( r, h){ let vol = PI * r * r * h; document.write(\"Volume of Cylinder = \" + vol + \"<br/>\");} // Function To Calculate Total Surface Area OF Cylinderfunction totalsurfacearea( r, h){ let tsurf_ar = (2 * PI * r * h) + (2 * PI * r * r); document.write(\"Total Surface Area Of Cylinder = \" + tsurf_ar+ \"<br/>\");} // Function To Calculate Curved Surface Area OF Cylinderfunction curvedsurfacearea( r, h){ let cursurf_ar = (2 * PI * r * h); document.write(\"Curved Surface Area Of Cylinder = \" + cursurf_ar+ \"<br/>\");} // Driver Code let r = 5; let h = 8; // Function Call And Printing Volume, TSA, CSA Of Cylinder volume(r, h); totalsurfacearea(r, h); curvedsurfacearea(r, h); // This code is contributed by Rajput-Ji</script>",
"e": 32708,
"s": 31843,
"text": null
},
{
"code": null,
"e": 32718,
"s": 32708,
"text": "Output: "
},
{
"code": null,
"e": 32871,
"s": 32718,
"text": "Volume Of Cylinder = 628.3185307179587\nTotal Surface Area Of Cylinder = 408.4070449666731\nTotal Surface Area Of Cylinder = 251.32741228718345"
},
{
"code": null,
"e": 32878,
"s": 32873,
"text": "vt_m"
},
{
"code": null,
"e": 32894,
"s": 32878,
"text": "gowtham_yuvaraj"
},
{
"code": null,
"e": 32904,
"s": 32894,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32925,
"s": 32904,
"text": "area-volume-programs"
},
{
"code": null,
"e": 32938,
"s": 32925,
"text": "Mathematical"
},
{
"code": null,
"e": 32957,
"s": 32938,
"text": "School Programming"
},
{
"code": null,
"e": 32970,
"s": 32957,
"text": "Mathematical"
},
{
"code": null,
"e": 33068,
"s": 32970,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33077,
"s": 33068,
"text": "Comments"
},
{
"code": null,
"e": 33090,
"s": 33077,
"text": "Old Comments"
},
{
"code": null,
"e": 33122,
"s": 33090,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 33153,
"s": 33122,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 33186,
"s": 33153,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33230,
"s": 33186,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 33265,
"s": 33230,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 33283,
"s": 33265,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33299,
"s": 33283,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 33318,
"s": 33299,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 33343,
"s": 33318,
"text": "Reverse a string in Java"
}
] |
JavaScript | Comments - GeeksforGeeks
|
26 Oct, 2021
Comments are used to prevent the execution of statements. Comments are ignored while the compiler executes the code. Comments are user-friendly as users can get explanations of code using comments.
Syntax:
// For single line comment
/* For block of lines comment
...
...
*/
Return Value: During execution of code, comments are ignored.
Example 1: This example illustrates the single line comment using //.
html
<!DOCTYPE html><html> <head> <title> JavaScript Comments </title> <script> // Function to add two numbers function add() { // Declare three variables var x, y, z; // Input a number and store it into variable x x = Number( document.getElementById("num1").value ); // Input a number and store it into variable x y = Number( document.getElementById("num2").value ); // Sum of two numbers z= x +y; // Return the sum document.getElementById("sum").value = z; } </script></head> <body> Enter the First number: <input id="num1"><br><br> Enter the Second number: <input id="num2"><br><br> <button onclick="add()"> Sum </button> <input id="sum"></body> </html>
Example 2: This example illustrates the multi-line comment using /* ... */
html
<!DOCTYPE html><html> <head> <title> JavaScript Comments </title> <script> /* Script to get two input from user and add them */ function add() { /* Declare three variable */ var x, y, z; /* Input the two nos. num1, num2 Input num1 and store it in x Input num2 and store it in y The sum is stored in a variable z*/ x = Number(document.getElementById("num1").value); y = Number(document.getElementById("num2").value); z = x + y; document.getElementById("sum").value = z; } </script></head> <body> Enter the First number : <input id="num1"><br><br> Enter the Second number: <input id="num2"><br><br> <button onclick="add()"> Sum </button> <input id="sum"></body> </html>
Example 3: This example illustrates that commented code will never execute.
html
<!DOCTYPE html><html> <head> <title> JavaScript Comments </title> <script> function add() { var x, y, z; x = Number( document.getElementById("num1").value ); y = Number( document.getElementById("num2").value ); z= x +y; // Comment the code section //document.getElementById("sum").value = z; } </script></head> <body> Enter the First number: <input id="num1"><br><br> Enter the Second number: <input id="num2"><br><br> <button onclick="add()"> Sum </button> <input id="sum"></body> </html>
shrijitpandey
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 30004,
"s": 29976,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 30202,
"s": 30004,
"text": "Comments are used to prevent the execution of statements. Comments are ignored while the compiler executes the code. Comments are user-friendly as users can get explanations of code using comments."
},
{
"code": null,
"e": 30210,
"s": 30202,
"text": "Syntax:"
},
{
"code": null,
"e": 30237,
"s": 30210,
"text": "// For single line comment"
},
{
"code": null,
"e": 30278,
"s": 30237,
"text": "/* For block of lines comment\n...\n...\n*/"
},
{
"code": null,
"e": 30340,
"s": 30278,
"text": "Return Value: During execution of code, comments are ignored."
},
{
"code": null,
"e": 30410,
"s": 30340,
"text": "Example 1: This example illustrates the single line comment using //."
},
{
"code": null,
"e": 30415,
"s": 30410,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Comments </title> <script> // Function to add two numbers function add() { // Declare three variables var x, y, z; // Input a number and store it into variable x x = Number( document.getElementById(\"num1\").value ); // Input a number and store it into variable x y = Number( document.getElementById(\"num2\").value ); // Sum of two numbers z= x +y; // Return the sum document.getElementById(\"sum\").value = z; } </script></head> <body> Enter the First number: <input id=\"num1\"><br><br> Enter the Second number: <input id=\"num2\"><br><br> <button onclick=\"add()\"> Sum </button> <input id=\"sum\"></body> </html> ",
"e": 31360,
"s": 30415,
"text": null
},
{
"code": null,
"e": 31435,
"s": 31360,
"text": "Example 2: This example illustrates the multi-line comment using /* ... */"
},
{
"code": null,
"e": 31440,
"s": 31435,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Comments </title> <script> /* Script to get two input from user and add them */ function add() { /* Declare three variable */ var x, y, z; /* Input the two nos. num1, num2 Input num1 and store it in x Input num2 and store it in y The sum is stored in a variable z*/ x = Number(document.getElementById(\"num1\").value); y = Number(document.getElementById(\"num2\").value); z = x + y; document.getElementById(\"sum\").value = z; } </script></head> <body> Enter the First number : <input id=\"num1\"><br><br> Enter the Second number: <input id=\"num2\"><br><br> <button onclick=\"add()\"> Sum </button> <input id=\"sum\"></body> </html> ",
"e": 32377,
"s": 31440,
"text": null
},
{
"code": null,
"e": 32453,
"s": 32377,
"text": "Example 3: This example illustrates that commented code will never execute."
},
{
"code": null,
"e": 32458,
"s": 32453,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Comments </title> <script> function add() { var x, y, z; x = Number( document.getElementById(\"num1\").value ); y = Number( document.getElementById(\"num2\").value ); z= x +y; // Comment the code section //document.getElementById(\"sum\").value = z; } </script></head> <body> Enter the First number: <input id=\"num1\"><br><br> Enter the Second number: <input id=\"num2\"><br><br> <button onclick=\"add()\"> Sum </button> <input id=\"sum\"></body> </html> ",
"e": 33190,
"s": 32458,
"text": null
},
{
"code": null,
"e": 33204,
"s": 33190,
"text": "shrijitpandey"
},
{
"code": null,
"e": 33222,
"s": 33204,
"text": "javascript-basics"
},
{
"code": null,
"e": 33229,
"s": 33222,
"text": "Picked"
},
{
"code": null,
"e": 33240,
"s": 33229,
"text": "JavaScript"
},
{
"code": null,
"e": 33257,
"s": 33240,
"text": "Web Technologies"
},
{
"code": null,
"e": 33355,
"s": 33257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33364,
"s": 33355,
"text": "Comments"
},
{
"code": null,
"e": 33377,
"s": 33364,
"text": "Old Comments"
},
{
"code": null,
"e": 33422,
"s": 33377,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33491,
"s": 33422,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 33552,
"s": 33491,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33624,
"s": 33552,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 33651,
"s": 33624,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 33693,
"s": 33651,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 33726,
"s": 33693,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33788,
"s": 33726,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33838,
"s": 33788,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to find the class of clicked element using jQuery ? - GeeksforGeeks
|
18 Jan, 2021
In this article, we will find the class of the clicked element using jQuery. To find the class of clicked element, we use this.className property. The className property is used to set or return the value of an element’s class attribute. Using this property, the user can change the class of an element to the desired class.
Approach:
Here, we use this.className property to get the class name of the current div element. Here, we have added five div elements with different class name and then use jQuery this.className property to get the clicked div elements class name and display it on the console.
Syntax:
$("div").click(function () {
var getClass = this.className;
console.log(getClass);
});
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <title> How to find the class of the clicked element using jquery? </title> <!-- Import jQuery cdn library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("div").click(function () { var getClass = this.className; console.log(getClass); }); }); </script></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to find the class of the clicked element using jquery? </h3> <div class="main">Main Div</div> <div class="GFG">GFG</div> <div class="Geeks">Geeks</div> <div class="G4G">GeeksforGeeks</div> <div class="welcome">Welcome</div></body> </html>
Output:
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
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26816,
"s": 26788,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 27141,
"s": 26816,
"text": "In this article, we will find the class of the clicked element using jQuery. To find the class of clicked element, we use this.className property. The className property is used to set or return the value of an element’s class attribute. Using this property, the user can change the class of an element to the desired class."
},
{
"code": null,
"e": 27151,
"s": 27141,
"text": "Approach:"
},
{
"code": null,
"e": 27420,
"s": 27151,
"text": "Here, we use this.className property to get the class name of the current div element. Here, we have added five div elements with different class name and then use jQuery this.className property to get the clicked div elements class name and display it on the console."
},
{
"code": null,
"e": 27428,
"s": 27420,
"text": "Syntax:"
},
{
"code": null,
"e": 27523,
"s": 27428,
"text": "$(\"div\").click(function () {\n var getClass = this.className;\n console.log(getClass);\n});"
},
{
"code": null,
"e": 27532,
"s": 27523,
"text": "Example:"
},
{
"code": null,
"e": 27537,
"s": 27532,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to find the class of the clicked element using jquery? </title> <!-- Import jQuery cdn library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"div\").click(function () { var getClass = this.className; console.log(getClass); }); }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to find the class of the clicked element using jquery? </h3> <div class=\"main\">Main Div</div> <div class=\"GFG\">GFG</div> <div class=\"Geeks\">Geeks</div> <div class=\"G4G\">GeeksforGeeks</div> <div class=\"welcome\">Welcome</div></body> </html>",
"e": 28418,
"s": 27537,
"text": null
},
{
"code": null,
"e": 28426,
"s": 28418,
"text": "Output:"
},
{
"code": null,
"e": 28563,
"s": 28426,
"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": 28572,
"s": 28563,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28582,
"s": 28572,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28594,
"s": 28582,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28598,
"s": 28594,
"text": "CSS"
},
{
"code": null,
"e": 28603,
"s": 28598,
"text": "HTML"
},
{
"code": null,
"e": 28610,
"s": 28603,
"text": "JQuery"
},
{
"code": null,
"e": 28627,
"s": 28610,
"text": "Web Technologies"
},
{
"code": null,
"e": 28632,
"s": 28627,
"text": "HTML"
},
{
"code": null,
"e": 28730,
"s": 28632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28769,
"s": 28730,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28806,
"s": 28769,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28835,
"s": 28806,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28870,
"s": 28835,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28912,
"s": 28870,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28972,
"s": 28912,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29025,
"s": 28972,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29086,
"s": 29025,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29110,
"s": 29086,
"text": "REST API (Introduction)"
}
] |
Web Development with Python: Dash (complete tutorial) | by Mauro Di Pietro | Towards Data Science
|
Welcome to this hardcore Dash tutorial, following this article you will be able to produce and deploy a basic prototype (minimum viable product) for any kind of web application.
On the occasion of my best friend’s wedding, I tried to make his life easier with a dashboard for seat arrangement. While coding it, I realized this simple project contains all the key features necessary to develop a basic but good prototype. So I thought it’s worth sharing it.
Through this tutorial, I will explain how to build a complete Dash web application, using my Wedding Planner App as an example (link below).
app-wedding-planner.herokuapp.com
I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate this example (link to the full code below).
github.com
In particular, I will go through:
Setup of the environment
Data & Model
Prepare the basic structure of the dash application (Navbar, Body, Layout)
Inputs (Form, Slider, Manual, File Upload, Change inputs after an event)
Outputs (Plotly, File Download, Spinner while loading)
Deploy the app on Heroku
First of all, I will install the following libraries through the terminal:
## for applicationdash==1.20.0dash-bootstrap-components==0.12.2## to produce random datanames==0.3.0## for data processingnumpy==1.19.5pandas==1.1.5## for plottingplotly==4.14.3## for read and write excel filesopenpyxl==3.0.7xlrd==1.2.0
To make the dashboard look pretty, we’ll use Bootstrap, a CSS/JS framework that contains design templates for forms, buttons, navigation, and other interface components. The package Dash-Bootstrap-Components enables easy integration of Bootstrap into our dash app.
The names package generates random names and I’ll use it to create a dataset of random guests.
Please note that the latest version of xlrd (2.0.0) doesn’t accept .xlsx files, therefore use the 1.2.0 if you want to upload Excel files.
In a nutshell, the idea is to create a random guest list and run an optimization algorithm to arrange the seats. Alternatively, we’ll give users the possibility to upload their Excel file and the algorithm is going to use that instead of a random dataset.
import namesimport pandas as pdimport numpy as np'''Generate random guests list:parameter :param n: num - number of guests and length of dtf :param lst_categories: list - ["family", "friends", ...] :param n_rules: num - number of restrictions to apply (ex. if 1 then 2 guests can't be sit together):return dtf with guests'''def random_data(n=100, lst_categories=["family","friends", "work","university","tennis"], n_rules=0): ## basic list lst_dics = [] for i in range(n): name = names.get_full_name() category = np.random.choice(lst_categories) if len(lst_categories) > 0 else np.nan lst_dics.append({"id":i, "name":name, "category":category, "avoid":np.nan}) dtf = pd.DataFrame(lst_dics) ## add rules if n_rules > 0: for i in range(n_rules): choices = dtf[dtf["avoid"].isna()]["id"] ids = np.random.choice(choices, size=2) dtf["avoid"].iloc[ids[0]] = int(ids[1]) if int(ids[1]) != ids[0] else int(ids[1])+1 return dtf
This function creates a table with guests' information.
I’ll use the “category” column to display the guests with different colors:
The “avoid” column will be used to make sure that two guests that hate each other will not be placed at the same table.
The app will be arranging seats based on:
a reward of +1 when two people belonging to the same category are seated next to each other
a penalty of -1 when two people that want to avoid each other are placed at the same table.
This function returns the same dataframe with a new column for the table assigned:
Now we can start with the cool part: building the application. I’m gonna divide it into 3 sections: the Navbar, the Body, the Layout. Moreover, each section will contain 3 parts:
Input — the section of the app where the user can insert and select the parameters and data that will be used by the back-end to return the desired output (The Navbar doesn’t need Input).
Output — the section of the app where the user can visualize the results.
Callbacks — a decorator wrapping a function, in which you need to specify outputs, inputs, and states; the latter allow you to pass along extra values without firing the callbacks (Callbacks may look scary but actually they are your best friends).
# setupimport dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_bootstrap_components as dbc# App Instanceapp = dash.Dash(name="name")app.title = "name"########################## Navbar ########################### Input# Outputnavbar = dbc.Nav()# Callbacks@app.callback()def function(): return 0########################## Body ########################### Inputinputs = dbc.FormGroup()# Outputbody = dbc.Row([ ## input dbc.Col(md=3), ## output dbc.Col(md=9)])# Callbacks@app.callback()def function(): return 0########################## App Layout ##########################app.layout = dbc.Container(fluid=True, children=[ html.H1("name", id="nav-pills"), navbar, html.Br(),html.Br(),html.Br(), body])########################## Run ##########################if __name__ == "__main__": app.run_server(debug=True)
Let’s start with the style. The wonderful Dash-Bootstrap-Components offers a huge variety of predefined styles. You can check them out here. Once you choose one, you can insert it in the app instance as an external stylesheet. You can even use more than one:
theme = dbc.themes.LUXcss = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'# App Instanceapp = dash.Dash(name="name", external_stylesheets=[theme, css])
Let’s move on to the top Navbar, I’ll include a link, a popover, and a dropdown menu.
As you can see, the navbar is cool and reactive on click, with pop-ups and a drop-down menu. The “Links” drop-down menu is easy as you don’t need a Callback to make it work, while the “About” popover is a bit tricky.
The navbar contains 3 nav-items: the logo, the “About” button, the drop-down menu. The “About” button incorporates 2 elements: a nav-link (which usually is used to navigate a multi-page application but in this case href=”/”), and a popover (green and red marks). Those 2 elements are called in the Callback as both outputs, inputs, and states like that if the “About” nav-link is clicked then popover becomes active and shows up. The python function about_popover() expects 3 arguments because the Callback has one input and two states, and returns 2 variables because the Callback has two outputs. When the app starts and the button is not clicked n=0.
Please note that the drop-down menu (blue part) includes fonts imported with the external stylesheet (i.e. className=”fa fa-linkedin”).
The navbar we’ve just seen is one of the elements of the final Layout, together with the title and the main Body:
Now, let’s talk about the elephant in the room... the main Body. It’s composed of the Inputs (left side) and the Outputs (right side), which interact together thanks to Callbacks.
Normally, inputs are wrapped in a Form group and are sent when the Form button is clicked. Sliders and manual inputs are the most common Form elements.
This is how you can create a normal slider:
dcc.Slider(id="n-guests", min=10, max=100, step=1, value=50, tooltip={'always_visible':False})
and here’s how to force only specific values in the slider:
dcc.Slider(id="n-iter", min=10, max=1000, step=None, marks={10:"10", 100:"100", 500:"500", 1000:"1000"}, value=0),
This is a simple manual input:
dbc.Input(id="max-capacity", placeholder="table capacity", type="number", value="10"),
Let’s increase the difficulty and tackle the “file Upload” situation. I’m going to give users the possibility to upload an Excel file containing a similar dataset that we generated randomly:
When uploading a file, I want two things to happen:
display the file name just to be sure that the right one was selected and it was loaded correctly
hide the first two sliders because they are meant for a random simulation and become useless when a custom file is uploaded
How do we achieve that? Easy, with a magic Callback that changes the CSS style of the HTML components:
In order to use the uploaded file, we need to parse it and transform it into a pandas dataframe, and we’re going to use this function for that:
import pandas as pdimport base64import io'''When a file is uploaded it contains "contents", "filename", "date":parameter :param contents: file :param filename: str:return pandas table'''def upload_file(contents, filename): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: return pd.read_csv(io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: return pd.read_excel(io.BytesIO(decoded)) except Exception as e: print("ERROR:", e) return 'There was an error processing this file.'
Before moving on with the Outputs, let’s recap what we have seen so far. Here’s the full code of the Inputs in the main Body:
########################## Body ########################### Inputinputs = dbc.FormGroup([ ## hide these 2 inputs if file is uploaded html.Div(id='hide-seek', children=[ dbc.Label("Number of Guests", html_for="n-guests"), dcc.Slider(id="n-guests", min=10, max=100, step=1, value=50, tooltip={'always_visible':False}), dbc.Label("Number of Rules", html_for="n-rules"), dcc.Slider(id="n-rules", min=0, max=10, step=1, value=3, tooltip={'always_visible':False}) ], style={'display':'block'}), ## always visible dbc.Label("Number of Trials", html_for="n-iter"), dcc.Slider(id="n-iter", min=10, max=1000, step=None, marks={10:"10", 100:"100", 500:"500", 1000:"1000"}, value=0), html.Br(), dbc.Label("Max Guests per Table", html_for="max-capacity"), dbc.Input(id="max-capacity", placeholder="table capacity", type="number", value="10"), ## upload a file html.Br(), dbc.Label("Or Upload your Excel", html_for="upload-excel"), dcc.Upload(id='upload-excel', children=html.Div([ 'Drag and Drop or ', html.A('Select Files')]), style={'width':'100%', 'height':'60px', 'lineHeight':'60px', 'borderWidth':'1px', 'borderStyle':'dashed', 'borderRadius':'5px', 'textAlign':'center', 'margin':'10px'} ), html.Div(id='excel-name', style={"marginLeft":"20px"}), ## run button html.Br(),html.Br(), dbc.Col(dbc.Button("run", id="run", color="primary"))])# Callbacks@app.callback( output=[ Output(component_id="hide-seek", component_property="style"), Output(component_id="excel-name", component_property="children")], inputs=[ Input(component_id="upload-excel",component_property="filename")])def upload_event(filename): div = "" if filename is None else "Use file "+filename return {'display':'block'} if filename is None else {'display':'none'}, div
The back-end shall produce 3 outputs: the title, a link to download the results as an Excel file, and obviously the plot.
Let’s get started with the plot made with Plotly. Essentially, there are two major modules of this amazing graphic library: plotly express and graph_objects. The former is a high-level graphic tool containing functions that can create entire figures at once (I find it similar to seaborn), while the latter allows you to build a figure brick by brick (it is in fact what plotly express runs under the hood).
Plotly express is perfect when you want to style your data based on the value of specific columns, so here I’m going to use that, but if you want to see examples of plots made with graph_objects check out this article.
So... what’s this?
It may look like a drawing but it is a proper geometric figure: it’s a scatter plot in which the color is based on the category guests belong to (family, friends, ...), the size is determined by whether a guest wants to avoid someone or not (basically I’m highlighting the problematic ones), and the facet component is linked to the table assigned to each guest. Facet plots are figures made up of multiple subplots which have the same set of axes, where each subplot shows a subset of the data.
First of all, I need to add the x and y coordinates for the plot using the circle equation: (x, y) = (r*cosθ, r*sinθ). Then I add the “size” column based on the “avoid” column:
def prepare_data(dtf): ## mark the rules dtf["avoid"] = dtf["avoid"].apply(lambda x: dtf[dtf["id"]==x]["name"].iloc[0] if pd.notnull(x) else "none") dtf["size"] = dtf["avoid"].apply(lambda x: 1 if x == "none" else 3) ## create axis dtf_out = pd.DataFrame() lst_tables = [] for t in dtf["table"].unique(): dtf_t = dtf[dtf["table"]==t] n = len(dtf_t) theta = np.linspace(0, 2*np.pi, n) dtf_t["x"] = 1*np.cos(theta) dtf_t["y"] = 1*np.sin(theta) dtf_out = dtf_out.append(dtf_t) return dtf_out.reset_index(drop=True).sort_values("table")
Then I can simply use plotly commands to produce figures and specify what information visualize when the mouse hovers over the points:
import plotly.express as pxfig = px.scatter(dtf, x="x", y="y", color="category", hover_name="name", facet_col="table", facet_col_wrap=3, size="size", hover_data={"x":False, "y":False, "category":True, "avoid":True, "size":False, "table":False} ) fig.add_shape(type="circle", opacity=0.1, fillcolor="black", col="all", row="all", exclude_empty_subplots=True, x0=dtf["x"].min(), y0=dtf["y"].min(), x1=dtf["x"].max(), y1=dtf["y"].max() ) fig.update_layout(plot_bgcolor='white', legend={"bordercolor":"black", "borderwidth":1, "orientation":"h"} )
Full code for plotly (and the title):
Now that the plot is done, how to download the results as an Excel file? We just need a function that transforms the pandas dataframe into a file and passes the link to download it to the UI:
import pandas as pdimport ioimport base64'''Write excel:parameter :param dtf: pandas table:return link'''def download_file(dtf): xlsx_io = io.BytesIO() writer = pd.ExcelWriter(xlsx_io) dtf.to_excel(writer, index=False) writer.save() xlsx_io.seek(0) media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' data = base64.b64encode(xlsx_io.read()).decode("utf-8") link = f'data:{media_type};base64,{data}' return link
On the front-end side, we have to add the HTML link for downloading and do the usual trick with a Callback:
As you may have noticed, the outputs (title, download, plot) are wrapped inside a Spinner, which renders this nice effect of loading state while elaborating the inputs:
Finally, we are ready to deploy this application. Here’s the full code of the dash app (you can check out the rest of the repo on GitHub):
Personally, I like Heroku for deploying prototypes. You’re gonna need to add a requirements.txt and a Procfile. If you need help with that, you can find detailed tutorials here and here.
This article has been an (almost) complete tutorial about how to build a nice web application with Python Dash. This app is pretty straightforward as it doesn’t have any DB and user login feature (maybe material for the next tutorial?). Here I just wanted to demonstrate how you can easily transform your ideas into a prototype to show the world. And now that you know how it works, you can develop your own app.
I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects.
👉 Let’s Connect 👈
This article is part of the series App Development with Python, see also:
|
[
{
"code": null,
"e": 225,
"s": 47,
"text": "Welcome to this hardcore Dash tutorial, following this article you will be able to produce and deploy a basic prototype (minimum viable product) for any kind of web application."
},
{
"code": null,
"e": 504,
"s": 225,
"text": "On the occasion of my best friend’s wedding, I tried to make his life easier with a dashboard for seat arrangement. While coding it, I realized this simple project contains all the key features necessary to develop a basic but good prototype. So I thought it’s worth sharing it."
},
{
"code": null,
"e": 645,
"s": 504,
"text": "Through this tutorial, I will explain how to build a complete Dash web application, using my Wedding Planner App as an example (link below)."
},
{
"code": null,
"e": 679,
"s": 645,
"text": "app-wedding-planner.herokuapp.com"
},
{
"code": null,
"e": 912,
"s": 679,
"text": "I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate this example (link to the full code below)."
},
{
"code": null,
"e": 923,
"s": 912,
"text": "github.com"
},
{
"code": null,
"e": 957,
"s": 923,
"text": "In particular, I will go through:"
},
{
"code": null,
"e": 982,
"s": 957,
"text": "Setup of the environment"
},
{
"code": null,
"e": 995,
"s": 982,
"text": "Data & Model"
},
{
"code": null,
"e": 1070,
"s": 995,
"text": "Prepare the basic structure of the dash application (Navbar, Body, Layout)"
},
{
"code": null,
"e": 1143,
"s": 1070,
"text": "Inputs (Form, Slider, Manual, File Upload, Change inputs after an event)"
},
{
"code": null,
"e": 1198,
"s": 1143,
"text": "Outputs (Plotly, File Download, Spinner while loading)"
},
{
"code": null,
"e": 1223,
"s": 1198,
"text": "Deploy the app on Heroku"
},
{
"code": null,
"e": 1298,
"s": 1223,
"text": "First of all, I will install the following libraries through the terminal:"
},
{
"code": null,
"e": 1535,
"s": 1298,
"text": "## for applicationdash==1.20.0dash-bootstrap-components==0.12.2## to produce random datanames==0.3.0## for data processingnumpy==1.19.5pandas==1.1.5## for plottingplotly==4.14.3## for read and write excel filesopenpyxl==3.0.7xlrd==1.2.0"
},
{
"code": null,
"e": 1800,
"s": 1535,
"text": "To make the dashboard look pretty, we’ll use Bootstrap, a CSS/JS framework that contains design templates for forms, buttons, navigation, and other interface components. The package Dash-Bootstrap-Components enables easy integration of Bootstrap into our dash app."
},
{
"code": null,
"e": 1895,
"s": 1800,
"text": "The names package generates random names and I’ll use it to create a dataset of random guests."
},
{
"code": null,
"e": 2034,
"s": 1895,
"text": "Please note that the latest version of xlrd (2.0.0) doesn’t accept .xlsx files, therefore use the 1.2.0 if you want to upload Excel files."
},
{
"code": null,
"e": 2290,
"s": 2034,
"text": "In a nutshell, the idea is to create a random guest list and run an optimization algorithm to arrange the seats. Alternatively, we’ll give users the possibility to upload their Excel file and the algorithm is going to use that instead of a random dataset."
},
{
"code": null,
"e": 3397,
"s": 2290,
"text": "import namesimport pandas as pdimport numpy as np'''Generate random guests list:parameter :param n: num - number of guests and length of dtf :param lst_categories: list - [\"family\", \"friends\", ...] :param n_rules: num - number of restrictions to apply (ex. if 1 then 2 guests can't be sit together):return dtf with guests'''def random_data(n=100, lst_categories=[\"family\",\"friends\", \"work\",\"university\",\"tennis\"], n_rules=0): ## basic list lst_dics = [] for i in range(n): name = names.get_full_name() category = np.random.choice(lst_categories) if len(lst_categories) > 0 else np.nan lst_dics.append({\"id\":i, \"name\":name, \"category\":category, \"avoid\":np.nan}) dtf = pd.DataFrame(lst_dics) ## add rules if n_rules > 0: for i in range(n_rules): choices = dtf[dtf[\"avoid\"].isna()][\"id\"] ids = np.random.choice(choices, size=2) dtf[\"avoid\"].iloc[ids[0]] = int(ids[1]) if int(ids[1]) != ids[0] else int(ids[1])+1 return dtf"
},
{
"code": null,
"e": 3453,
"s": 3397,
"text": "This function creates a table with guests' information."
},
{
"code": null,
"e": 3529,
"s": 3453,
"text": "I’ll use the “category” column to display the guests with different colors:"
},
{
"code": null,
"e": 3649,
"s": 3529,
"text": "The “avoid” column will be used to make sure that two guests that hate each other will not be placed at the same table."
},
{
"code": null,
"e": 3691,
"s": 3649,
"text": "The app will be arranging seats based on:"
},
{
"code": null,
"e": 3783,
"s": 3691,
"text": "a reward of +1 when two people belonging to the same category are seated next to each other"
},
{
"code": null,
"e": 3875,
"s": 3783,
"text": "a penalty of -1 when two people that want to avoid each other are placed at the same table."
},
{
"code": null,
"e": 3958,
"s": 3875,
"text": "This function returns the same dataframe with a new column for the table assigned:"
},
{
"code": null,
"e": 4137,
"s": 3958,
"text": "Now we can start with the cool part: building the application. I’m gonna divide it into 3 sections: the Navbar, the Body, the Layout. Moreover, each section will contain 3 parts:"
},
{
"code": null,
"e": 4325,
"s": 4137,
"text": "Input — the section of the app where the user can insert and select the parameters and data that will be used by the back-end to return the desired output (The Navbar doesn’t need Input)."
},
{
"code": null,
"e": 4399,
"s": 4325,
"text": "Output — the section of the app where the user can visualize the results."
},
{
"code": null,
"e": 4647,
"s": 4399,
"text": "Callbacks — a decorator wrapping a function, in which you need to specify outputs, inputs, and states; the latter allow you to pass along extra values without firing the callbacks (Callbacks may look scary but actually they are your best friends)."
},
{
"code": null,
"e": 5591,
"s": 4647,
"text": "# setupimport dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_bootstrap_components as dbc# App Instanceapp = dash.Dash(name=\"name\")app.title = \"name\"########################## Navbar ########################### Input# Outputnavbar = dbc.Nav()# Callbacks@app.callback()def function(): return 0########################## Body ########################### Inputinputs = dbc.FormGroup()# Outputbody = dbc.Row([ ## input dbc.Col(md=3), ## output dbc.Col(md=9)])# Callbacks@app.callback()def function(): return 0########################## App Layout ##########################app.layout = dbc.Container(fluid=True, children=[ html.H1(\"name\", id=\"nav-pills\"), navbar, html.Br(),html.Br(),html.Br(), body])########################## Run ##########################if __name__ == \"__main__\": app.run_server(debug=True)"
},
{
"code": null,
"e": 5850,
"s": 5591,
"text": "Let’s start with the style. The wonderful Dash-Bootstrap-Components offers a huge variety of predefined styles. You can check them out here. Once you choose one, you can insert it in the app instance as an external stylesheet. You can even use more than one:"
},
{
"code": null,
"e": 6055,
"s": 5850,
"text": "theme = dbc.themes.LUXcss = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'# App Instanceapp = dash.Dash(name=\"name\", external_stylesheets=[theme, css])"
},
{
"code": null,
"e": 6141,
"s": 6055,
"text": "Let’s move on to the top Navbar, I’ll include a link, a popover, and a dropdown menu."
},
{
"code": null,
"e": 6358,
"s": 6141,
"text": "As you can see, the navbar is cool and reactive on click, with pop-ups and a drop-down menu. The “Links” drop-down menu is easy as you don’t need a Callback to make it work, while the “About” popover is a bit tricky."
},
{
"code": null,
"e": 7012,
"s": 6358,
"text": "The navbar contains 3 nav-items: the logo, the “About” button, the drop-down menu. The “About” button incorporates 2 elements: a nav-link (which usually is used to navigate a multi-page application but in this case href=”/”), and a popover (green and red marks). Those 2 elements are called in the Callback as both outputs, inputs, and states like that if the “About” nav-link is clicked then popover becomes active and shows up. The python function about_popover() expects 3 arguments because the Callback has one input and two states, and returns 2 variables because the Callback has two outputs. When the app starts and the button is not clicked n=0."
},
{
"code": null,
"e": 7148,
"s": 7012,
"text": "Please note that the drop-down menu (blue part) includes fonts imported with the external stylesheet (i.e. className=”fa fa-linkedin”)."
},
{
"code": null,
"e": 7262,
"s": 7148,
"text": "The navbar we’ve just seen is one of the elements of the final Layout, together with the title and the main Body:"
},
{
"code": null,
"e": 7442,
"s": 7262,
"text": "Now, let’s talk about the elephant in the room... the main Body. It’s composed of the Inputs (left side) and the Outputs (right side), which interact together thanks to Callbacks."
},
{
"code": null,
"e": 7594,
"s": 7442,
"text": "Normally, inputs are wrapped in a Form group and are sent when the Form button is clicked. Sliders and manual inputs are the most common Form elements."
},
{
"code": null,
"e": 7638,
"s": 7594,
"text": "This is how you can create a normal slider:"
},
{
"code": null,
"e": 7744,
"s": 7638,
"text": "dcc.Slider(id=\"n-guests\", min=10, max=100, step=1, value=50, tooltip={'always_visible':False})"
},
{
"code": null,
"e": 7804,
"s": 7744,
"text": "and here’s how to force only specific values in the slider:"
},
{
"code": null,
"e": 7941,
"s": 7804,
"text": "dcc.Slider(id=\"n-iter\", min=10, max=1000, step=None, marks={10:\"10\", 100:\"100\", 500:\"500\", 1000:\"1000\"}, value=0),"
},
{
"code": null,
"e": 7972,
"s": 7941,
"text": "This is a simple manual input:"
},
{
"code": null,
"e": 8069,
"s": 7972,
"text": "dbc.Input(id=\"max-capacity\", placeholder=\"table capacity\", type=\"number\", value=\"10\"),"
},
{
"code": null,
"e": 8260,
"s": 8069,
"text": "Let’s increase the difficulty and tackle the “file Upload” situation. I’m going to give users the possibility to upload an Excel file containing a similar dataset that we generated randomly:"
},
{
"code": null,
"e": 8312,
"s": 8260,
"text": "When uploading a file, I want two things to happen:"
},
{
"code": null,
"e": 8410,
"s": 8312,
"text": "display the file name just to be sure that the right one was selected and it was loaded correctly"
},
{
"code": null,
"e": 8534,
"s": 8410,
"text": "hide the first two sliders because they are meant for a random simulation and become useless when a custom file is uploaded"
},
{
"code": null,
"e": 8637,
"s": 8534,
"text": "How do we achieve that? Easy, with a magic Callback that changes the CSS style of the HTML components:"
},
{
"code": null,
"e": 8781,
"s": 8637,
"text": "In order to use the uploaded file, we need to parse it and transform it into a pandas dataframe, and we’re going to use this function for that:"
},
{
"code": null,
"e": 9411,
"s": 8781,
"text": "import pandas as pdimport base64import io'''When a file is uploaded it contains \"contents\", \"filename\", \"date\":parameter :param contents: file :param filename: str:return pandas table'''def upload_file(contents, filename): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: return pd.read_csv(io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: return pd.read_excel(io.BytesIO(decoded)) except Exception as e: print(\"ERROR:\", e) return 'There was an error processing this file.'"
},
{
"code": null,
"e": 9537,
"s": 9411,
"text": "Before moving on with the Outputs, let’s recap what we have seen so far. Here’s the full code of the Inputs in the main Body:"
},
{
"code": null,
"e": 11569,
"s": 9537,
"text": "########################## Body ########################### Inputinputs = dbc.FormGroup([ ## hide these 2 inputs if file is uploaded html.Div(id='hide-seek', children=[ dbc.Label(\"Number of Guests\", html_for=\"n-guests\"), dcc.Slider(id=\"n-guests\", min=10, max=100, step=1, value=50, tooltip={'always_visible':False}), dbc.Label(\"Number of Rules\", html_for=\"n-rules\"), dcc.Slider(id=\"n-rules\", min=0, max=10, step=1, value=3, tooltip={'always_visible':False}) ], style={'display':'block'}), ## always visible dbc.Label(\"Number of Trials\", html_for=\"n-iter\"), dcc.Slider(id=\"n-iter\", min=10, max=1000, step=None, marks={10:\"10\", 100:\"100\", 500:\"500\", 1000:\"1000\"}, value=0), html.Br(), dbc.Label(\"Max Guests per Table\", html_for=\"max-capacity\"), dbc.Input(id=\"max-capacity\", placeholder=\"table capacity\", type=\"number\", value=\"10\"), ## upload a file html.Br(), dbc.Label(\"Or Upload your Excel\", html_for=\"upload-excel\"), dcc.Upload(id='upload-excel', children=html.Div([ 'Drag and Drop or ', html.A('Select Files')]), style={'width':'100%', 'height':'60px', 'lineHeight':'60px', 'borderWidth':'1px', 'borderStyle':'dashed', 'borderRadius':'5px', 'textAlign':'center', 'margin':'10px'} ), html.Div(id='excel-name', style={\"marginLeft\":\"20px\"}), ## run button html.Br(),html.Br(), dbc.Col(dbc.Button(\"run\", id=\"run\", color=\"primary\"))])# Callbacks@app.callback( output=[ Output(component_id=\"hide-seek\", component_property=\"style\"), Output(component_id=\"excel-name\", component_property=\"children\")], inputs=[ Input(component_id=\"upload-excel\",component_property=\"filename\")])def upload_event(filename): div = \"\" if filename is None else \"Use file \"+filename return {'display':'block'} if filename is None else {'display':'none'}, div"
},
{
"code": null,
"e": 11691,
"s": 11569,
"text": "The back-end shall produce 3 outputs: the title, a link to download the results as an Excel file, and obviously the plot."
},
{
"code": null,
"e": 12099,
"s": 11691,
"text": "Let’s get started with the plot made with Plotly. Essentially, there are two major modules of this amazing graphic library: plotly express and graph_objects. The former is a high-level graphic tool containing functions that can create entire figures at once (I find it similar to seaborn), while the latter allows you to build a figure brick by brick (it is in fact what plotly express runs under the hood)."
},
{
"code": null,
"e": 12318,
"s": 12099,
"text": "Plotly express is perfect when you want to style your data based on the value of specific columns, so here I’m going to use that, but if you want to see examples of plots made with graph_objects check out this article."
},
{
"code": null,
"e": 12337,
"s": 12318,
"text": "So... what’s this?"
},
{
"code": null,
"e": 12833,
"s": 12337,
"text": "It may look like a drawing but it is a proper geometric figure: it’s a scatter plot in which the color is based on the category guests belong to (family, friends, ...), the size is determined by whether a guest wants to avoid someone or not (basically I’m highlighting the problematic ones), and the facet component is linked to the table assigned to each guest. Facet plots are figures made up of multiple subplots which have the same set of axes, where each subplot shows a subset of the data."
},
{
"code": null,
"e": 13010,
"s": 12833,
"text": "First of all, I need to add the x and y coordinates for the plot using the circle equation: (x, y) = (r*cosθ, r*sinθ). Then I add the “size” column based on the “avoid” column:"
},
{
"code": null,
"e": 13672,
"s": 13010,
"text": "def prepare_data(dtf): ## mark the rules dtf[\"avoid\"] = dtf[\"avoid\"].apply(lambda x: dtf[dtf[\"id\"]==x][\"name\"].iloc[0] if pd.notnull(x) else \"none\") dtf[\"size\"] = dtf[\"avoid\"].apply(lambda x: 1 if x == \"none\" else 3) ## create axis dtf_out = pd.DataFrame() lst_tables = [] for t in dtf[\"table\"].unique(): dtf_t = dtf[dtf[\"table\"]==t] n = len(dtf_t) theta = np.linspace(0, 2*np.pi, n) dtf_t[\"x\"] = 1*np.cos(theta) dtf_t[\"y\"] = 1*np.sin(theta) dtf_out = dtf_out.append(dtf_t) return dtf_out.reset_index(drop=True).sort_values(\"table\")"
},
{
"code": null,
"e": 13807,
"s": 13672,
"text": "Then I can simply use plotly commands to produce figures and specify what information visualize when the mouse hovers over the points:"
},
{
"code": null,
"e": 14674,
"s": 13807,
"text": "import plotly.express as pxfig = px.scatter(dtf, x=\"x\", y=\"y\", color=\"category\", hover_name=\"name\", facet_col=\"table\", facet_col_wrap=3, size=\"size\", hover_data={\"x\":False, \"y\":False, \"category\":True, \"avoid\":True, \"size\":False, \"table\":False} ) fig.add_shape(type=\"circle\", opacity=0.1, fillcolor=\"black\", col=\"all\", row=\"all\", exclude_empty_subplots=True, x0=dtf[\"x\"].min(), y0=dtf[\"y\"].min(), x1=dtf[\"x\"].max(), y1=dtf[\"y\"].max() ) fig.update_layout(plot_bgcolor='white', legend={\"bordercolor\":\"black\", \"borderwidth\":1, \"orientation\":\"h\"} )"
},
{
"code": null,
"e": 14712,
"s": 14674,
"text": "Full code for plotly (and the title):"
},
{
"code": null,
"e": 14904,
"s": 14712,
"text": "Now that the plot is done, how to download the results as an Excel file? We just need a function that transforms the pandas dataframe into a file and passes the link to download it to the UI:"
},
{
"code": null,
"e": 15377,
"s": 14904,
"text": "import pandas as pdimport ioimport base64'''Write excel:parameter :param dtf: pandas table:return link'''def download_file(dtf): xlsx_io = io.BytesIO() writer = pd.ExcelWriter(xlsx_io) dtf.to_excel(writer, index=False) writer.save() xlsx_io.seek(0) media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' data = base64.b64encode(xlsx_io.read()).decode(\"utf-8\") link = f'data:{media_type};base64,{data}' return link"
},
{
"code": null,
"e": 15485,
"s": 15377,
"text": "On the front-end side, we have to add the HTML link for downloading and do the usual trick with a Callback:"
},
{
"code": null,
"e": 15654,
"s": 15485,
"text": "As you may have noticed, the outputs (title, download, plot) are wrapped inside a Spinner, which renders this nice effect of loading state while elaborating the inputs:"
},
{
"code": null,
"e": 15793,
"s": 15654,
"text": "Finally, we are ready to deploy this application. Here’s the full code of the dash app (you can check out the rest of the repo on GitHub):"
},
{
"code": null,
"e": 15980,
"s": 15793,
"text": "Personally, I like Heroku for deploying prototypes. You’re gonna need to add a requirements.txt and a Procfile. If you need help with that, you can find detailed tutorials here and here."
},
{
"code": null,
"e": 16393,
"s": 15980,
"text": "This article has been an (almost) complete tutorial about how to build a nice web application with Python Dash. This app is pretty straightforward as it doesn’t have any DB and user login feature (maybe material for the next tutorial?). Here I just wanted to demonstrate how you can easily transform your ideas into a prototype to show the world. And now that you know how it works, you can develop your own app."
},
{
"code": null,
"e": 16511,
"s": 16393,
"text": "I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects."
},
{
"code": null,
"e": 16529,
"s": 16511,
"text": "👉 Let’s Connect 👈"
}
] |
C Program for Fibonacci numbers - GeeksforGeeks
|
04 Dec, 2018
The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.
C
// Fibonacci Series using Recursion#include <stdio.h>int fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);} int main(){ int n = 9; printf("%d", fib(n)); getchar(); return 0;}
34
Time Complexity: T(n) = T(n-1) + T(n-2) which is exponential.We can observe that this implementation does a lot of repeated work (see the following recursion tree). So this is a bad implementation for nth Fibonacci number.
fib(5)
/
fib(4) fib(3)
/ /
fib(3) fib(2) fib(2) fib(1)
/ / /
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/
fib(1) fib(0)
Extra Space: O(n) if we consider the function call stack size, otherwise O(1).
Method 2 ( Use Dynamic Programming )We can avoid the repeated work done is the method 1 by storing the Fibonacci numbers calculated so far.
C
// Fibonacci Series using Dynamic Programming#include <stdio.h> int fib(int n){ /* Declare an array to store Fibonacci numbers. */ int f[n + 1]; int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { /* Add the previous 2 numbers in the series and store it */ f[i] = f[i - 1] + f[i - 2]; } return f[n];} int main(){ int n = 9; printf("%d", fib(n)); getchar(); return 0;}
34
Time Complexity: O(n)Extra Space: O(n)
Method 3 ( Space Optimized Method 2 )We can optimize the space used in method 2 by storing the previous two numbers only because that is all we need to get the next Fibonacci number in series.
C/C++
// Fibonacci Series using Space Optimized Method#include <stdio.h>int fib(int n){ int a = 0, b = 1, c, i; if (n == 0) return a; for (i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b;} int main(){ int n = 9; printf("%d", fib(n)); getchar(); return 0;}
34
Please refer complete article on Program for Fibonacci numbers for more details!
Fibonacci
C Programs
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
How to Append a Character to a String in C
Producer Consumer Problem in C
time() function in C
Program to find Prime Numbers Between given Interval
C Program to Swap two Numbers
Program to calculate First and Follow sets of given grammar
C program to find the length of a string
Flex (Fast Lexical Analyzer Generator )
Set, Clear and Toggle a given bit of a number in C
|
[
{
"code": null,
"e": 24722,
"s": 24694,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 24795,
"s": 24722,
"text": "The Fibonacci numbers are the numbers in the following integer sequence."
},
{
"code": null,
"e": 24850,
"s": 24795,
"text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........"
},
{
"code": null,
"e": 24948,
"s": 24850,
"text": "In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation"
},
{
"code": null,
"e": 24969,
"s": 24948,
"text": " Fn = Fn-1 + Fn-2"
},
{
"code": null,
"e": 24986,
"s": 24969,
"text": "with seed values"
},
{
"code": null,
"e": 25008,
"s": 24986,
"text": " F0 = 0 and F1 = 1."
},
{
"code": null,
"e": 25010,
"s": 25008,
"text": "C"
},
{
"code": "// Fibonacci Series using Recursion#include <stdio.h>int fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);} int main(){ int n = 9; printf(\"%d\", fib(n)); getchar(); return 0;}",
"e": 25227,
"s": 25010,
"text": null
},
{
"code": null,
"e": 25231,
"s": 25227,
"text": "34\n"
},
{
"code": null,
"e": 25454,
"s": 25231,
"text": "Time Complexity: T(n) = T(n-1) + T(n-2) which is exponential.We can observe that this implementation does a lot of repeated work (see the following recursion tree). So this is a bad implementation for nth Fibonacci number."
},
{
"code": null,
"e": 25785,
"s": 25454,
"text": " fib(5) \n / \n fib(4) fib(3) \n / / \n fib(3) fib(2) fib(2) fib(1)\n / / / \n fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)\n / \nfib(1) fib(0)\n"
},
{
"code": null,
"e": 25864,
"s": 25785,
"text": "Extra Space: O(n) if we consider the function call stack size, otherwise O(1)."
},
{
"code": null,
"e": 26004,
"s": 25864,
"text": "Method 2 ( Use Dynamic Programming )We can avoid the repeated work done is the method 1 by storing the Fibonacci numbers calculated so far."
},
{
"code": null,
"e": 26006,
"s": 26004,
"text": "C"
},
{
"code": "// Fibonacci Series using Dynamic Programming#include <stdio.h> int fib(int n){ /* Declare an array to store Fibonacci numbers. */ int f[n + 1]; int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { /* Add the previous 2 numbers in the series and store it */ f[i] = f[i - 1] + f[i - 2]; } return f[n];} int main(){ int n = 9; printf(\"%d\", fib(n)); getchar(); return 0;}",
"e": 26495,
"s": 26006,
"text": null
},
{
"code": null,
"e": 26499,
"s": 26495,
"text": "34\n"
},
{
"code": null,
"e": 26538,
"s": 26499,
"text": "Time Complexity: O(n)Extra Space: O(n)"
},
{
"code": null,
"e": 26731,
"s": 26538,
"text": "Method 3 ( Space Optimized Method 2 )We can optimize the space used in method 2 by storing the previous two numbers only because that is all we need to get the next Fibonacci number in series."
},
{
"code": null,
"e": 26737,
"s": 26731,
"text": "C/C++"
},
{
"code": "// Fibonacci Series using Space Optimized Method#include <stdio.h>int fib(int n){ int a = 0, b = 1, c, i; if (n == 0) return a; for (i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b;} int main(){ int n = 9; printf(\"%d\", fib(n)); getchar(); return 0;}",
"e": 27053,
"s": 26737,
"text": null
},
{
"code": null,
"e": 27057,
"s": 27053,
"text": "34\n"
},
{
"code": null,
"e": 27138,
"s": 27057,
"text": "Please refer complete article on Program for Fibonacci numbers for more details!"
},
{
"code": null,
"e": 27148,
"s": 27138,
"text": "Fibonacci"
},
{
"code": null,
"e": 27159,
"s": 27148,
"text": "C Programs"
},
{
"code": null,
"e": 27169,
"s": 27159,
"text": "Fibonacci"
},
{
"code": null,
"e": 27267,
"s": 27169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27308,
"s": 27267,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27351,
"s": 27308,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 27382,
"s": 27351,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27403,
"s": 27382,
"text": "time() function in C"
},
{
"code": null,
"e": 27456,
"s": 27403,
"text": "Program to find Prime Numbers Between given Interval"
},
{
"code": null,
"e": 27486,
"s": 27456,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 27546,
"s": 27486,
"text": "Program to calculate First and Follow sets of given grammar"
},
{
"code": null,
"e": 27587,
"s": 27546,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 27627,
"s": 27587,
"text": "Flex (Fast Lexical Analyzer Generator )"
}
] |
Extract Unique dictionary values in Python Program
|
When it is required to extract unique values from a dictionary, a dictionary is created, and the ‘sorted’ method and dictionary comprehension is used.
Below is a demonstration for the same −
Live Demo
my_dict = {'hi' : [5,3,8, 0],
'there' : [22, 51, 63, 77],
'how' : [7, 0, 22],
'are' : [12, 11, 45],
'you' : [56, 31, 89, 90]}
print("The dictionary is : ")
print(my_dict)
my_result = list(sorted({elem for val in my_dict.values() for elem in val}))
print("The unique values are : ")
print(my_result)
The dictionary is :
{'hi': [5, 3, 8, 0], 'there': [22, 51, 63, 77], 'how': [7, 0, 22], 'are': [12, 11, 45], 'you': [56, 31, 89, 90]}
The unique values are :
[0, 3, 5, 7, 8, 11, 12, 22, 31, 45, 51, 56, 63, 77, 89, 90]
A dictionary is defined, and is displayed on the console.
A dictionary is defined, and is displayed on the console.
The values of the dictionary are accessed using the ‘.values’ method.
The values of the dictionary are accessed using the ‘.values’ method.
It is converted into a list, and is assigned to a variable.
It is converted into a list, and is assigned to a variable.
This is displayed as output on the console.
This is displayed as output on the console.
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "When it is required to extract unique values from a dictionary, a dictionary is created, and the ‘sorted’ method and dictionary comprehension is used."
},
{
"code": null,
"e": 1253,
"s": 1213,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1264,
"s": 1253,
"text": " Live Demo"
},
{
"code": null,
"e": 1578,
"s": 1264,
"text": "my_dict = {'hi' : [5,3,8, 0],\n 'there' : [22, 51, 63, 77],\n 'how' : [7, 0, 22],\n 'are' : [12, 11, 45],\n 'you' : [56, 31, 89, 90]}\n\nprint(\"The dictionary is : \")\nprint(my_dict)\n\nmy_result = list(sorted({elem for val in my_dict.values() for elem in val}))\n\nprint(\"The unique values are : \")\nprint(my_result)"
},
{
"code": null,
"e": 1795,
"s": 1578,
"text": "The dictionary is :\n{'hi': [5, 3, 8, 0], 'there': [22, 51, 63, 77], 'how': [7, 0, 22], 'are': [12, 11, 45], 'you': [56, 31, 89, 90]}\nThe unique values are :\n[0, 3, 5, 7, 8, 11, 12, 22, 31, 45, 51, 56, 63, 77, 89, 90]"
},
{
"code": null,
"e": 1853,
"s": 1795,
"text": "A dictionary is defined, and is displayed on the console."
},
{
"code": null,
"e": 1911,
"s": 1853,
"text": "A dictionary is defined, and is displayed on the console."
},
{
"code": null,
"e": 1981,
"s": 1911,
"text": "The values of the dictionary are accessed using the ‘.values’ method."
},
{
"code": null,
"e": 2051,
"s": 1981,
"text": "The values of the dictionary are accessed using the ‘.values’ method."
},
{
"code": null,
"e": 2111,
"s": 2051,
"text": "It is converted into a list, and is assigned to a variable."
},
{
"code": null,
"e": 2171,
"s": 2111,
"text": "It is converted into a list, and is assigned to a variable."
},
{
"code": null,
"e": 2215,
"s": 2171,
"text": "This is displayed as output on the console."
},
{
"code": null,
"e": 2259,
"s": 2215,
"text": "This is displayed as output on the console."
}
] |
Class getTypeName() method in Java with Examples - GeeksforGeeks
|
25 Jan, 2022
The getTypeName() method of java.lang.Class class is used to get the type name of this class, which provides the information about this class’ type. The method returns the type name of this class in the form of String. Syntax:
public String getTypeName()
Parameter: This method does not accept any parameter.Return Value: This method returns the type name of this class in the form of String. Below programs demonstrate the getTypeName() method.Example 1:
Java
// Java program to demonstrate getTypeName() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the type name of myClass // using getTypeName() method System.out.println("TypeName of myClass: " + myClass.getTypeName()); }}
Class represented by myClass: class Test
TypeName of myClass: Test
Example 2:
Java
// Java program to demonstrate getTypeName() method import java.util.*; class Main { public Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the type name of myClass // using getTypeName() method System.out.println("TypeName of myClass: " + myClass.getTypeName()); }}
TypeName of myClass: Main$1Arr
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getTypeName–
saurabh1990aror
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 24176,
"s": 23948,
"text": "The getTypeName() method of java.lang.Class class is used to get the type name of this class, which provides the information about this class’ type. The method returns the type name of this class in the form of String. Syntax: "
},
{
"code": null,
"e": 24204,
"s": 24176,
"text": "public String getTypeName()"
},
{
"code": null,
"e": 24406,
"s": 24204,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns the type name of this class in the form of String. Below programs demonstrate the getTypeName() method.Example 1: "
},
{
"code": null,
"e": 24411,
"s": 24406,
"text": "Java"
},
{
"code": "// Java program to demonstrate getTypeName() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the type name of myClass // using getTypeName() method System.out.println(\"TypeName of myClass: \" + myClass.getTypeName()); }}",
"e": 24978,
"s": 24411,
"text": null
},
{
"code": null,
"e": 25045,
"s": 24978,
"text": "Class represented by myClass: class Test\nTypeName of myClass: Test"
},
{
"code": null,
"e": 25058,
"s": 25047,
"text": "Example 2:"
},
{
"code": null,
"e": 25063,
"s": 25058,
"text": "Java"
},
{
"code": "// Java program to demonstrate getTypeName() method import java.util.*; class Main { public Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the type name of myClass // using getTypeName() method System.out.println(\"TypeName of myClass: \" + myClass.getTypeName()); }}",
"e": 25622,
"s": 25063,
"text": null
},
{
"code": null,
"e": 25653,
"s": 25622,
"text": "TypeName of myClass: Main$1Arr"
},
{
"code": null,
"e": 25742,
"s": 25655,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getTypeName–"
},
{
"code": null,
"e": 25758,
"s": 25742,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 25773,
"s": 25758,
"text": "Java-Functions"
},
{
"code": null,
"e": 25791,
"s": 25773,
"text": "Java-lang package"
},
{
"code": null,
"e": 25807,
"s": 25791,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 25812,
"s": 25807,
"text": "Java"
},
{
"code": null,
"e": 25817,
"s": 25812,
"text": "Java"
},
{
"code": null,
"e": 25915,
"s": 25817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25930,
"s": 25915,
"text": "Stream In Java"
},
{
"code": null,
"e": 25976,
"s": 25930,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25997,
"s": 25976,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26016,
"s": 25997,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26033,
"s": 26016,
"text": "Generics in Java"
},
{
"code": null,
"e": 26063,
"s": 26033,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26106,
"s": 26063,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26135,
"s": 26106,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26156,
"s": 26135,
"text": "Introduction to Java"
}
] |
D3.js | d3.max() function - GeeksforGeeks
|
26 Jun, 2019
The d3.max() function in D3.js is used to returns the maximum value in the given array using natural order. If an array is empty then it returns undefined as output.
Syntax:
d3.max(Array)
Parameters: This function accepts a parameters Array which is an array of elements whose maximum value is to be calculated. Here elements might be integers or any strings.
Return Value: It returns the maximum value.
Below programs illustrate the d3.max() function in D3.js.Example 1:
<html> <head> <title>Getting maximum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = [10, 20, 30, 40, 50, 60]; var Array2 = [1, 2]; var Array3 = [0, 1.5, 6.8]; var Array4 = [.8, .08, .008]; // Calling to d3.max() function A = d3.max(Array1); B = d3.max(Array2); C = d3.max(Array3); D = d3.max(Array4); // Getting maximum value document.write(A + "<br>"); document.write(B + "<br>"); document.write(C + "<br>"); document.write(D + "<br>"); </script></body> </html>
Output:
60
2
6.8
0.8
Example 2:
<html> <head> <title>Getting maximum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = []; var Array2 = ["a", "b", "c"]; var Array3 = ["A", "B", "C"]; var Array4 = ["Geek", "Geeks", "GeeksforGeeks"]; // Calling to d3.max() function A = d3.max(Array1); B = d3.max(Array2); C = d3.max(Array3); D = d3.max(Array4); // Getting maximum value document.write(A + "<br>"); document.write(B + "<br>"); document.write(C + "<br>"); document.write(D + "<br>"); </script></body> </html>
Output:
undefined
c
C
GeeksforGeeks
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
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
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24222,
"s": 24194,
"text": "\n26 Jun, 2019"
},
{
"code": null,
"e": 24388,
"s": 24222,
"text": "The d3.max() function in D3.js is used to returns the maximum value in the given array using natural order. If an array is empty then it returns undefined as output."
},
{
"code": null,
"e": 24396,
"s": 24388,
"text": "Syntax:"
},
{
"code": null,
"e": 24410,
"s": 24396,
"text": "d3.max(Array)"
},
{
"code": null,
"e": 24582,
"s": 24410,
"text": "Parameters: This function accepts a parameters Array which is an array of elements whose maximum value is to be calculated. Here elements might be integers or any strings."
},
{
"code": null,
"e": 24626,
"s": 24582,
"text": "Return Value: It returns the maximum value."
},
{
"code": null,
"e": 24694,
"s": 24626,
"text": "Below programs illustrate the d3.max() function in D3.js.Example 1:"
},
{
"code": "<html> <head> <title>Getting maximum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = [10, 20, 30, 40, 50, 60]; var Array2 = [1, 2]; var Array3 = [0, 1.5, 6.8]; var Array4 = [.8, .08, .008]; // Calling to d3.max() function A = d3.max(Array1); B = d3.max(Array2); C = d3.max(Array3); D = d3.max(Array4); // Getting maximum value document.write(A + \"<br>\"); document.write(B + \"<br>\"); document.write(C + \"<br>\"); document.write(D + \"<br>\"); </script></body> </html>",
"e": 25380,
"s": 24694,
"text": null
},
{
"code": null,
"e": 25388,
"s": 25380,
"text": "Output:"
},
{
"code": null,
"e": 25401,
"s": 25388,
"text": "60\n2\n6.8\n0.8"
},
{
"code": null,
"e": 25412,
"s": 25401,
"text": "Example 2:"
},
{
"code": "<html> <head> <title>Getting maximum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = []; var Array2 = [\"a\", \"b\", \"c\"]; var Array3 = [\"A\", \"B\", \"C\"]; var Array4 = [\"Geek\", \"Geeks\", \"GeeksforGeeks\"]; // Calling to d3.max() function A = d3.max(Array1); B = d3.max(Array2); C = d3.max(Array3); D = d3.max(Array4); // Getting maximum value document.write(A + \"<br>\"); document.write(B + \"<br>\"); document.write(C + \"<br>\"); document.write(D + \"<br>\"); </script></body> </html>",
"e": 26106,
"s": 25412,
"text": null
},
{
"code": null,
"e": 26114,
"s": 26106,
"text": "Output:"
},
{
"code": null,
"e": 26142,
"s": 26114,
"text": "undefined\nc\nC\nGeeksforGeeks"
},
{
"code": null,
"e": 26148,
"s": 26142,
"text": "D3.js"
},
{
"code": null,
"e": 26159,
"s": 26148,
"text": "JavaScript"
},
{
"code": null,
"e": 26176,
"s": 26159,
"text": "Web Technologies"
},
{
"code": null,
"e": 26274,
"s": 26176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26319,
"s": 26274,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26380,
"s": 26319,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26452,
"s": 26380,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26498,
"s": 26452,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26539,
"s": 26498,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26581,
"s": 26539,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26614,
"s": 26581,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26657,
"s": 26614,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26719,
"s": 26657,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.