title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Minimum Cost To Make Two Strings Identical - GeeksforGeeks
|
04 Mar, 2022
Given two strings X and Y, and two values costX and costY. We need to find minimum cost required to make the given two strings identical. We can delete characters from both the strings. The cost of deleting a character from string X is costX and from Y is costY. Cost of removing all characters from a string is same.
Examples :
Input : X = "abcd", Y = "acdb", costX = 10, costY = 20.
Output: 30
For Making both strings identical we have to delete
character 'b' from both the string, hence cost will
be = 10 + 20 = 30.
Input : X = "ef", Y = "gh", costX = 10, costY = 20.
Output: 60
For making both strings identical, we have to delete 2-2
characters from both the strings, hence cost will be =
10 + 10 + 20 + 20 = 60.
This problem is a variation of Longest Common Subsequence ( LCS ). The idea is simple, we first find the length of longest common subsequence of strings X and Y. Now subtracting len_LCS with lengths of individual strings gives us number of characters to be removed to make them identical.
// Cost of making two strings identical is SUM of following two
// 1) Cost of removing extra characters (other than LCS)
// from X[]
// 2) Cost of removing extra characters (other than LCS)
// from Y[]
Minimum Cost to make strings identical = costX * (m - len_LCS) +
costY * (n - len_LCS).
m ==> Length of string X
m ==> Length of string Y
len_LCS ==> Length of LCS Of X and Y.
costX ==> Cost of removing a character from X[]
costY ==> Cost of removing a character from Y[]
Note that cost of removing all characters from a string
is same.
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
/* C++ code to find minimum cost to make two strings identical */#include<bits/stdc++.h>using namespace std; /* Returns length of LCS for X[0..m-1], Y[0..n-1] */int lcs(char *X, char *Y, int m, int n){ int L[m+1][n+1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} // Returns cost of making X[] and Y[] identical. costX is// cost of removing a character from X[] and costY is cost// of removing a character from Y[]/int findMinCost(char X[], char Y[], int costX, int costY){ // Find LCS of X[] and Y[] int m = strlen(X), n = strlen(Y); int len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical is SUM of // following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters from // second string return costX * (m - len_LCS) + costY * (n - len_LCS);} /* Driver program to test above function */int main(){ char X[] = "ef"; char Y[] = "gh"; cout << "Minimum Cost to make two strings " << " identical is = " << findMinCost(X, Y, 10, 20); return 0;}
// Java code to find minimum cost to// make two strings identicalimport java.io.*; class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { int L[][]=new int[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // Returns cost of making X[] and Y[] identical. // costX is cost of removing a character from X[] // and costY is cost of removing a character from Y[]/ static int findMinCost(String X, String Y, int costX, int costY) { // Find LCS of X[] and Y[] int m = X.length(); int n = Y.length(); int len_LCS; len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical // is SUM of following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters // from second string return costX * (m - len_LCS) + costY * (n - len_LCS); } // Driver code public static void main (String[] args) { String X = "ef"; String Y = "gh"; System.out.println( "Minimum Cost to make two strings " + " identical is = " + findMinCost(X, Y, 10, 20)); }} // This code is contributed by vt_m
# Python code to find minimum cost# to make two strings identical # Returns length of LCS for# X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): L = [[0 for i in range(n + 1)] for i in range(m + 1)] # Following steps build # L[m+1][n+1] in bottom # up fashion. Note that # L[i][j] contains length # of LCS of X[0..i-1] and Y[0..j-1] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 else if X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of # LCS for X[0..n-1] and Y[0..m-1] return L[m][n] # Returns cost of making X[]# and Y[] identical. costX is# cost of removing a character# from X[] and costY is cost# of removing a character from Y[]def findMinCost(X, Y, costX, costY): # Find LCS of X[] and Y[] m = len(X) n = len(Y) len_LCS =lcs(X, Y, m, n) # Cost of making two strings # identical is SUM of following two # 1) Cost of removing extra # characters from first string # 2) Cost of removing extra # characters from second string return (costX * (m - len_LCS) + costY * (n - len_LCS)) # Driver CodeX = "ef"Y = "gh"print('Minimum Cost to make two strings ', end = '')print('identical is = ', findMinCost(X, Y, 10, 20)) # This code is contributed# by sahilshelangia
// C# code to find minimum cost to// make two strings identicalusing System; class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { int [,]L = new int[m + 1, n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i,j] = 0; else if (X[i - 1] == Y[j - 1]) L[i,j] = L[i - 1,j - 1] + 1; else L[i,j] = Math.Max(L[i - 1,j], L[i,j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m,n]; } // Returns cost of making X[] and Y[] identical. // costX is cost of removing a character from X[] // and costY is cost of removing a character from Y[] static int findMinCost(String X, String Y, int costX, int costY) { // Find LCS of X[] and Y[] int m = X.Length; int n = Y.Length; int len_LCS; len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical // is SUM of following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters // from second string return costX * (m - len_LCS) + costY * (n - len_LCS); } // Driver code public static void Main () { String X = "ef"; String Y = "gh"; Console.Write( "Minimum Cost to make two strings " + " identical is = " + findMinCost(X, Y, 10, 20)); }} // This code is contributed by nitin mittal.
<?php/* PHP code to find minimum cost to make two strings identical */ /* Returns length of LCS for X[0..m-1], Y[0..n-1] */function lcs($X, $Y, $m, $n){ $L = array_fill(0,($m+1),array_fill(0,($n+1),NULL)); /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for ($i=0; $i<=$m; $i++) { for ($j=0; $j<=$n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i-1] == $Y[$j-1]) $L[$i][$j] = $L[$i-1][$j-1] + 1; else $L[$i][$j] = max($L[$i-1][$j], $L[$i][$j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return $L[$m][$n];} // Returns cost of making X[] and Y[] identical. costX is// cost of removing a character from X[] and costY is cost// of removing a character from Y[]/function findMinCost(&$X, &$Y,$costX, $costY){ // Find LCS of X[] and Y[] $m = strlen($X); $n = strlen($Y); $len_LCS = lcs($X, $Y, $m, $n); // Cost of making two strings identical is SUM of // following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters from // second string return $costX * ($m - $len_LCS) + $costY * ($n - $len_LCS);} /* Driver program to test above function */$X = "ef";$Y = "gh";echo "Minimum Cost to make two strings ". " identical is = " . findMinCost($X, $Y, 10, 20);return 0;?>
<script>// Javascript code to find minimum cost to// make two strings identical // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X, Y, m, n) { let L = new Array(m+1); for(let i = 0; i < m + 1; i++) { L[i] = new Array(n + 1); } for(let i = 0; i < m + 1; i++) { for(let j = 0; j < n + 1; j++) { L[i][j] = 0; } } /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // Returns cost of making X[] and Y[] identical. // costX is cost of removing a character from X[] // and costY is cost of removing a character from Y[]/ function findMinCost(X,Y,costX,costY) { // Find LCS of X[] and Y[] let m = X.length; let n = Y.length; let len_LCS; len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical // is SUM of following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters // from second string return costX * (m - len_LCS) + costY * (n - len_LCS); } // Driver code let X = "ef"; let Y = "gh"; document.write( "Minimum Cost to make two strings " + " identical is = " + findMinCost(X, Y, 10, 20)); // This code is contributed by avanitrachhadiya2155</script>
Output:
Minimum Cost to make two strings identical is = 60
This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team geeksforgeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
sahilshelangia
ukasp
avanitrachhadiya2155
sweetyty
simmytarika5
LCS
Dynamic Programming
Strings
Strings
Dynamic Programming
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Subset Sum Problem | DP-25
Write a program to print all permutations of a given string
Reverse a string in Java
KMP Algorithm for Pattern Searching
C++ Data Types
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 24841,
"s": 24813,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 25160,
"s": 24841,
"text": "Given two strings X and Y, and two values costX and costY. We need to find minimum cost required to make the given two strings identical. We can delete characters from both the strings. The cost of deleting a character from string X is costX and from Y is costY. Cost of removing all characters from a string is same. "
},
{
"code": null,
"e": 25172,
"s": 25160,
"text": "Examples : "
},
{
"code": null,
"e": 25568,
"s": 25172,
"text": "Input : X = \"abcd\", Y = \"acdb\", costX = 10, costY = 20.\nOutput: 30\nFor Making both strings identical we have to delete \ncharacter 'b' from both the string, hence cost will\nbe = 10 + 20 = 30.\n\nInput : X = \"ef\", Y = \"gh\", costX = 10, costY = 20.\nOutput: 60\nFor making both strings identical, we have to delete 2-2\ncharacters from both the strings, hence cost will be =\n 10 + 10 + 20 + 20 = 60."
},
{
"code": null,
"e": 25859,
"s": 25568,
"text": "This problem is a variation of Longest Common Subsequence ( LCS ). The idea is simple, we first find the length of longest common subsequence of strings X and Y. Now subtracting len_LCS with lengths of individual strings gives us number of characters to be removed to make them identical. "
},
{
"code": null,
"e": 26475,
"s": 25859,
"text": "// Cost of making two strings identical is SUM of following two\n// 1) Cost of removing extra characters (other than LCS) \n// from X[]\n// 2) Cost of removing extra characters (other than LCS) \n// from Y[]\nMinimum Cost to make strings identical = costX * (m - len_LCS) + \n costY * (n - len_LCS). \n\nm ==> Length of string X\nm ==> Length of string Y\nlen_LCS ==> Length of LCS Of X and Y.\ncostX ==> Cost of removing a character from X[]\ncostY ==> Cost of removing a character from Y[]\n\nNote that cost of removing all characters from a string\nis same. "
},
{
"code": null,
"e": 26519,
"s": 26475,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 26523,
"s": 26519,
"text": "C++"
},
{
"code": null,
"e": 26528,
"s": 26523,
"text": "Java"
},
{
"code": null,
"e": 26536,
"s": 26528,
"text": "Python3"
},
{
"code": null,
"e": 26539,
"s": 26536,
"text": "C#"
},
{
"code": null,
"e": 26543,
"s": 26539,
"text": "PHP"
},
{
"code": null,
"e": 26554,
"s": 26543,
"text": "Javascript"
},
{
"code": "/* C++ code to find minimum cost to make two strings identical */#include<bits/stdc++.h>using namespace std; /* Returns length of LCS for X[0..m-1], Y[0..n-1] */int lcs(char *X, char *Y, int m, int n){ int L[m+1][n+1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} // Returns cost of making X[] and Y[] identical. costX is// cost of removing a character from X[] and costY is cost// of removing a character from Y[]/int findMinCost(char X[], char Y[], int costX, int costY){ // Find LCS of X[] and Y[] int m = strlen(X), n = strlen(Y); int len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical is SUM of // following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters from // second string return costX * (m - len_LCS) + costY * (n - len_LCS);} /* Driver program to test above function */int main(){ char X[] = \"ef\"; char Y[] = \"gh\"; cout << \"Minimum Cost to make two strings \" << \" identical is = \" << findMinCost(X, Y, 10, 20); return 0;}",
"e": 28137,
"s": 26554,
"text": null
},
{
"code": "// Java code to find minimum cost to// make two strings identicalimport java.io.*; class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { int L[][]=new int[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // Returns cost of making X[] and Y[] identical. // costX is cost of removing a character from X[] // and costY is cost of removing a character from Y[]/ static int findMinCost(String X, String Y, int costX, int costY) { // Find LCS of X[] and Y[] int m = X.length(); int n = Y.length(); int len_LCS; len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical // is SUM of following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters // from second string return costX * (m - len_LCS) + costY * (n - len_LCS); } // Driver code public static void main (String[] args) { String X = \"ef\"; String Y = \"gh\"; System.out.println( \"Minimum Cost to make two strings \" + \" identical is = \" + findMinCost(X, Y, 10, 20)); }} // This code is contributed by vt_m",
"e": 30088,
"s": 28137,
"text": null
},
{
"code": "# Python code to find minimum cost# to make two strings identical # Returns length of LCS for# X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): L = [[0 for i in range(n + 1)] for i in range(m + 1)] # Following steps build # L[m+1][n+1] in bottom # up fashion. Note that # L[i][j] contains length # of LCS of X[0..i-1] and Y[0..j-1] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 else if X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of # LCS for X[0..n-1] and Y[0..m-1] return L[m][n] # Returns cost of making X[]# and Y[] identical. costX is# cost of removing a character# from X[] and costY is cost# of removing a character from Y[]def findMinCost(X, Y, costX, costY): # Find LCS of X[] and Y[] m = len(X) n = len(Y) len_LCS =lcs(X, Y, m, n) # Cost of making two strings # identical is SUM of following two # 1) Cost of removing extra # characters from first string # 2) Cost of removing extra # characters from second string return (costX * (m - len_LCS) + costY * (n - len_LCS)) # Driver CodeX = \"ef\"Y = \"gh\"print('Minimum Cost to make two strings ', end = '')print('identical is = ', findMinCost(X, Y, 10, 20)) # This code is contributed# by sahilshelangia",
"e": 31599,
"s": 30088,
"text": null
},
{
"code": "// C# code to find minimum cost to// make two strings identicalusing System; class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { int [,]L = new int[m + 1, n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i,j] = 0; else if (X[i - 1] == Y[j - 1]) L[i,j] = L[i - 1,j - 1] + 1; else L[i,j] = Math.Max(L[i - 1,j], L[i,j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m,n]; } // Returns cost of making X[] and Y[] identical. // costX is cost of removing a character from X[] // and costY is cost of removing a character from Y[] static int findMinCost(String X, String Y, int costX, int costY) { // Find LCS of X[] and Y[] int m = X.Length; int n = Y.Length; int len_LCS; len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical // is SUM of following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters // from second string return costX * (m - len_LCS) + costY * (n - len_LCS); } // Driver code public static void Main () { String X = \"ef\"; String Y = \"gh\"; Console.Write( \"Minimum Cost to make two strings \" + \" identical is = \" + findMinCost(X, Y, 10, 20)); }} // This code is contributed by nitin mittal.",
"e": 33522,
"s": 31599,
"text": null
},
{
"code": "<?php/* PHP code to find minimum cost to make two strings identical */ /* Returns length of LCS for X[0..m-1], Y[0..n-1] */function lcs($X, $Y, $m, $n){ $L = array_fill(0,($m+1),array_fill(0,($n+1),NULL)); /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for ($i=0; $i<=$m; $i++) { for ($j=0; $j<=$n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i-1] == $Y[$j-1]) $L[$i][$j] = $L[$i-1][$j-1] + 1; else $L[$i][$j] = max($L[$i-1][$j], $L[$i][$j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return $L[$m][$n];} // Returns cost of making X[] and Y[] identical. costX is// cost of removing a character from X[] and costY is cost// of removing a character from Y[]/function findMinCost(&$X, &$Y,$costX, $costY){ // Find LCS of X[] and Y[] $m = strlen($X); $n = strlen($Y); $len_LCS = lcs($X, $Y, $m, $n); // Cost of making two strings identical is SUM of // following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters from // second string return $costX * ($m - $len_LCS) + $costY * ($n - $len_LCS);} /* Driver program to test above function */$X = \"ef\";$Y = \"gh\";echo \"Minimum Cost to make two strings \". \" identical is = \" . findMinCost($X, $Y, 10, 20);return 0;?>",
"e": 35084,
"s": 33522,
"text": null
},
{
"code": "<script>// Javascript code to find minimum cost to// make two strings identical // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X, Y, m, n) { let L = new Array(m+1); for(let i = 0; i < m + 1; i++) { L[i] = new Array(n + 1); } for(let i = 0; i < m + 1; i++) { for(let j = 0; j < n + 1; j++) { L[i][j] = 0; } } /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // Returns cost of making X[] and Y[] identical. // costX is cost of removing a character from X[] // and costY is cost of removing a character from Y[]/ function findMinCost(X,Y,costX,costY) { // Find LCS of X[] and Y[] let m = X.length; let n = Y.length; let len_LCS; len_LCS = lcs(X, Y, m, n); // Cost of making two strings identical // is SUM of following two // 1) Cost of removing extra characters // from first string // 2) Cost of removing extra characters // from second string return costX * (m - len_LCS) + costY * (n - len_LCS); } // Driver code let X = \"ef\"; let Y = \"gh\"; document.write( \"Minimum Cost to make two strings \" + \" identical is = \" + findMinCost(X, Y, 10, 20)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 37178,
"s": 35084,
"text": null
},
{
"code": null,
"e": 37187,
"s": 37178,
"text": "Output: "
},
{
"code": null,
"e": 37240,
"s": 37187,
"text": " Minimum Cost to make two strings identical is = 60"
},
{
"code": null,
"e": 37472,
"s": 37240,
"text": "This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team geeksforgeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37485,
"s": 37472,
"text": "nitin mittal"
},
{
"code": null,
"e": 37500,
"s": 37485,
"text": "sahilshelangia"
},
{
"code": null,
"e": 37506,
"s": 37500,
"text": "ukasp"
},
{
"code": null,
"e": 37527,
"s": 37506,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 37536,
"s": 37527,
"text": "sweetyty"
},
{
"code": null,
"e": 37549,
"s": 37536,
"text": "simmytarika5"
},
{
"code": null,
"e": 37553,
"s": 37549,
"text": "LCS"
},
{
"code": null,
"e": 37573,
"s": 37553,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37581,
"s": 37573,
"text": "Strings"
},
{
"code": null,
"e": 37589,
"s": 37581,
"text": "Strings"
},
{
"code": null,
"e": 37609,
"s": 37589,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37613,
"s": 37609,
"text": "LCS"
},
{
"code": null,
"e": 37711,
"s": 37613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37720,
"s": 37711,
"text": "Comments"
},
{
"code": null,
"e": 37733,
"s": 37720,
"text": "Old Comments"
},
{
"code": null,
"e": 37764,
"s": 37733,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 37797,
"s": 37764,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 37816,
"s": 37797,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 37851,
"s": 37816,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 37878,
"s": 37851,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 37938,
"s": 37878,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37963,
"s": 37938,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37999,
"s": 37963,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 38014,
"s": 37999,
"text": "C++ Data Types"
}
] |
Java Program to Write a Paragraph in a Word Document - GeeksforGeeks
|
02 Dec, 2020
Java provides us various packages in-built into the environment, which facilitate the ease of reading, writing, and modifying the documents. The package org.apache.poi.xwpf.usermodel provides us the various features of formatting and appending the content in word documents. There are various classes available in this package like XWPFDocument to create a new word document and XWPFParagraph to create and write new paragraphs into the corresponding created document. File class can be used to create a file at the specified path-name and FileOutputStream to create a file stream connection.
Approaches: The following procedure is followed to add a paragraph in the document :
1. XWPFDocument: A Java class to create and work with .docx files. Each time a blank .docx document is created. An object of this class is created, to begin with, the process, using new XWPFDocument() in Java. A file output stream is also parallel created to create and append contents of the document to a file at the local system. A stream connection is established by using FileOutputStream class.
2. XWPFParagraph: A Java class to create paragraphs corresponding to the XWPFDocument created. Multiple paragraphs can be created in a single document, each of which is instantiated using the specified document. The following method is invoked using the created object of the XWPFDocument in Java.
Syntax:
1. createParagraph()
xwpfdocument.createParagraph()
Return type: An object of the class XWPF Paragraph.
2. createRun()
XWPFRun is a Java class to add a run to each of the paragraphs created in the document. XWPFRun simulates the addition of content to the paragraph using the createRun() method. The following method is invoked on the paragraph created in Java :
xwpfparagraph.createRun()
Return type: An object of the class XWPF Run.
3. setText()
The setText() method is invoked over this created run object to add content in Java :
xwpfrun.setText(content)
Arguments: The content in string form is accepted as an argument.
Return type: Doesn’t return anything.
Note: The content specified in the document is then written to the file stream connection using the stream connection object and appended by invoking write() method over the XWPFDocument object. And, then the connection is closed successively.
Implementation: Java Programming to Write a paragraph in a Word Document
Java
// Java Programming to Write a paragraph in a Word Document // Importing required packagesimport java.io.File;import java.io.FileOutputStream;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.poi.xwpf.usermodel.XWPFRun; public class GFG { // Main driver method public static void main(String[] args) throws Exception { // Create a blank document XWPFDocument xwpfdocument = new XWPFDocument(); // Create a blank file at C: File file = new File("C:/addParagraph.docx"); // Create a file output stream connection FileOutputStream ostream = new FileOutputStream(file); /* Create a new paragraph using the document */ // CreateParagraph() method is used // to instantiate a new paragraph XWPFParagraph para = xwpfdocument.createParagraph(); // CreateRun method appends a new run to the // paragraph created XWPFRun xwpfrun = para.createRun(); // SetText sets the text to the run // created using XWPF run xwpfrun.setText( "Geeks for Geeks is a computer science portal which aims " + "to provide all in one platform for learning and " + "practicing.We can learn multiple programming languages here. "); // Write content set using XWPF classes available xwpfdocument.write(ostream); // Close connection ostream.close(); }}
Output: The program produces the following file in the local directory:
Picked
Java
Java Programs
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
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 24542,
"s": 23948,
"text": "Java provides us various packages in-built into the environment, which facilitate the ease of reading, writing, and modifying the documents. The package org.apache.poi.xwpf.usermodel provides us the various features of formatting and appending the content in word documents. There are various classes available in this package like XWPFDocument to create a new word document and XWPFParagraph to create and write new paragraphs into the corresponding created document. File class can be used to create a file at the specified path-name and FileOutputStream to create a file stream connection. "
},
{
"code": null,
"e": 24628,
"s": 24542,
"text": "Approaches: The following procedure is followed to add a paragraph in the document : "
},
{
"code": null,
"e": 25030,
"s": 24628,
"text": "1. XWPFDocument: A Java class to create and work with .docx files. Each time a blank .docx document is created. An object of this class is created, to begin with, the process, using new XWPFDocument() in Java. A file output stream is also parallel created to create and append contents of the document to a file at the local system. A stream connection is established by using FileOutputStream class. "
},
{
"code": null,
"e": 25328,
"s": 25030,
"text": "2. XWPFParagraph: A Java class to create paragraphs corresponding to the XWPFDocument created. Multiple paragraphs can be created in a single document, each of which is instantiated using the specified document. The following method is invoked using the created object of the XWPFDocument in Java."
},
{
"code": null,
"e": 25337,
"s": 25328,
"text": "Syntax: "
},
{
"code": null,
"e": 25358,
"s": 25337,
"text": "1. createParagraph()"
},
{
"code": null,
"e": 25389,
"s": 25358,
"text": "xwpfdocument.createParagraph()"
},
{
"code": null,
"e": 25442,
"s": 25389,
"text": "Return type: An object of the class XWPF Paragraph. "
},
{
"code": null,
"e": 25457,
"s": 25442,
"text": "2. createRun()"
},
{
"code": null,
"e": 25702,
"s": 25457,
"text": "XWPFRun is a Java class to add a run to each of the paragraphs created in the document. XWPFRun simulates the addition of content to the paragraph using the createRun() method. The following method is invoked on the paragraph created in Java : "
},
{
"code": null,
"e": 25728,
"s": 25702,
"text": "xwpfparagraph.createRun()"
},
{
"code": null,
"e": 25774,
"s": 25728,
"text": "Return type: An object of the class XWPF Run."
},
{
"code": null,
"e": 25787,
"s": 25774,
"text": "3. setText()"
},
{
"code": null,
"e": 25874,
"s": 25787,
"text": "The setText() method is invoked over this created run object to add content in Java : "
},
{
"code": null,
"e": 25899,
"s": 25874,
"text": "xwpfrun.setText(content)"
},
{
"code": null,
"e": 25966,
"s": 25899,
"text": "Arguments: The content in string form is accepted as an argument. "
},
{
"code": null,
"e": 26005,
"s": 25966,
"text": "Return type: Doesn’t return anything. "
},
{
"code": null,
"e": 26249,
"s": 26005,
"text": "Note: The content specified in the document is then written to the file stream connection using the stream connection object and appended by invoking write() method over the XWPFDocument object. And, then the connection is closed successively."
},
{
"code": null,
"e": 26322,
"s": 26249,
"text": "Implementation: Java Programming to Write a paragraph in a Word Document"
},
{
"code": null,
"e": 26327,
"s": 26322,
"text": "Java"
},
{
"code": "// Java Programming to Write a paragraph in a Word Document // Importing required packagesimport java.io.File;import java.io.FileOutputStream;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.poi.xwpf.usermodel.XWPFRun; public class GFG { // Main driver method public static void main(String[] args) throws Exception { // Create a blank document XWPFDocument xwpfdocument = new XWPFDocument(); // Create a blank file at C: File file = new File(\"C:/addParagraph.docx\"); // Create a file output stream connection FileOutputStream ostream = new FileOutputStream(file); /* Create a new paragraph using the document */ // CreateParagraph() method is used // to instantiate a new paragraph XWPFParagraph para = xwpfdocument.createParagraph(); // CreateRun method appends a new run to the // paragraph created XWPFRun xwpfrun = para.createRun(); // SetText sets the text to the run // created using XWPF run xwpfrun.setText( \"Geeks for Geeks is a computer science portal which aims \" + \"to provide all in one platform for learning and \" + \"practicing.We can learn multiple programming languages here. \"); // Write content set using XWPF classes available xwpfdocument.write(ostream); // Close connection ostream.close(); }}",
"e": 27831,
"s": 26327,
"text": null
},
{
"code": null,
"e": 27903,
"s": 27831,
"text": "Output: The program produces the following file in the local directory:"
},
{
"code": null,
"e": 27910,
"s": 27903,
"text": "Picked"
},
{
"code": null,
"e": 27915,
"s": 27910,
"text": "Java"
},
{
"code": null,
"e": 27929,
"s": 27915,
"text": "Java Programs"
},
{
"code": null,
"e": 27934,
"s": 27929,
"text": "Java"
},
{
"code": null,
"e": 28032,
"s": 27934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28047,
"s": 28032,
"text": "Stream In Java"
},
{
"code": null,
"e": 28093,
"s": 28047,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28114,
"s": 28093,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28133,
"s": 28114,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28163,
"s": 28133,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28207,
"s": 28163,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28233,
"s": 28207,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28267,
"s": 28233,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28314,
"s": 28267,
"text": "Implementing a Linked List in Java using Class"
}
] |
Get table column names in alphabetical order in MySQL?
|
To get the table column names in alphabetical order, you need to use ORDER BY. The syntax
is as follows −
SELECT anyReferenceName.COLUMN_NAME FROM
INFORMATION_SCHEMA.COLUMNS anyReferenceName
WHERE anyReferenceName.TABLE_NAME = ’yourTableName’
ORDER BY anyReferenceName.COLUMN_NAME
First, we need to get all the columns and then we need to use ORDER BY. In the above query,
we are getting all columns using INFORMATION_SCHEMA.COLUMNS.
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table ColumnsOrder
-> (
-> StudentFirstName varchar(20),
-> Id int,
-> StudentAge int,
-> StudentLastName varchar(20)
-> );
Query OK, 0 rows affected (0.90 sec)
Implement the above syntax to get table columns in alphabetical order.
Case 1 − By default, ORDER BY gives ascending order.
The query is as follows −
mysql> select ref.column_name from information_schema.columns ref
-> where ref.table_name = 'ColumnsOrder'
-> order by ref.column_name;
The following is the output −
+------------------+
| COLUMN_NAME |
+------------------+
| Id |
| StudentAge |
| StudentFirstName |
| StudentLastName |
+------------------+
4 rows in set (0.13 sec)
Case 2 − If you want in descending order, then use DESC command in the end.
The query is as follows −
mysql> select ref.column_name from information_schema.columns ref
-> where ref.table_name = 'ColumnsOrder'
-> order by ref.column_name desc;
The following is the output −
+------------------+
| COLUMN_NAME |
+------------------+
| StudentLastName |
| StudentFirstName |
| StudentAge |
| Id |
+------------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "To get the table column names in alphabetical order, you need to use ORDER BY. The syntax\nis as follows −"
},
{
"code": null,
"e": 1343,
"s": 1168,
"text": "SELECT anyReferenceName.COLUMN_NAME FROM\nINFORMATION_SCHEMA.COLUMNS anyReferenceName\nWHERE anyReferenceName.TABLE_NAME = ’yourTableName’\nORDER BY anyReferenceName.COLUMN_NAME"
},
{
"code": null,
"e": 1496,
"s": 1343,
"text": "First, we need to get all the columns and then we need to use ORDER BY. In the above query,\nwe are getting all columns using INFORMATION_SCHEMA.COLUMNS."
},
{
"code": null,
"e": 1595,
"s": 1496,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1788,
"s": 1595,
"text": "mysql> create table ColumnsOrder\n -> (\n -> StudentFirstName varchar(20),\n -> Id int,\n -> StudentAge int,\n -> StudentLastName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.90 sec)"
},
{
"code": null,
"e": 1859,
"s": 1788,
"text": "Implement the above syntax to get table columns in alphabetical order."
},
{
"code": null,
"e": 1912,
"s": 1859,
"text": "Case 1 − By default, ORDER BY gives ascending order."
},
{
"code": null,
"e": 1938,
"s": 1912,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2080,
"s": 1938,
"text": "mysql> select ref.column_name from information_schema.columns ref\n -> where ref.table_name = 'ColumnsOrder'\n -> order by ref.column_name;"
},
{
"code": null,
"e": 2110,
"s": 2080,
"text": "The following is the output −"
},
{
"code": null,
"e": 2303,
"s": 2110,
"text": "+------------------+\n| COLUMN_NAME |\n+------------------+\n| Id |\n| StudentAge |\n| StudentFirstName |\n| StudentLastName |\n+------------------+\n4 rows in set (0.13 sec)"
},
{
"code": null,
"e": 2380,
"s": 2303,
"text": "Case 2 − If you want in descending order, then use DESC command in the end. "
},
{
"code": null,
"e": 2406,
"s": 2380,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2553,
"s": 2406,
"text": "mysql> select ref.column_name from information_schema.columns ref\n -> where ref.table_name = 'ColumnsOrder'\n -> order by ref.column_name desc;"
},
{
"code": null,
"e": 2583,
"s": 2553,
"text": "The following is the output −"
},
{
"code": null,
"e": 2776,
"s": 2583,
"text": "+------------------+\n| COLUMN_NAME |\n+------------------+\n| StudentLastName |\n| StudentFirstName |\n| StudentAge |\n| Id |\n+------------------+\n4 rows in set (0.00 sec)"
}
] |
11 Essential Code Blocks for EDA (Exploratory Data Analysis) | by Susan Maina | Jan, 2021 | Towards Data Science | Towards Data Science
|
Exploratory Data Analysis, or EDA, is one of the first steps of the data science process. It involves learning as much as possible about the data, without spending too much time. Here, you get an instinctive as well as a high-level practical understanding of the data. By the end of this process, you should have a general idea of the structure of the data set, some cleaning ideas, the target variable and, possible modeling techniques.
There are some general strategies to quickly perform EDA in most problems. In this article, I will use the Melbourne Housing snapshot dataset from Kaggle to demonstrate the 11 blocks of code you can use to perform a satisfactory exploratory data analysis. The dataset includes Address, Type of Real estate, Suburb, Method of Selling, Rooms, Price(the target feature), Real Estate Agent (SellerG), Date of Sale and, Distance from C.B.D. You can follow along by downloading the dataset here.
Note: If your project involves predicting a binary or multi-class feature, you can follow this article.
towardsdatascience.com
The first step is importing the libraries required. We will need Pandas, Numpy, matplotlib and seaborn. To make sure all our columns are displayed, use pd.set_option(’display.max_columns’, 100) . By default, pandas displays 20 columns and hides the rest.
import pandas as pdpd.set_option('display.max_columns',100)import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snssns.set_style('darkgrid')
Panda’s pd.read_csv(path) reads in the csv file as a DataFrame.
data = pd.read_csv('melb_data.csv')
Shape (dimensions) of the DataFrame
Shape (dimensions) of the DataFrame
The .shape attribute of a Pandas DataFrame gives an overall structure of the data. It returns a tuple of length 2 that translates to how many rows of observations and columns the dataset has.
data.shape### Results(13580, 21)
We can see that the dataset has 13,580 observations and 21 features, and one of those features is the target variable.
2. Data types of the various columns
The DataFrame’s .dtypes attribute displays the data types of the columns as a Panda’s Series (Series means a column of values and their indices).
data.dtypes### ResultsSuburb objectAddress objectRooms int64Type objectPrice float64Method objectSellerG objectDate objectDistance float64Postcode float64Bedroom2 float64Bathroom float64Car float64Landsize float64BuildingArea float64YearBuilt float64CouncilArea objectLattitude float64Longtitude float64Regionname objectPropertycount float64dtype: object
We observe that our dataset has a combination of categorical (object) and numeric (float and int) features. At this point, I went back to the Kaggle page for an understanding of the columns and their meanings. Check out the table of columns and their definitions here created with Datawrapper.
What to look out for;
Numeric features that should be categorical and vice versa.
From a quick analysis, I did not find any mismatch for the datatypes. This makes sense as this dataset version is a cleaned snapshot of the original Melbourne data.
3. Display a few rows
The Pandas DataFrame has very handy functions for displaying a few observations. data.head()displays the first 5 observations, data.tail() the last 5, and data.sample() an observation chosen randomly from the dataset. You can display 5 random observations using data.sample(5)
data.head()data.tail()data.sample(5)
What to look out for:
Can you understand the column names? Do they make sense? (Check with the variable definitions again if needed)
Do the values in these columns make sense?
Are there significant missing values (NaN) sighted?
What types of classes do the categorical features have?
My insights; the Postcode and Propertycount features both changed according to the Suburb feature. Also, there were significant missing values for the BuildingArea and YearBuilt.
This refers to how the values in a feature are distributed, or how often they occur. For numeric features, we’ll see how many times groups of numbers appear in a particular column, and for categorical features, the classes for each column and their frequency. We will use both graphs and actual summary statistics. The graphs enable us to get an overall idea of the distributions while the statistics give us factual numbers. These two strategies are both recommended as they complement each other.
4. Plot each numeric feature
We will use Pandas histogram. A histogram groups numbers into ranges (or bins) and the height of a bar shows how many numbers fall in that range. df.hist() plots a histogram of the data’s numeric features in a grid. We will also provide the figsize and xrot arguments to increase the grid size and rotate the x-axis by 45 degrees.
data.hist(figsize=(14,14), xrot=45)plt.show()
What to look out for:
Possible outliers that cannot be explained or might be measurement errors
Numeric features that should be categorical. For example, Gender represented by 1 and 0.
Boundaries that do not make sense such as percentage values> 100.
From the histogram, I noted that BuildingArea and LandSize had potential outliers to the right. Our target feature Price was also highly skewed to the right. I also noted that YearBuilt was very skewed to the left and the boundary started at the year 1200 which was odd. Let’s move on to the summary statistics for a clearer picture.
5. Summary statistics of the numerical features
Now that we have an intuitive feel of the numeric features, we will look at actual statistics using df.describe()which displays their summary statistics.
data.describe()
We can see for each numeric feature, the count of values in it, the mean value, std or standard deviation, minimum value, the 25th percentile, the 50th percentile or median, the 75th percentile, and the maximum value. From the count we can also identify the features with missing values; their count is not equal to the total number of rows of the dataset. These are Car, LandSize and YearBuilt.
I noted that the minimum for both the LandSize and BuildingArea is 0. We also see that the Price ranges from 85,000 to 9,000,000 which is a big range. We will explore these columns in detailed analysis later in the project.
Looking at the YearBuilt feature, however, we note that the minimum year is 1196. This could be a possible data entry error that will be removed during cleaning.
6. Summary statistics of the categorical features
For categorical features, it is important to show the summary statistics before we plot graphs because some features have a lot of unique classes (like we will see for the Address) and the classes would be unreadable if visualized on a countplot.
To check the summary statistics of only the categorical features, we will use df.describe(include=’object’)
data.describe(include='object')
This table is a bit different from the one for numeric features. Here, we get the count of the values of each feature, the number of unique classes, the top most frequent class, and how frequently that class occurs in the data set.
We note that some classes have a lot of unique values such as Address, followed by Suburb and SellerG. From these findings, I will only plot the columns with 10 or less unique classes. We also note that CouncilArea has missing values.
7. Plot each categorical feature
Using the statistics above, we note that Type, Method and Regionname have less than 10 classes and can be effectively visualized. We will plot these features using the Seaborn countplot, which is like a histogram for categorical variables. Each bar in a countplot represents a unique class.
I created a For loop. For each categorical feature, a countplot will be displayed to show how the classes are distributed for that feature. The line df.select_dtypes(include=’object’) selects the categorical columns with their values and displays them. We will also include an If-statement so as to pick only the three columns with 10 or fewer classes using the line Series.nunique() < 10. Read the .nunique() documentation here.
for column in data.select_dtypes(include='object'): if data[column].nunique() < 10: sns.countplot(y=column, data=data) plt.show()
What to look out for:
Sparse classes which have the potential to affect a model’s performance.
Mistakes in labeling of the classes, for example 2 exact classes with minor spelling differences.
We note that Regionname has some sparse classes which might need to be merged or re-assigned during modeling.
Segmentation allows us to cut the data and observe the relationship between categorical and numeric features.
8. Segment the target variable by categorical features.
Here, we will compare the target feature, Price, between the various classes of our main categorical features (Type, Method and Regionname) and see how the Price changes with the classes.
We use the Seaborn boxplot which plots the distribution of Price across the classes of categorical features. This tutorial, from where I borrowed the Image below, explains the boxplot’s features clearly. The dots at both ends represent outliers.
Again, I used a for loop to plot a boxplot of each categorical feature with Price.
for column in data.select_dtypes(include=’object’): if data[column].nunique() < 10: sns.boxplot(y=column, x=’Price’, data=data) plt.show()
What to look out for:
which classes most affect the target variables.
Note how the Price is still sparsely distributed among the 3 sparse classes of Regionname seen earlier, strengthening our case against these classes.
Also note how the SA class (the least frequent Method class) commands high prices, almost similar prices of the most frequently occurring class S.
9. Group numeric features by each categorical feature.
Here we will see how all the other numeric features, not just Price, change with each categorical feature by summarizing the numeric features across the classes. We use the Dataframe’s groupby function to group the data by a category and calculate a metric (such as mean, median, min, std, etc) across the various numeric features.
For only the 3 categorical features with less than 10 classes, we group the data, then calculate the mean across the numeric features. We use display() which results to a cleaner table than print().
for column in data.select_dtypes(include='object'): if data[column].nunique() < 10: display(data.groupby(column).mean())
We get to compare the Type, Method and Regionname classes across the numeric features to see how they are distributed.
10. Correlations matrix for the different numerical features
A correlation is a value between -1 and 1 that amounts to how closely values of two separate features move simultaneously. A positive correlation means that as one feature increases the other one also increases, while a negative correlation means one feature increases as the other decreases. Correlations close to 0 indicate a weak relationship while closer to -1 or 1 signifies a strong relationship.
We will use df.corr() to calculate the correlations between the numeric features and it returns a DataFrame.
corrs = data.corr()corrs
This might not mean much now, so let us plot a heatmap to visualize the correlations.
11. Heatmap of the correlations
We will use a Seaborn heatmap to plot the grid as a rectangular color-coded matrix. We use sns.heatmap(corrs, cmap=’RdBu_r’,annot=True).
The cmap=‘RdBu_r’ argument tells the heatmap what colour palette to use. A high positive correlation appears as dark red and a high negative correlation as dark blue. Closer to white signifies a weak relationship. Read this nice tutorial for other color palettes. annot=True includes the values of the correlations in the boxes for easier reading and interpretation.
plt.figure(figsize=(10,8))sns.heatmap(corrs, cmap='RdBu_r', annot=True)plt.show()
What to look out for:
Strongly correlated features; either dark red (positive) or dark blue(negative).
Target variable; If it has strong positive or negative relationships with other features.
We note that Rooms, Bedrooms2, Bathrooms, and Price have strong positive relationships. On the other hand, Price, our target feature, has a slightly weak negative correlation with YearBuilt and an even weaker negative relationship with Distance from CBD.
In this article, we explored the Melbourne dataset and got a high-level understanding of the structure and its features. At this stage, we do not need to be 100% comprehensive because in future stages we will explore the data more elaborately. You can get the full code on Github here. I will be uploading the dataset’s cleaning concepts soon.
Also check out the 13 key code blocks for EDA - classification task for dealing with binary or multi-class prediction problems.
|
[
{
"code": null,
"e": 610,
"s": 172,
"text": "Exploratory Data Analysis, or EDA, is one of the first steps of the data science process. It involves learning as much as possible about the data, without spending too much time. Here, you get an instinctive as well as a high-level practical understanding of the data. By the end of this process, you should have a general idea of the structure of the data set, some cleaning ideas, the target variable and, possible modeling techniques."
},
{
"code": null,
"e": 1100,
"s": 610,
"text": "There are some general strategies to quickly perform EDA in most problems. In this article, I will use the Melbourne Housing snapshot dataset from Kaggle to demonstrate the 11 blocks of code you can use to perform a satisfactory exploratory data analysis. The dataset includes Address, Type of Real estate, Suburb, Method of Selling, Rooms, Price(the target feature), Real Estate Agent (SellerG), Date of Sale and, Distance from C.B.D. You can follow along by downloading the dataset here."
},
{
"code": null,
"e": 1204,
"s": 1100,
"text": "Note: If your project involves predicting a binary or multi-class feature, you can follow this article."
},
{
"code": null,
"e": 1227,
"s": 1204,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1482,
"s": 1227,
"text": "The first step is importing the libraries required. We will need Pandas, Numpy, matplotlib and seaborn. To make sure all our columns are displayed, use pd.set_option(’display.max_columns’, 100) . By default, pandas displays 20 columns and hides the rest."
},
{
"code": null,
"e": 1655,
"s": 1482,
"text": "import pandas as pdpd.set_option('display.max_columns',100)import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snssns.set_style('darkgrid')"
},
{
"code": null,
"e": 1719,
"s": 1655,
"text": "Panda’s pd.read_csv(path) reads in the csv file as a DataFrame."
},
{
"code": null,
"e": 1755,
"s": 1719,
"text": "data = pd.read_csv('melb_data.csv')"
},
{
"code": null,
"e": 1791,
"s": 1755,
"text": "Shape (dimensions) of the DataFrame"
},
{
"code": null,
"e": 1827,
"s": 1791,
"text": "Shape (dimensions) of the DataFrame"
},
{
"code": null,
"e": 2019,
"s": 1827,
"text": "The .shape attribute of a Pandas DataFrame gives an overall structure of the data. It returns a tuple of length 2 that translates to how many rows of observations and columns the dataset has."
},
{
"code": null,
"e": 2052,
"s": 2019,
"text": "data.shape### Results(13580, 21)"
},
{
"code": null,
"e": 2171,
"s": 2052,
"text": "We can see that the dataset has 13,580 observations and 21 features, and one of those features is the target variable."
},
{
"code": null,
"e": 2208,
"s": 2171,
"text": "2. Data types of the various columns"
},
{
"code": null,
"e": 2354,
"s": 2208,
"text": "The DataFrame’s .dtypes attribute displays the data types of the columns as a Panda’s Series (Series means a column of values and their indices)."
},
{
"code": null,
"e": 2894,
"s": 2354,
"text": "data.dtypes### ResultsSuburb objectAddress objectRooms int64Type objectPrice float64Method objectSellerG objectDate objectDistance float64Postcode float64Bedroom2 float64Bathroom float64Car float64Landsize float64BuildingArea float64YearBuilt float64CouncilArea objectLattitude float64Longtitude float64Regionname objectPropertycount float64dtype: object"
},
{
"code": null,
"e": 3188,
"s": 2894,
"text": "We observe that our dataset has a combination of categorical (object) and numeric (float and int) features. At this point, I went back to the Kaggle page for an understanding of the columns and their meanings. Check out the table of columns and their definitions here created with Datawrapper."
},
{
"code": null,
"e": 3210,
"s": 3188,
"text": "What to look out for;"
},
{
"code": null,
"e": 3270,
"s": 3210,
"text": "Numeric features that should be categorical and vice versa."
},
{
"code": null,
"e": 3435,
"s": 3270,
"text": "From a quick analysis, I did not find any mismatch for the datatypes. This makes sense as this dataset version is a cleaned snapshot of the original Melbourne data."
},
{
"code": null,
"e": 3457,
"s": 3435,
"text": "3. Display a few rows"
},
{
"code": null,
"e": 3734,
"s": 3457,
"text": "The Pandas DataFrame has very handy functions for displaying a few observations. data.head()displays the first 5 observations, data.tail() the last 5, and data.sample() an observation chosen randomly from the dataset. You can display 5 random observations using data.sample(5)"
},
{
"code": null,
"e": 3771,
"s": 3734,
"text": "data.head()data.tail()data.sample(5)"
},
{
"code": null,
"e": 3793,
"s": 3771,
"text": "What to look out for:"
},
{
"code": null,
"e": 3904,
"s": 3793,
"text": "Can you understand the column names? Do they make sense? (Check with the variable definitions again if needed)"
},
{
"code": null,
"e": 3947,
"s": 3904,
"text": "Do the values in these columns make sense?"
},
{
"code": null,
"e": 3999,
"s": 3947,
"text": "Are there significant missing values (NaN) sighted?"
},
{
"code": null,
"e": 4055,
"s": 3999,
"text": "What types of classes do the categorical features have?"
},
{
"code": null,
"e": 4234,
"s": 4055,
"text": "My insights; the Postcode and Propertycount features both changed according to the Suburb feature. Also, there were significant missing values for the BuildingArea and YearBuilt."
},
{
"code": null,
"e": 4733,
"s": 4234,
"text": "This refers to how the values in a feature are distributed, or how often they occur. For numeric features, we’ll see how many times groups of numbers appear in a particular column, and for categorical features, the classes for each column and their frequency. We will use both graphs and actual summary statistics. The graphs enable us to get an overall idea of the distributions while the statistics give us factual numbers. These two strategies are both recommended as they complement each other."
},
{
"code": null,
"e": 4762,
"s": 4733,
"text": "4. Plot each numeric feature"
},
{
"code": null,
"e": 5093,
"s": 4762,
"text": "We will use Pandas histogram. A histogram groups numbers into ranges (or bins) and the height of a bar shows how many numbers fall in that range. df.hist() plots a histogram of the data’s numeric features in a grid. We will also provide the figsize and xrot arguments to increase the grid size and rotate the x-axis by 45 degrees."
},
{
"code": null,
"e": 5139,
"s": 5093,
"text": "data.hist(figsize=(14,14), xrot=45)plt.show()"
},
{
"code": null,
"e": 5161,
"s": 5139,
"text": "What to look out for:"
},
{
"code": null,
"e": 5235,
"s": 5161,
"text": "Possible outliers that cannot be explained or might be measurement errors"
},
{
"code": null,
"e": 5324,
"s": 5235,
"text": "Numeric features that should be categorical. For example, Gender represented by 1 and 0."
},
{
"code": null,
"e": 5390,
"s": 5324,
"text": "Boundaries that do not make sense such as percentage values> 100."
},
{
"code": null,
"e": 5724,
"s": 5390,
"text": "From the histogram, I noted that BuildingArea and LandSize had potential outliers to the right. Our target feature Price was also highly skewed to the right. I also noted that YearBuilt was very skewed to the left and the boundary started at the year 1200 which was odd. Let’s move on to the summary statistics for a clearer picture."
},
{
"code": null,
"e": 5772,
"s": 5724,
"text": "5. Summary statistics of the numerical features"
},
{
"code": null,
"e": 5926,
"s": 5772,
"text": "Now that we have an intuitive feel of the numeric features, we will look at actual statistics using df.describe()which displays their summary statistics."
},
{
"code": null,
"e": 5942,
"s": 5926,
"text": "data.describe()"
},
{
"code": null,
"e": 6338,
"s": 5942,
"text": "We can see for each numeric feature, the count of values in it, the mean value, std or standard deviation, minimum value, the 25th percentile, the 50th percentile or median, the 75th percentile, and the maximum value. From the count we can also identify the features with missing values; their count is not equal to the total number of rows of the dataset. These are Car, LandSize and YearBuilt."
},
{
"code": null,
"e": 6562,
"s": 6338,
"text": "I noted that the minimum for both the LandSize and BuildingArea is 0. We also see that the Price ranges from 85,000 to 9,000,000 which is a big range. We will explore these columns in detailed analysis later in the project."
},
{
"code": null,
"e": 6724,
"s": 6562,
"text": "Looking at the YearBuilt feature, however, we note that the minimum year is 1196. This could be a possible data entry error that will be removed during cleaning."
},
{
"code": null,
"e": 6774,
"s": 6724,
"text": "6. Summary statistics of the categorical features"
},
{
"code": null,
"e": 7021,
"s": 6774,
"text": "For categorical features, it is important to show the summary statistics before we plot graphs because some features have a lot of unique classes (like we will see for the Address) and the classes would be unreadable if visualized on a countplot."
},
{
"code": null,
"e": 7129,
"s": 7021,
"text": "To check the summary statistics of only the categorical features, we will use df.describe(include=’object’)"
},
{
"code": null,
"e": 7161,
"s": 7129,
"text": "data.describe(include='object')"
},
{
"code": null,
"e": 7393,
"s": 7161,
"text": "This table is a bit different from the one for numeric features. Here, we get the count of the values of each feature, the number of unique classes, the top most frequent class, and how frequently that class occurs in the data set."
},
{
"code": null,
"e": 7628,
"s": 7393,
"text": "We note that some classes have a lot of unique values such as Address, followed by Suburb and SellerG. From these findings, I will only plot the columns with 10 or less unique classes. We also note that CouncilArea has missing values."
},
{
"code": null,
"e": 7661,
"s": 7628,
"text": "7. Plot each categorical feature"
},
{
"code": null,
"e": 7952,
"s": 7661,
"text": "Using the statistics above, we note that Type, Method and Regionname have less than 10 classes and can be effectively visualized. We will plot these features using the Seaborn countplot, which is like a histogram for categorical variables. Each bar in a countplot represents a unique class."
},
{
"code": null,
"e": 8382,
"s": 7952,
"text": "I created a For loop. For each categorical feature, a countplot will be displayed to show how the classes are distributed for that feature. The line df.select_dtypes(include=’object’) selects the categorical columns with their values and displays them. We will also include an If-statement so as to pick only the three columns with 10 or fewer classes using the line Series.nunique() < 10. Read the .nunique() documentation here."
},
{
"code": null,
"e": 8529,
"s": 8382,
"text": "for column in data.select_dtypes(include='object'): if data[column].nunique() < 10: sns.countplot(y=column, data=data) plt.show()"
},
{
"code": null,
"e": 8551,
"s": 8529,
"text": "What to look out for:"
},
{
"code": null,
"e": 8624,
"s": 8551,
"text": "Sparse classes which have the potential to affect a model’s performance."
},
{
"code": null,
"e": 8722,
"s": 8624,
"text": "Mistakes in labeling of the classes, for example 2 exact classes with minor spelling differences."
},
{
"code": null,
"e": 8832,
"s": 8722,
"text": "We note that Regionname has some sparse classes which might need to be merged or re-assigned during modeling."
},
{
"code": null,
"e": 8942,
"s": 8832,
"text": "Segmentation allows us to cut the data and observe the relationship between categorical and numeric features."
},
{
"code": null,
"e": 8998,
"s": 8942,
"text": "8. Segment the target variable by categorical features."
},
{
"code": null,
"e": 9186,
"s": 8998,
"text": "Here, we will compare the target feature, Price, between the various classes of our main categorical features (Type, Method and Regionname) and see how the Price changes with the classes."
},
{
"code": null,
"e": 9432,
"s": 9186,
"text": "We use the Seaborn boxplot which plots the distribution of Price across the classes of categorical features. This tutorial, from where I borrowed the Image below, explains the boxplot’s features clearly. The dots at both ends represent outliers."
},
{
"code": null,
"e": 9515,
"s": 9432,
"text": "Again, I used a for loop to plot a boxplot of each categorical feature with Price."
},
{
"code": null,
"e": 9654,
"s": 9515,
"text": "for column in data.select_dtypes(include=’object’): if data[column].nunique() < 10: sns.boxplot(y=column, x=’Price’, data=data) plt.show()"
},
{
"code": null,
"e": 9676,
"s": 9654,
"text": "What to look out for:"
},
{
"code": null,
"e": 9724,
"s": 9676,
"text": "which classes most affect the target variables."
},
{
"code": null,
"e": 9874,
"s": 9724,
"text": "Note how the Price is still sparsely distributed among the 3 sparse classes of Regionname seen earlier, strengthening our case against these classes."
},
{
"code": null,
"e": 10021,
"s": 9874,
"text": "Also note how the SA class (the least frequent Method class) commands high prices, almost similar prices of the most frequently occurring class S."
},
{
"code": null,
"e": 10076,
"s": 10021,
"text": "9. Group numeric features by each categorical feature."
},
{
"code": null,
"e": 10408,
"s": 10076,
"text": "Here we will see how all the other numeric features, not just Price, change with each categorical feature by summarizing the numeric features across the classes. We use the Dataframe’s groupby function to group the data by a category and calculate a metric (such as mean, median, min, std, etc) across the various numeric features."
},
{
"code": null,
"e": 10607,
"s": 10408,
"text": "For only the 3 categorical features with less than 10 classes, we group the data, then calculate the mean across the numeric features. We use display() which results to a cleaner table than print()."
},
{
"code": null,
"e": 10738,
"s": 10607,
"text": "for column in data.select_dtypes(include='object'): if data[column].nunique() < 10: display(data.groupby(column).mean())"
},
{
"code": null,
"e": 10857,
"s": 10738,
"text": "We get to compare the Type, Method and Regionname classes across the numeric features to see how they are distributed."
},
{
"code": null,
"e": 10918,
"s": 10857,
"text": "10. Correlations matrix for the different numerical features"
},
{
"code": null,
"e": 11321,
"s": 10918,
"text": "A correlation is a value between -1 and 1 that amounts to how closely values of two separate features move simultaneously. A positive correlation means that as one feature increases the other one also increases, while a negative correlation means one feature increases as the other decreases. Correlations close to 0 indicate a weak relationship while closer to -1 or 1 signifies a strong relationship."
},
{
"code": null,
"e": 11430,
"s": 11321,
"text": "We will use df.corr() to calculate the correlations between the numeric features and it returns a DataFrame."
},
{
"code": null,
"e": 11455,
"s": 11430,
"text": "corrs = data.corr()corrs"
},
{
"code": null,
"e": 11541,
"s": 11455,
"text": "This might not mean much now, so let us plot a heatmap to visualize the correlations."
},
{
"code": null,
"e": 11573,
"s": 11541,
"text": "11. Heatmap of the correlations"
},
{
"code": null,
"e": 11710,
"s": 11573,
"text": "We will use a Seaborn heatmap to plot the grid as a rectangular color-coded matrix. We use sns.heatmap(corrs, cmap=’RdBu_r’,annot=True)."
},
{
"code": null,
"e": 12077,
"s": 11710,
"text": "The cmap=‘RdBu_r’ argument tells the heatmap what colour palette to use. A high positive correlation appears as dark red and a high negative correlation as dark blue. Closer to white signifies a weak relationship. Read this nice tutorial for other color palettes. annot=True includes the values of the correlations in the boxes for easier reading and interpretation."
},
{
"code": null,
"e": 12159,
"s": 12077,
"text": "plt.figure(figsize=(10,8))sns.heatmap(corrs, cmap='RdBu_r', annot=True)plt.show()"
},
{
"code": null,
"e": 12181,
"s": 12159,
"text": "What to look out for:"
},
{
"code": null,
"e": 12262,
"s": 12181,
"text": "Strongly correlated features; either dark red (positive) or dark blue(negative)."
},
{
"code": null,
"e": 12352,
"s": 12262,
"text": "Target variable; If it has strong positive or negative relationships with other features."
},
{
"code": null,
"e": 12607,
"s": 12352,
"text": "We note that Rooms, Bedrooms2, Bathrooms, and Price have strong positive relationships. On the other hand, Price, our target feature, has a slightly weak negative correlation with YearBuilt and an even weaker negative relationship with Distance from CBD."
},
{
"code": null,
"e": 12951,
"s": 12607,
"text": "In this article, we explored the Melbourne dataset and got a high-level understanding of the structure and its features. At this stage, we do not need to be 100% comprehensive because in future stages we will explore the data more elaborately. You can get the full code on Github here. I will be uploading the dataset’s cleaning concepts soon."
}
] |
Report Groups
|
Groups in JasperReports help to organize data on report in a logical manner. A report group represents a sequence of consecutive records in the data source, which have something in common, such as the value of a certain report fields. A report group is defined by the <group> element. A report can have any number of groups. Once declared, groups can be referred throughout the report.
A report group has three elements −
Group expression − This indicates the data that must change to start a new data group.
Group expression − This indicates the data that must change to start a new data group.
Group header section − Helps place label at the beginning of the grouped data.
Group header section − Helps place label at the beginning of the grouped data.
Group footer section − Helps place label at the end of the grouped data.
Group footer section − Helps place label at the end of the grouped data.
During the iteration through the data source at report-filling time if the value of the group expression changes, a group rupture occurs and the corresponding <groupFooter> and <groupHeader> sections are inserted in the resulting document.
Report group mechanism does not perform any sorting on the data supplied by the data source. Data grouping works as expected only when the records in the data source are already ordered according to the group expressions used in the report.
The <group> element contains attributes that allow us to control how grouped data is laid out. The attributes are summarized in table below −
name
This is mandatory. It references the group in report expressions by name. It follows the same naming conventions that we mentioned for the report parameters, fields, and report variables. It can be used in other JRXML attributes when you want to refer a particular report group.
isStartNewColumn
When set to true, each data group will begin on a new column. Default value is false.
isStartNewPage
When set to true, each data group will begin on a new page. Default value is false.
isResetPageNumber
When set to true, the report page number will be reset every time a new group starts. Default value is false.
isReprintHeaderOnEachPage
minHeightToStartNewPage
Defines minimum amount of vertical space needed at the bottom of the column in order to place the group header on the current column. The amount is specified in report units.
footerPosition
Renders position of the group footer on the page, as well as its behavior in relation to the report sections that follow it.Its value can be: Normal, StackAtBottom, ForceAtBottom, and CollateAtBottom. Default value is Normal.
keepTogether
When set to true, prevents the group from splitting on its first break attempt.
Let's add a group (CountryGroup) to existing report template (Chapter Report Designs). Occurrence of each country is counted and the count is displayed as the group footer. In the group header, the count of each record is prefixed. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −
<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
"//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "jasper_report_template" pageWidth = "595"
pageHeight = "842" columnWidth = "515"
leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50">
<parameter name = "ReportTitle" class = "java.lang.String"/>
<parameter name = "Author" class = "java.lang.String"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name = "country" class = "java.lang.String">
<fieldDescription><![CDATA[country]]></fieldDescription>
</field>
<field name = "name" class = "java.lang.String">
<fieldDescription><![CDATA[name]]></fieldDescription>
</field>
<sortField name = "country" order = "Descending"/>
<sortField name = "name"/>
<variable name = "CountryNumber" class = "java.lang.Integer"
incrementType = "Group" incrementGroup = "CountryGroup"
calculation = "Count">
<variableExpression><![CDATA[Boolean.TRUE]]></variableExpression>
</variable>
<group name = "CountryGroup" minHeightToStartNewPage = "60">
<groupExpression><![CDATA[$F{country}]]></groupExpression>
<groupHeader>
<band height = "20">
<textField evaluationTime = "Group" evaluationGroup = "CountryGroup"
bookmarkLevel = "1">
<reportElement mode = "Opaque" x = "0" y = "5" width = "515"
height = "15" backcolor = "#C0C0C0"/>
<box leftPadding = "10">
<bottomPen lineWidth = "1.0"/>
</box>
<textElement/>
<textFieldExpression class = "java.lang.String">
<![CDATA[" " + String.valueOf($V{CountryNumber}) + ". "
+ String.valueOf($F{country})]]>
</textFieldExpression>
<anchorNameExpression>
<![CDATA[String.valueOf($F{country})]]>
</anchorNameExpression>
</textField>
</band>
</groupHeader>
<groupFooter>
<band height = "20">
<staticText>
<reportElement x = "400" y = "1" width = "60" height = "15"/>
<textElement textAlignment = "Right"/>
<text><![CDATA[Count :]]></text>
</staticText>
<textField>
<reportElement x = "460" y = "1" width = "30" height = "15"/>
<textElement textAlignment = "Right"/>
<textFieldExpression class = "java.lang.Integer">
<![CDATA[$V{CountryGroup_COUNT}]]>
</textFieldExpression>
</textField>
</band>
</groupFooter>
</group>
<title>
<band height = "70">
<line>
<reportElement x = "0" y = "0" width = "515" height = "1"/>
</line>
<textField isBlankWhenNull = "true" bookmarkLevel = "1">
<reportElement x = "0" y = "10" width = "515" height = "30"/>
<textElement textAlignment = "Center">
<font size = "22"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$P{ReportTitle}]]>
</textFieldExpression>
<anchorNameExpression>
<![CDATA["Title"]]>
</anchorNameExpression>
</textField>
<textField isBlankWhenNull = "true">
<reportElement x = "0" y = "40" width = "515" height = "20"/>
<textElement textAlignment = "Center">
<font size = "10"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$P{Author}]]>
</textFieldExpression>
</textField>
</band>
</title>
<columnHeader>
<band height = "23">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15"
backcolor = "#70A9A9" />
<box>
<bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
</box>
<textElement />
<text>
<![CDATA[]]>
</text>
</staticText>
<staticText>
<reportElement x = "414" y = "3" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement x = "0" y = "3" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height = "16">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14"
backcolor = "#E5ECF9" />
<box>
<bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
</box>
<textElement />
<text>
<![CDATA[]]>
</text>
</staticText>
<textField>
<reportElement x = "414" y = "0" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font size = "9" />
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{country}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x = "0" y = "0" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle" />
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
public class JasperReportFill {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String sourceFileName =
"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";
DataBeanList DataBeanList = new DataBeanList();
ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource =
new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
/**
* Passing ReportTitle and Author as parameters
*/
parameters.put("ReportTitle", "List of Contacts");
parameters.put("Author", "Prepared By Manisha");
try {
JasperFillManager.fillReportToFile(
sourceFileName, parameters, beanColDataSource);
} catch (JRException e) {
e.printStackTrace();
}
}
}
The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as below −
package com.tutorialspoint;
public class DataBean {
private String name;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −
package com.tutorialspoint;
import java.util.ArrayList;
public class DataBeanList {
public ArrayList<DataBean> getDataBeanList() {
ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();
dataBeanList.add(produce("Manisha", "India"));
dataBeanList.add(produce("Dennis Ritchie", "USA"));
dataBeanList.add(produce("V.Anand", "India"));
dataBeanList.add(produce("Shrinath", "California"));
return dataBeanList;
}
/**
* This method returns a DataBean object,
* with name and country set in it.
*/
private DataBean produce(String name, String country) {
DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setCountry(country);
return dataBean;
}
}
We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as below.
The import file - baseBuild.xml is picked up from chapter Environment Setup and should be placed in the same directory as the build.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
<import file = "baseBuild.xml" />
<target name = "viewFillReport" depends = "compile,compilereportdesing,run"
description = "Launches the report viewer to preview
the report stored in the .JRprint file.">
<java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
<arg value = "-F${file.name}.JRprint" />
<classpath refid = "classpath" />
</java>
</target>
<target name = "compilereportdesing" description = "Compiles the JXML file and
produces the .jasper file.">
<taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
<classpath refid = "classpath" />
</taskdef>
<jrc destdir = ".">
<src>
<fileset dir = ".">
<include name = "*.jrxml" />
</fileset>
</src>
<classpath refid = "classpath" />
</jrc>
</target>
</project>
Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −
C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
clean-sample:
[delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint
compile:
[mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
[javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning:
'includeantruntime' was not set, defaulting to build.sysclasspath=last;
set to false for repeatable builds
[javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes
compilereportdesing:
[jrc] Compiling 1 report design files.
[jrc] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[jrc] log4j:WARN Please initialize the log4j system properly.
[jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
for more info.
[jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.
run:
[echo] Runnin class : com.tutorialspoint.JasperReportFill
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
viewFillReport:
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
BUILD SUCCESSFUL
Total time: 18 seconds
As a result of above compilation, a JasperViewer window opens up as in the screen below −
Here, we see that the each country is grouped and the count of occurrence of each country is displayed at the footer of each group.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2641,
"s": 2254,
"text": "Groups in JasperReports help to organize data on report in a logical manner. A report group represents a sequence of consecutive records in the data source, which have something in common, such as the value of a certain report fields. A report group is defined by the <group> element. A report can have any number of groups. Once declared, groups can be referred throughout the report.\n"
},
{
"code": null,
"e": 2677,
"s": 2641,
"text": "A report group has three elements −"
},
{
"code": null,
"e": 2764,
"s": 2677,
"text": "Group expression − This indicates the data that must change to start a new data group."
},
{
"code": null,
"e": 2851,
"s": 2764,
"text": "Group expression − This indicates the data that must change to start a new data group."
},
{
"code": null,
"e": 2930,
"s": 2851,
"text": "Group header section − Helps place label at the beginning of the grouped data."
},
{
"code": null,
"e": 3009,
"s": 2930,
"text": "Group header section − Helps place label at the beginning of the grouped data."
},
{
"code": null,
"e": 3082,
"s": 3009,
"text": "Group footer section − Helps place label at the end of the grouped data."
},
{
"code": null,
"e": 3155,
"s": 3082,
"text": "Group footer section − Helps place label at the end of the grouped data."
},
{
"code": null,
"e": 3395,
"s": 3155,
"text": "During the iteration through the data source at report-filling time if the value of the group expression changes, a group rupture occurs and the corresponding <groupFooter> and <groupHeader> sections are inserted in the resulting document."
},
{
"code": null,
"e": 3636,
"s": 3395,
"text": "Report group mechanism does not perform any sorting on the data supplied by the data source. Data grouping works as expected only when the records in the data source are already ordered according to the group expressions used in the report."
},
{
"code": null,
"e": 3778,
"s": 3636,
"text": "The <group> element contains attributes that allow us to control how grouped data is laid out. The attributes are summarized in table below −"
},
{
"code": null,
"e": 3783,
"s": 3778,
"text": "name"
},
{
"code": null,
"e": 4062,
"s": 3783,
"text": "This is mandatory. It references the group in report expressions by name. It follows the same naming conventions that we mentioned for the report parameters, fields, and report variables. It can be used in other JRXML attributes when you want to refer a particular report group."
},
{
"code": null,
"e": 4079,
"s": 4062,
"text": "isStartNewColumn"
},
{
"code": null,
"e": 4165,
"s": 4079,
"text": "When set to true, each data group will begin on a new column. Default value is false."
},
{
"code": null,
"e": 4180,
"s": 4165,
"text": "isStartNewPage"
},
{
"code": null,
"e": 4264,
"s": 4180,
"text": "When set to true, each data group will begin on a new page. Default value is false."
},
{
"code": null,
"e": 4282,
"s": 4264,
"text": "isResetPageNumber"
},
{
"code": null,
"e": 4392,
"s": 4282,
"text": "When set to true, the report page number will be reset every time a new group starts. Default value is false."
},
{
"code": null,
"e": 4418,
"s": 4392,
"text": "isReprintHeaderOnEachPage"
},
{
"code": null,
"e": 4442,
"s": 4418,
"text": "minHeightToStartNewPage"
},
{
"code": null,
"e": 4617,
"s": 4442,
"text": "Defines minimum amount of vertical space needed at the bottom of the column in order to place the group header on the current column. The amount is specified in report units."
},
{
"code": null,
"e": 4632,
"s": 4617,
"text": "footerPosition"
},
{
"code": null,
"e": 4858,
"s": 4632,
"text": "Renders position of the group footer on the page, as well as its behavior in relation to the report sections that follow it.Its value can be: Normal, StackAtBottom, ForceAtBottom, and CollateAtBottom. Default value is Normal."
},
{
"code": null,
"e": 4871,
"s": 4858,
"text": "keepTogether"
},
{
"code": null,
"e": 4951,
"s": 4871,
"text": "When set to true, prevents the group from splitting on its first break attempt."
},
{
"code": null,
"e": 5314,
"s": 4951,
"text": "Let's add a group (CountryGroup) to existing report template (Chapter Report Designs). Occurrence of each country is counted and the count is displayed as the group footer. In the group header, the count of each record is prefixed. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\\tools\\jasperreports-5.0.1\\test directory −"
},
{
"code": null,
"e": 12166,
"s": 5314,
"text": "<?xml version = \"1.0\"?>\n<!DOCTYPE jasperReport PUBLIC\n \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"515\"\n leftMargin = \"40\" rightMargin = \"40\" topMargin = \"50\" bottomMargin = \"50\">\n\n <parameter name = \"ReportTitle\" class = \"java.lang.String\"/>\n <parameter name = \"Author\" class = \"java.lang.String\"/>\n\n <queryString>\n <![CDATA[]]>\n </queryString>\n\n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n </field>\n\n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n </field>\n \n <sortField name = \"country\" order = \"Descending\"/>\n <sortField name = \"name\"/>\n \n <variable name = \"CountryNumber\" class = \"java.lang.Integer\"\n incrementType = \"Group\" incrementGroup = \"CountryGroup\"\n calculation = \"Count\">\n <variableExpression><![CDATA[Boolean.TRUE]]></variableExpression>\n </variable>\n \n <group name = \"CountryGroup\" minHeightToStartNewPage = \"60\">\n <groupExpression><![CDATA[$F{country}]]></groupExpression>\n \n <groupHeader>\n <band height = \"20\">\n \n <textField evaluationTime = \"Group\" evaluationGroup = \"CountryGroup\"\n bookmarkLevel = \"1\">\n <reportElement mode = \"Opaque\" x = \"0\" y = \"5\" width = \"515\"\n height = \"15\" backcolor = \"#C0C0C0\"/>\n \n <box leftPadding = \"10\">\n <bottomPen lineWidth = \"1.0\"/>\n </box>\n <textElement/>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[\" \" + String.valueOf($V{CountryNumber}) + \". \"\n + String.valueOf($F{country})]]>\n </textFieldExpression>\n \n <anchorNameExpression>\n <![CDATA[String.valueOf($F{country})]]>\n </anchorNameExpression>\n </textField>\n \n </band>\n </groupHeader>\n \n <groupFooter>\n <band height = \"20\">\n \n <staticText>\n <reportElement x = \"400\" y = \"1\" width = \"60\" height = \"15\"/>\n <textElement textAlignment = \"Right\"/>\n <text><![CDATA[Count :]]></text>\n </staticText>\n \n <textField>\n <reportElement x = \"460\" y = \"1\" width = \"30\" height = \"15\"/>\n <textElement textAlignment = \"Right\"/>\n \n <textFieldExpression class = \"java.lang.Integer\">\n <![CDATA[$V{CountryGroup_COUNT}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </groupFooter>\n \n </group>\n \n <title>\n <band height = \"70\">\n \n <line>\n <reportElement x = \"0\" y = \"0\" width = \"515\" height = \"1\"/>\n </line>\n \n <textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n \n <anchorNameExpression>\n <![CDATA[\"Title\"]]>\n </anchorNameExpression>\n </textField>\n \n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </title>\n\n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" width = \"535\" height = \"15\"\n backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n\n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" width = \"535\" height = \"14\"\n backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n\t\t\t\t\n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]> \n </text>\n </staticText>\n \n <textField>\n <reportElement x = \"414\" y = \"0\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n\t\n</jasperReport>"
},
{
"code": null,
"e": 12344,
"s": 12166,
"text": "The java codes for report filling remains unchanged. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportFill.java are as given below −"
},
{
"code": null,
"e": 13478,
"s": 12344,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName =\n \"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource =\n new JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n /**\n * Passing ReportTitle and Author as parameters\n */\n parameters.put(\"ReportTitle\", \"List of Contacts\");\n parameters.put(\"Author\", \"Prepared By Manisha\");\n\n try {\n JasperFillManager.fillReportToFile(\n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 13594,
"s": 13478,
"text": "The contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as below −"
},
{
"code": null,
"e": 13962,
"s": 13594,
"text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}"
},
{
"code": null,
"e": 14083,
"s": 13962,
"text": "The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as given below −"
},
{
"code": null,
"e": 14847,
"s": 14083,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}"
},
{
"code": null,
"e": 15034,
"s": 14847,
"text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as below."
},
{
"code": null,
"e": 15171,
"s": 15034,
"text": "The import file - baseBuild.xml is picked up from chapter Environment Setup and should be placed in the same directory as the build.xml."
},
{
"code": null,
"e": 16248,
"s": 15171,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview \n the report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n \n </target>\n\t\n</project>"
},
{
"code": null,
"e": 16462,
"s": 16248,
"text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −"
},
{
"code": null,
"e": 18135,
"s": 16462,
"text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28: warning:\n 'includeantruntime' was not set, defaulting to build.sysclasspath=last;\n set to false for repeatable builds\n [javac] Compiling 7 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig\n for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 18 seconds\n"
},
{
"code": null,
"e": 18225,
"s": 18135,
"text": "As a result of above compilation, a JasperViewer window opens up as in the screen below −"
},
{
"code": null,
"e": 18357,
"s": 18225,
"text": "Here, we see that the each country is grouped and the count of occurrence of each country is displayed at the footer of each group."
},
{
"code": null,
"e": 18364,
"s": 18357,
"text": " Print"
},
{
"code": null,
"e": 18375,
"s": 18364,
"text": " Add Notes"
}
] |
Get unique values from a column in Pandas DataFrame - GeeksforGeeks
|
10 Dec, 2018
Let’s discuss how to get unique values from a column in Pandas DataFrame.
Create a simple dataframe with dictionary of lists, say columns name are A, B, C, D, E with duplicate elements.
Now, let’s get the unique values of a column in this dataframe.
Example #1: Get the unique values of ‘B’ column
# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B4'], 'C':['C1', 'C2', 'C3', 'C3', 'C3'], 'D':['D1', 'D2', 'D2', 'D2', 'D2'], 'E':['E1', 'E1', 'E1', 'E1', 'E1'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Get the unique values of 'B' columndf.B.unique()
Output:
Example #2: Get the unique values of ‘E’ column
# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B4'], 'C':['C1', 'C2', 'C3', 'C3', 'C3'], 'D':['D1', 'D2', 'D2', 'D2', 'D2'], 'E':['E1', 'E1', 'E1', 'E1', 'E1'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Get the unique values of 'E' columndf.E.unique()
Output:
Example #3: Get number of unique values in a column
# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B4'], 'C':['C1', 'C2', 'C3', 'C3', 'C3'], 'D':['D1', 'D2', 'D2', 'D2', 'D2'], 'E':['E1', 'E1', 'E1', 'E1', 'E1'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Get number of unique values in column 'C'df.C.nunique(dropna = True)
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24671,
"s": 24643,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 24745,
"s": 24671,
"text": "Let’s discuss how to get unique values from a column in Pandas DataFrame."
},
{
"code": null,
"e": 24857,
"s": 24745,
"text": "Create a simple dataframe with dictionary of lists, say columns name are A, B, C, D, E with duplicate elements."
},
{
"code": null,
"e": 24921,
"s": 24857,
"text": "Now, let’s get the unique values of a column in this dataframe."
},
{
"code": null,
"e": 24969,
"s": 24921,
"text": "Example #1: Get the unique values of ‘B’ column"
},
{
"code": "# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B4'], 'C':['C1', 'C2', 'C3', 'C3', 'C3'], 'D':['D1', 'D2', 'D2', 'D2', 'D2'], 'E':['E1', 'E1', 'E1', 'E1', 'E1'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Get the unique values of 'B' columndf.B.unique()",
"e": 25383,
"s": 24969,
"text": null
},
{
"code": null,
"e": 25391,
"s": 25383,
"text": "Output:"
},
{
"code": null,
"e": 25440,
"s": 25391,
"text": " Example #2: Get the unique values of ‘E’ column"
},
{
"code": "# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B4'], 'C':['C1', 'C2', 'C3', 'C3', 'C3'], 'D':['D1', 'D2', 'D2', 'D2', 'D2'], 'E':['E1', 'E1', 'E1', 'E1', 'E1'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Get the unique values of 'E' columndf.E.unique()",
"e": 25854,
"s": 25440,
"text": null
},
{
"code": null,
"e": 25862,
"s": 25854,
"text": "Output:"
},
{
"code": null,
"e": 25914,
"s": 25862,
"text": "Example #3: Get number of unique values in a column"
},
{
"code": "# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B4'], 'C':['C1', 'C2', 'C3', 'C3', 'C3'], 'D':['D1', 'D2', 'D2', 'D2', 'D2'], 'E':['E1', 'E1', 'E1', 'E1', 'E1'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Get number of unique values in column 'C'df.C.nunique(dropna = True)",
"e": 26348,
"s": 25914,
"text": null
},
{
"code": null,
"e": 26356,
"s": 26348,
"text": "Output:"
},
{
"code": null,
"e": 26381,
"s": 26356,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 26388,
"s": 26381,
"text": "Picked"
},
{
"code": null,
"e": 26412,
"s": 26388,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26426,
"s": 26412,
"text": "Python-pandas"
},
{
"code": null,
"e": 26450,
"s": 26426,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 26457,
"s": 26450,
"text": "Python"
},
{
"code": null,
"e": 26476,
"s": 26457,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26574,
"s": 26476,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26583,
"s": 26574,
"text": "Comments"
},
{
"code": null,
"e": 26596,
"s": 26583,
"text": "Old Comments"
},
{
"code": null,
"e": 26614,
"s": 26596,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26649,
"s": 26614,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26671,
"s": 26649,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26703,
"s": 26671,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26733,
"s": 26703,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26775,
"s": 26733,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26818,
"s": 26775,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26844,
"s": 26818,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26888,
"s": 26844,
"text": "Reading and Writing to text files in Python"
}
] |
Update a column of text with MySQL REPLACE()
|
Let us first create a table −
mysql> create table DemoTable
(
Code varchar(100)
);
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('8565-9848-7474');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('9994-6464-8737');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('6574-9090-7643');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------------+
| Code |
+----------------+
| 8565-9848-7474 |
| 9994-6464-8737 |
| 6574-9090-7643 |
+----------------+
3 rows in set (0.00 sec)
Following is the query to replace column value −
mysql> update DemoTable
set Code=replace(Code,'9994-6464-8737','9994-9999-88888');
Query OK, 1 row affected (0.10 sec)
Rows matched : 3 Changed : 1 Warnings : 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-----------------+
| Code |
+-----------------+
| 8565-9848-7474 |
| 9994-9999-88888 |
| 6574-9090-7643 |
+-----------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1185,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n Code varchar(100)\n);\nQuery OK, 0 rows affected (0.50 sec)"
},
{
"code": null,
"e": 1241,
"s": 1185,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1514,
"s": 1241,
"text": "mysql> insert into DemoTable values('8565-9848-7474');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('9994-6464-8737');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('6574-9090-7643');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1574,
"s": 1514,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1605,
"s": 1574,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1646,
"s": 1605,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1804,
"s": 1646,
"text": "+----------------+\n| Code |\n+----------------+\n| 8565-9848-7474 |\n| 9994-6464-8737 |\n| 6574-9090-7643 |\n+----------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1853,
"s": 1804,
"text": "Following is the query to replace column value −"
},
{
"code": null,
"e": 2014,
"s": 1853,
"text": "mysql> update DemoTable\nset Code=replace(Code,'9994-6464-8737','9994-9999-88888');\nQuery OK, 1 row affected (0.10 sec)\nRows matched : 3 Changed : 1 Warnings : 0"
},
{
"code": null,
"e": 2058,
"s": 2014,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2089,
"s": 2058,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2130,
"s": 2089,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2295,
"s": 2130,
"text": "+-----------------+\n| Code |\n+-----------------+\n| 8565-9848-7474 |\n| 9994-9999-88888 |\n| 6574-9090-7643 |\n+-----------------+\n3 rows in set (0.00 sec)"
}
] |
Working with Missing Data in Pandas - GeeksforGeeks
|
20 May, 2021
Missing Data can occur when no information is provided for one or more items or for a whole unit. Missing Data is a very big problem in a real-life scenarios. Missing Data can also refer to as NA(Not Available) values in pandas. In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed. For Example, Suppose different users being surveyed may choose not to share their income, some users may choose not to share the address in this way many datasets went missing.
In Pandas missing data is represented by two value:
None: None is a Python singleton object that is often used for missing data in Python code.
NaN : NaN (an acronym for Not a Number), is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation
YouTubeGeeksforGeeks500K subscribersHandling Missing Values in Pandas Dataframe | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 22:17•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uDr67HBIPz8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Pandas treat None and NaN as essentially interchangeable for indicating missing or null values. To facilitate this convention, there are several useful functions for detecting, removing, and replacing null values in Pandas DataFrame :
isnull()
notnull()
dropna()
fillna()
replace()
interpolate()
In this article we are using CSV file, to download the CSV file used, Click Here.
In order to check missing values in Pandas DataFrame, we use a function isnull() and notnull(). Both function help in checking whether a value is NaN or not. These function can also be used in Pandas Series in order to find null values in a series.
In order to check null values in Pandas DataFrame, we use isnull() function this function return dataframe of Boolean values which are True for NaN values.
Code #1:
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from listdf = pd.DataFrame(dict) # using isnull() function df.isnull()
Output: Code #2:
# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # creating bool series True for NaN values bool_series = pd.isnull(data["Gender"]) # filtering data # displaying data only with Gender = NaN data[bool_series]
Output:As shown in the output image, only the rows having Gender = NULL are displayed.
In order to check null values in Pandas Dataframe, we use notnull() function this function return dataframe of Boolean values which are False for NaN values.
Code #3:
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe using dictionarydf = pd.DataFrame(dict) # using notnull() function df.notnull()
Output: Code #4:
# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # creating bool series True for NaN values bool_series = pd.notnull(data["Gender"]) # filtering data # displayind data only with Gender = Not NaN data[bool_series]
Output:As shown in the output image, only the rows having Gender = NOT NULL are displayed.
In order to fill null values in a datasets, we use fillna(), replace() and interpolate() function these function replace NaN values with some value of their own. All these function help in filling a null values in datasets of a DataFrame. Interpolate() function is basically used to fill NA values in the dataframe but it uses various interpolation technique to fill the missing values rather than hard-coding the value.
Code #1: Filling null values with a single value
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # filling missing value using fillna() df.fillna(0)
Output: Code #2: Filling null values with the previous ones
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # filling a missing value with# previous ones df.fillna(method ='pad')
Output: Code #3: Filling null value with the next ones
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # filling null value using fillna() function df.fillna(method ='bfill')
Output: Code #4: Filling null values in CSV File
# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # Printing the first 10 to 24 rows of# the data frame for visualization data[10:25]
Now we are going to fill all the null values in Gender column with “No Gender”
# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # filling a null values using fillna() data["Gender"].fillna("No Gender", inplace = True) data
Output:Code #5: Filling a null values using replace() method
# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # Printing the first 10 to 24 rows of# the data frame for visualization data[10:25]
Output:Now we are going to replace the all Nan value in the data frame with -99 value.
# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # will replace Nan value in dataframe with value -99 data.replace(to_replace = np.nan, value = -99)
Output: Code #6: Using interpolate() function to fill the missing values using linear method.
# importing pandas as pd import pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[None, 2, 54, 3, None], "C":[20, 16, None, 3, 8], "D":[14, 3, None, None, 6]}) # Print the dataframe df
Let’s interpolate the missing values using Linear method. Note that Linear method ignore the index and treat the values as equally spaced.
# to interpolate the missing values df.interpolate(method ='linear', limit_direction ='forward')
Output:As we can see the output, values in the first row could not get filled as the direction of filling of values is forward and there is no previous value which could have been used in interpolation.
In order to drop a null values from a dataframe, we used dropna() function this function drop Rows/Columns of datasets with Null values in different ways.
Code #1: Dropping rows with at least 1 null value.
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, 40, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) df
Now we drop rows with at least one Nan value (Null value)
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, 40, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # using dropna() function df.dropna()
Output:Code #2: Dropping rows if all values in that row are missing.
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) df
Now we drop a rows whose all data is missing or contain null values(NaN)
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} df = pd.DataFrame(dict) # using dropna() function df.dropna(how = 'all')
Output:
Code #3: Dropping columns with at least 1 null value.
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[60, 67, 68, 65]} # creating a dataframe from dictionary df = pd.DataFrame(dict) df
Now we drop a columns which have at least 1 missing values
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[60, 67, 68, 65]} # creating a dataframe from dictionary df = pd.DataFrame(dict) # using dropna() function df.dropna(axis = 1)
Output : Code #4: Dropping Rows with at least 1 null value in CSV file
# importing pandas module import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # making new data frame with dropped NA values new_data = data.dropna(axis = 0, how ='any') new_data
Output:Now we compare sizes of data frames so that we can come to know how many rows had at least 1 Null value
print("Old data frame length:", len(data))print("New data frame length:", len(new_data)) print("Number of rows with at least 1 NA value: ", (len(data)-len(new_data)))
Output :
Old data frame length: 1000
New data frame length: 764
Number of rows with at least 1 NA value: 236
Since the difference is 236, there were 236 rows which had at least 1 Null value in any column.
Akanksha_Rai
Python pandas-dataFrame
Python pandas-missingData
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
|
[
{
"code": null,
"e": 24441,
"s": 24413,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 24985,
"s": 24441,
"text": "Missing Data can occur when no information is provided for one or more items or for a whole unit. Missing Data is a very big problem in a real-life scenarios. Missing Data can also refer to as NA(Not Available) values in pandas. In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed. For Example, Suppose different users being surveyed may choose not to share their income, some users may choose not to share the address in this way many datasets went missing."
},
{
"code": null,
"e": 25037,
"s": 24985,
"text": "In Pandas missing data is represented by two value:"
},
{
"code": null,
"e": 25129,
"s": 25037,
"text": "None: None is a Python singleton object that is often used for missing data in Python code."
},
{
"code": null,
"e": 25287,
"s": 25129,
"text": "NaN : NaN (an acronym for Not a Number), is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation"
},
{
"code": null,
"e": 26130,
"s": 25287,
"text": "YouTubeGeeksforGeeks500K subscribersHandling Missing Values in Pandas Dataframe | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 22:17•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uDr67HBIPz8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 26365,
"s": 26130,
"text": "Pandas treat None and NaN as essentially interchangeable for indicating missing or null values. To facilitate this convention, there are several useful functions for detecting, removing, and replacing null values in Pandas DataFrame :"
},
{
"code": null,
"e": 26374,
"s": 26365,
"text": "isnull()"
},
{
"code": null,
"e": 26384,
"s": 26374,
"text": "notnull()"
},
{
"code": null,
"e": 26393,
"s": 26384,
"text": "dropna()"
},
{
"code": null,
"e": 26402,
"s": 26393,
"text": "fillna()"
},
{
"code": null,
"e": 26412,
"s": 26402,
"text": "replace()"
},
{
"code": null,
"e": 26426,
"s": 26412,
"text": "interpolate()"
},
{
"code": null,
"e": 26508,
"s": 26426,
"text": "In this article we are using CSV file, to download the CSV file used, Click Here."
},
{
"code": null,
"e": 26757,
"s": 26508,
"text": "In order to check missing values in Pandas DataFrame, we use a function isnull() and notnull(). Both function help in checking whether a value is NaN or not. These function can also be used in Pandas Series in order to find null values in a series."
},
{
"code": null,
"e": 26913,
"s": 26757,
"text": "In order to check null values in Pandas DataFrame, we use isnull() function this function return dataframe of Boolean values which are True for NaN values."
},
{
"code": null,
"e": 26922,
"s": 26913,
"text": "Code #1:"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from listdf = pd.DataFrame(dict) # using isnull() function df.isnull()",
"e": 27261,
"s": 26922,
"text": null
},
{
"code": null,
"e": 27278,
"s": 27261,
"text": "Output: Code #2:"
},
{
"code": "# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # creating bool series True for NaN values bool_series = pd.isnull(data[\"Gender\"]) # filtering data # displaying data only with Gender = NaN data[bool_series] ",
"e": 27567,
"s": 27278,
"text": null
},
{
"code": null,
"e": 27655,
"s": 27567,
"text": "Output:As shown in the output image, only the rows having Gender = NULL are displayed. "
},
{
"code": null,
"e": 27813,
"s": 27655,
"text": "In order to check null values in Pandas Dataframe, we use notnull() function this function return dataframe of Boolean values which are False for NaN values."
},
{
"code": null,
"e": 27822,
"s": 27813,
"text": "Code #3:"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe using dictionarydf = pd.DataFrame(dict) # using notnull() function df.notnull()",
"e": 28169,
"s": 27822,
"text": null
},
{
"code": null,
"e": 28186,
"s": 28169,
"text": "Output: Code #4:"
},
{
"code": "# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # creating bool series True for NaN values bool_series = pd.notnull(data[\"Gender\"]) # filtering data # displayind data only with Gender = Not NaN data[bool_series] ",
"e": 28480,
"s": 28186,
"text": null
},
{
"code": null,
"e": 28572,
"s": 28480,
"text": "Output:As shown in the output image, only the rows having Gender = NOT NULL are displayed. "
},
{
"code": null,
"e": 28993,
"s": 28572,
"text": "In order to fill null values in a datasets, we use fillna(), replace() and interpolate() function these function replace NaN values with some value of their own. All these function help in filling a null values in datasets of a DataFrame. Interpolate() function is basically used to fill NA values in the dataframe but it uses various interpolation technique to fill the missing values rather than hard-coding the value."
},
{
"code": null,
"e": 29042,
"s": 28993,
"text": "Code #1: Filling null values with a single value"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # filling missing value using fillna() df.fillna(0)",
"e": 29401,
"s": 29042,
"text": null
},
{
"code": null,
"e": 29461,
"s": 29401,
"text": "Output: Code #2: Filling null values with the previous ones"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # filling a missing value with# previous ones df.fillna(method ='pad')",
"e": 29839,
"s": 29461,
"text": null
},
{
"code": null,
"e": 29894,
"s": 29839,
"text": "Output: Code #3: Filling null value with the next ones"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # filling null value using fillna() function df.fillna(method ='bfill')",
"e": 30274,
"s": 29894,
"text": null
},
{
"code": null,
"e": 30323,
"s": 30274,
"text": "Output: Code #4: Filling null values in CSV File"
},
{
"code": "# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # Printing the first 10 to 24 rows of# the data frame for visualization data[10:25]",
"e": 30531,
"s": 30323,
"text": null
},
{
"code": null,
"e": 30610,
"s": 30531,
"text": "Now we are going to fill all the null values in Gender column with “No Gender”"
},
{
"code": "# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # filling a null values using fillna() data[\"Gender\"].fillna(\"No Gender\", inplace = True) data",
"e": 30830,
"s": 30610,
"text": null
},
{
"code": null,
"e": 30891,
"s": 30830,
"text": "Output:Code #5: Filling a null values using replace() method"
},
{
"code": "# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # Printing the first 10 to 24 rows of# the data frame for visualization data[10:25]",
"e": 31099,
"s": 30891,
"text": null
},
{
"code": null,
"e": 31186,
"s": 31099,
"text": "Output:Now we are going to replace the all Nan value in the data frame with -99 value."
},
{
"code": "# importing pandas package import pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # will replace Nan value in dataframe with value -99 data.replace(to_replace = np.nan, value = -99) ",
"e": 31414,
"s": 31186,
"text": null
},
{
"code": null,
"e": 31508,
"s": 31414,
"text": "Output: Code #6: Using interpolate() function to fill the missing values using linear method."
},
{
"code": "# importing pandas as pd import pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[None, 2, 54, 3, None], \"C\":[20, 16, None, 3, 8], \"D\":[14, 3, None, None, 6]}) # Print the dataframe df ",
"e": 31797,
"s": 31508,
"text": null
},
{
"code": null,
"e": 31936,
"s": 31797,
"text": "Let’s interpolate the missing values using Linear method. Note that Linear method ignore the index and treat the values as equally spaced."
},
{
"code": "# to interpolate the missing values df.interpolate(method ='linear', limit_direction ='forward')",
"e": 32033,
"s": 31936,
"text": null
},
{
"code": null,
"e": 32237,
"s": 32033,
"text": "Output:As we can see the output, values in the first row could not get filled as the direction of filling of values is forward and there is no previous value which could have been used in interpolation. "
},
{
"code": null,
"e": 32392,
"s": 32237,
"text": "In order to drop a null values from a dataframe, we used dropna() function this function drop Rows/Columns of datasets with Null values in different ways."
},
{
"code": null,
"e": 32443,
"s": 32392,
"text": "Code #1: Dropping rows with at least 1 null value."
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, 40, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) df",
"e": 32802,
"s": 32443,
"text": null
},
{
"code": null,
"e": 32860,
"s": 32802,
"text": "Now we drop rows with at least one Nan value (Null value)"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, 40, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # using dropna() function df.dropna()",
"e": 33253,
"s": 32860,
"text": null
},
{
"code": null,
"e": 33322,
"s": 33253,
"text": "Output:Code #2: Dropping rows if all values in that row are missing."
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) df",
"e": 33689,
"s": 33322,
"text": null
},
{
"code": null,
"e": 33762,
"s": 33689,
"text": "Now we drop a rows whose all data is missing or contain null values(NaN)"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[np.nan, np.nan, np.nan, 65]} df = pd.DataFrame(dict) # using dropna() function df.dropna(how = 'all')",
"e": 34138,
"s": 33762,
"text": null
},
{
"code": null,
"e": 34146,
"s": 34138,
"text": "Output:"
},
{
"code": null,
"e": 34200,
"s": 34146,
"text": "Code #3: Dropping columns with at least 1 null value."
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[60, 67, 68, 65]} # creating a dataframe from dictionary df = pd.DataFrame(dict) df",
"e": 34559,
"s": 34200,
"text": null
},
{
"code": null,
"e": 34618,
"s": 34559,
"text": "Now we drop a columns which have at least 1 missing values"
},
{
"code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {'First Score':[100, np.nan, np.nan, 95], 'Second Score': [30, np.nan, 45, 56], 'Third Score':[52, np.nan, 80, 98], 'Fourth Score':[60, 67, 68, 65]} # creating a dataframe from dictionary df = pd.DataFrame(dict) # using dropna() function df.dropna(axis = 1)",
"e": 35022,
"s": 34618,
"text": null
},
{
"code": null,
"e": 35093,
"s": 35022,
"text": "Output : Code #4: Dropping Rows with at least 1 null value in CSV file"
},
{
"code": "# importing pandas module import pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # making new data frame with dropped NA values new_data = data.dropna(axis = 0, how ='any') new_data",
"e": 35322,
"s": 35093,
"text": null
},
{
"code": null,
"e": 35433,
"s": 35322,
"text": "Output:Now we compare sizes of data frames so that we can come to know how many rows had at least 1 Null value"
},
{
"code": "print(\"Old data frame length:\", len(data))print(\"New data frame length:\", len(new_data)) print(\"Number of rows with at least 1 NA value: \", (len(data)-len(new_data)))",
"e": 35600,
"s": 35433,
"text": null
},
{
"code": null,
"e": 35609,
"s": 35600,
"text": "Output :"
},
{
"code": null,
"e": 35711,
"s": 35609,
"text": "Old data frame length: 1000\nNew data frame length: 764\nNumber of rows with at least 1 NA value: 236\n"
},
{
"code": null,
"e": 35807,
"s": 35711,
"text": "Since the difference is 236, there were 236 rows which had at least 1 Null value in any column."
},
{
"code": null,
"e": 35820,
"s": 35807,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35844,
"s": 35820,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 35870,
"s": 35844,
"text": "Python pandas-missingData"
},
{
"code": null,
"e": 35884,
"s": 35870,
"text": "Python-pandas"
},
{
"code": null,
"e": 35891,
"s": 35884,
"text": "Python"
},
{
"code": null,
"e": 35989,
"s": 35891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35998,
"s": 35989,
"text": "Comments"
},
{
"code": null,
"e": 36011,
"s": 35998,
"text": "Old Comments"
},
{
"code": null,
"e": 36048,
"s": 36011,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 36084,
"s": 36048,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 36102,
"s": 36084,
"text": "Python Dictionary"
},
{
"code": null,
"e": 36125,
"s": 36102,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 36147,
"s": 36125,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 36186,
"s": 36147,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 36219,
"s": 36186,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 36268,
"s": 36219,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 36301,
"s": 36268,
"text": "Graph Plotting in Python | Set 1"
}
] |
Express.js | app.METHOD() Function - GeeksforGeeks
|
18 Jun, 2020
The app.METHOD() function is used to route an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so on.
Syntax:
app.METHOD(path, callback [, callback ...])
Parameters:
Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above.
Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.
A string representing a path.
A path pattern.
A regular expression pattern to match paths.
An array of combinations of any of the above.
Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above.
A middleware function.
A series of middleware functions (separated by commas).
An array of middleware functions.
A combination of all of the above.
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
var express = require('express');var app = express();var PORT = 3000; // Handling GET Requestapp.get('/user', function(req, res){ res.send("Handled GET Request");}); // Handling POST Requestapp.post('/user', function(req, res){ res.send("Handled POST Request");}); // Handling DELETE Requestapp.delete('/remove', function(req, res){ res.send("Handled DELETE Request");}); app.listen(PORT, function(err){ if (err) console.log("Error in server setup"); console.log("Server listening on Port", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on Port 3000
The project structure will look like this:
Make sure you have installed express module using the following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on Port 3000
node index.js
Output:
Server listening on Port 3000
So this is how you can use the express app.METHOD() function which is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase.
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js crypto.createCipheriv() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Explain the working of Node.js
How to make Mongoose multiple collections using Node.js ?
Disabling Sessions in Passport.js
Top 10 Front End Developer Skills That You Need in 2022
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?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24759,
"s": 24731,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 24990,
"s": 24759,
"text": "The app.METHOD() function is used to route an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so on."
},
{
"code": null,
"e": 24998,
"s": 24990,
"text": "Syntax:"
},
{
"code": null,
"e": 25042,
"s": 24998,
"text": "app.METHOD(path, callback [, callback ...])"
},
{
"code": null,
"e": 25054,
"s": 25042,
"text": "Parameters:"
},
{
"code": null,
"e": 25446,
"s": 25054,
"text": "Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above."
},
{
"code": null,
"e": 25658,
"s": 25446,
"text": "Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above."
},
{
"code": null,
"e": 25688,
"s": 25658,
"text": "A string representing a path."
},
{
"code": null,
"e": 25704,
"s": 25688,
"text": "A path pattern."
},
{
"code": null,
"e": 25749,
"s": 25704,
"text": "A regular expression pattern to match paths."
},
{
"code": null,
"e": 25795,
"s": 25749,
"text": "An array of combinations of any of the above."
},
{
"code": null,
"e": 25976,
"s": 25795,
"text": "Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above."
},
{
"code": null,
"e": 25999,
"s": 25976,
"text": "A middleware function."
},
{
"code": null,
"e": 26055,
"s": 25999,
"text": "A series of middleware functions (separated by commas)."
},
{
"code": null,
"e": 26089,
"s": 26055,
"text": "An array of middleware functions."
},
{
"code": null,
"e": 26124,
"s": 26089,
"text": "A combination of all of the above."
},
{
"code": null,
"e": 26156,
"s": 26124,
"text": "Installation of express module:"
},
{
"code": null,
"e": 26542,
"s": 26156,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 26663,
"s": 26542,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 26683,
"s": 26663,
"text": "npm install express"
},
{
"code": null,
"e": 26807,
"s": 26683,
"text": "After installing express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 26827,
"s": 26807,
"text": "npm version express"
},
{
"code": null,
"e": 26970,
"s": 26827,
"text": "After that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 26984,
"s": 26970,
"text": "node index.js"
},
{
"code": null,
"e": 27003,
"s": 26984,
"text": "Filename: index.js"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Handling GET Requestapp.get('/user', function(req, res){ res.send(\"Handled GET Request\");}); // Handling POST Requestapp.post('/user', function(req, res){ res.send(\"Handled POST Request\");}); // Handling DELETE Requestapp.delete('/remove', function(req, res){ res.send(\"Handled DELETE Request\");}); app.listen(PORT, function(err){ if (err) console.log(\"Error in server setup\"); console.log(\"Server listening on Port\", PORT);});",
"e": 27523,
"s": 27003,
"text": null
},
{
"code": null,
"e": 27549,
"s": 27523,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 27771,
"s": 27549,
"text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on Port 3000\n"
},
{
"code": null,
"e": 27814,
"s": 27771,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 27906,
"s": 27814,
"text": "Make sure you have installed express module using the following command:npm install express"
},
{
"code": null,
"e": 27926,
"s": 27906,
"text": "npm install express"
},
{
"code": null,
"e": 28015,
"s": 27926,
"text": "Run index.js file using below command:node index.jsOutput:Server listening on Port 3000\n"
},
{
"code": null,
"e": 28029,
"s": 28015,
"text": "node index.js"
},
{
"code": null,
"e": 28037,
"s": 28029,
"text": "Output:"
},
{
"code": null,
"e": 28068,
"s": 28037,
"text": "Server listening on Port 3000\n"
},
{
"code": null,
"e": 28219,
"s": 28068,
"text": "So this is how you can use the express app.METHOD() function which is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase."
},
{
"code": null,
"e": 28230,
"s": 28219,
"text": "Express.js"
},
{
"code": null,
"e": 28238,
"s": 28230,
"text": "Node.js"
},
{
"code": null,
"e": 28255,
"s": 28238,
"text": "Web Technologies"
},
{
"code": null,
"e": 28353,
"s": 28255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28362,
"s": 28353,
"text": "Comments"
},
{
"code": null,
"e": 28375,
"s": 28362,
"text": "Old Comments"
},
{
"code": null,
"e": 28414,
"s": 28375,
"text": "Node.js crypto.createCipheriv() Method"
},
{
"code": null,
"e": 28471,
"s": 28414,
"text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas"
},
{
"code": null,
"e": 28502,
"s": 28471,
"text": "Explain the working of Node.js"
},
{
"code": null,
"e": 28560,
"s": 28502,
"text": "How to make Mongoose multiple collections using Node.js ?"
},
{
"code": null,
"e": 28594,
"s": 28560,
"text": "Disabling Sessions in Passport.js"
},
{
"code": null,
"e": 28650,
"s": 28594,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28712,
"s": 28650,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28755,
"s": 28712,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28805,
"s": 28755,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
HTML Web Resources
|
In this chapter, we will learn about the various web resources in Microsoft Dynamics CRM.
An HTML Web Resource in CRM can contain any HTML content that can be rendered on a browser. Consider the following scenarios where you would like to use HTML Web Resources −
You have a static HTML page that you want to show inside CRM screen.
You have a static HTML page that you want to show inside CRM screen.
You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM.
You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM.
You want to display some information with a different look and feel from the standard CRM UI.
You want to display some information with a different look and feel from the standard CRM UI.
You have a custom ASPX page (outside CRM application) which gets rendered based on the input parameters. Since CRM does not allow you to have ASPX web resources, you can create an HTML Web Resource and call the external ASPX page from this HTML page.
We will create a very simple HTML Web Resource which will display a custom text ‘Welcome to TutorialsPoint’. Note that this is a very simple example of an HTML Web Resource. Practically, the HTML Web Resources would be more complex than this.
Step 1 − Create an HTML file named sampleHTMLWebResource.html and copy the following code.
<!DOCTYPE html>
<htmllang = "en"xmlns = "http://www.w3.org/1999/xhtml">
<head>
<metacharset = "utf-8"/>
<title>Welcome to Tutorials Point</title>
</head>
<body>
<h1>Welcome to Tutorials Point. This is an example of HTML Web Resource.</h1>
</body>
</html>
Step 2 − First, we will create a new Web Resource and then reference it on the Contact form. Open the DefaultSolution and navigate to WebResources tab from the left panel. Click New.
Step 3 − It will open a New Web Resource window. Enter the details as shown in the following screenshot and browse the HTML file that we created in Step 1. Click Save and Publish. Close the window.
Step 4 − You will see the new Web Resource added to the Web Resources grid.
Step 5 − Now open the Contact form via Settings → Customizations → Customize the System → Contact → Main Form. Select the Contact Information section and switch to Insert tab from the top ribbon bar. Click Web Resource.
Step 6 − It will open an Add Web Resource window. Click the Web Resource Lookup from this window, which will open the Web Resource Lookup Record window. Search the Web Resource that you just created (new_sampleHTMLWebResource), select it from the grid and click Add.
Step 7 − Coming back to Add Web Resource, enter the Name and Label as shown in the following screenshot and click OK. Close the window.
You will see the HTML Web Resource added below the Address field.
Step 8 − To test this out, open any Contact record and you will see the HTML Web Resource content displayed there.
There is no supported way of using the server-side code in HTML Web Resources.
There is no supported way of using the server-side code in HTML Web Resources.
HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end.
HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end.
16 Lectures
11.5 hours
SHIVPRASAD KOIRALA
33 Lectures
3 hours
Abhishek And Pukhraj
33 Lectures
5.5 hours
Abhishek And Pukhraj
40 Lectures
6.5 hours
Syed Raza
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2131,
"s": 2041,
"text": "In this chapter, we will learn about the various web resources in Microsoft Dynamics CRM."
},
{
"code": null,
"e": 2305,
"s": 2131,
"text": "An HTML Web Resource in CRM can contain any HTML content that can be rendered on a browser. Consider the following scenarios where you would like to use HTML Web Resources −"
},
{
"code": null,
"e": 2374,
"s": 2305,
"text": "You have a static HTML page that you want to show inside CRM screen."
},
{
"code": null,
"e": 2443,
"s": 2374,
"text": "You have a static HTML page that you want to show inside CRM screen."
},
{
"code": null,
"e": 2682,
"s": 2443,
"text": "You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM."
},
{
"code": null,
"e": 2921,
"s": 2682,
"text": "You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM."
},
{
"code": null,
"e": 3015,
"s": 2921,
"text": "You want to display some information with a different look and feel from the standard CRM UI."
},
{
"code": null,
"e": 3109,
"s": 3015,
"text": "You want to display some information with a different look and feel from the standard CRM UI."
},
{
"code": null,
"e": 3360,
"s": 3109,
"text": "You have a custom ASPX page (outside CRM application) which gets rendered based on the input parameters. Since CRM does not allow you to have ASPX web resources, you can create an HTML Web Resource and call the external ASPX page from this HTML page."
},
{
"code": null,
"e": 3603,
"s": 3360,
"text": "We will create a very simple HTML Web Resource which will display a custom text ‘Welcome to TutorialsPoint’. Note that this is a very simple example of an HTML Web Resource. Practically, the HTML Web Resources would be more complex than this."
},
{
"code": null,
"e": 3694,
"s": 3603,
"text": "Step 1 − Create an HTML file named sampleHTMLWebResource.html and copy the following code."
},
{
"code": null,
"e": 3993,
"s": 3694,
"text": "<!DOCTYPE html> \n<htmllang = \"en\"xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <metacharset = \"utf-8\"/> \n <title>Welcome to Tutorials Point</title> \n </head> \n \n <body> \n <h1>Welcome to Tutorials Point. This is an example of HTML Web Resource.</h1> \n </body> \n</html> "
},
{
"code": null,
"e": 4176,
"s": 3993,
"text": "Step 2 − First, we will create a new Web Resource and then reference it on the Contact form. Open the DefaultSolution and navigate to WebResources tab from the left panel. Click New."
},
{
"code": null,
"e": 4374,
"s": 4176,
"text": "Step 3 − It will open a New Web Resource window. Enter the details as shown in the following screenshot and browse the HTML file that we created in Step 1. Click Save and Publish. Close the window."
},
{
"code": null,
"e": 4450,
"s": 4374,
"text": "Step 4 − You will see the new Web Resource added to the Web Resources grid."
},
{
"code": null,
"e": 4670,
"s": 4450,
"text": "Step 5 − Now open the Contact form via Settings → Customizations → Customize the System → Contact → Main Form. Select the Contact Information section and switch to Insert tab from the top ribbon bar. Click Web Resource."
},
{
"code": null,
"e": 4937,
"s": 4670,
"text": "Step 6 − It will open an Add Web Resource window. Click the Web Resource Lookup from this window, which will open the Web Resource Lookup Record window. Search the Web Resource that you just created (new_sampleHTMLWebResource), select it from the grid and click Add."
},
{
"code": null,
"e": 5073,
"s": 4937,
"text": "Step 7 − Coming back to Add Web Resource, enter the Name and Label as shown in the following screenshot and click OK. Close the window."
},
{
"code": null,
"e": 5139,
"s": 5073,
"text": "You will see the HTML Web Resource added below the Address field."
},
{
"code": null,
"e": 5254,
"s": 5139,
"text": "Step 8 − To test this out, open any Contact record and you will see the HTML Web Resource content displayed there."
},
{
"code": null,
"e": 5333,
"s": 5254,
"text": "There is no supported way of using the server-side code in HTML Web Resources."
},
{
"code": null,
"e": 5412,
"s": 5333,
"text": "There is no supported way of using the server-side code in HTML Web Resources."
},
{
"code": null,
"e": 5608,
"s": 5412,
"text": "HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end."
},
{
"code": null,
"e": 5804,
"s": 5608,
"text": "HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end."
},
{
"code": null,
"e": 5840,
"s": 5804,
"text": "\n 16 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 5860,
"s": 5840,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5893,
"s": 5860,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5915,
"s": 5893,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5950,
"s": 5915,
"text": "\n 33 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5972,
"s": 5950,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 6007,
"s": 5972,
"text": "\n 40 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6018,
"s": 6007,
"text": " Syed Raza"
},
{
"code": null,
"e": 6051,
"s": 6018,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6091,
"s": 6051,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 6126,
"s": 6091,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6166,
"s": 6126,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 6173,
"s": 6166,
"text": " Print"
},
{
"code": null,
"e": 6184,
"s": 6173,
"text": " Add Notes"
}
] |
Beyond Grid Search: Hypercharge Hyperparameter Tuning for XGBoost | by Druce Vertes | Towards Data Science
|
Bayesian optimization of machine learning model hyperparameters works faster and better than grid search. Here’s how we can speed up hyperparameter tuning with 1) Bayesian optimization with Hyperopt and Optuna, running on... 2) the Ray distributed machine learning framework, with a unified Ray Tune API to many hyperparameter search algos and early stopping schedulers, and... 3) a distributed cluster of cloud instances for even faster tuning.
ResultsHyperparameter tuning overviewBayesian optimizationEarly stoppingImplementation detailsBaseline linear regressionElasticNetCV (Linear regression with L1 and L2 regularization)ElasticNet with GridSearchCVXGBoost: sequential grid search over hyperparameter subsets with early stoppingXGBoost: Hyperopt and Optuna search algorithmsLightGBM: Hyperopt and Optuna search algorithmsXGBoost on a Ray clusterLightGBM on a Ray clusterConcluding remarks
Results
Hyperparameter tuning overview
Bayesian optimization
Early stopping
Implementation details
Baseline linear regression
ElasticNetCV (Linear regression with L1 and L2 regularization)
ElasticNet with GridSearchCV
XGBoost: sequential grid search over hyperparameter subsets with early stopping
XGBoost: Hyperopt and Optuna search algorithms
LightGBM: Hyperopt and Optuna search algorithms
XGBoost on a Ray cluster
LightGBM on a Ray cluster
Concluding remarks
Bottom line up front: Here are results on the Ames housing data set, predicting Iowa home prices:
Times for single-instance are on a local desktop with 12 threads, comparable to EC2 4xlarge. Times for cluster are on m5.large x 32 (1 head node + 31 workers).
We obtain a big speedup when using Hyperopt and Optuna locally, compared to grid search. The sequential search performed about 261 trials, so the XGB/Optuna search performed about 3x as many trials in half the time and got a similar result.
The cluster of 32 instances (64 threads) gave a modest RMSE improvement vs. the local desktop with 12 threads. I tried to set this up so we would get some improvement in RMSE vs. local Hyperopt/Optuna (which we did with 2048 trials), and some speedup in training time (which we did not get with 64 threads). It ran twice the number of trials in slightly less than twice the time. The comparison is imperfect, local desktop vs. AWS, running Ray 1.0 on local and 1.1 on the cluster, different number of trials (better hyperparameter configs don’t get early-stopped and take longer to train). But the point was to see what kind of improvement one might obtain in practice, leveraging a cluster vs. a local desktop or laptop. Bottom line, modest benefit here from a 32-node cluster.
RMSEs are similar across the board. XGB with 2048 trials is best by a small margin among the boosting models.
LightGBM doesn’t offer an improvement over XGBoost here in RMSE or run time. In my experience, LightGBM is often faster, so you can train and tune more in a given time. But we don’t see that here. Possibly XGB interacts better with ASHA early stopping.
Similar RMSE between Hyperopt and Optuna. Optuna is consistently faster (up to 35% with LGBM/cluster).
Our simple ElasticNet baseline yields slightly better results than boosting, in seconds. This may be because our feature engineering was intensive and designed to fit the linear model. Not shown, SVR and KernelRidge outperform ElasticNet, and an ensemble improves over all individual algos.
Full notebooks are on GitHub.
(If you are not a data scientist ninja, here is some context. If you are, you can safely skip to the Bayesian Optimization section and the implementations below.)
Any sufficiently advanced machine learning model is indistinguishable from magic, and any sufficiently advanced machine learning model needs good tuning.
Backing up a step, here is a typical modeling workflow:
Exploratory data analysis: understand your data.
Feature engineering and feature selection: clean, transform and engineer the best possible features
Modeling: model selection and hyperparameter tuning to identify the best model architecture, and ensembling to combine multiple models
Evaluation: Describe the out-of-sample error and its expected distribution.
To minimize the out-of-sample error, you minimize the error from bias, meaning the model isn’t sufficiently sensitive to the signal in the data, and variance, meaning the model is too sensitive to the signal specific to the training data in ways that don’t generalize out-of-sample. Modeling is 90% data prep, the other half is all finding the optimal bias-variance tradeoff.
Hyperparameters help you tune the bias-variance tradeoff. For a simple logistic regression predicting survival on the Titanic, a regularization parameter lets you control overfitting by penalizing sensitivity to any individual feature. For a massive neural network doing machine translation, the number and types of layers, units, activation function, in addition to regularization, are hyperparameters. We select the best hyperparameters using k-fold cross-validation; this is what we call hyperparameter tuning.
The regression algorithms we use in this post are XGBoost and LightGBM, which are variations on gradient boosting. Gradient boosting is an ensembling method that usually involves decision trees. A decision tree constructs rules like, if the passenger is in first class and female, they probably survived the sinking of the Titanic. Trees are powerful, but a single deep decision tree with all your features will tend to overfit the training data. A random forest algorithm builds many decision trees based on random subsets of observations and features which then vote (bagging). The outcome of a vote by weak learners is less overfitted than training on all the data rows and all the feature columns to generate a single strong learner and performs better out-of-sample. Random forest hyperparameters include the number of trees, tree depth, and how many features and observations each tree should use.
Instead of aggregating many independent learners working in parallel, i.e. bagging, boosting uses many learners in series:
Start with a simple estimate like the median or base rate.
Fit a tree to the error in this prediction.
If you can predict the error, you can adjust for it and improve the prediction. Adjust the prediction not all the way to the tree prediction, but part of the way based on a learning rate (a hyperparameter).
Fit another tree to the error in the updated prediction and adjust the prediction further based on the learning rate.
Iteratively continue reducing the error for a specified number of boosting rounds (another hyperparameter).
The final estimate is the initial prediction plus the sum of all the predicted necessary adjustments (weighted by the learning rate).
The learning rate performs a similar function to voting in random forest, in the sense that no single decision tree determines too much of the final estimate. This ‘wisdom of crowds’ approach helps prevent overfitting.
Gradient boosting is the current state of the art for regression and classification on traditional structured tabular data (in contrast to less structured data like image/video/natural language processing, where deep learning, i.e. deep neural nets are state of the art).
Gradient boosting algorithms like XGBoost, LightGBM, and CatBoost have a very large number of hyperparameters, and tuning is an important part of using them.
These are the principal approaches to hyperparameter tuning:
Grid search: Given a finite set of discrete values for each hyperparameter, exhaustively cross-validate all combinations.
Random search: Given a discrete or continuous distribution for each hyperparameter, randomly sample from the joint distribution. Generally more efficient than exhaustive grid search.
Bayesian optimization: Sample like random search, but update the search space you sample from as you go, based on outcomes of prior searches.
Gradient-based optimization: Attempt to estimate the gradient of the cross-validation metric with respect to the hyperparameters and ascend/descend the gradient.
Evolutionary optimization: Sample the search space, discard combinations with poor metrics, and genetically evolve new combinations based on the successful combinations.
Population-based training: A method of performing hyperparameter optimization at the same time as training.
In this post, we focus on Bayesian optimization with Hyperopt and Optuna.
What is Bayesian optimization? When we perform a grid search, the search space is a prior: we believe that the best hyperparameter vector is in this search space. And a priori perhaps each hyperparameter combination has equal probability of being the best combination (a uniform distribution). So we try them all and pick the best one.
Perhaps we might do two passes of grid search. After an initial search on a broad, coarsely spaced grid, we do a deeper dive in a smaller area around the best metric from the first pass, with a more finely-spaced grid. In Bayesian terminology, we updated our prior.
Bayesian optimization starts by sampling randomly, e.g. 30 combinations, and computes the cross-validation metric for each of the 30 randomly sampled combinations using k-fold cross-validation. Then the algorithm updates the distribution it samples from, so that it is more likely to sample combinations similar to the good metrics, and less likely to sample combinations similar to the poor metrics. As it continues to sample, it continues to update the search distribution it samples from, based on the metrics it finds.
Good metrics are generally not uniformly distributed. If they are found close to one another in a Gaussian distribution or any distribution which we can model, then Bayesian optimization can exploit the underlying pattern, and is likely to be more efficient than grid search or naive random search.
HyperOpt is a Bayesian optimization algorithm by James Bergstra et al., see this excellent blog post by Subir Mansukhani.
Optuna is a Bayesian optimization algorithm by Takuya Akiba et al., see this excellent blog post by Crissman Loomis.
If, while evaluating a hyperparameter combination, the evaluation metric is not improving in training, or not improving fast enough to beat our best to date, we can discard a combination before fully training on it. Early stopping of unsuccessful training runs increases the speed and effectiveness of our search.
XGBoost and LightGBM helpfully provide early stopping callbacks to check on training progress and stop a training trial early (XGBoost; LightGBM). Hyperopt, Optuna, and Ray use these callbacks to stop bad trials quickly and accelerate performance.
In this post, we will use the Asynchronous Successive Halving Algorithm (ASHA) for early stopping, described in this blog post.
Hyper-Parameter Optimization: A Review of Algorithms and Applications Tong Yu, Hong Zhu (2020)
Hyperparameter Search in Machine Learning, Marc Claesen, Bart De Moor (2015)
Hyperparameter Optimization, Matthias Feurer, Frank Hutter (2019)
We use data from the Ames Housing Dataset. The original data set has 79 raw features. The data we will use has 100 features with a fair amount of feature engineering from my own attempt at modeling, which was in the top 5% or so when I submitted it to Kaggle. We model the log of the sale price, and use RMSE as our metric for model selection. We convert the RMSE back to raw dollar units for easier interpretability.
We use 4 regression algorithms:
LinearRegression: baseline with no hyperparameters
ElasticNet: Linear regression with L1 and L2 regularization (2 hyperparameters).
XGBoost
LightGBM
We use 5 approaches:
Native CV: In sklearn if an algorithm xxx has hyperparameters it will often have an xxxCV version, like ElasticNetCV, which performs automated grid search over hyperparameter iterators with specified kfolds.
GridSearchCV: Abstract grid search that can wrap around any sklearn algorithm, running multithreaded trials over specified kfolds.
Manual sequential grid search: How we typically implement grid search with XGBoost, which doesn’t play very well with GridSearchCV and has too many hyperparameters to tune in one pass.
Ray Tune on local desktop: Hyperopt and Optuna with ASHA early stopping.
Ray Tune on AWS cluster: Additionally scale out to run a single hyperparameter optimization task over many instances in a cluster.
Use the same kfolds for each run so the variation in the RMSE metric is not due to variation in kfolds.
We fit on the log response, so we convert error back to dollar units, for interpretability.
sklearn.model_selection.cross_val_score for evaluation
Jupyter %%time magic for wall time
n_jobs=-1 to run folds in parallel using all CPU cores available.
Note the wall time < 1 second and RMSE of 18192.
Full notebooks are on GitHub.
%%time# always use same RANDOM_STATE k-folds for comparability between tests, reproducibilityRANDOMSTATE = 42np.random.seed(RANDOMSTATE)kfolds = KFold(n_splits=10, shuffle=True, random_state=RANDOMSTATE)MEAN_RESPONSE=df[response].mean()def cv_to_raw(cv_val, mean_response=MEAN_RESPONSE): """convert log1p rmse to underlying SalePrice error""" # MEAN_RESPONSE assumes folds have same mean response, which is true in expectation but not in each fold # we can also pass the mean response for each fold # but we're really just looking to consistently convert the log value to a more meaningful unit return np.expm1(mean_response+cv_val) - np.expm1(mean_response) lr = LinearRegression()# compute CV metric for each foldscores = -cross_val_score(lr, df[predictors], df[response], scoring="neg_root_mean_squared_error", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print("Raw CV RMSE %.0f (STD %.0f)" % (np.mean(raw_scores), np.std(raw_scores)))
Raw CV RMSE 18192 (STD 1839)
Wall time: 65.4 ms
ElasticNet is linear regression with L1 and L2 regularization (2 hyperparameters).
When we use regularization, we need to scale our data so that the coefficient penalty has a similar impact across features. We use a pipeline with RobustScaler for scaling.
Fit a model and extract hyperparameters from the fitted model.
Then we do cross_val_score with reported hyperparams (There doesn't appear to be a way to extract the score from the fitted model without refitting)
Verbose output reports 130 tasks, for full grid search on 10 folds we would expect 13x9x10=1170. Apparently a clever optimization.
Note the modest reduction in RMSE vs. linear regression without regularization.
elasticnetcv = make_pipeline(RobustScaler(), ElasticNetCV(max_iter=100000, l1_ratio=[0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99], alphas=np.logspace(-4, -2, 9), cv=kfolds, n_jobs=-1, verbose=1, ))#train and get hyperparamselasticnetcv.fit(df[predictors], df[response])l1_ratio = elasticnetcv._final_estimator.l1_ratio_alpha = elasticnetcv._final_estimator.alpha_print('l1_ratio', l1_ratio)print('alpha', alpha)# evaluate using kfolds on full dataset# I don't see API to get CV error from elasticnetcv, so we use cross_val_scoreelasticnet = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=10000)scores = -cross_val_score(elasticnet, df[predictors], df[response], scoring="neg_root_mean_squared_error", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print()print("Log1p CV RMSE %.04f (STD %.04f)" % (np.mean(scores), np.std(scores)))print("Raw CV RMSE %.0f (STD %.0f)" % (np.mean(raw_scores), np.std(raw_scores)))l1_ratio 0.01alpha 0.0031622776601683794Log1p CV RMSE 0.1030 (STD 0.0109)Raw CV RMSE 18061 (STD 2008)CPU times: user 5.93 s, sys: 3.67 s, total: 9.6 sWall time: 1.61 s
Identical result, runs a little slower.
GridSearchCV verbose output shows 1170 jobs, which is the expected number 13x9x10.
gs = make_pipeline(RobustScaler(), GridSearchCV(ElasticNet(max_iter=100000), param_grid={'l1_ratio': [0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99], 'alpha': np.logspace(-4, -2, 9), }, scoring='neg_root_mean_squared_error', refit=True, cv=kfolds, n_jobs=-1, verbose=1 ))# do cv using kfolds on full datasetgs.fit(df[predictors], df[response])print('best params', gs._final_estimator.best_params_)print('best score', -gs._final_estimator.best_score_)l1_ratio = gs._final_estimator.best_params_['l1_ratio']alpha = gs._final_estimator.best_params_['alpha']# eval similarly to beforeelasticnet = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=100000)print(elasticnet)scores = -cross_val_score(elasticnet, df[predictors], df[response], scoring="neg_root_mean_squared_error", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print()print("Log1p CV RMSE %.06f (STD %.04f)" % (np.mean(scores), np.std(scores)))print("Raw CV RMSE %.0f (STD %.0f)" % (np.mean(raw_scores), np.std(raw_scores)))best params {'alpha': 0.0031622776601683794, 'l1_ratio': 0.01}best score 0.10247177583755482ElasticNet(alpha=0.0031622776601683794, l1_ratio=0.01, max_iter=100000)Log1p CV RMSE 0.103003 (STD 0.0109)Raw CV RMSE 18061 (STD 2008)Wall time: 5 s
It should be possible to use GridSearchCV with XGBoost. But when we also try to use early stopping, XGBoost wants an eval set. OK, we can give it a static eval set held out from GridSearchCV. Now, GridSearchCV does k-fold cross-validation in the training set but XGBoost uses a separate dedicated eval set for early stopping. It’s a bit of a Frankenstein methodology. See the notebook for the attempt at GridSearchCV with XGBoost and early stopping if you’re really interested.
Instead, we write our own grid search that gives XGBoost the correct hold-out set for each CV fold:
EARLY_STOPPING_ROUNDS=100 # stop if no improvement after 100 roundsdef my_cv(df, predictors, response, kfolds, regressor, verbose=False): """Roll our own CV train each kfold with early stopping return average metric, sd over kfolds, average best round""" metrics = [] best_iterations = [] for train_fold, cv_fold in kfolds.split(df): fold_X_train=df[predictors].values[train_fold] fold_y_train=df[response].values[train_fold] fold_X_test=df[predictors].values[cv_fold] fold_y_test=df[response].values[cv_fold] regressor.fit(fold_X_train, fold_y_train, early_stopping_rounds=EARLY_STOPPING_ROUNDS, eval_set=[(fold_X_test, fold_y_test)], eval_metric='rmse', verbose=verbose ) y_pred_test=regressor.predict(fold_X_test) metrics.append(np.sqrt(mean_squared_error(fold_y_test, y_pred_test))) best_iterations.append(regressor.best_iteration) return np.average(metrics), np.std(metrics), np.average(best_iterations)
XGBoost has many tuning parameters so an exhaustive grid search has an unreasonable number of combinations. Instead, we tune reduced sets sequentially using grid search and use early stopping.
This is the typical grid search methodology to tune XGBoost:
Set an initial set of starting parameters.
Tune sequentially on groups of hyperparameters that don’t interact too much between groups, to reduce the number of combinations tested.
First, tune max_depth.
Then tune subsample, colsample_bytree, and colsample_bylevel.
Finally, tune learning rate: a lower learning rate will need more boosting rounds (n_estimators).
Do 10-fold cross-validation on each hyperparameter combination. Pick hyperparameters to minimize average RMSE over kfolds.
Use XGboost early stopping to halt training in each fold if no improvement after 100 rounds.
After tuning and selecting the best hyperparameters, retrain and evaluate on the full dataset without early stopping, using the average boosting rounds across xval kfolds.1
As discussed, we use the XGBoost sklearn API and roll our own grid search which understands early stopping with k-folds, instead of GridSearchCV. (An alternative would be to use native xgboost .cv which understands early stopping but doesn’t use sklearn API (uses DMatrix, not numpy array or dataframe))
We write a helper function cv_over_param_dict which takes a list of param_dict dictionaries, runs trials over all dictionaries, and returns the best param_dict dictionary plus a dataframe of results.
We run cv_over_param_dict 3 times to do 3 grid searches over our 3 tuning rounds.
BOOST_ROUNDS=50000 # we use early stopping so make this arbitrarily highdef cv_over_param_dict(df, param_dict, predictors, response, kfolds, verbose=False): """given a list of dictionaries of xgb params run my_cv on params, store result in array return updated param_dict, results dataframe """ start_time = datetime.now() print("%-20s %s" % ("Start Time", start_time)) results = [] for i, d in enumerate(param_dict): xgb = XGBRegressor( objective='reg:squarederror', n_estimators=BOOST_ROUNDS, random_state=RANDOMSTATE, verbosity=1, n_jobs=-1, booster='gbtree', **d ) metric_rmse, metric_std, best_iteration = my_cv(df, predictors, response, kfolds, xgb, verbose=False) results.append([metric_rmse, metric_std, best_iteration, d]) print("%s %3d result mean: %.6f std: %.6f, iter: %.2f" % (datetime.strftime(datetime.now(), "%T"), i, metric_rmse, metric_std, best_iteration)) end_time = datetime.now() print("%-20s %s" % ("Start Time", start_time)) print("%-20s %s" % ("End Time", end_time)) print(str(timedelta(seconds=(end_time-start_time).seconds))) results_df = pd.DataFrame(results, columns=['rmse', 'std', 'best_iter', 'param_dict']).sort_values('rmse') display(results_df.head()) best_params = results_df.iloc[0]['param_dict'] return best_params, results_df# initial hyperparamscurrent_params = { 'max_depth': 5, 'colsample_bytree': 0.5, 'colsample_bylevel': 0.5, 'subsample': 0.5, 'learning_rate': 0.01,}################################################### round 1: tune depth##################################################max_depths = list(range(2,8))grid_search_dicts = [{'max_depth': md} for md in max_depths]# merge into full param dictsfull_search_dicts = [{**current_params, **d} for d in grid_search_dicts]# cv and get best paramscurrent_params, results_df = cv_over_param_dict(df, full_search_dicts, predictors, response, kfolds)################################################### round 2: tune subsample, colsample_bytree, colsample_bylevel################################################### subsamples = np.linspace(0.01, 1.0, 10)# colsample_bytrees = np.linspace(0.1, 1.0, 10)# colsample_bylevel = np.linspace(0.1, 1.0, 10)# narrower searchsubsamples = np.linspace(0.25, 0.75, 11)colsample_bytrees = np.linspace(0.1, 0.3, 5)colsample_bylevel = np.linspace(0.1, 0.3, 5)# subsamples = np.linspace(0.4, 0.9, 11)# colsample_bytrees = np.linspace(0.05, 0.25, 5)grid_search_dicts = [dict(zip(['subsample', 'colsample_bytree', 'colsample_bylevel'], [a, b, c])) for a,b,c in product(subsamples, colsample_bytrees, colsample_bylevel)]# merge into full param dictsfull_search_dicts = [{**current_params, **d} for d in grid_search_dicts]# cv and get best paramscurrent_params, results_df = cv_over_param_dict(df, full_search_dicts, predictors, response, kfolds)# round 3: learning ratelearning_rates = np.logspace(-3, -1, 5)grid_search_dicts = [{'learning_rate': lr} for lr in learning_rates]# merge into full param dictsfull_search_dicts = [{**current_params, **d} for d in grid_search_dicts]# cv and get best paramscurrent_params, results_df = cv_over_param_dict(df, full_search_dicts, predictors, response, kfolds, verbose=False)
The total training duration (the sum of times over the 3 iterations) is 1:24:22. This time may be an underestimate, since this search space is based on prior experience.
Finally, we refit using the best hyperparameters and evaluate:
xgb = XGBRegressor( objective='reg:squarederror', n_estimators=3438, random_state=RANDOMSTATE, verbosity=1, n_jobs=-1, booster='gbtree', **current_params) print(xgb)scores = -cross_val_score(xgb, df[predictors], df[response], scoring="neg_root_mean_squared_error", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print()print("Log1p CV RMSE %.06f (STD %.04f)" % (np.mean(scores), np.std(scores)))print("Raw CV RMSE %.0f (STD %.0f)" % (np.mean(raw_scores), np.std(raw_scores)))
The result essentially matches linear regression but is not as good as ElasticNet.
Raw CV RMSE 18193 (STD 2461)
The steps to run a Ray tuning job with Hyperopt are:
Set up a Ray search space as a config dict.Refactor the training loop into a function which takes the config dict as an argument and calls tune.report(rmse=rmse) to optimize a metric like RMSE.Call ray.tune with the config and a num_samples argument which specifies how many times to sample.
Set up a Ray search space as a config dict.
Refactor the training loop into a function which takes the config dict as an argument and calls tune.report(rmse=rmse) to optimize a metric like RMSE.
Call ray.tune with the config and a num_samples argument which specifies how many times to sample.
Set up the Ray search space:
xgb_tune_kwargs = { "n_estimators": tune.loguniform(100, 10000), "max_depth": tune.randint(0, 5), "subsample": tune.quniform(0.25, 0.75, 0.01), "colsample_bytree": tune.quniform(0.05, 0.5, 0.01), "colsample_bylevel": tune.quniform(0.05, 0.5, 0.01), "learning_rate": tune.quniform(-3.0, -1.0, 0.5), # powers of 10}xgb_tune_params = [k for k in xgb_tune_kwargs.keys() if k != 'wandb']xgb_tune_params
Set up the training function. Note that some search algos expect all hyperparameters to be floats and some search intervals to start at 0. So we convert params as necessary.
def my_xgb(config): # fix these configs to match calling convention # search wants to pass in floats but xgb wants ints config['n_estimators'] = int(config['n_estimators']) # pass float eg loguniform distribution, use int # hyperopt needs left to start at 0 but we want to start at 2 config['max_depth'] = int(config['max_depth']) + 2 config['learning_rate'] = 10 ** config['learning_rate'] xgb = XGBRegressor( objective='reg:squarederror', n_jobs=1, random_state=RANDOMSTATE, booster='gbtree', scale_pos_weight=1, **config, ) scores = -cross_val_score(xgb, df[predictors], df[response], scoring="neg_root_mean_squared_error", cv=kfolds) rmse = np.mean(scores) tune.report(rmse=rmse) return {"rmse": rmse}
Run Ray Tune:
algo = HyperOptSearch(random_state_seed=RANDOMSTATE)# ASHAscheduler = AsyncHyperBandScheduler()analysis = tune.run(my_xgb, num_samples=NUM_SAMPLES, config=xgb_tune_kwargs, name="hyperopt_xgb", metric="rmse", mode="min", search_alg=algo, scheduler=scheduler, verbose=1, )
Extract the best hyperparameters, and evaluate a model using them:
# results dataframe sorted by best metricparam_cols = ['config.' + k for k in xgb_tune_params]analysis_results_df = analysis.results_df[['rmse', 'date', 'time_this_iter_s'] + param_cols].sort_values('rmse')# extract top rowbest_config = {z: analysis_results_df.iloc[0]['config.' + z] for z in xgb_tune_params}xgb = XGBRegressor( objective='reg:squarederror', random_state=RANDOMSTATE, verbosity=1, n_jobs=-1, **best_config)print(xgb)scores = -cross_val_score(xgb, df[predictors], df[response], scoring="neg_root_mean_squared_error", cv=kfolds)raw_scores = [cv_to_raw(x) for x in scores]print()print("Log1p CV RMSE %.06f (STD %.04f)" % (np.mean(scores), np.std(scores)))print("Raw CV RMSE %.0f (STD %.0f)" % (np.mean(raw_scores), np.std(raw_scores)))
With NUM_SAMPLES=1024 we obtain:
Raw CV RMSE 18309 (STD 2428)
We can swap out Hyperopt for Optuna as simply as:
algo = OptunaSearch()
With NUM_SAMPLES=1024 we obtain:
Raw CV RMSE 18325 (STD 2473)
We can also easily swap out XGBoost for LightGBM.
Update the search space using LightGBM equivalents.
Update the search space using LightGBM equivalents.
lgbm_tune_kwargs = { "n_estimators": tune.loguniform(100, 10000), "max_depth": tune.randint(0, 5), 'num_leaves': tune.quniform(1, 10, 1.0), # xgb max_leaves "bagging_fraction": tune.quniform(0.5, 0.8, 0.01), # xgb subsample "feature_fraction": tune.quniform(0.05, 0.5, 0.01), # xgb colsample_bytree "learning_rate": tune.quniform(-3.0, -1.0, 0.5), }
Update training function:
Update training function:
def my_lgbm(config): # fix these configs config['n_estimators'] = int(config['n_estimators']) # pass float eg loguniform distribution, use int config['num_leaves'] = int(2**config['num_leaves']) config['learning_rate'] = 10**config['learning_rate'] lgbm = LGBMRegressor(objective='regression', max_bin=200, feature_fraction_seed=7, min_data_in_leaf=2, verbose=-1, n_jobs=1, # these are specified to suppress warnings colsample_bytree=None, min_child_samples=None, subsample=None, **config, ) scores = -cross_val_score(lgbm, df[predictors], df[response], scoring="neg_root_mean_squared_error", cv=kfolds) rmse=np.mean(scores) tune.report(rmse=rmse) return {'rmse': np.mean(scores)}
and run as before, swapping my_lgbm in place of my_xgb. Results for LGBM: (NUM_SAMPLES=1024):
Raw CV RMSE 18615 (STD 2356)
Swapping out Hyperopt for Optuna:
Raw CV RMSE 18614 (STD 2423)
Ray is a distributed framework. We can run a Ray Tune job over many instances using a cluster with a head node and many worker nodes.
Launching Ray is straightforward. On the head node we run ray start. On each worker node we run ray start --address x.x.x.x with the address of the head node. Then in python we call ray.init() to connect to the head node. Everything else proceeds as before, and the head node runs trials using all instances in the cluster and stores results in Redis.
Where it gets more complicated is specifying all the AWS details, instance types, regions, subnets, etc.
Clusters are defined in ray1.1.yaml. (So far in this notebook we have been using the current production ray 1.0, but I had difficulty getting a cluster to run with ray 1.0 so I switched to the dev nightly. YMMV.)
boto3 and AWS CLI configured credentials are used to spawn instances, so install and configure AWS CLI
Edit ray1.1.yaml file with, at a minimum, your AWS region and availability zone. Imageid may vary across regions, search for the current Deep Learning AMI (Ubuntu 18.04). You may not need to specify subnet, I had an issue with an inaccessible subnet when I let Ray default the subnet, possibly bad defaults somewhere.
To obtain those variables, launch the latest Deep Learning AMI (Ubuntu 18.04) currently Version 35.0 into a small instance in your favorite region/zone
Test that it works
Note the 4 variables: region, availability zone, subnet, AMI imageid
Terminate the instance and edit ray1.1.yaml with your region, availability zone, AMI imageid, optionally subnet
It may be advisable create your own image with all updates and requirements pre-installed and specify its AMI imageid, instead of using the generic image and installing everything at launch.
To run the cluster: ray up ray1.1.yaml
Creates head instance using AMI specified.
Installs Ray and related requirements including XGBoost from requirements.txt
Clones the druce/iowa repo from GitHub
Launches worker nodes per auto-scaling parameters (currently we fix the number of nodes because we’re not benchmarking the time the cluster will take to auto-scale)
After the cluster starts you can check the AWS console and note that several instances were launched.
Check ray monitor ray1.1.yaml for any error messages
Run Jupyter on the cluster with port forwarding ray exec ray1.1.yaml --port-forward=8899 'jupyter notebook --port=8899'
Open the notebook on the generated URL which is printed on the console at startup e.g. http://localhost:8899/?token=5f46d4355ae7174524ba71f30ef3f0633a20b19a204b93b4
You can run a terminal on the head node of the cluster with ray attach /Users/drucev/projects/iowa/ray1.1.yaml
You can ssh explicitly with the IP address and the generated private key ssh -o IdentitiesOnly=yes -i ~/.ssh/ray-autoscaler_1_us-east-1.pem ubuntu@54.161.200.54
Run port forwarding to the Ray dashboard with ray dashboard ray1.1.yaml and then open http://localhost:8265/
Make sure to choose the default kernel in Jupyter to run in the correct conda environment with all installs
Make sure to use the ray.init() command given in the startup messages. ray.init(address='localhost:6379', _redis_password='5241590000000000')
The cluster will incur AWS charges so ray down ray1.1.yaml when complete
See hyperparameter_optimization_cluster.ipynb, separated out so each notebook can be run end-to-end with/without cluster setup
See Ray docs for additional info on Ray clusters.
Besides connecting to the cluster instead of running Ray Tune locally, no other change to code is needed to run on the cluster
analysis = tune.run(my_xgb, num_samples=NUM_SAMPLES, config=xgb_tune_kwargs, name="hyperopt_xgb", metric="rmse", mode="min", search_alg=algo, scheduler=scheduler, # add this because distributed jobs occasionally error out raise_on_failed_trial=False, # otherwise no reults df returned if any trial error verbose=1, )
Results for XGBM on cluster (2048 samples, cluster is 32 m5.large instances):
Hyperopt (time 1:30:58)
Raw CV RMSE 18030 (STD 2356)
Optuna (time 1:29:57)
Raw CV RMSE 18028 (STD 2353)
Similarly for LightGBM:
analysis = tune.run(my_lgbm, num_samples=NUM_SAMPLES, config = lgbm_tune_kwargs, name="hyperopt_lgbm", metric="rmse", mode="min", search_alg=algo, scheduler=scheduler, raise_on_failed_trial=False, # otherwise no reults df returned if any trial error verbose=1, )
Results for LightGBM on cluster (2048 samples, cluster is 32 m5.large instances):
Hyperopt (time: 1:05:19) :
Raw CV RMSE 18459 (STD 2511)
Optuna (time 0:48:16):
Raw CV RMSE 18458 (STD 2511)
In every case I’ve applied them, Hyperopt and Optuna have given me at least a small improvement in the best metrics I found using grid search methods. Bayesian optimization tunes faster with a less manual process vs. sequential tuning. It’s fire-and-forget.
Is Ray Tune the way to go for hyperparameter tuning? Provisionally, yes. Ray provides integration between the underlying ML (e.g. XGBoost), the Bayesian search (e.g. Hyperopt), and early stopping (ASHA). It allows us to easily swap search algorithms.
There are other alternative search algorithms in the Ray docs but these seem to be the most popular, and I haven’t got the others to run yet. If after a while I find I am always using e.g. Hyperopt and never use clusters, I might use the native Hyperopt/XGBoost integration without Ray, to access any native Hyperopt features and because it’s one less technology in the stack.
Clusters? Most of the time I don’t have a need, costs add up, did not see as large a speedup as expected. I only see ~2x speedup on the 32-instance cluster. Setting up the test I expected a bit less than 4x speedup accounting for slightly less-than-linear scaling. The longest run I have tried, with 4096 samples, ran overnight on desktop. My MacBook Pro w/16 threads and desktop with 12 threads and GPU are plenty powerful for this data set. Still, it’s useful to have the clustering option in the back pocket. In production, it may be more standard and maintainable to deploy with e.g. Terraform, Kubernetes than the Ray native YAML cluster config file. If you want to train big data at scale you need to really understand and streamline your pipeline.
It continues to surprise me that ElasticNet, i.e. regularized linear regression, performs slightly better than boosting on this dataset. I heavily engineered features so that linear methods work well. Predictors were chosen using Lasso/ElasticNet and I used log and Box-Cox transforms to force predictors to follow assumptions of least-squares. But still, boosting is supposed to be the gold standard for tabular data.
This may tend to validate one of the critiques of machine learning, that the most powerful machine learning methods don’t necessarily always converge all the way to the best solution. If you have a ground truth that is linear plus noise, a complex XGBoost or neural network algorithm should get arbitrarily close to the closed-form optimal solution, but will probably never match the optimal solution exactly. XGBoost regression is piecewise constant and the complex neural network is subject to the vagaries of stochastic gradient descent. I thought arbitrarily close meant almost indistinguishable. But clearly this is not always the case.
ElasticNet with L1 + L2 regularization plus gradient descent and hyperparameter optimization is still machine learning. It’s simply a form of ML better matched to this problem. In the real world where data sets don’t match assumptions of OLS, gradient boosting generally performs extremely well. And even on this dataset, engineered for success with the linear models, SVR and KernelRidge performed better than ElasticNet (not shown) and ensembling ElasticNet with XGBoost, LightGBM, SVR, neural networks worked best of all.
To paraphrase Casey Stengel, clever feature engineering will always outperform clever model algorithms and vice-versa2. But improving your hyperparameters will always improve your results. Bayesian optimization can be considered a best practice.
Again, the full code is on GitHub
1 It would be more sound to separately tune the stopping rounds. Just averaging the best stopping time across kfolds is questionable. In a real world scenario, we should keep a holdout test set. We should retrain on the full training dataset (not kfolds) with early stopping to get the best number of boosting rounds. Then we should measure RMSE in the test set using all the cross-validated parameters including number of boosting rounds for the expected OOS RMSE. However, for the purpose of comparing tuning methods, the CV error is OK. We just want to look at how we would make model decisions using CV and not worry too much about the generalization error. One could even argue it adds a little more noise to the comparison of hyperparameter selection. But a test set would be the correct methodology in practice. It wouldn’t change conclusions directionally and I’m not going to rerun everything but if I were to start over I would do it that way.
2 This is not intended to make sense.
|
[
{
"code": null,
"e": 618,
"s": 172,
"text": "Bayesian optimization of machine learning model hyperparameters works faster and better than grid search. Here’s how we can speed up hyperparameter tuning with 1) Bayesian optimization with Hyperopt and Optuna, running on... 2) the Ray distributed machine learning framework, with a unified Ray Tune API to many hyperparameter search algos and early stopping schedulers, and... 3) a distributed cluster of cloud instances for even faster tuning."
},
{
"code": null,
"e": 1068,
"s": 618,
"text": "ResultsHyperparameter tuning overviewBayesian optimizationEarly stoppingImplementation detailsBaseline linear regressionElasticNetCV (Linear regression with L1 and L2 regularization)ElasticNet with GridSearchCVXGBoost: sequential grid search over hyperparameter subsets with early stoppingXGBoost: Hyperopt and Optuna search algorithmsLightGBM: Hyperopt and Optuna search algorithmsXGBoost on a Ray clusterLightGBM on a Ray clusterConcluding remarks"
},
{
"code": null,
"e": 1076,
"s": 1068,
"text": "Results"
},
{
"code": null,
"e": 1107,
"s": 1076,
"text": "Hyperparameter tuning overview"
},
{
"code": null,
"e": 1129,
"s": 1107,
"text": "Bayesian optimization"
},
{
"code": null,
"e": 1144,
"s": 1129,
"text": "Early stopping"
},
{
"code": null,
"e": 1167,
"s": 1144,
"text": "Implementation details"
},
{
"code": null,
"e": 1194,
"s": 1167,
"text": "Baseline linear regression"
},
{
"code": null,
"e": 1257,
"s": 1194,
"text": "ElasticNetCV (Linear regression with L1 and L2 regularization)"
},
{
"code": null,
"e": 1286,
"s": 1257,
"text": "ElasticNet with GridSearchCV"
},
{
"code": null,
"e": 1366,
"s": 1286,
"text": "XGBoost: sequential grid search over hyperparameter subsets with early stopping"
},
{
"code": null,
"e": 1413,
"s": 1366,
"text": "XGBoost: Hyperopt and Optuna search algorithms"
},
{
"code": null,
"e": 1461,
"s": 1413,
"text": "LightGBM: Hyperopt and Optuna search algorithms"
},
{
"code": null,
"e": 1486,
"s": 1461,
"text": "XGBoost on a Ray cluster"
},
{
"code": null,
"e": 1512,
"s": 1486,
"text": "LightGBM on a Ray cluster"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Concluding remarks"
},
{
"code": null,
"e": 1629,
"s": 1531,
"text": "Bottom line up front: Here are results on the Ames housing data set, predicting Iowa home prices:"
},
{
"code": null,
"e": 1789,
"s": 1629,
"text": "Times for single-instance are on a local desktop with 12 threads, comparable to EC2 4xlarge. Times for cluster are on m5.large x 32 (1 head node + 31 workers)."
},
{
"code": null,
"e": 2030,
"s": 1789,
"text": "We obtain a big speedup when using Hyperopt and Optuna locally, compared to grid search. The sequential search performed about 261 trials, so the XGB/Optuna search performed about 3x as many trials in half the time and got a similar result."
},
{
"code": null,
"e": 2809,
"s": 2030,
"text": "The cluster of 32 instances (64 threads) gave a modest RMSE improvement vs. the local desktop with 12 threads. I tried to set this up so we would get some improvement in RMSE vs. local Hyperopt/Optuna (which we did with 2048 trials), and some speedup in training time (which we did not get with 64 threads). It ran twice the number of trials in slightly less than twice the time. The comparison is imperfect, local desktop vs. AWS, running Ray 1.0 on local and 1.1 on the cluster, different number of trials (better hyperparameter configs don’t get early-stopped and take longer to train). But the point was to see what kind of improvement one might obtain in practice, leveraging a cluster vs. a local desktop or laptop. Bottom line, modest benefit here from a 32-node cluster."
},
{
"code": null,
"e": 2919,
"s": 2809,
"text": "RMSEs are similar across the board. XGB with 2048 trials is best by a small margin among the boosting models."
},
{
"code": null,
"e": 3172,
"s": 2919,
"text": "LightGBM doesn’t offer an improvement over XGBoost here in RMSE or run time. In my experience, LightGBM is often faster, so you can train and tune more in a given time. But we don’t see that here. Possibly XGB interacts better with ASHA early stopping."
},
{
"code": null,
"e": 3275,
"s": 3172,
"text": "Similar RMSE between Hyperopt and Optuna. Optuna is consistently faster (up to 35% with LGBM/cluster)."
},
{
"code": null,
"e": 3566,
"s": 3275,
"text": "Our simple ElasticNet baseline yields slightly better results than boosting, in seconds. This may be because our feature engineering was intensive and designed to fit the linear model. Not shown, SVR and KernelRidge outperform ElasticNet, and an ensemble improves over all individual algos."
},
{
"code": null,
"e": 3596,
"s": 3566,
"text": "Full notebooks are on GitHub."
},
{
"code": null,
"e": 3759,
"s": 3596,
"text": "(If you are not a data scientist ninja, here is some context. If you are, you can safely skip to the Bayesian Optimization section and the implementations below.)"
},
{
"code": null,
"e": 3913,
"s": 3759,
"text": "Any sufficiently advanced machine learning model is indistinguishable from magic, and any sufficiently advanced machine learning model needs good tuning."
},
{
"code": null,
"e": 3969,
"s": 3913,
"text": "Backing up a step, here is a typical modeling workflow:"
},
{
"code": null,
"e": 4018,
"s": 3969,
"text": "Exploratory data analysis: understand your data."
},
{
"code": null,
"e": 4118,
"s": 4018,
"text": "Feature engineering and feature selection: clean, transform and engineer the best possible features"
},
{
"code": null,
"e": 4253,
"s": 4118,
"text": "Modeling: model selection and hyperparameter tuning to identify the best model architecture, and ensembling to combine multiple models"
},
{
"code": null,
"e": 4329,
"s": 4253,
"text": "Evaluation: Describe the out-of-sample error and its expected distribution."
},
{
"code": null,
"e": 4705,
"s": 4329,
"text": "To minimize the out-of-sample error, you minimize the error from bias, meaning the model isn’t sufficiently sensitive to the signal in the data, and variance, meaning the model is too sensitive to the signal specific to the training data in ways that don’t generalize out-of-sample. Modeling is 90% data prep, the other half is all finding the optimal bias-variance tradeoff."
},
{
"code": null,
"e": 5219,
"s": 4705,
"text": "Hyperparameters help you tune the bias-variance tradeoff. For a simple logistic regression predicting survival on the Titanic, a regularization parameter lets you control overfitting by penalizing sensitivity to any individual feature. For a massive neural network doing machine translation, the number and types of layers, units, activation function, in addition to regularization, are hyperparameters. We select the best hyperparameters using k-fold cross-validation; this is what we call hyperparameter tuning."
},
{
"code": null,
"e": 6123,
"s": 5219,
"text": "The regression algorithms we use in this post are XGBoost and LightGBM, which are variations on gradient boosting. Gradient boosting is an ensembling method that usually involves decision trees. A decision tree constructs rules like, if the passenger is in first class and female, they probably survived the sinking of the Titanic. Trees are powerful, but a single deep decision tree with all your features will tend to overfit the training data. A random forest algorithm builds many decision trees based on random subsets of observations and features which then vote (bagging). The outcome of a vote by weak learners is less overfitted than training on all the data rows and all the feature columns to generate a single strong learner and performs better out-of-sample. Random forest hyperparameters include the number of trees, tree depth, and how many features and observations each tree should use."
},
{
"code": null,
"e": 6246,
"s": 6123,
"text": "Instead of aggregating many independent learners working in parallel, i.e. bagging, boosting uses many learners in series:"
},
{
"code": null,
"e": 6305,
"s": 6246,
"text": "Start with a simple estimate like the median or base rate."
},
{
"code": null,
"e": 6349,
"s": 6305,
"text": "Fit a tree to the error in this prediction."
},
{
"code": null,
"e": 6556,
"s": 6349,
"text": "If you can predict the error, you can adjust for it and improve the prediction. Adjust the prediction not all the way to the tree prediction, but part of the way based on a learning rate (a hyperparameter)."
},
{
"code": null,
"e": 6674,
"s": 6556,
"text": "Fit another tree to the error in the updated prediction and adjust the prediction further based on the learning rate."
},
{
"code": null,
"e": 6782,
"s": 6674,
"text": "Iteratively continue reducing the error for a specified number of boosting rounds (another hyperparameter)."
},
{
"code": null,
"e": 6916,
"s": 6782,
"text": "The final estimate is the initial prediction plus the sum of all the predicted necessary adjustments (weighted by the learning rate)."
},
{
"code": null,
"e": 7135,
"s": 6916,
"text": "The learning rate performs a similar function to voting in random forest, in the sense that no single decision tree determines too much of the final estimate. This ‘wisdom of crowds’ approach helps prevent overfitting."
},
{
"code": null,
"e": 7407,
"s": 7135,
"text": "Gradient boosting is the current state of the art for regression and classification on traditional structured tabular data (in contrast to less structured data like image/video/natural language processing, where deep learning, i.e. deep neural nets are state of the art)."
},
{
"code": null,
"e": 7565,
"s": 7407,
"text": "Gradient boosting algorithms like XGBoost, LightGBM, and CatBoost have a very large number of hyperparameters, and tuning is an important part of using them."
},
{
"code": null,
"e": 7626,
"s": 7565,
"text": "These are the principal approaches to hyperparameter tuning:"
},
{
"code": null,
"e": 7748,
"s": 7626,
"text": "Grid search: Given a finite set of discrete values for each hyperparameter, exhaustively cross-validate all combinations."
},
{
"code": null,
"e": 7931,
"s": 7748,
"text": "Random search: Given a discrete or continuous distribution for each hyperparameter, randomly sample from the joint distribution. Generally more efficient than exhaustive grid search."
},
{
"code": null,
"e": 8073,
"s": 7931,
"text": "Bayesian optimization: Sample like random search, but update the search space you sample from as you go, based on outcomes of prior searches."
},
{
"code": null,
"e": 8235,
"s": 8073,
"text": "Gradient-based optimization: Attempt to estimate the gradient of the cross-validation metric with respect to the hyperparameters and ascend/descend the gradient."
},
{
"code": null,
"e": 8405,
"s": 8235,
"text": "Evolutionary optimization: Sample the search space, discard combinations with poor metrics, and genetically evolve new combinations based on the successful combinations."
},
{
"code": null,
"e": 8513,
"s": 8405,
"text": "Population-based training: A method of performing hyperparameter optimization at the same time as training."
},
{
"code": null,
"e": 8587,
"s": 8513,
"text": "In this post, we focus on Bayesian optimization with Hyperopt and Optuna."
},
{
"code": null,
"e": 8923,
"s": 8587,
"text": "What is Bayesian optimization? When we perform a grid search, the search space is a prior: we believe that the best hyperparameter vector is in this search space. And a priori perhaps each hyperparameter combination has equal probability of being the best combination (a uniform distribution). So we try them all and pick the best one."
},
{
"code": null,
"e": 9189,
"s": 8923,
"text": "Perhaps we might do two passes of grid search. After an initial search on a broad, coarsely spaced grid, we do a deeper dive in a smaller area around the best metric from the first pass, with a more finely-spaced grid. In Bayesian terminology, we updated our prior."
},
{
"code": null,
"e": 9712,
"s": 9189,
"text": "Bayesian optimization starts by sampling randomly, e.g. 30 combinations, and computes the cross-validation metric for each of the 30 randomly sampled combinations using k-fold cross-validation. Then the algorithm updates the distribution it samples from, so that it is more likely to sample combinations similar to the good metrics, and less likely to sample combinations similar to the poor metrics. As it continues to sample, it continues to update the search distribution it samples from, based on the metrics it finds."
},
{
"code": null,
"e": 10011,
"s": 9712,
"text": "Good metrics are generally not uniformly distributed. If they are found close to one another in a Gaussian distribution or any distribution which we can model, then Bayesian optimization can exploit the underlying pattern, and is likely to be more efficient than grid search or naive random search."
},
{
"code": null,
"e": 10133,
"s": 10011,
"text": "HyperOpt is a Bayesian optimization algorithm by James Bergstra et al., see this excellent blog post by Subir Mansukhani."
},
{
"code": null,
"e": 10250,
"s": 10133,
"text": "Optuna is a Bayesian optimization algorithm by Takuya Akiba et al., see this excellent blog post by Crissman Loomis."
},
{
"code": null,
"e": 10564,
"s": 10250,
"text": "If, while evaluating a hyperparameter combination, the evaluation metric is not improving in training, or not improving fast enough to beat our best to date, we can discard a combination before fully training on it. Early stopping of unsuccessful training runs increases the speed and effectiveness of our search."
},
{
"code": null,
"e": 10812,
"s": 10564,
"text": "XGBoost and LightGBM helpfully provide early stopping callbacks to check on training progress and stop a training trial early (XGBoost; LightGBM). Hyperopt, Optuna, and Ray use these callbacks to stop bad trials quickly and accelerate performance."
},
{
"code": null,
"e": 10940,
"s": 10812,
"text": "In this post, we will use the Asynchronous Successive Halving Algorithm (ASHA) for early stopping, described in this blog post."
},
{
"code": null,
"e": 11035,
"s": 10940,
"text": "Hyper-Parameter Optimization: A Review of Algorithms and Applications Tong Yu, Hong Zhu (2020)"
},
{
"code": null,
"e": 11112,
"s": 11035,
"text": "Hyperparameter Search in Machine Learning, Marc Claesen, Bart De Moor (2015)"
},
{
"code": null,
"e": 11178,
"s": 11112,
"text": "Hyperparameter Optimization, Matthias Feurer, Frank Hutter (2019)"
},
{
"code": null,
"e": 11596,
"s": 11178,
"text": "We use data from the Ames Housing Dataset. The original data set has 79 raw features. The data we will use has 100 features with a fair amount of feature engineering from my own attempt at modeling, which was in the top 5% or so when I submitted it to Kaggle. We model the log of the sale price, and use RMSE as our metric for model selection. We convert the RMSE back to raw dollar units for easier interpretability."
},
{
"code": null,
"e": 11628,
"s": 11596,
"text": "We use 4 regression algorithms:"
},
{
"code": null,
"e": 11679,
"s": 11628,
"text": "LinearRegression: baseline with no hyperparameters"
},
{
"code": null,
"e": 11760,
"s": 11679,
"text": "ElasticNet: Linear regression with L1 and L2 regularization (2 hyperparameters)."
},
{
"code": null,
"e": 11768,
"s": 11760,
"text": "XGBoost"
},
{
"code": null,
"e": 11777,
"s": 11768,
"text": "LightGBM"
},
{
"code": null,
"e": 11798,
"s": 11777,
"text": "We use 5 approaches:"
},
{
"code": null,
"e": 12006,
"s": 11798,
"text": "Native CV: In sklearn if an algorithm xxx has hyperparameters it will often have an xxxCV version, like ElasticNetCV, which performs automated grid search over hyperparameter iterators with specified kfolds."
},
{
"code": null,
"e": 12137,
"s": 12006,
"text": "GridSearchCV: Abstract grid search that can wrap around any sklearn algorithm, running multithreaded trials over specified kfolds."
},
{
"code": null,
"e": 12322,
"s": 12137,
"text": "Manual sequential grid search: How we typically implement grid search with XGBoost, which doesn’t play very well with GridSearchCV and has too many hyperparameters to tune in one pass."
},
{
"code": null,
"e": 12395,
"s": 12322,
"text": "Ray Tune on local desktop: Hyperopt and Optuna with ASHA early stopping."
},
{
"code": null,
"e": 12526,
"s": 12395,
"text": "Ray Tune on AWS cluster: Additionally scale out to run a single hyperparameter optimization task over many instances in a cluster."
},
{
"code": null,
"e": 12630,
"s": 12526,
"text": "Use the same kfolds for each run so the variation in the RMSE metric is not due to variation in kfolds."
},
{
"code": null,
"e": 12722,
"s": 12630,
"text": "We fit on the log response, so we convert error back to dollar units, for interpretability."
},
{
"code": null,
"e": 12777,
"s": 12722,
"text": "sklearn.model_selection.cross_val_score for evaluation"
},
{
"code": null,
"e": 12812,
"s": 12777,
"text": "Jupyter %%time magic for wall time"
},
{
"code": null,
"e": 12878,
"s": 12812,
"text": "n_jobs=-1 to run folds in parallel using all CPU cores available."
},
{
"code": null,
"e": 12927,
"s": 12878,
"text": "Note the wall time < 1 second and RMSE of 18192."
},
{
"code": null,
"e": 12957,
"s": 12927,
"text": "Full notebooks are on GitHub."
},
{
"code": null,
"e": 14009,
"s": 12957,
"text": "%%time# always use same RANDOM_STATE k-folds for comparability between tests, reproducibilityRANDOMSTATE = 42np.random.seed(RANDOMSTATE)kfolds = KFold(n_splits=10, shuffle=True, random_state=RANDOMSTATE)MEAN_RESPONSE=df[response].mean()def cv_to_raw(cv_val, mean_response=MEAN_RESPONSE): \"\"\"convert log1p rmse to underlying SalePrice error\"\"\" # MEAN_RESPONSE assumes folds have same mean response, which is true in expectation but not in each fold # we can also pass the mean response for each fold # but we're really just looking to consistently convert the log value to a more meaningful unit return np.expm1(mean_response+cv_val) - np.expm1(mean_response) lr = LinearRegression()# compute CV metric for each foldscores = -cross_val_score(lr, df[predictors], df[response], scoring=\"neg_root_mean_squared_error\", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print(\"Raw CV RMSE %.0f (STD %.0f)\" % (np.mean(raw_scores), np.std(raw_scores)))"
},
{
"code": null,
"e": 14038,
"s": 14009,
"text": "Raw CV RMSE 18192 (STD 1839)"
},
{
"code": null,
"e": 14057,
"s": 14038,
"text": "Wall time: 65.4 ms"
},
{
"code": null,
"e": 14140,
"s": 14057,
"text": "ElasticNet is linear regression with L1 and L2 regularization (2 hyperparameters)."
},
{
"code": null,
"e": 14313,
"s": 14140,
"text": "When we use regularization, we need to scale our data so that the coefficient penalty has a similar impact across features. We use a pipeline with RobustScaler for scaling."
},
{
"code": null,
"e": 14376,
"s": 14313,
"text": "Fit a model and extract hyperparameters from the fitted model."
},
{
"code": null,
"e": 14525,
"s": 14376,
"text": "Then we do cross_val_score with reported hyperparams (There doesn't appear to be a way to extract the score from the fitted model without refitting)"
},
{
"code": null,
"e": 14656,
"s": 14525,
"text": "Verbose output reports 130 tasks, for full grid search on 10 folds we would expect 13x9x10=1170. Apparently a clever optimization."
},
{
"code": null,
"e": 14736,
"s": 14656,
"text": "Note the modest reduction in RMSE vs. linear regression without regularization."
},
{
"code": null,
"e": 16256,
"s": 14736,
"text": "elasticnetcv = make_pipeline(RobustScaler(), ElasticNetCV(max_iter=100000, l1_ratio=[0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99], alphas=np.logspace(-4, -2, 9), cv=kfolds, n_jobs=-1, verbose=1, ))#train and get hyperparamselasticnetcv.fit(df[predictors], df[response])l1_ratio = elasticnetcv._final_estimator.l1_ratio_alpha = elasticnetcv._final_estimator.alpha_print('l1_ratio', l1_ratio)print('alpha', alpha)# evaluate using kfolds on full dataset# I don't see API to get CV error from elasticnetcv, so we use cross_val_scoreelasticnet = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=10000)scores = -cross_val_score(elasticnet, df[predictors], df[response], scoring=\"neg_root_mean_squared_error\", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print()print(\"Log1p CV RMSE %.04f (STD %.04f)\" % (np.mean(scores), np.std(scores)))print(\"Raw CV RMSE %.0f (STD %.0f)\" % (np.mean(raw_scores), np.std(raw_scores)))l1_ratio 0.01alpha 0.0031622776601683794Log1p CV RMSE 0.1030 (STD 0.0109)Raw CV RMSE 18061 (STD 2008)CPU times: user 5.93 s, sys: 3.67 s, total: 9.6 sWall time: 1.61 s"
},
{
"code": null,
"e": 16296,
"s": 16256,
"text": "Identical result, runs a little slower."
},
{
"code": null,
"e": 16379,
"s": 16296,
"text": "GridSearchCV verbose output shows 1170 jobs, which is the expected number 13x9x10."
},
{
"code": null,
"e": 18085,
"s": 16379,
"text": "gs = make_pipeline(RobustScaler(), GridSearchCV(ElasticNet(max_iter=100000), param_grid={'l1_ratio': [0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99], 'alpha': np.logspace(-4, -2, 9), }, scoring='neg_root_mean_squared_error', refit=True, cv=kfolds, n_jobs=-1, verbose=1 ))# do cv using kfolds on full datasetgs.fit(df[predictors], df[response])print('best params', gs._final_estimator.best_params_)print('best score', -gs._final_estimator.best_score_)l1_ratio = gs._final_estimator.best_params_['l1_ratio']alpha = gs._final_estimator.best_params_['alpha']# eval similarly to beforeelasticnet = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=100000)print(elasticnet)scores = -cross_val_score(elasticnet, df[predictors], df[response], scoring=\"neg_root_mean_squared_error\", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print()print(\"Log1p CV RMSE %.06f (STD %.04f)\" % (np.mean(scores), np.std(scores)))print(\"Raw CV RMSE %.0f (STD %.0f)\" % (np.mean(raw_scores), np.std(raw_scores)))best params {'alpha': 0.0031622776601683794, 'l1_ratio': 0.01}best score 0.10247177583755482ElasticNet(alpha=0.0031622776601683794, l1_ratio=0.01, max_iter=100000)Log1p CV RMSE 0.103003 (STD 0.0109)Raw CV RMSE 18061 (STD 2008)Wall time: 5 s"
},
{
"code": null,
"e": 18563,
"s": 18085,
"text": "It should be possible to use GridSearchCV with XGBoost. But when we also try to use early stopping, XGBoost wants an eval set. OK, we can give it a static eval set held out from GridSearchCV. Now, GridSearchCV does k-fold cross-validation in the training set but XGBoost uses a separate dedicated eval set for early stopping. It’s a bit of a Frankenstein methodology. See the notebook for the attempt at GridSearchCV with XGBoost and early stopping if you’re really interested."
},
{
"code": null,
"e": 18663,
"s": 18563,
"text": "Instead, we write our own grid search that gives XGBoost the correct hold-out set for each CV fold:"
},
{
"code": null,
"e": 19756,
"s": 18663,
"text": "EARLY_STOPPING_ROUNDS=100 # stop if no improvement after 100 roundsdef my_cv(df, predictors, response, kfolds, regressor, verbose=False): \"\"\"Roll our own CV train each kfold with early stopping return average metric, sd over kfolds, average best round\"\"\" metrics = [] best_iterations = [] for train_fold, cv_fold in kfolds.split(df): fold_X_train=df[predictors].values[train_fold] fold_y_train=df[response].values[train_fold] fold_X_test=df[predictors].values[cv_fold] fold_y_test=df[response].values[cv_fold] regressor.fit(fold_X_train, fold_y_train, early_stopping_rounds=EARLY_STOPPING_ROUNDS, eval_set=[(fold_X_test, fold_y_test)], eval_metric='rmse', verbose=verbose ) y_pred_test=regressor.predict(fold_X_test) metrics.append(np.sqrt(mean_squared_error(fold_y_test, y_pred_test))) best_iterations.append(regressor.best_iteration) return np.average(metrics), np.std(metrics), np.average(best_iterations)"
},
{
"code": null,
"e": 19949,
"s": 19756,
"text": "XGBoost has many tuning parameters so an exhaustive grid search has an unreasonable number of combinations. Instead, we tune reduced sets sequentially using grid search and use early stopping."
},
{
"code": null,
"e": 20010,
"s": 19949,
"text": "This is the typical grid search methodology to tune XGBoost:"
},
{
"code": null,
"e": 20053,
"s": 20010,
"text": "Set an initial set of starting parameters."
},
{
"code": null,
"e": 20190,
"s": 20053,
"text": "Tune sequentially on groups of hyperparameters that don’t interact too much between groups, to reduce the number of combinations tested."
},
{
"code": null,
"e": 20213,
"s": 20190,
"text": "First, tune max_depth."
},
{
"code": null,
"e": 20275,
"s": 20213,
"text": "Then tune subsample, colsample_bytree, and colsample_bylevel."
},
{
"code": null,
"e": 20373,
"s": 20275,
"text": "Finally, tune learning rate: a lower learning rate will need more boosting rounds (n_estimators)."
},
{
"code": null,
"e": 20496,
"s": 20373,
"text": "Do 10-fold cross-validation on each hyperparameter combination. Pick hyperparameters to minimize average RMSE over kfolds."
},
{
"code": null,
"e": 20589,
"s": 20496,
"text": "Use XGboost early stopping to halt training in each fold if no improvement after 100 rounds."
},
{
"code": null,
"e": 20762,
"s": 20589,
"text": "After tuning and selecting the best hyperparameters, retrain and evaluate on the full dataset without early stopping, using the average boosting rounds across xval kfolds.1"
},
{
"code": null,
"e": 21066,
"s": 20762,
"text": "As discussed, we use the XGBoost sklearn API and roll our own grid search which understands early stopping with k-folds, instead of GridSearchCV. (An alternative would be to use native xgboost .cv which understands early stopping but doesn’t use sklearn API (uses DMatrix, not numpy array or dataframe))"
},
{
"code": null,
"e": 21266,
"s": 21066,
"text": "We write a helper function cv_over_param_dict which takes a list of param_dict dictionaries, runs trials over all dictionaries, and returns the best param_dict dictionary plus a dataframe of results."
},
{
"code": null,
"e": 21348,
"s": 21266,
"text": "We run cv_over_param_dict 3 times to do 3 grid searches over our 3 tuning rounds."
},
{
"code": null,
"e": 24724,
"s": 21348,
"text": "BOOST_ROUNDS=50000 # we use early stopping so make this arbitrarily highdef cv_over_param_dict(df, param_dict, predictors, response, kfolds, verbose=False): \"\"\"given a list of dictionaries of xgb params run my_cv on params, store result in array return updated param_dict, results dataframe \"\"\" start_time = datetime.now() print(\"%-20s %s\" % (\"Start Time\", start_time)) results = [] for i, d in enumerate(param_dict): xgb = XGBRegressor( objective='reg:squarederror', n_estimators=BOOST_ROUNDS, random_state=RANDOMSTATE, verbosity=1, n_jobs=-1, booster='gbtree', **d ) metric_rmse, metric_std, best_iteration = my_cv(df, predictors, response, kfolds, xgb, verbose=False) results.append([metric_rmse, metric_std, best_iteration, d]) print(\"%s %3d result mean: %.6f std: %.6f, iter: %.2f\" % (datetime.strftime(datetime.now(), \"%T\"), i, metric_rmse, metric_std, best_iteration)) end_time = datetime.now() print(\"%-20s %s\" % (\"Start Time\", start_time)) print(\"%-20s %s\" % (\"End Time\", end_time)) print(str(timedelta(seconds=(end_time-start_time).seconds))) results_df = pd.DataFrame(results, columns=['rmse', 'std', 'best_iter', 'param_dict']).sort_values('rmse') display(results_df.head()) best_params = results_df.iloc[0]['param_dict'] return best_params, results_df# initial hyperparamscurrent_params = { 'max_depth': 5, 'colsample_bytree': 0.5, 'colsample_bylevel': 0.5, 'subsample': 0.5, 'learning_rate': 0.01,}################################################### round 1: tune depth##################################################max_depths = list(range(2,8))grid_search_dicts = [{'max_depth': md} for md in max_depths]# merge into full param dictsfull_search_dicts = [{**current_params, **d} for d in grid_search_dicts]# cv and get best paramscurrent_params, results_df = cv_over_param_dict(df, full_search_dicts, predictors, response, kfolds)################################################### round 2: tune subsample, colsample_bytree, colsample_bylevel################################################### subsamples = np.linspace(0.01, 1.0, 10)# colsample_bytrees = np.linspace(0.1, 1.0, 10)# colsample_bylevel = np.linspace(0.1, 1.0, 10)# narrower searchsubsamples = np.linspace(0.25, 0.75, 11)colsample_bytrees = np.linspace(0.1, 0.3, 5)colsample_bylevel = np.linspace(0.1, 0.3, 5)# subsamples = np.linspace(0.4, 0.9, 11)# colsample_bytrees = np.linspace(0.05, 0.25, 5)grid_search_dicts = [dict(zip(['subsample', 'colsample_bytree', 'colsample_bylevel'], [a, b, c])) for a,b,c in product(subsamples, colsample_bytrees, colsample_bylevel)]# merge into full param dictsfull_search_dicts = [{**current_params, **d} for d in grid_search_dicts]# cv and get best paramscurrent_params, results_df = cv_over_param_dict(df, full_search_dicts, predictors, response, kfolds)# round 3: learning ratelearning_rates = np.logspace(-3, -1, 5)grid_search_dicts = [{'learning_rate': lr} for lr in learning_rates]# merge into full param dictsfull_search_dicts = [{**current_params, **d} for d in grid_search_dicts]# cv and get best paramscurrent_params, results_df = cv_over_param_dict(df, full_search_dicts, predictors, response, kfolds, verbose=False)"
},
{
"code": null,
"e": 24894,
"s": 24724,
"text": "The total training duration (the sum of times over the 3 iterations) is 1:24:22. This time may be an underestimate, since this search space is based on prior experience."
},
{
"code": null,
"e": 24957,
"s": 24894,
"text": "Finally, we refit using the best hyperparameters and evaluate:"
},
{
"code": null,
"e": 25556,
"s": 24957,
"text": "xgb = XGBRegressor( objective='reg:squarederror', n_estimators=3438, random_state=RANDOMSTATE, verbosity=1, n_jobs=-1, booster='gbtree', **current_params) print(xgb)scores = -cross_val_score(xgb, df[predictors], df[response], scoring=\"neg_root_mean_squared_error\", cv=kfolds, n_jobs=-1)raw_scores = [cv_to_raw(x) for x in scores]print()print(\"Log1p CV RMSE %.06f (STD %.04f)\" % (np.mean(scores), np.std(scores)))print(\"Raw CV RMSE %.0f (STD %.0f)\" % (np.mean(raw_scores), np.std(raw_scores)))"
},
{
"code": null,
"e": 25639,
"s": 25556,
"text": "The result essentially matches linear regression but is not as good as ElasticNet."
},
{
"code": null,
"e": 25668,
"s": 25639,
"text": "Raw CV RMSE 18193 (STD 2461)"
},
{
"code": null,
"e": 25721,
"s": 25668,
"text": "The steps to run a Ray tuning job with Hyperopt are:"
},
{
"code": null,
"e": 26013,
"s": 25721,
"text": "Set up a Ray search space as a config dict.Refactor the training loop into a function which takes the config dict as an argument and calls tune.report(rmse=rmse) to optimize a metric like RMSE.Call ray.tune with the config and a num_samples argument which specifies how many times to sample."
},
{
"code": null,
"e": 26057,
"s": 26013,
"text": "Set up a Ray search space as a config dict."
},
{
"code": null,
"e": 26208,
"s": 26057,
"text": "Refactor the training loop into a function which takes the config dict as an argument and calls tune.report(rmse=rmse) to optimize a metric like RMSE."
},
{
"code": null,
"e": 26307,
"s": 26208,
"text": "Call ray.tune with the config and a num_samples argument which specifies how many times to sample."
},
{
"code": null,
"e": 26336,
"s": 26307,
"text": "Set up the Ray search space:"
},
{
"code": null,
"e": 26757,
"s": 26336,
"text": "xgb_tune_kwargs = { \"n_estimators\": tune.loguniform(100, 10000), \"max_depth\": tune.randint(0, 5), \"subsample\": tune.quniform(0.25, 0.75, 0.01), \"colsample_bytree\": tune.quniform(0.05, 0.5, 0.01), \"colsample_bylevel\": tune.quniform(0.05, 0.5, 0.01), \"learning_rate\": tune.quniform(-3.0, -1.0, 0.5), # powers of 10}xgb_tune_params = [k for k in xgb_tune_kwargs.keys() if k != 'wandb']xgb_tune_params"
},
{
"code": null,
"e": 26931,
"s": 26757,
"text": "Set up the training function. Note that some search algos expect all hyperparameters to be floats and some search intervals to start at 0. So we convert params as necessary."
},
{
"code": null,
"e": 27807,
"s": 26931,
"text": "def my_xgb(config): # fix these configs to match calling convention # search wants to pass in floats but xgb wants ints config['n_estimators'] = int(config['n_estimators']) # pass float eg loguniform distribution, use int # hyperopt needs left to start at 0 but we want to start at 2 config['max_depth'] = int(config['max_depth']) + 2 config['learning_rate'] = 10 ** config['learning_rate'] xgb = XGBRegressor( objective='reg:squarederror', n_jobs=1, random_state=RANDOMSTATE, booster='gbtree', scale_pos_weight=1, **config, ) scores = -cross_val_score(xgb, df[predictors], df[response], scoring=\"neg_root_mean_squared_error\", cv=kfolds) rmse = np.mean(scores) tune.report(rmse=rmse) return {\"rmse\": rmse}"
},
{
"code": null,
"e": 27821,
"s": 27807,
"text": "Run Ray Tune:"
},
{
"code": null,
"e": 28282,
"s": 27821,
"text": "algo = HyperOptSearch(random_state_seed=RANDOMSTATE)# ASHAscheduler = AsyncHyperBandScheduler()analysis = tune.run(my_xgb, num_samples=NUM_SAMPLES, config=xgb_tune_kwargs, name=\"hyperopt_xgb\", metric=\"rmse\", mode=\"min\", search_alg=algo, scheduler=scheduler, verbose=1, )"
},
{
"code": null,
"e": 28349,
"s": 28282,
"text": "Extract the best hyperparameters, and evaluate a model using them:"
},
{
"code": null,
"e": 29168,
"s": 28349,
"text": "# results dataframe sorted by best metricparam_cols = ['config.' + k for k in xgb_tune_params]analysis_results_df = analysis.results_df[['rmse', 'date', 'time_this_iter_s'] + param_cols].sort_values('rmse')# extract top rowbest_config = {z: analysis_results_df.iloc[0]['config.' + z] for z in xgb_tune_params}xgb = XGBRegressor( objective='reg:squarederror', random_state=RANDOMSTATE, verbosity=1, n_jobs=-1, **best_config)print(xgb)scores = -cross_val_score(xgb, df[predictors], df[response], scoring=\"neg_root_mean_squared_error\", cv=kfolds)raw_scores = [cv_to_raw(x) for x in scores]print()print(\"Log1p CV RMSE %.06f (STD %.04f)\" % (np.mean(scores), np.std(scores)))print(\"Raw CV RMSE %.0f (STD %.0f)\" % (np.mean(raw_scores), np.std(raw_scores)))"
},
{
"code": null,
"e": 29201,
"s": 29168,
"text": "With NUM_SAMPLES=1024 we obtain:"
},
{
"code": null,
"e": 29230,
"s": 29201,
"text": "Raw CV RMSE 18309 (STD 2428)"
},
{
"code": null,
"e": 29280,
"s": 29230,
"text": "We can swap out Hyperopt for Optuna as simply as:"
},
{
"code": null,
"e": 29302,
"s": 29280,
"text": "algo = OptunaSearch()"
},
{
"code": null,
"e": 29335,
"s": 29302,
"text": "With NUM_SAMPLES=1024 we obtain:"
},
{
"code": null,
"e": 29364,
"s": 29335,
"text": "Raw CV RMSE 18325 (STD 2473)"
},
{
"code": null,
"e": 29414,
"s": 29364,
"text": "We can also easily swap out XGBoost for LightGBM."
},
{
"code": null,
"e": 29466,
"s": 29414,
"text": "Update the search space using LightGBM equivalents."
},
{
"code": null,
"e": 29518,
"s": 29466,
"text": "Update the search space using LightGBM equivalents."
},
{
"code": null,
"e": 29925,
"s": 29518,
"text": "lgbm_tune_kwargs = { \"n_estimators\": tune.loguniform(100, 10000), \"max_depth\": tune.randint(0, 5), 'num_leaves': tune.quniform(1, 10, 1.0), # xgb max_leaves \"bagging_fraction\": tune.quniform(0.5, 0.8, 0.01), # xgb subsample \"feature_fraction\": tune.quniform(0.05, 0.5, 0.01), # xgb colsample_bytree \"learning_rate\": tune.quniform(-3.0, -1.0, 0.5), }"
},
{
"code": null,
"e": 29951,
"s": 29925,
"text": "Update training function:"
},
{
"code": null,
"e": 29977,
"s": 29951,
"text": "Update training function:"
},
{
"code": null,
"e": 31028,
"s": 29977,
"text": "def my_lgbm(config): # fix these configs config['n_estimators'] = int(config['n_estimators']) # pass float eg loguniform distribution, use int config['num_leaves'] = int(2**config['num_leaves']) config['learning_rate'] = 10**config['learning_rate'] lgbm = LGBMRegressor(objective='regression', max_bin=200, feature_fraction_seed=7, min_data_in_leaf=2, verbose=-1, n_jobs=1, # these are specified to suppress warnings colsample_bytree=None, min_child_samples=None, subsample=None, **config, ) scores = -cross_val_score(lgbm, df[predictors], df[response], scoring=\"neg_root_mean_squared_error\", cv=kfolds) rmse=np.mean(scores) tune.report(rmse=rmse) return {'rmse': np.mean(scores)}"
},
{
"code": null,
"e": 31122,
"s": 31028,
"text": "and run as before, swapping my_lgbm in place of my_xgb. Results for LGBM: (NUM_SAMPLES=1024):"
},
{
"code": null,
"e": 31151,
"s": 31122,
"text": "Raw CV RMSE 18615 (STD 2356)"
},
{
"code": null,
"e": 31185,
"s": 31151,
"text": "Swapping out Hyperopt for Optuna:"
},
{
"code": null,
"e": 31214,
"s": 31185,
"text": "Raw CV RMSE 18614 (STD 2423)"
},
{
"code": null,
"e": 31348,
"s": 31214,
"text": "Ray is a distributed framework. We can run a Ray Tune job over many instances using a cluster with a head node and many worker nodes."
},
{
"code": null,
"e": 31700,
"s": 31348,
"text": "Launching Ray is straightforward. On the head node we run ray start. On each worker node we run ray start --address x.x.x.x with the address of the head node. Then in python we call ray.init() to connect to the head node. Everything else proceeds as before, and the head node runs trials using all instances in the cluster and stores results in Redis."
},
{
"code": null,
"e": 31805,
"s": 31700,
"text": "Where it gets more complicated is specifying all the AWS details, instance types, regions, subnets, etc."
},
{
"code": null,
"e": 32018,
"s": 31805,
"text": "Clusters are defined in ray1.1.yaml. (So far in this notebook we have been using the current production ray 1.0, but I had difficulty getting a cluster to run with ray 1.0 so I switched to the dev nightly. YMMV.)"
},
{
"code": null,
"e": 32121,
"s": 32018,
"text": "boto3 and AWS CLI configured credentials are used to spawn instances, so install and configure AWS CLI"
},
{
"code": null,
"e": 32439,
"s": 32121,
"text": "Edit ray1.1.yaml file with, at a minimum, your AWS region and availability zone. Imageid may vary across regions, search for the current Deep Learning AMI (Ubuntu 18.04). You may not need to specify subnet, I had an issue with an inaccessible subnet when I let Ray default the subnet, possibly bad defaults somewhere."
},
{
"code": null,
"e": 32591,
"s": 32439,
"text": "To obtain those variables, launch the latest Deep Learning AMI (Ubuntu 18.04) currently Version 35.0 into a small instance in your favorite region/zone"
},
{
"code": null,
"e": 32610,
"s": 32591,
"text": "Test that it works"
},
{
"code": null,
"e": 32679,
"s": 32610,
"text": "Note the 4 variables: region, availability zone, subnet, AMI imageid"
},
{
"code": null,
"e": 32791,
"s": 32679,
"text": "Terminate the instance and edit ray1.1.yaml with your region, availability zone, AMI imageid, optionally subnet"
},
{
"code": null,
"e": 32982,
"s": 32791,
"text": "It may be advisable create your own image with all updates and requirements pre-installed and specify its AMI imageid, instead of using the generic image and installing everything at launch."
},
{
"code": null,
"e": 33021,
"s": 32982,
"text": "To run the cluster: ray up ray1.1.yaml"
},
{
"code": null,
"e": 33064,
"s": 33021,
"text": "Creates head instance using AMI specified."
},
{
"code": null,
"e": 33142,
"s": 33064,
"text": "Installs Ray and related requirements including XGBoost from requirements.txt"
},
{
"code": null,
"e": 33181,
"s": 33142,
"text": "Clones the druce/iowa repo from GitHub"
},
{
"code": null,
"e": 33346,
"s": 33181,
"text": "Launches worker nodes per auto-scaling parameters (currently we fix the number of nodes because we’re not benchmarking the time the cluster will take to auto-scale)"
},
{
"code": null,
"e": 33448,
"s": 33346,
"text": "After the cluster starts you can check the AWS console and note that several instances were launched."
},
{
"code": null,
"e": 33501,
"s": 33448,
"text": "Check ray monitor ray1.1.yaml for any error messages"
},
{
"code": null,
"e": 33621,
"s": 33501,
"text": "Run Jupyter on the cluster with port forwarding ray exec ray1.1.yaml --port-forward=8899 'jupyter notebook --port=8899'"
},
{
"code": null,
"e": 33786,
"s": 33621,
"text": "Open the notebook on the generated URL which is printed on the console at startup e.g. http://localhost:8899/?token=5f46d4355ae7174524ba71f30ef3f0633a20b19a204b93b4"
},
{
"code": null,
"e": 33897,
"s": 33786,
"text": "You can run a terminal on the head node of the cluster with ray attach /Users/drucev/projects/iowa/ray1.1.yaml"
},
{
"code": null,
"e": 34058,
"s": 33897,
"text": "You can ssh explicitly with the IP address and the generated private key ssh -o IdentitiesOnly=yes -i ~/.ssh/ray-autoscaler_1_us-east-1.pem ubuntu@54.161.200.54"
},
{
"code": null,
"e": 34167,
"s": 34058,
"text": "Run port forwarding to the Ray dashboard with ray dashboard ray1.1.yaml and then open http://localhost:8265/"
},
{
"code": null,
"e": 34275,
"s": 34167,
"text": "Make sure to choose the default kernel in Jupyter to run in the correct conda environment with all installs"
},
{
"code": null,
"e": 34417,
"s": 34275,
"text": "Make sure to use the ray.init() command given in the startup messages. ray.init(address='localhost:6379', _redis_password='5241590000000000')"
},
{
"code": null,
"e": 34490,
"s": 34417,
"text": "The cluster will incur AWS charges so ray down ray1.1.yaml when complete"
},
{
"code": null,
"e": 34617,
"s": 34490,
"text": "See hyperparameter_optimization_cluster.ipynb, separated out so each notebook can be run end-to-end with/without cluster setup"
},
{
"code": null,
"e": 34667,
"s": 34617,
"text": "See Ray docs for additional info on Ray clusters."
},
{
"code": null,
"e": 34794,
"s": 34667,
"text": "Besides connecting to the cluster instead of running Ray Tune locally, no other change to code is needed to run on the cluster"
},
{
"code": null,
"e": 35350,
"s": 34794,
"text": "analysis = tune.run(my_xgb, num_samples=NUM_SAMPLES, config=xgb_tune_kwargs, name=\"hyperopt_xgb\", metric=\"rmse\", mode=\"min\", search_alg=algo, scheduler=scheduler, # add this because distributed jobs occasionally error out raise_on_failed_trial=False, # otherwise no reults df returned if any trial error verbose=1, )"
},
{
"code": null,
"e": 35428,
"s": 35350,
"text": "Results for XGBM on cluster (2048 samples, cluster is 32 m5.large instances):"
},
{
"code": null,
"e": 35452,
"s": 35428,
"text": "Hyperopt (time 1:30:58)"
},
{
"code": null,
"e": 35481,
"s": 35452,
"text": "Raw CV RMSE 18030 (STD 2356)"
},
{
"code": null,
"e": 35503,
"s": 35481,
"text": "Optuna (time 1:29:57)"
},
{
"code": null,
"e": 35532,
"s": 35503,
"text": "Raw CV RMSE 18028 (STD 2353)"
},
{
"code": null,
"e": 35556,
"s": 35532,
"text": "Similarly for LightGBM:"
},
{
"code": null,
"e": 36068,
"s": 35556,
"text": "analysis = tune.run(my_lgbm, num_samples=NUM_SAMPLES, config = lgbm_tune_kwargs, name=\"hyperopt_lgbm\", metric=\"rmse\", mode=\"min\", search_alg=algo, scheduler=scheduler, raise_on_failed_trial=False, # otherwise no reults df returned if any trial error verbose=1, )"
},
{
"code": null,
"e": 36150,
"s": 36068,
"text": "Results for LightGBM on cluster (2048 samples, cluster is 32 m5.large instances):"
},
{
"code": null,
"e": 36177,
"s": 36150,
"text": "Hyperopt (time: 1:05:19) :"
},
{
"code": null,
"e": 36206,
"s": 36177,
"text": "Raw CV RMSE 18459 (STD 2511)"
},
{
"code": null,
"e": 36229,
"s": 36206,
"text": "Optuna (time 0:48:16):"
},
{
"code": null,
"e": 36258,
"s": 36229,
"text": "Raw CV RMSE 18458 (STD 2511)"
},
{
"code": null,
"e": 36516,
"s": 36258,
"text": "In every case I’ve applied them, Hyperopt and Optuna have given me at least a small improvement in the best metrics I found using grid search methods. Bayesian optimization tunes faster with a less manual process vs. sequential tuning. It’s fire-and-forget."
},
{
"code": null,
"e": 36767,
"s": 36516,
"text": "Is Ray Tune the way to go for hyperparameter tuning? Provisionally, yes. Ray provides integration between the underlying ML (e.g. XGBoost), the Bayesian search (e.g. Hyperopt), and early stopping (ASHA). It allows us to easily swap search algorithms."
},
{
"code": null,
"e": 37144,
"s": 36767,
"text": "There are other alternative search algorithms in the Ray docs but these seem to be the most popular, and I haven’t got the others to run yet. If after a while I find I am always using e.g. Hyperopt and never use clusters, I might use the native Hyperopt/XGBoost integration without Ray, to access any native Hyperopt features and because it’s one less technology in the stack."
},
{
"code": null,
"e": 37899,
"s": 37144,
"text": "Clusters? Most of the time I don’t have a need, costs add up, did not see as large a speedup as expected. I only see ~2x speedup on the 32-instance cluster. Setting up the test I expected a bit less than 4x speedup accounting for slightly less-than-linear scaling. The longest run I have tried, with 4096 samples, ran overnight on desktop. My MacBook Pro w/16 threads and desktop with 12 threads and GPU are plenty powerful for this data set. Still, it’s useful to have the clustering option in the back pocket. In production, it may be more standard and maintainable to deploy with e.g. Terraform, Kubernetes than the Ray native YAML cluster config file. If you want to train big data at scale you need to really understand and streamline your pipeline."
},
{
"code": null,
"e": 38318,
"s": 37899,
"text": "It continues to surprise me that ElasticNet, i.e. regularized linear regression, performs slightly better than boosting on this dataset. I heavily engineered features so that linear methods work well. Predictors were chosen using Lasso/ElasticNet and I used log and Box-Cox transforms to force predictors to follow assumptions of least-squares. But still, boosting is supposed to be the gold standard for tabular data."
},
{
"code": null,
"e": 38960,
"s": 38318,
"text": "This may tend to validate one of the critiques of machine learning, that the most powerful machine learning methods don’t necessarily always converge all the way to the best solution. If you have a ground truth that is linear plus noise, a complex XGBoost or neural network algorithm should get arbitrarily close to the closed-form optimal solution, but will probably never match the optimal solution exactly. XGBoost regression is piecewise constant and the complex neural network is subject to the vagaries of stochastic gradient descent. I thought arbitrarily close meant almost indistinguishable. But clearly this is not always the case."
},
{
"code": null,
"e": 39485,
"s": 38960,
"text": "ElasticNet with L1 + L2 regularization plus gradient descent and hyperparameter optimization is still machine learning. It’s simply a form of ML better matched to this problem. In the real world where data sets don’t match assumptions of OLS, gradient boosting generally performs extremely well. And even on this dataset, engineered for success with the linear models, SVR and KernelRidge performed better than ElasticNet (not shown) and ensembling ElasticNet with XGBoost, LightGBM, SVR, neural networks worked best of all."
},
{
"code": null,
"e": 39731,
"s": 39485,
"text": "To paraphrase Casey Stengel, clever feature engineering will always outperform clever model algorithms and vice-versa2. But improving your hyperparameters will always improve your results. Bayesian optimization can be considered a best practice."
},
{
"code": null,
"e": 39765,
"s": 39731,
"text": "Again, the full code is on GitHub"
},
{
"code": null,
"e": 40719,
"s": 39765,
"text": "1 It would be more sound to separately tune the stopping rounds. Just averaging the best stopping time across kfolds is questionable. In a real world scenario, we should keep a holdout test set. We should retrain on the full training dataset (not kfolds) with early stopping to get the best number of boosting rounds. Then we should measure RMSE in the test set using all the cross-validated parameters including number of boosting rounds for the expected OOS RMSE. However, for the purpose of comparing tuning methods, the CV error is OK. We just want to look at how we would make model decisions using CV and not worry too much about the generalization error. One could even argue it adds a little more noise to the comparison of hyperparameter selection. But a test set would be the correct methodology in practice. It wouldn’t change conclusions directionally and I’m not going to rerun everything but if I were to start over I would do it that way."
}
] |
Error-in-Variables Models: Deming Regression | by Dr. Robert Kübler | Towards Data Science
|
Machine learning is often all about the following question:
Given a dataset (X, y), where X is a feature matrix and y is a target vector, find an f with f(X) ≈ y.
We usually do not enforce a strict equality à la f(X) = y because there are errors in the target values y. These errors arise from the fact that we usually cannot observe everything in the universe and put it into our feature matrix X. And even if we could, quantum mechanics tells us that there might still be randomness left in the system, making it possible for us to receive different outcomes given the same inputs.
Side note: This indeterminism makes it possible to design algorithms for quantum computers that allow us to factor giant numbers into a product of prime numbers — for example, 900 = 2 * 32 * 5, just much larger — to break important encryption schemes such as RSA which are used everywhere on the internet nowadays. It also allows us to search an unsorted array of length n in time √n, which is a rather surprising result achieved with Grover’s algorithm.
Long story short, labels are noisy, and we deal with this by introducing an error term ɛ, such as in y = a*x + b + ɛ in the case of linear regression. Nothing new so far. But answer me the following question:
Have you ever thought of errors in the feature variables X?
I certainly didn’t. So let me show you when this might be important.
I’m a fan of classic, unremarkable examples. They don’t distract you and let you focus on new things, step by step. So, let’s use the following one: Predict the height of a person, given their weight! Never done this one before, right? 😉
Your goal is to find the relationship between weight and height. If a person is 1 kg heavier than another person, what can you say about their heights? You want to use a linear model, so basically the task is to compute the slope of the line.
The story: You invited 500 people to your innovative study and took their weights and heights.
The twist: After the experiment is over, you noticed that your scale is quite inaccurate — after repeatedly weighing yourself, you got a lot of numbers that are all over the place, although their mean is at least around your real weight. And this is the same for the other 500 weights, too. Oops. How to deal with this situation? Re-running the whole experiment is definitely not an option.
We start by generating some data that you could have obtained running the experiment: First, we generate the real weights x_true and derive heights y from them. Then, we add some noise to the weights x_true and call the result x.
Note: I use x instead of X, because we only have a single feature here.
import numpy as npnp.random.seed(0)n = 500x_true = 10*np.random.randn(n) + 70 # the true, unobserved weightsy = x_true + 100 + 5*np.random.randn(n) # the observed heightsx = x_true + 10*np.random.randn(n) # the noisy, observed weights
In real life, we are only given x and y to work with, so this is what we see:
If we would not know about the broken scale — or simply don’t care — we could apply a linear regression model to the noisy x and y, for example like this:
from sklearn.linear_model import LinearRegressionlr = LinearRegression()lr.fit(x.reshape(-1, 1), y)print(f'height = {lr.coef_[0]:.2f}*weight + {lr.intercept_:.2f}')# OUTPUT: height = 0.50*weight + 134.09
Well, it looks like a reasonable result: the higher the weight, the higher the height. Sanity check passed. However, look back at how we generated the height values:
y = x_true + 100 + 5*np.random.randn(n)
The real coefficient is actually 1, the intercept is 100, which is a far cry from the coefficient 0.5 and intercept 134 we got from running linear regression. If this is a problem depends on you, though.
If you continue using your broken scale and you just want to predict, the current model height = 0.50*weight + 134.09 is the way to go since it's perfectly adapted to this setting. You just trained it that way.
On the other hand, if you want to learn the true relationship between height and true weight, you have to be smarter than that. The problem is that your slope is too small, which is also known as regression dilution or regression attenuation. We will now see how to solve this problem.
There are several ways to retrieve the correct coefficients even with dirty data. One of the simplest ones is the so-called Deming regression, a variant of ordinary least squares to account for the error.
Deming regression is named after Dr. William Edwards Deming who, by the way, didn’t even invent this method, but made it popular. Credits also go to the inventors R. J. Adcock and C. H. Kummell.
Before we start, let us go quickly over some notations. You have probably seen these things already, but let’s get everybody on the same page here. We assume that x=(x1, x2, x3, ..., xn) and y=(y1, y2, y3, ..., yn) is our dataset. Then, we define the following:
Before we come to the Deming regression formula, let me stress that with these notations we can also recover our ordinary least squares estimator coefficient again via
which in Python translates to
s_xy = ((x - x.mean()) * (y - y.mean())).sum() s_xx = ((x - x.mean())**2).sum()print(f'slope = {s_xy / s_xx:.2f}')# Output: slope = 0.50
You can also calculate the intercept from this, which I omit here. We know already from sklearn that it is 134.09.
Now, let’s do Deming, Adcock, and Kummell some justice and present the adjusted slope and intercept:
Alright, looks slightly more complicated, but still manageable. But what is this δ in the formula? Sadly, this is the main disadvantage of this approach. It’s nothing that we can compute, we just have to know or guess it.
δ is the ratio between the variance of the errors in y divided by the variance of the errors in x. I mean the following: the regression formula y = a*x + b + ɛ, contains a normally distributed random variable ɛ, so we assume. It has some variance σγ. This is what I mean with “variance of the errors in y”.
We further assume that our observed weights x are also obtained by adding Gaussian noise to the real weights x_true, which also has some variance, the “variance of the errors in x”.
In our example, we are given everything. Let me paste the formulas that we used to create the dataset:
x_true = 10*np.random.randn(n) + 70y = x_true + 100 + 5*np.random.randn(n)x = x_true + 10*np.random.randn(n)
Here, we can see that the variance of the errors in y is exactly 52 = 25. The variance of the errors in x is 102 = 100, thus δ = 25/100 = 1/4. Plugging everything in gives us
x_mean = x.mean()y_mean = y.mean()s_xy = ((x - x.mean()) * (y - y.mean())).sum() s_xx = ((x - x.mean())**2).sum()s_yy = ((y - y.mean())**2).sum()delta = 1/4deming_slope = (s_yy - delta*s_xx + np.sqrt((s_yy - delta*s_xx)**2 + 4*delta*s_xy**2)) / (2*s_xy)deming_intercept = y_mean - x_mean*deming_slopeprint(f'Deming slope = {deming_slope:.2f}')print(f'Deming intercept = {deming_intercept:.2f}')# Output: Deming slope = 1.03, Deming intercept = 97.01
This is close enough to the true values 1 and 100! Sure, it’s not 100% accurate, but that is the usual deal with maximum likelihood estimates. We can visualize the results:
We can again see that the regression line trained on the noisy data is too flat — the so-called regression dilution.
I said earlier that Deming regression is a variant of simple linear regression with one variable. To be more precise, it is even a generalization of linear regression. What I mean is the following:
If there are no errors in the features x, Deming regression and simple linear regression yield the same result.
For me, this is rather intuitive, but looking at the formulas, it’s difficult to see. I will not prove it here, but I try to make you believe.
If x has no errors, the variance of the errors in x is zero, implying that there is actually no δ that we could compute, as we would divide by zero. But let us naively say that δ is infinity in this case because for s>0 we have
or for the non-mathematicians:
A positive number divided by an extremely tiny positive number is a giant number.
Since we can’t plug in infinity directly, we use a poor man’s trick and simulate it by setting δ to a huge number.
x_mean = x.mean()y_mean = y.mean()s_xy = ((x - x.mean()) * (y - y.mean())).sum() s_xx = ((x - x.mean())**2).sum()s_yy = ((y - y.mean())**2).sum()delta = 99999deming_slope = (s_yy - delta*s_xx + np.sqrt((s_yy - delta*s_xx)**2 + 4*delta*s_xy**2)) / (2*s_xy)deming_intercept = y_mean - x_mean*deming_slopeprint(f'Deming slope = {deming_slope:.2f}')print(f'Deming intercept = {deming_intercept:.2f}')# Output: Deming slope = 0.50, Deming intercept = 134.09
This is exactly our simple linear regression result, nice! Careful: This is not a proof, yet it gives a nice feeling for it.
And think about the other extreme: What happens if the errors in the features are extremely large, let’s say infinity? Well, then δ becomes zero and the whole Deming slope term becomes just zero as well, which is easy to calculate (do it!). The intercept is then the mean of the labels y. Basically, the model is only a flat line then.
This also makes sense intuitively since the features are essentially useless in this case, so it’s good to ignore them and act like there are no features at all. And the best model without features that minimizes the sum of squares error is just the constant mean prediction.
In this article, we introduced the problem of errors in the features X and how they can influence the true relationships between variables. Simple linear regression yields a slope that is usually substantially lower than the truth, called regression dilution.
However, smart people invented another kind of regression to adjust for these errors: Deming regression. It makes it possible to still come to the correct conclusion without re-running the experiment another time, which can save time, money, and nerves.
Deming regression is great, but it is tricky to guess the correct values for δ, which is a major drawback because the result of the regression relies heavily on δ. Still, it’s nice that you can even make a statement in the case of features with errors.
A natural question to ask now is the following: What happens if we have more than one feature? Mathematicians got us covered, there is the total least squares method which is a direct generalization of Deming regression to more than one variable. And there are many more models, as you can see here.
Now you know that it makes sense to also pay attention to errors in all of your measurements and act accordingly to weaken their effects as well as possible.
I hope that you learned something new, interesting, and useful today. Thanks for reading!
As the last point, if you
want to support me in writing more about machine learning andplan to get a Medium subscription anyway,
want to support me in writing more about machine learning and
plan to get a Medium subscription anyway,
why not do it via this link? This would help me a lot! 😊
To be transparent, the price for you does not change, but about half of the subscription fees go directly to me.
Thanks a lot, if you consider supporting me!
If you have any questions, write me on LinkedIn!
|
[
{
"code": null,
"e": 107,
"s": 47,
"text": "Machine learning is often all about the following question:"
},
{
"code": null,
"e": 210,
"s": 107,
"text": "Given a dataset (X, y), where X is a feature matrix and y is a target vector, find an f with f(X) ≈ y."
},
{
"code": null,
"e": 632,
"s": 210,
"text": "We usually do not enforce a strict equality à la f(X) = y because there are errors in the target values y. These errors arise from the fact that we usually cannot observe everything in the universe and put it into our feature matrix X. And even if we could, quantum mechanics tells us that there might still be randomness left in the system, making it possible for us to receive different outcomes given the same inputs."
},
{
"code": null,
"e": 1087,
"s": 632,
"text": "Side note: This indeterminism makes it possible to design algorithms for quantum computers that allow us to factor giant numbers into a product of prime numbers — for example, 900 = 2 * 32 * 5, just much larger — to break important encryption schemes such as RSA which are used everywhere on the internet nowadays. It also allows us to search an unsorted array of length n in time √n, which is a rather surprising result achieved with Grover’s algorithm."
},
{
"code": null,
"e": 1296,
"s": 1087,
"text": "Long story short, labels are noisy, and we deal with this by introducing an error term ɛ, such as in y = a*x + b + ɛ in the case of linear regression. Nothing new so far. But answer me the following question:"
},
{
"code": null,
"e": 1356,
"s": 1296,
"text": "Have you ever thought of errors in the feature variables X?"
},
{
"code": null,
"e": 1425,
"s": 1356,
"text": "I certainly didn’t. So let me show you when this might be important."
},
{
"code": null,
"e": 1663,
"s": 1425,
"text": "I’m a fan of classic, unremarkable examples. They don’t distract you and let you focus on new things, step by step. So, let’s use the following one: Predict the height of a person, given their weight! Never done this one before, right? 😉"
},
{
"code": null,
"e": 1906,
"s": 1663,
"text": "Your goal is to find the relationship between weight and height. If a person is 1 kg heavier than another person, what can you say about their heights? You want to use a linear model, so basically the task is to compute the slope of the line."
},
{
"code": null,
"e": 2001,
"s": 1906,
"text": "The story: You invited 500 people to your innovative study and took their weights and heights."
},
{
"code": null,
"e": 2392,
"s": 2001,
"text": "The twist: After the experiment is over, you noticed that your scale is quite inaccurate — after repeatedly weighing yourself, you got a lot of numbers that are all over the place, although their mean is at least around your real weight. And this is the same for the other 500 weights, too. Oops. How to deal with this situation? Re-running the whole experiment is definitely not an option."
},
{
"code": null,
"e": 2622,
"s": 2392,
"text": "We start by generating some data that you could have obtained running the experiment: First, we generate the real weights x_true and derive heights y from them. Then, we add some noise to the weights x_true and call the result x."
},
{
"code": null,
"e": 2694,
"s": 2622,
"text": "Note: I use x instead of X, because we only have a single feature here."
},
{
"code": null,
"e": 2929,
"s": 2694,
"text": "import numpy as npnp.random.seed(0)n = 500x_true = 10*np.random.randn(n) + 70 # the true, unobserved weightsy = x_true + 100 + 5*np.random.randn(n) # the observed heightsx = x_true + 10*np.random.randn(n) # the noisy, observed weights"
},
{
"code": null,
"e": 3007,
"s": 2929,
"text": "In real life, we are only given x and y to work with, so this is what we see:"
},
{
"code": null,
"e": 3162,
"s": 3007,
"text": "If we would not know about the broken scale — or simply don’t care — we could apply a linear regression model to the noisy x and y, for example like this:"
},
{
"code": null,
"e": 3366,
"s": 3162,
"text": "from sklearn.linear_model import LinearRegressionlr = LinearRegression()lr.fit(x.reshape(-1, 1), y)print(f'height = {lr.coef_[0]:.2f}*weight + {lr.intercept_:.2f}')# OUTPUT: height = 0.50*weight + 134.09"
},
{
"code": null,
"e": 3532,
"s": 3366,
"text": "Well, it looks like a reasonable result: the higher the weight, the higher the height. Sanity check passed. However, look back at how we generated the height values:"
},
{
"code": null,
"e": 3572,
"s": 3532,
"text": "y = x_true + 100 + 5*np.random.randn(n)"
},
{
"code": null,
"e": 3776,
"s": 3572,
"text": "The real coefficient is actually 1, the intercept is 100, which is a far cry from the coefficient 0.5 and intercept 134 we got from running linear regression. If this is a problem depends on you, though."
},
{
"code": null,
"e": 3987,
"s": 3776,
"text": "If you continue using your broken scale and you just want to predict, the current model height = 0.50*weight + 134.09 is the way to go since it's perfectly adapted to this setting. You just trained it that way."
},
{
"code": null,
"e": 4273,
"s": 3987,
"text": "On the other hand, if you want to learn the true relationship between height and true weight, you have to be smarter than that. The problem is that your slope is too small, which is also known as regression dilution or regression attenuation. We will now see how to solve this problem."
},
{
"code": null,
"e": 4478,
"s": 4273,
"text": "There are several ways to retrieve the correct coefficients even with dirty data. One of the simplest ones is the so-called Deming regression, a variant of ordinary least squares to account for the error."
},
{
"code": null,
"e": 4673,
"s": 4478,
"text": "Deming regression is named after Dr. William Edwards Deming who, by the way, didn’t even invent this method, but made it popular. Credits also go to the inventors R. J. Adcock and C. H. Kummell."
},
{
"code": null,
"e": 4935,
"s": 4673,
"text": "Before we start, let us go quickly over some notations. You have probably seen these things already, but let’s get everybody on the same page here. We assume that x=(x1, x2, x3, ..., xn) and y=(y1, y2, y3, ..., yn) is our dataset. Then, we define the following:"
},
{
"code": null,
"e": 5103,
"s": 4935,
"text": "Before we come to the Deming regression formula, let me stress that with these notations we can also recover our ordinary least squares estimator coefficient again via"
},
{
"code": null,
"e": 5133,
"s": 5103,
"text": "which in Python translates to"
},
{
"code": null,
"e": 5270,
"s": 5133,
"text": "s_xy = ((x - x.mean()) * (y - y.mean())).sum() s_xx = ((x - x.mean())**2).sum()print(f'slope = {s_xy / s_xx:.2f}')# Output: slope = 0.50"
},
{
"code": null,
"e": 5385,
"s": 5270,
"text": "You can also calculate the intercept from this, which I omit here. We know already from sklearn that it is 134.09."
},
{
"code": null,
"e": 5486,
"s": 5385,
"text": "Now, let’s do Deming, Adcock, and Kummell some justice and present the adjusted slope and intercept:"
},
{
"code": null,
"e": 5708,
"s": 5486,
"text": "Alright, looks slightly more complicated, but still manageable. But what is this δ in the formula? Sadly, this is the main disadvantage of this approach. It’s nothing that we can compute, we just have to know or guess it."
},
{
"code": null,
"e": 6015,
"s": 5708,
"text": "δ is the ratio between the variance of the errors in y divided by the variance of the errors in x. I mean the following: the regression formula y = a*x + b + ɛ, contains a normally distributed random variable ɛ, so we assume. It has some variance σγ. This is what I mean with “variance of the errors in y”."
},
{
"code": null,
"e": 6197,
"s": 6015,
"text": "We further assume that our observed weights x are also obtained by adding Gaussian noise to the real weights x_true, which also has some variance, the “variance of the errors in x”."
},
{
"code": null,
"e": 6300,
"s": 6197,
"text": "In our example, we are given everything. Let me paste the formulas that we used to create the dataset:"
},
{
"code": null,
"e": 6409,
"s": 6300,
"text": "x_true = 10*np.random.randn(n) + 70y = x_true + 100 + 5*np.random.randn(n)x = x_true + 10*np.random.randn(n)"
},
{
"code": null,
"e": 6584,
"s": 6409,
"text": "Here, we can see that the variance of the errors in y is exactly 52 = 25. The variance of the errors in x is 102 = 100, thus δ = 25/100 = 1/4. Plugging everything in gives us"
},
{
"code": null,
"e": 7034,
"s": 6584,
"text": "x_mean = x.mean()y_mean = y.mean()s_xy = ((x - x.mean()) * (y - y.mean())).sum() s_xx = ((x - x.mean())**2).sum()s_yy = ((y - y.mean())**2).sum()delta = 1/4deming_slope = (s_yy - delta*s_xx + np.sqrt((s_yy - delta*s_xx)**2 + 4*delta*s_xy**2)) / (2*s_xy)deming_intercept = y_mean - x_mean*deming_slopeprint(f'Deming slope = {deming_slope:.2f}')print(f'Deming intercept = {deming_intercept:.2f}')# Output: Deming slope = 1.03, Deming intercept = 97.01"
},
{
"code": null,
"e": 7207,
"s": 7034,
"text": "This is close enough to the true values 1 and 100! Sure, it’s not 100% accurate, but that is the usual deal with maximum likelihood estimates. We can visualize the results:"
},
{
"code": null,
"e": 7324,
"s": 7207,
"text": "We can again see that the regression line trained on the noisy data is too flat — the so-called regression dilution."
},
{
"code": null,
"e": 7522,
"s": 7324,
"text": "I said earlier that Deming regression is a variant of simple linear regression with one variable. To be more precise, it is even a generalization of linear regression. What I mean is the following:"
},
{
"code": null,
"e": 7634,
"s": 7522,
"text": "If there are no errors in the features x, Deming regression and simple linear regression yield the same result."
},
{
"code": null,
"e": 7777,
"s": 7634,
"text": "For me, this is rather intuitive, but looking at the formulas, it’s difficult to see. I will not prove it here, but I try to make you believe."
},
{
"code": null,
"e": 8005,
"s": 7777,
"text": "If x has no errors, the variance of the errors in x is zero, implying that there is actually no δ that we could compute, as we would divide by zero. But let us naively say that δ is infinity in this case because for s>0 we have"
},
{
"code": null,
"e": 8036,
"s": 8005,
"text": "or for the non-mathematicians:"
},
{
"code": null,
"e": 8118,
"s": 8036,
"text": "A positive number divided by an extremely tiny positive number is a giant number."
},
{
"code": null,
"e": 8233,
"s": 8118,
"text": "Since we can’t plug in infinity directly, we use a poor man’s trick and simulate it by setting δ to a huge number."
},
{
"code": null,
"e": 8686,
"s": 8233,
"text": "x_mean = x.mean()y_mean = y.mean()s_xy = ((x - x.mean()) * (y - y.mean())).sum() s_xx = ((x - x.mean())**2).sum()s_yy = ((y - y.mean())**2).sum()delta = 99999deming_slope = (s_yy - delta*s_xx + np.sqrt((s_yy - delta*s_xx)**2 + 4*delta*s_xy**2)) / (2*s_xy)deming_intercept = y_mean - x_mean*deming_slopeprint(f'Deming slope = {deming_slope:.2f}')print(f'Deming intercept = {deming_intercept:.2f}')# Output: Deming slope = 0.50, Deming intercept = 134.09"
},
{
"code": null,
"e": 8811,
"s": 8686,
"text": "This is exactly our simple linear regression result, nice! Careful: This is not a proof, yet it gives a nice feeling for it."
},
{
"code": null,
"e": 9147,
"s": 8811,
"text": "And think about the other extreme: What happens if the errors in the features are extremely large, let’s say infinity? Well, then δ becomes zero and the whole Deming slope term becomes just zero as well, which is easy to calculate (do it!). The intercept is then the mean of the labels y. Basically, the model is only a flat line then."
},
{
"code": null,
"e": 9423,
"s": 9147,
"text": "This also makes sense intuitively since the features are essentially useless in this case, so it’s good to ignore them and act like there are no features at all. And the best model without features that minimizes the sum of squares error is just the constant mean prediction."
},
{
"code": null,
"e": 9683,
"s": 9423,
"text": "In this article, we introduced the problem of errors in the features X and how they can influence the true relationships between variables. Simple linear regression yields a slope that is usually substantially lower than the truth, called regression dilution."
},
{
"code": null,
"e": 9937,
"s": 9683,
"text": "However, smart people invented another kind of regression to adjust for these errors: Deming regression. It makes it possible to still come to the correct conclusion without re-running the experiment another time, which can save time, money, and nerves."
},
{
"code": null,
"e": 10190,
"s": 9937,
"text": "Deming regression is great, but it is tricky to guess the correct values for δ, which is a major drawback because the result of the regression relies heavily on δ. Still, it’s nice that you can even make a statement in the case of features with errors."
},
{
"code": null,
"e": 10490,
"s": 10190,
"text": "A natural question to ask now is the following: What happens if we have more than one feature? Mathematicians got us covered, there is the total least squares method which is a direct generalization of Deming regression to more than one variable. And there are many more models, as you can see here."
},
{
"code": null,
"e": 10648,
"s": 10490,
"text": "Now you know that it makes sense to also pay attention to errors in all of your measurements and act accordingly to weaken their effects as well as possible."
},
{
"code": null,
"e": 10738,
"s": 10648,
"text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!"
},
{
"code": null,
"e": 10764,
"s": 10738,
"text": "As the last point, if you"
},
{
"code": null,
"e": 10867,
"s": 10764,
"text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway,"
},
{
"code": null,
"e": 10929,
"s": 10867,
"text": "want to support me in writing more about machine learning and"
},
{
"code": null,
"e": 10971,
"s": 10929,
"text": "plan to get a Medium subscription anyway,"
},
{
"code": null,
"e": 11028,
"s": 10971,
"text": "why not do it via this link? This would help me a lot! 😊"
},
{
"code": null,
"e": 11141,
"s": 11028,
"text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me."
},
{
"code": null,
"e": 11186,
"s": 11141,
"text": "Thanks a lot, if you consider supporting me!"
}
] |
numpy.geomspace() in Python - GeeksforGeeks
|
31 May, 2021
numpy.geomspace() is used to return numbers spaced evenly on a log scale (a geometric progression). This is similar to numpy.logspace() but with endpoints specified directly. Each output sample is a constant multiple of the previous.
Syntax : numpy.geomspace(start, stop, num=50, endpoint=True, dtype=None)Parameters : start : [scalar] The starting value of the sequence. stop : [scalar] The final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned. num : [integer, optional] Number of samples to generate. Default is 50. endpoint : [boolean, optional] If true, stop is the last sample. Otherwise, it is not included. Default is True. dtype : [dtype] The type of the output array. If dtype is not given, infer the data type from the other input arguments.Return : samples : [ndarray] num samples, equally spaced on a log scale.
Code #1 : Working
Python
# Python3 Program demonstrate# numpy.geomspace() function import numpy as geek print("B\n", geek.geomspace(2.0, 3.0, num = 5), "\n") # To evaluate sin() in long rangepoint = geek.geomspace(1, 2, 10)print("A\n", geek.sin(point))
Output :
B
[ 2. 2.21336384 2.44948974 2.71080601 3. ]
A
[ 0.84147098 0.88198596 0.91939085 0.95206619 0.9780296 0.9948976
0.99986214 0.98969411 0.96079161 0.90929743]
Code #2 : Graphical Representation of numpy.geomspace()
Python
# Graphical Representation of numpy.geomspace()import numpy as geekimport pylab as p% matplotlib inline # Start = 1# End = 3 # Samples to generate = 10x1 = geek.geomspace(1, 3, 10, endpoint = False)y1 = geek.ones(10) p.plot(x1, y1, '+')
Output :
anikaseth98
Pyhton numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
|
[
{
"code": null,
"e": 23755,
"s": 23727,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 23991,
"s": 23755,
"text": "numpy.geomspace() is used to return numbers spaced evenly on a log scale (a geometric progression). This is similar to numpy.logspace() but with endpoints specified directly. Each output sample is a constant multiple of the previous. "
},
{
"code": null,
"e": 24723,
"s": 23991,
"text": "Syntax : numpy.geomspace(start, stop, num=50, endpoint=True, dtype=None)Parameters : start : [scalar] The starting value of the sequence. stop : [scalar] The final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned. num : [integer, optional] Number of samples to generate. Default is 50. endpoint : [boolean, optional] If true, stop is the last sample. Otherwise, it is not included. Default is True. dtype : [dtype] The type of the output array. If dtype is not given, infer the data type from the other input arguments.Return : samples : [ndarray] num samples, equally spaced on a log scale. "
},
{
"code": null,
"e": 24743,
"s": 24723,
"text": "Code #1 : Working "
},
{
"code": null,
"e": 24750,
"s": 24743,
"text": "Python"
},
{
"code": "# Python3 Program demonstrate# numpy.geomspace() function import numpy as geek print(\"B\\n\", geek.geomspace(2.0, 3.0, num = 5), \"\\n\") # To evaluate sin() in long rangepoint = geek.geomspace(1, 2, 10)print(\"A\\n\", geek.sin(point))",
"e": 24979,
"s": 24750,
"text": null
},
{
"code": null,
"e": 24990,
"s": 24979,
"text": "Output : "
},
{
"code": null,
"e": 25182,
"s": 24990,
"text": "B\n [ 2. 2.21336384 2.44948974 2.71080601 3. ] \n\nA\n [ 0.84147098 0.88198596 0.91939085 0.95206619 0.9780296 0.9948976\n 0.99986214 0.98969411 0.96079161 0.90929743]"
},
{
"code": null,
"e": 25242,
"s": 25182,
"text": " Code #2 : Graphical Representation of numpy.geomspace() "
},
{
"code": null,
"e": 25249,
"s": 25242,
"text": "Python"
},
{
"code": "# Graphical Representation of numpy.geomspace()import numpy as geekimport pylab as p% matplotlib inline # Start = 1# End = 3 # Samples to generate = 10x1 = geek.geomspace(1, 3, 10, endpoint = False)y1 = geek.ones(10) p.plot(x1, y1, '+')",
"e": 25489,
"s": 25249,
"text": null
},
{
"code": null,
"e": 25500,
"s": 25489,
"text": "Output : "
},
{
"code": null,
"e": 25514,
"s": 25502,
"text": "anikaseth98"
},
{
"code": null,
"e": 25541,
"s": 25514,
"text": "Pyhton numpy-arrayCreation"
},
{
"code": null,
"e": 25554,
"s": 25541,
"text": "Python-numpy"
},
{
"code": null,
"e": 25561,
"s": 25554,
"text": "Python"
},
{
"code": null,
"e": 25659,
"s": 25561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25668,
"s": 25659,
"text": "Comments"
},
{
"code": null,
"e": 25681,
"s": 25668,
"text": "Old Comments"
},
{
"code": null,
"e": 25703,
"s": 25681,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25738,
"s": 25703,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25760,
"s": 25738,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25802,
"s": 25760,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25827,
"s": 25802,
"text": "sum() function in Python"
},
{
"code": null,
"e": 25857,
"s": 25827,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25889,
"s": 25857,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25905,
"s": 25889,
"text": "Deque in Python"
},
{
"code": null,
"e": 25931,
"s": 25905,
"text": "Python String | replace()"
}
] |
How to download APK files from Google Play Store on Linux
|
Do you know how to download APK (Android packaging kit) files from Google Play store on Linux? One of the easiest way is to install APK on Android mobile for downloading APK files from Google Play Store to Hard Disk and install them on the Android device manually.
There are several ways to download APK file(s) on Linux. One of the most used ways is via an open-source Linux software called GooglePlayDownloader. It works on python based GUI. It enables you to search and download APK files from Google play store. This article gives information about, how to install GooglePlayDownloader and download the APK files from it.
GooglePlayDownloader requires Python with SNI (Server Name Indication) support for SSL/TLS communication. This feature comes with Python 2.7.9 or higher. So before installing Googleplaydownloader,install python packages.
Step 1 – Install all dependencies for GooglePlayDownloader
Before installing GooglePlayDownloader, download python-ndg-httpsclient deb package for installing any missing dependencies on older Ubuntu distributions. To install python deb packages, use the following command –
$ wget http://mirrors.kernel.org/ubuntu/pool/main/n/ndg-httpsclient/python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb
The output should be like this –
tp@linux:~$ wget http://mirrors.kernel.org/ubuntu/pool/main/n/ndg-httpsclient/python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb
--2016-02-11 15:07:01-- http://mirrors.kernel.org/ubuntu/pool/main/n/ndg-httpsclient/python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb
Resolving mirrors.kernel.org (mirrors.kernel.org)... 198.145.20.143, 149.20.37.36, 2620:3:c000:a:0:1994:3:14, ...
Connecting to mirrors.kernel.org (mirrors.kernel.org)|198.145.20.143|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 20814 (20K) [application/octet-stream]
Saving to: ‘python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb’
100%[======================================>] 20,814 73.2KB/s in 0.3s
2016-02-11 15:07:02 (73.2 KB/s) - ‘python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb’ saved [20814/20814]
Step 2 – To install GooglePlayDownloader, use the following command –
$ wget http://codingteam.net/project/googleplaydownloader/download/file/googleplaydownloader_1.7-1_all.deb
The output should be like this –
$ wget http://codingteam.net/project/googleplaydownloader/download/file/googleplaydownloader_1.7-1_all.deb
--2016-02-11 15:08:54-- http://codingteam.net/project/googleplaydownloader/download/file/googleplaydownloader_1.7-1_all.deb
Resolving codingteam.net (codingteam.net)... 212.83.148.207
Connecting to codingteam.net (codingteam.net)|212.83.148.207|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://codingteam.net/project/googleplaydownloader/upload/releases/googleplaydownloader_1.7-1_all.deb [following]
--2016-02-11 15:08:54-- http://codingteam.net/project/googleplaydownloader/upload/releases/googleplaydownloader_1.7-1_all.deb
Reusing existing connection to codingteam.net:80.
HTTP request sent, awaiting response... 200 OK
Length: 148458 (145K) [application/x-debian-package]
Saving to: ‘googleplaydownloader_1.7-1_all.deb’
100%[======================================>] 1,48,458 197KB/s in 0.7s
2016-02-11 15:08:55 (197 KB/s) - ‘googleplaydownloader_1.7-1_all.deb’ saved [148458/148458]
Step 1 – Install gdebi Packages
Usegdebi command that will automatically handle all other commands. To install gdebi package, use the following command –
$ sudo apt-get install gdebi-core
The output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
gdebi-core
0 upgraded, 1 newly installed, 0 to remove and 275 not upgraded.
Need to get 9,772 B of archives.
After this operation, 135 kB of additional disk space will be used.
Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty-updates/main gdebi-core all 0.9.5.3ubuntu2 [9,772 B]
Fetched 9,772 B in 5s (1,757 B/s)
Selecting previously unselected package gdebi-core.
.....
Step 2 – Install python-ndg-httpsclient
To install python-ndg-httpsclient, use the following command –
$ sudo gdebi python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb
The output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
Building data structures... Done
Building data structures... Done
enhanced HTTPS support for httplib and urllib2 using PyOpenSSL
ndg-httpsclient is a HTTPS client implementation for httplib and
urllib2 based on PyOpenSSL. PyOpenSSL provides a more fully featured SSL
implementation over the default provided with Python and importantly
enables full verification of the SSL peer.
Do you want to install the software package? [y/N]:y
Selecting previously unselected package python-ndg-httpsclient.
(Reading database ... 204828 files and directories currently installed.)
Preparing to unpack python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb ...
Unpacking python-ndg-httpsclient (0.3.2-1ubuntu4) ...
Setting up python-ndg-httpsclient (0.3.2-1ubuntu4) ...
....
Step 3 – Install GooglePlayDownloader
To install GoogleplayDownloader, Use the following command –
$ sudo gdebi googleplaydownloader_1.7-1_all.deb
The output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
Building data structures... Done
Building data structures... Done
Requires the installation of the following packages: libjs-jquery libjs-sphinxdoc libjs-underscore libwxbase2.8-0 libwxgtk-media2.8-0 libwxgtk2.8-0 python-configparser python-protobuf python-pyasn1 python-wxgtk2.8 python-wxversion
Google Play Downloader
Download Android application APK from Google Play Store
without any personal Google account.
Do you want to install the software package? [y/N]:y
Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty/universe libwxbase2.8-0 amd64 2.8.12.1+dfsg-2ubuntu2 [460 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu/ trusty/universe libwxgtk2.8-0 amd64 2.8.12.1+dfsg-2ubuntu2 [2371 kB]
Get:3 http://in.archive.ubuntu.com/ubuntu/ trusty/universe libwxgtk-media2.8-0 amd64 2.8.12.1+dfsg-2ubuntu2 [28.6 kB]
Get:4 http://in.archive.ubuntu.com/ubuntu/ trusty/main libjs-jquery all 1.7.2+dfsg-2ubuntu1 [78.8 kB]
Get:5 http://in.archive.ubuntu.com/ubuntu/ trusty/main libjs-underscore all 1.4.4-2ubuntu1 [45.6 kB]
.....
To open GooglePlayDownloader, use the following command –
$ googleplaydownloader
The output should be like this –
At search bar, Type the name of the APK file that you want to download. Suppose, I have searched for tutorialspoint. The output should be like this –
Click on theDownload selected Apk(s) button. It shows the output should be like this –
Finally, you will get a selected APK file on Hard disk.
Congratulations! Now, you know “How to download APK files from Google Play Store on Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
|
[
{
"code": null,
"e": 1327,
"s": 1062,
"text": "Do you know how to download APK (Android packaging kit) files from Google Play store on Linux? One of the easiest way is to install APK on Android mobile for downloading APK files from Google Play Store to Hard Disk and install them on the Android device manually."
},
{
"code": null,
"e": 1688,
"s": 1327,
"text": "There are several ways to download APK file(s) on Linux. One of the most used ways is via an open-source Linux software called GooglePlayDownloader. It works on python based GUI. It enables you to search and download APK files from Google play store. This article gives information about, how to install GooglePlayDownloader and download the APK files from it."
},
{
"code": null,
"e": 1909,
"s": 1688,
"text": "GooglePlayDownloader requires Python with SNI (Server Name Indication) support for SSL/TLS communication. This feature comes with Python 2.7.9 or higher. So before installing Googleplaydownloader,install python packages."
},
{
"code": null,
"e": 1969,
"s": 1909,
"text": "Step 1 – Install all dependencies for GooglePlayDownloader"
},
{
"code": null,
"e": 2184,
"s": 1969,
"text": "Before installing GooglePlayDownloader, download python-ndg-httpsclient deb package for installing any missing dependencies on older Ubuntu distributions. To install python deb packages, use the following command –"
},
{
"code": null,
"e": 2298,
"s": 2184,
"text": "$ wget http://mirrors.kernel.org/ubuntu/pool/main/n/ndg-httpsclient/python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb"
},
{
"code": null,
"e": 2331,
"s": 2298,
"text": "The output should be like this –"
},
{
"code": null,
"e": 3114,
"s": 2331,
"text": "tp@linux:~$ wget http://mirrors.kernel.org/ubuntu/pool/main/n/ndg-httpsclient/python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb\n--2016-02-11 15:07:01-- http://mirrors.kernel.org/ubuntu/pool/main/n/ndg-httpsclient/python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb\nResolving mirrors.kernel.org (mirrors.kernel.org)... 198.145.20.143, 149.20.37.36, 2620:3:c000:a:0:1994:3:14, ...\nConnecting to mirrors.kernel.org (mirrors.kernel.org)|198.145.20.143|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 20814 (20K) [application/octet-stream]\nSaving to: ‘python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb’\n\n100%[======================================>] 20,814 73.2KB/s in 0.3s\n\n2016-02-11 15:07:02 (73.2 KB/s) - ‘python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb’ saved [20814/20814]"
},
{
"code": null,
"e": 3184,
"s": 3114,
"text": "Step 2 – To install GooglePlayDownloader, use the following command –"
},
{
"code": null,
"e": 3291,
"s": 3184,
"text": "$ wget http://codingteam.net/project/googleplaydownloader/download/file/googleplaydownloader_1.7-1_all.deb"
},
{
"code": null,
"e": 3324,
"s": 3291,
"text": "The output should be like this –"
},
{
"code": null,
"e": 4357,
"s": 3324,
"text": "$ wget http://codingteam.net/project/googleplaydownloader/download/file/googleplaydownloader_1.7-1_all.deb\n--2016-02-11 15:08:54-- http://codingteam.net/project/googleplaydownloader/download/file/googleplaydownloader_1.7-1_all.deb\nResolving codingteam.net (codingteam.net)... 212.83.148.207\nConnecting to codingteam.net (codingteam.net)|212.83.148.207|:80... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: http://codingteam.net/project/googleplaydownloader/upload/releases/googleplaydownloader_1.7-1_all.deb [following]\n--2016-02-11 15:08:54-- http://codingteam.net/project/googleplaydownloader/upload/releases/googleplaydownloader_1.7-1_all.deb\nReusing existing connection to codingteam.net:80.\nHTTP request sent, awaiting response... 200 OK\nLength: 148458 (145K) [application/x-debian-package]\nSaving to: ‘googleplaydownloader_1.7-1_all.deb’\n\n100%[======================================>] 1,48,458 197KB/s in 0.7s\n\n2016-02-11 15:08:55 (197 KB/s) - ‘googleplaydownloader_1.7-1_all.deb’ saved [148458/148458]"
},
{
"code": null,
"e": 4389,
"s": 4357,
"text": "Step 1 – Install gdebi Packages"
},
{
"code": null,
"e": 4511,
"s": 4389,
"text": "Usegdebi command that will automatically handle all other commands. To install gdebi package, use the following command –"
},
{
"code": null,
"e": 4545,
"s": 4511,
"text": "$ sudo apt-get install gdebi-core"
},
{
"code": null,
"e": 4578,
"s": 4545,
"text": "The output should be like this –"
},
{
"code": null,
"e": 5085,
"s": 4578,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following NEW packages will be installed:\ngdebi-core\n0 upgraded, 1 newly installed, 0 to remove and 275 not upgraded.\nNeed to get 9,772 B of archives.\nAfter this operation, 135 kB of additional disk space will be used.\nGet:1 http://in.archive.ubuntu.com/ubuntu/ trusty-updates/main gdebi-core all 0.9.5.3ubuntu2 [9,772 B]\nFetched 9,772 B in 5s (1,757 B/s)\nSelecting previously unselected package gdebi-core.\n....."
},
{
"code": null,
"e": 5125,
"s": 5085,
"text": "Step 2 – Install python-ndg-httpsclient"
},
{
"code": null,
"e": 5188,
"s": 5125,
"text": "To install python-ndg-httpsclient, use the following command –"
},
{
"code": null,
"e": 5247,
"s": 5188,
"text": "$ sudo gdebi python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb"
},
{
"code": null,
"e": 5280,
"s": 5247,
"text": "The output should be like this –"
},
{
"code": null,
"e": 6123,
"s": 5280,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nBuilding data structures... Done\nBuilding data structures... Done\n\nenhanced HTTPS support for httplib and urllib2 using PyOpenSSL\nndg-httpsclient is a HTTPS client implementation for httplib and\nurllib2 based on PyOpenSSL. PyOpenSSL provides a more fully featured SSL\nimplementation over the default provided with Python and importantly\nenables full verification of the SSL peer.\nDo you want to install the software package? [y/N]:y\nSelecting previously unselected package python-ndg-httpsclient.\n(Reading database ... 204828 files and directories currently installed.)\nPreparing to unpack python-ndg-httpsclient_0.3.2-1ubuntu4_all.deb ...\nUnpacking python-ndg-httpsclient (0.3.2-1ubuntu4) ...\nSetting up python-ndg-httpsclient (0.3.2-1ubuntu4) ...\n...."
},
{
"code": null,
"e": 6161,
"s": 6123,
"text": "Step 3 – Install GooglePlayDownloader"
},
{
"code": null,
"e": 6222,
"s": 6161,
"text": "To install GoogleplayDownloader, Use the following command –"
},
{
"code": null,
"e": 6270,
"s": 6222,
"text": "$ sudo gdebi googleplaydownloader_1.7-1_all.deb"
},
{
"code": null,
"e": 6303,
"s": 6270,
"text": "The output should be like this –"
},
{
"code": null,
"e": 7410,
"s": 6303,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nBuilding data structures... Done\nBuilding data structures... Done\nRequires the installation of the following packages: libjs-jquery libjs-sphinxdoc libjs-underscore libwxbase2.8-0 libwxgtk-media2.8-0 libwxgtk2.8-0 python-configparser python-protobuf python-pyasn1 python-wxgtk2.8 python-wxversion\n\nGoogle Play Downloader\nDownload Android application APK from Google Play Store\nwithout any personal Google account.\nDo you want to install the software package? [y/N]:y\nGet:1 http://in.archive.ubuntu.com/ubuntu/ trusty/universe libwxbase2.8-0 amd64 2.8.12.1+dfsg-2ubuntu2 [460 kB]\nGet:2 http://in.archive.ubuntu.com/ubuntu/ trusty/universe libwxgtk2.8-0 amd64 2.8.12.1+dfsg-2ubuntu2 [2371 kB]\nGet:3 http://in.archive.ubuntu.com/ubuntu/ trusty/universe libwxgtk-media2.8-0 amd64 2.8.12.1+dfsg-2ubuntu2 [28.6 kB]\nGet:4 http://in.archive.ubuntu.com/ubuntu/ trusty/main libjs-jquery all 1.7.2+dfsg-2ubuntu1 [78.8 kB]\nGet:5 http://in.archive.ubuntu.com/ubuntu/ trusty/main libjs-underscore all 1.4.4-2ubuntu1 [45.6 kB]\n....."
},
{
"code": null,
"e": 7468,
"s": 7410,
"text": "To open GooglePlayDownloader, use the following command –"
},
{
"code": null,
"e": 7491,
"s": 7468,
"text": "$ googleplaydownloader"
},
{
"code": null,
"e": 7524,
"s": 7491,
"text": "The output should be like this –"
},
{
"code": null,
"e": 7674,
"s": 7524,
"text": "At search bar, Type the name of the APK file that you want to download. Suppose, I have searched for tutorialspoint. The output should be like this –"
},
{
"code": null,
"e": 7761,
"s": 7674,
"text": "Click on theDownload selected Apk(s) button. It shows the output should be like this –"
},
{
"code": null,
"e": 7817,
"s": 7761,
"text": "Finally, you will get a selected APK file on Hard disk."
},
{
"code": null,
"e": 7994,
"s": 7817,
"text": "Congratulations! Now, you know “How to download APK files from Google Play Store on Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!"
}
] |
DUAL table in SQL - GeeksforGeeks
|
25 Aug, 2020
There may be a situation where we want to query something that is not from a table. For example, getting the current date or querying a simple arithmetic expression like 2+2.
In Oracle, clause FROM is not exceptional. If we don’t write the FROM clause in Oracle, we’ll get an error.
Example-1: Oracle Query
SELECT SYSDATE;
Output –
ORA-00923: FROM keyword not found where expected
Example-2: Oracle Query
SELECT 'GeeksforGeeks';
Output –
ORA-00923: FROM keyword not found where expected
DUAL :It is a table that is automatically created by Oracle Database along with the data dictionary. DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value X.
Example: Oracle Query
SELECT *
FROM DUAL ;
Output –
X
Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once.
Oracle Query :
SELECT 'GeeksforGeeks'
AS NAME FROM DUAL;
Output –
GeeksforGeeks
Oracle Query :
SELECT 2+2
FROM DUAL;
Output :
2+2 = 4
Several other databases, including MS SQL Server, MySQL, PostgreSQL and SQLite, allows the omitting of FROM clause. This exception is the reason there is no dummy table like DUAL in other databases.
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
SQL | Views
SQL Interview Questions
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
|
[
{
"code": null,
"e": 24374,
"s": 24346,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 24549,
"s": 24374,
"text": "There may be a situation where we want to query something that is not from a table. For example, getting the current date or querying a simple arithmetic expression like 2+2."
},
{
"code": null,
"e": 24657,
"s": 24549,
"text": "In Oracle, clause FROM is not exceptional. If we don’t write the FROM clause in Oracle, we’ll get an error."
},
{
"code": null,
"e": 24681,
"s": 24657,
"text": "Example-1: Oracle Query"
},
{
"code": null,
"e": 24697,
"s": 24681,
"text": "SELECT SYSDATE;"
},
{
"code": null,
"e": 24706,
"s": 24697,
"text": "Output –"
},
{
"code": null,
"e": 24755,
"s": 24706,
"text": "ORA-00923: FROM keyword not found where expected"
},
{
"code": null,
"e": 24779,
"s": 24755,
"text": "Example-2: Oracle Query"
},
{
"code": null,
"e": 24803,
"s": 24779,
"text": "SELECT 'GeeksforGeeks';"
},
{
"code": null,
"e": 24812,
"s": 24803,
"text": "Output –"
},
{
"code": null,
"e": 24861,
"s": 24812,
"text": "ORA-00923: FROM keyword not found where expected"
},
{
"code": null,
"e": 25139,
"s": 24861,
"text": "DUAL :It is a table that is automatically created by Oracle Database along with the data dictionary. DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value X."
},
{
"code": null,
"e": 25161,
"s": 25139,
"text": "Example: Oracle Query"
},
{
"code": null,
"e": 25183,
"s": 25161,
"text": "SELECT * \nFROM DUAL ;"
},
{
"code": null,
"e": 25192,
"s": 25183,
"text": "Output –"
},
{
"code": null,
"e": 25195,
"s": 25192,
"text": "X "
},
{
"code": null,
"e": 25365,
"s": 25195,
"text": "Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once."
},
{
"code": null,
"e": 25380,
"s": 25365,
"text": "Oracle Query :"
},
{
"code": null,
"e": 25423,
"s": 25380,
"text": "SELECT 'GeeksforGeeks' \nAS NAME FROM DUAL;"
},
{
"code": null,
"e": 25432,
"s": 25423,
"text": "Output –"
},
{
"code": null,
"e": 25447,
"s": 25432,
"text": "GeeksforGeeks "
},
{
"code": null,
"e": 25462,
"s": 25447,
"text": "Oracle Query :"
},
{
"code": null,
"e": 25485,
"s": 25462,
"text": "SELECT 2+2 \nFROM DUAL;"
},
{
"code": null,
"e": 25494,
"s": 25485,
"text": "Output :"
},
{
"code": null,
"e": 25503,
"s": 25494,
"text": "2+2 = 4 "
},
{
"code": null,
"e": 25702,
"s": 25503,
"text": "Several other databases, including MS SQL Server, MySQL, PostgreSQL and SQLite, allows the omitting of FROM clause. This exception is the reason there is no dummy table like DUAL in other databases."
},
{
"code": null,
"e": 25711,
"s": 25702,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25716,
"s": 25711,
"text": "DBMS"
},
{
"code": null,
"e": 25720,
"s": 25716,
"text": "SQL"
},
{
"code": null,
"e": 25725,
"s": 25720,
"text": "DBMS"
},
{
"code": null,
"e": 25729,
"s": 25725,
"text": "SQL"
},
{
"code": null,
"e": 25827,
"s": 25729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25850,
"s": 25827,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 25903,
"s": 25850,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 25914,
"s": 25903,
"text": "CTE in SQL"
},
{
"code": null,
"e": 25926,
"s": 25914,
"text": "SQL | Views"
},
{
"code": null,
"e": 25950,
"s": 25926,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 25992,
"s": 25950,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 26036,
"s": 25992,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 26057,
"s": 26036,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 26068,
"s": 26057,
"text": "CTE in SQL"
}
] |
How to find Segmentation Error in C & C++ ? (Using GDB)
|
03 Sep, 2018
What is Segmentation Error ?– It is the runtime error caused because of the memory access violation. For Eg :-Stackoverflow, read violation etc..We often face this problem when working out with pointers in c++/c.In this example we will see how to find the segmentation error in the program. We will find which lines causes the segmentation fault error.Note :- I have used Linux distro – Ubuntu for this demonstration.So, Consider the following snippet of C++ Code.
// Segmentation Error Demonstration// Author - Rohan Prasad#include <iostream>using namespace std; int main(){ int* p = NULL; // This lines cause the segmentation // error because of accessing the // unknown memory location. *p = 1; cout << *p; return 0;}
How to find that error using gdb?Let’s say your file name is saved as Program1.cpp. Head our to your terminal (Be in the directory in which this Program1.cpp is available)
Step 1: Compile it.$ gcc -g Program1.cpp (in my case).Step 2: Run it.$ ./a.out (it is Object File)If it shows Segmentation fault (core dumped) then follow following steps.Step 3:Debug it$ gdb ./a.out coreYour output will look like something this:————————————————————————————GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-gitCopyright (C) 2018 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or laterThis is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. Type "show copying"and "show warranty" for details.This GDB was configured as "x86_64-linux-gnu".Type "show configuration" for configuration details.For bug reporting instructions, please see:.Find the GDB manual and other documentation resources online at:.For help, type "help".Type "apropos word" to search for commands related to "word"...Reading symbols from ./a.out...done./home/logarithm/Desktop/Test Case/Miccl/core: No such file or directory.(gdb)
————————————————————————————Then just type r and press the enter key .The output will be something like this showing the erroneous statement.———————————————————————————–(gdb) rStarting program: /home/logarithm/Desktop/Test Case/Miccl/a.out
Program received signal SIGSEGV, Segmentation fault.0x00005555555547de in main () at Sege.cpp:88 *p=1;(gdb)————————————————————————————Now you have got the line that causes segmentation error.Exit from debugger and correct the program.For exiting type quit and press enter.———————————————————————————–(gdb) quitA debugging session is active.
Inferior 1 [process 3617] will be killed.
Quit anyway? (y or n) y
———————————————————————————–So, wow you have resolved the head torturing segmentation fault.
C-Pointers
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Sep, 2018"
},
{
"code": null,
"e": 517,
"s": 52,
"text": "What is Segmentation Error ?– It is the runtime error caused because of the memory access violation. For Eg :-Stackoverflow, read violation etc..We often face this problem when working out with pointers in c++/c.In this example we will see how to find the segmentation error in the program. We will find which lines causes the segmentation fault error.Note :- I have used Linux distro – Ubuntu for this demonstration.So, Consider the following snippet of C++ Code."
},
{
"code": "// Segmentation Error Demonstration// Author - Rohan Prasad#include <iostream>using namespace std; int main(){ int* p = NULL; // This lines cause the segmentation // error because of accessing the // unknown memory location. *p = 1; cout << *p; return 0;}",
"e": 802,
"s": 517,
"text": null
},
{
"code": null,
"e": 974,
"s": 802,
"text": "How to find that error using gdb?Let’s say your file name is saved as Program1.cpp. Head our to your terminal (Be in the directory in which this Program1.cpp is available)"
},
{
"code": null,
"e": 1964,
"s": 974,
"text": "Step 1: Compile it.$ gcc -g Program1.cpp (in my case).Step 2: Run it.$ ./a.out (it is Object File)If it shows Segmentation fault (core dumped) then follow following steps.Step 3:Debug it$ gdb ./a.out coreYour output will look like something this:————————————————————————————GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-gitCopyright (C) 2018 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or laterThis is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-linux-gnu\".Type \"show configuration\" for configuration details.For bug reporting instructions, please see:.Find the GDB manual and other documentation resources online at:.For help, type \"help\".Type \"apropos word\" to search for commands related to \"word\"...Reading symbols from ./a.out...done./home/logarithm/Desktop/Test Case/Miccl/core: No such file or directory.(gdb)"
},
{
"code": null,
"e": 2204,
"s": 1964,
"text": "————————————————————————————Then just type r and press the enter key .The output will be something like this showing the erroneous statement.———————————————————————————–(gdb) rStarting program: /home/logarithm/Desktop/Test Case/Miccl/a.out"
},
{
"code": null,
"e": 2546,
"s": 2204,
"text": "Program received signal SIGSEGV, Segmentation fault.0x00005555555547de in main () at Sege.cpp:88 *p=1;(gdb)————————————————————————————Now you have got the line that causes segmentation error.Exit from debugger and correct the program.For exiting type quit and press enter.———————————————————————————–(gdb) quitA debugging session is active."
},
{
"code": null,
"e": 2588,
"s": 2546,
"text": "Inferior 1 [process 3617] will be killed."
},
{
"code": null,
"e": 2612,
"s": 2588,
"text": "Quit anyway? (y or n) y"
},
{
"code": null,
"e": 2705,
"s": 2612,
"text": "———————————————————————————–So, wow you have resolved the head torturing segmentation fault."
},
{
"code": null,
"e": 2716,
"s": 2705,
"text": "C-Pointers"
},
{
"code": null,
"e": 2728,
"s": 2716,
"text": "cpp-pointer"
},
{
"code": null,
"e": 2739,
"s": 2728,
"text": "C Language"
},
{
"code": null,
"e": 2743,
"s": 2739,
"text": "C++"
},
{
"code": null,
"e": 2747,
"s": 2743,
"text": "CPP"
},
{
"code": null,
"e": 2845,
"s": 2747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2862,
"s": 2845,
"text": "Substring in C++"
},
{
"code": null,
"e": 2884,
"s": 2862,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2919,
"s": 2884,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2965,
"s": 2919,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3010,
"s": 2965,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3028,
"s": 3010,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3071,
"s": 3028,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3117,
"s": 3071,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 3160,
"s": 3117,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Program to find third side of triangle using law of cosines
|
08 Jun, 2022
Given two sides A, B and angle C. Find the third side of the triangle using law of cosines.Examples:
Input : a = 5, b = 8, c = 49
Output : 6.04339
In particular, the Law of Cosines can be used to find the length of the third side of a triangle when you know the length of two sides and the angle in between. See here to learn to how to find the value of cos. Let us assume a, b, c are the sides of triangle where c is the side across from angle C. Then,
c^2 = a^2 + b^2 - 2*a*b*cos(c)
OR
c = sqrt(a^2 + b^2 - 2*a*b*cos(c))
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find third// side of triangle using// law of cosines #include <bits/stdc++.h>using namespace std; // Function to calculate cos value of angle cfloat cal_cos(float n){ float accuracy = 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // Maps the sum along the series cosx = x1; // Holds the actual value of sin(n) cosval = cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= fabs(cosval - cosx)); return cosx;} // Function to find third sidefloat third_side(int a, int b, float c){ float angle = cal_cos(c); return sqrt((a * a) + (b * b) - 2 * a * b * angle);}// Driver program to check the above functionint main(){ float c = 49; int a = 5, b = 8; // function call cout << third_side(a, b, c); return 0;}
// Java program to find third// side of triangle using// law of cosinesclass GFG{ // Function to calculate // cos value of angle c static float cal_cos(float n) { float accuracy = 0.0001f, x1; float denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142f / 180.0f); x1 = 1; // Maps the sum along the series cosx = x1; // Holds the actual value of sin(n) cosval = (float)Math.cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.abs(cosval - cosx)); return cosx; } // Function to find third side static float third_side(int a, int b, float c) { float angle = cal_cos(c); return (float)Math.sqrt((a * a) + (b * b) - 2 * a * b * angle);} // Driver codepublic static void main (String[] args){ float c = 49; int a = 5, b = 8; // function call System.out.print(Math.round(third_side(a, b, c)*100000.0)/100000.0);}} // This code is contributed by Anant Agarwal.
# Python3 program to find third side# of triangle using law of cosinesimport math as mt # Function to calculate cos# value of angle cdef cal_cos(n): accuracy = 0.0001 x1, denominator, cosx, cosval = 0, 0, 0, 0 # Converting degrees to radian n = n * (3.142 / 180.0) x1 = 1 # Maps the sum along the series cosx = x1 # Holds the actual value of sin(n) cosval = mt.cos(n) i = 1 while (accuracy <= abs(cosval - cosx)): denominator = 2 * i * (2 * i - 1) x1 = -x1 * n * n / denominator cosx = cosx + x1 i = i + 1 return cosx # Function to find third sidedef third_side(a, b, c): angle = cal_cos(c) return mt.sqrt((a * a) + (b * b) - 2 * a * b * angle) # Driver Codec = 49a, b = 5, 8print(third_side(a, b, c)) # This code is contributed by mohit kumar
// C# program to find third// side of triangle using// law of cosinesusing System; class GFG{ // Function to calculate // cos value of angle c static float cal_cos(float n) { float accuracy = 0.0001f, x1; float denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142f / 180.0f); x1 = 1; // Maps the sum along the series cosx = x1; // Holds the actual value of sin(n) cosval = (float)Math.Cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.Abs(cosval - cosx)); return cosx; } // Function to find third side static float third_side(int a, int b, float c) { float angle = cal_cos(c); return (float)Math.Sqrt((a * a) + (b * b) - 2 * a * b * angle); } // Driver code public static void Main () { float c = 49; int a = 5, b = 8; // function call Console.WriteLine(Math.Round(third_side(a, b, c)*100000.0)/100000.0); }} // This code is contributed by vt_m.
<?php// PHP program to find third// side of triangle using// law of cosines // Function to calculate// cos value of angle cfunction cal_cos( $n ){ $accuracy = 0.0001; $x1; $denominator; $cosx; $cosval; // Converting degrees // to radian $n = $n * (3.142 / 180.0); $x1 = 1; // Maps the sum // along the series $cosx = $x1; // Holds the actual // value of sin(n) $cosval = cos($n); $i = 1; do { $denominator = 2 * $i * (2 * $i - 1); $x1 = -$x1 * $n * $n / $denominator; $cosx = $cosx + $x1; $i = $i + 1; } while ($accuracy <= ($cosval - $cosx)); return $cosx;} // Function to find third sidefunction third_side($a, $b, $c){ $angle = cal_cos($c); return sqrt(($a * $a) + ($b * $b) - 2 * $a * $b * $angle);} // Driver Code$c = 49;$a = 5;$b = 8; // function callecho third_side($a, $b, $c); // This code is contributed// by ajit?>
<script>// Javascript program to find third// side of triangle using// law of cosines // Function to calculate // cos value of angle c function cal_cos( n) { let accuracy = 0.0001, x1; let denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // Maps the sum alet the series cosx = x1; // Holds the actual value of sin(n) cosval = Math.cos(n); let i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.abs(cosval - cosx)); return cosx; } // Function to find third side function third_side( a, b, c) { let angle = cal_cos(c); return Math.sqrt((a * a) + (b * b) - 2 * a * b * angle); } // Driver code let c = 49; let a = 5, b = 8; // function call document.write(Math.round(third_side(a, b, c) * 100000.0) / 100000.0); // This code is contributed by Rajput-Ji</script>
6.04339
Time Complexity: O(1), as the loop for calculating cosine value is limited by a period and so it runs a finite amount of time Auxiliary Space: O(1), as we are not using any extra space.
jit_t
mohit kumar 29
Rajput-Ji
rohitsingh57
triangle
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 157,
"s": 54,
"text": "Given two sides A, B and angle C. Find the third side of the triangle using law of cosines.Examples: "
},
{
"code": null,
"e": 205,
"s": 157,
"text": "Input : a = 5, b = 8, c = 49 \nOutput : 6.04339 "
},
{
"code": null,
"e": 516,
"s": 207,
"text": "In particular, the Law of Cosines can be used to find the length of the third side of a triangle when you know the length of two sides and the angle in between. See here to learn to how to find the value of cos. Let us assume a, b, c are the sides of triangle where c is the side across from angle C. Then, "
},
{
"code": null,
"e": 586,
"s": 516,
"text": "c^2 = a^2 + b^2 - 2*a*b*cos(c) \nOR\nc = sqrt(a^2 + b^2 - 2*a*b*cos(c))"
},
{
"code": null,
"e": 594,
"s": 590,
"text": "C++"
},
{
"code": null,
"e": 599,
"s": 594,
"text": "Java"
},
{
"code": null,
"e": 607,
"s": 599,
"text": "Python3"
},
{
"code": null,
"e": 610,
"s": 607,
"text": "C#"
},
{
"code": null,
"e": 614,
"s": 610,
"text": "PHP"
},
{
"code": null,
"e": 625,
"s": 614,
"text": "Javascript"
},
{
"code": "// CPP program to find third// side of triangle using// law of cosines #include <bits/stdc++.h>using namespace std; // Function to calculate cos value of angle cfloat cal_cos(float n){ float accuracy = 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // Maps the sum along the series cosx = x1; // Holds the actual value of sin(n) cosval = cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= fabs(cosval - cosx)); return cosx;} // Function to find third sidefloat third_side(int a, int b, float c){ float angle = cal_cos(c); return sqrt((a * a) + (b * b) - 2 * a * b * angle);}// Driver program to check the above functionint main(){ float c = 49; int a = 5, b = 8; // function call cout << third_side(a, b, c); return 0;}",
"e": 1583,
"s": 625,
"text": null
},
{
"code": "// Java program to find third// side of triangle using// law of cosinesclass GFG{ // Function to calculate // cos value of angle c static float cal_cos(float n) { float accuracy = 0.0001f, x1; float denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142f / 180.0f); x1 = 1; // Maps the sum along the series cosx = x1; // Holds the actual value of sin(n) cosval = (float)Math.cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.abs(cosval - cosx)); return cosx; } // Function to find third side static float third_side(int a, int b, float c) { float angle = cal_cos(c); return (float)Math.sqrt((a * a) + (b * b) - 2 * a * b * angle);} // Driver codepublic static void main (String[] args){ float c = 49; int a = 5, b = 8; // function call System.out.print(Math.round(third_side(a, b, c)*100000.0)/100000.0);}} // This code is contributed by Anant Agarwal.",
"e": 2843,
"s": 1583,
"text": null
},
{
"code": "# Python3 program to find third side# of triangle using law of cosinesimport math as mt # Function to calculate cos# value of angle cdef cal_cos(n): accuracy = 0.0001 x1, denominator, cosx, cosval = 0, 0, 0, 0 # Converting degrees to radian n = n * (3.142 / 180.0) x1 = 1 # Maps the sum along the series cosx = x1 # Holds the actual value of sin(n) cosval = mt.cos(n) i = 1 while (accuracy <= abs(cosval - cosx)): denominator = 2 * i * (2 * i - 1) x1 = -x1 * n * n / denominator cosx = cosx + x1 i = i + 1 return cosx # Function to find third sidedef third_side(a, b, c): angle = cal_cos(c) return mt.sqrt((a * a) + (b * b) - 2 * a * b * angle) # Driver Codec = 49a, b = 5, 8print(third_side(a, b, c)) # This code is contributed by mohit kumar",
"e": 3682,
"s": 2843,
"text": null
},
{
"code": "// C# program to find third// side of triangle using// law of cosinesusing System; class GFG{ // Function to calculate // cos value of angle c static float cal_cos(float n) { float accuracy = 0.0001f, x1; float denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142f / 180.0f); x1 = 1; // Maps the sum along the series cosx = x1; // Holds the actual value of sin(n) cosval = (float)Math.Cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.Abs(cosval - cosx)); return cosx; } // Function to find third side static float third_side(int a, int b, float c) { float angle = cal_cos(c); return (float)Math.Sqrt((a * a) + (b * b) - 2 * a * b * angle); } // Driver code public static void Main () { float c = 49; int a = 5, b = 8; // function call Console.WriteLine(Math.Round(third_side(a, b, c)*100000.0)/100000.0); }} // This code is contributed by vt_m.",
"e": 4981,
"s": 3682,
"text": null
},
{
"code": "<?php// PHP program to find third// side of triangle using// law of cosines // Function to calculate// cos value of angle cfunction cal_cos( $n ){ $accuracy = 0.0001; $x1; $denominator; $cosx; $cosval; // Converting degrees // to radian $n = $n * (3.142 / 180.0); $x1 = 1; // Maps the sum // along the series $cosx = $x1; // Holds the actual // value of sin(n) $cosval = cos($n); $i = 1; do { $denominator = 2 * $i * (2 * $i - 1); $x1 = -$x1 * $n * $n / $denominator; $cosx = $cosx + $x1; $i = $i + 1; } while ($accuracy <= ($cosval - $cosx)); return $cosx;} // Function to find third sidefunction third_side($a, $b, $c){ $angle = cal_cos($c); return sqrt(($a * $a) + ($b * $b) - 2 * $a * $b * $angle);} // Driver Code$c = 49;$a = 5;$b = 8; // function callecho third_side($a, $b, $c); // This code is contributed// by ajit?>",
"e": 5992,
"s": 4981,
"text": null
},
{
"code": "<script>// Javascript program to find third// side of triangle using// law of cosines // Function to calculate // cos value of angle c function cal_cos( n) { let accuracy = 0.0001, x1; let denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // Maps the sum alet the series cosx = x1; // Holds the actual value of sin(n) cosval = Math.cos(n); let i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.abs(cosval - cosx)); return cosx; } // Function to find third side function third_side( a, b, c) { let angle = cal_cos(c); return Math.sqrt((a * a) + (b * b) - 2 * a * b * angle); } // Driver code let c = 49; let a = 5, b = 8; // function call document.write(Math.round(third_side(a, b, c) * 100000.0) / 100000.0); // This code is contributed by Rajput-Ji</script>",
"e": 7096,
"s": 5992,
"text": null
},
{
"code": null,
"e": 7104,
"s": 7096,
"text": "6.04339"
},
{
"code": null,
"e": 7290,
"s": 7104,
"text": "Time Complexity: O(1), as the loop for calculating cosine value is limited by a period and so it runs a finite amount of time Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 7296,
"s": 7290,
"text": "jit_t"
},
{
"code": null,
"e": 7311,
"s": 7296,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7321,
"s": 7311,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7334,
"s": 7321,
"text": "rohitsingh57"
},
{
"code": null,
"e": 7343,
"s": 7334,
"text": "triangle"
},
{
"code": null,
"e": 7353,
"s": 7343,
"text": "Geometric"
},
{
"code": null,
"e": 7372,
"s": 7353,
"text": "School Programming"
},
{
"code": null,
"e": 7382,
"s": 7372,
"text": "Geometric"
}
] |
Neo4j Create Relationship
|
23 Aug, 2019
In Neo4j to create relationship between nodes you have to use the CREATE statement like we used to create nodes. lets create relation between two already created nodes.Example:
Already created nodes:
Query to create relation:$ MATCH (a:GeeksforGeeks), (b:W3School)
WHERE a.Name = "A Computer Science Portal" AND b.Name = "We are the Learner"
CREATE (a)-[r:edutech]->(b)
RETURN r
$ MATCH (a:GeeksforGeeks), (b:W3School)
WHERE a.Name = "A Computer Science Portal" AND b.Name = "We are the Learner"
CREATE (a)-[r:edutech]->(b)
RETURN r
Output of above query:
To create multiple relationship between nodes:You can see how easy it is to continue creating more nodes and relationships between them. So we will create one more node and add two more relationships.
Creating a new node:$ CREATE (c:Company { Name: "Tuitorial" })Output:
$ CREATE (c:Company { Name: "Tuitorial" })
Output:
Creating relationship:MATCH (a:GeeksforGeeks), (b:W3School), (c:Comapny)
WHERE a.Tag = "A Computer Science Portal" AND b.Tag = "We are the Learner" AND
c.Name = "Tuitorial" CREATE (c)-[pr:PRODUCED]->(b), (c)-[pr1:PROVIDER]->(a)
RETURN a, b, cOutput:My Personal Notes
arrow_drop_upSave
MATCH (a:GeeksforGeeks), (b:W3School), (c:Comapny)
WHERE a.Tag = "A Computer Science Portal" AND b.Tag = "We are the Learner" AND
c.Name = "Tuitorial" CREATE (c)-[pr:PRODUCED]->(b), (c)-[pr1:PROVIDER]->(a)
RETURN a, b, c
Output:
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2019"
},
{
"code": null,
"e": 205,
"s": 28,
"text": "In Neo4j to create relationship between nodes you have to use the CREATE statement like we used to create nodes. lets create relation between two already created nodes.Example:"
},
{
"code": null,
"e": 229,
"s": 205,
"text": "Already created nodes: "
},
{
"code": null,
"e": 408,
"s": 229,
"text": "Query to create relation:$ MATCH (a:GeeksforGeeks), (b:W3School)\nWHERE a.Name = \"A Computer Science Portal\" AND b.Name = \"We are the Learner\"\nCREATE (a)-[r:edutech]->(b)\nRETURN r"
},
{
"code": null,
"e": 562,
"s": 408,
"text": "$ MATCH (a:GeeksforGeeks), (b:W3School)\nWHERE a.Name = \"A Computer Science Portal\" AND b.Name = \"We are the Learner\"\nCREATE (a)-[r:edutech]->(b)\nRETURN r"
},
{
"code": null,
"e": 585,
"s": 562,
"text": "Output of above query:"
},
{
"code": null,
"e": 786,
"s": 585,
"text": "To create multiple relationship between nodes:You can see how easy it is to continue creating more nodes and relationships between them. So we will create one more node and add two more relationships."
},
{
"code": null,
"e": 856,
"s": 786,
"text": "Creating a new node:$ CREATE (c:Company { Name: \"Tuitorial\" })Output:"
},
{
"code": null,
"e": 899,
"s": 856,
"text": "$ CREATE (c:Company { Name: \"Tuitorial\" })"
},
{
"code": null,
"e": 907,
"s": 899,
"text": "Output:"
},
{
"code": null,
"e": 1193,
"s": 907,
"text": "Creating relationship:MATCH (a:GeeksforGeeks), (b:W3School), (c:Comapny)\nWHERE a.Tag = \"A Computer Science Portal\" AND b.Tag = \"We are the Learner\" AND \nc.Name = \"Tuitorial\" CREATE (c)-[pr:PRODUCED]->(b), (c)-[pr1:PROVIDER]->(a)\nRETURN a, b, cOutput:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 1415,
"s": 1193,
"text": "MATCH (a:GeeksforGeeks), (b:W3School), (c:Comapny)\nWHERE a.Tag = \"A Computer Science Portal\" AND b.Tag = \"We are the Learner\" AND \nc.Name = \"Tuitorial\" CREATE (c)-[pr:PRODUCED]->(b), (c)-[pr1:PROVIDER]->(a)\nRETURN a, b, c"
},
{
"code": null,
"e": 1423,
"s": 1415,
"text": "Output:"
},
{
"code": null,
"e": 1428,
"s": 1423,
"text": "DBMS"
},
{
"code": null,
"e": 1433,
"s": 1428,
"text": "DBMS"
}
] |
Lagrange’s Interpolation
|
03 Dec, 2021
What is Interpolation? Interpolation is a method of finding new data points within the range of a discrete set of known data points (Source Wiki). In other words interpolation is the technique to estimate the value of a mathematical function, for any intermediate value of the independent variable. For example, in the given table we’re given 4 set of discrete data points, for an unknown function f(x) :
How to find? Here we can apply the Lagrange’s interpolation formula to get our solution. The Lagrange’s Interpolation formula: If, y = f(x) takes the values y0, y1, ... , yn corresponding to x = x0, x1 , ... , xn then,
This method is preferred over its counterparts like Newton’s method because it is applicable even for unequally spaced values of x.We can use interpolation techniques to find an intermediate data point say at x = 3.
Advantages of Lagrange Interpolation:
This formula is used to find the value of the function even when the arguments are not equally spaced.
This formula is used to find the value of independent variable x corresponding to a given value of a function.
Disadvantages of Lagrange Interpolation:
A change of degree in Lagrangian polynomial involves a completely new computation of all the terms.
For a polynomial of high degree, the formula involves a large number of multiplications which make the process quite slow.
In the Lagrange Interpolation, the degree of polynomial is chosen at the outset. So it is difficult to find the degree of approximating polynomial which is suitable for given set of tabulated points.
C++
Java
Python3
C#
Javascript
// C++ program for implementation of Lagrange's Interpolation#include<bits/stdc++.h>using namespace std; // To represent a data point corresponding to x and y = f(x)struct Data{ int x, y;}; // function to interpolate the given data points using Lagrange's formula// xi corresponds to the new data point whose value is to be obtained// n represents the number of known data pointsdouble interpolate(Data f[], int xi, int n){ double result = 0; // Initialize result for (int i=0; i<n; i++) { // Compute individual terms of above formula double term = f[i].y; for (int j=0;j<n;j++) { if (j!=i) term = term*(xi - f[j].x)/double(f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // driver function to check the programint main(){ // creating an array of 4 known data points Data f[] = {{0,2}, {1,3}, {2,12}, {5,147}}; // Using the interpolate function to obtain a data point // corresponding to x=3 cout << "Value of f(3) is : " << interpolate(f, 3, 5); return 0;}
// Java program for implementation// of Lagrange's Interpolation import java.util.*; class GFG{ // To represent a data point// corresponding to x and y = f(x)static class Data{ int x, y; public Data(int x, int y) { super(); this.x = x; this.y = y; } }; // function to interpolate the given// data points using Lagrange's formula// xi corresponds to the new data point// whose value is to be obtained n// represents the number of known data pointsstatic double interpolate(Data f[], int xi, int n){ double result = 0; // Initialize result for (int i = 0; i < n; i++) { // Compute individual terms of above formula double term = f[i].y; for (int j = 0; j < n; j++) { if (j != i) term = term*(xi - f[j].x) / (f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // Driver codepublic static void main(String[] args){ // creating an array of 4 known data points Data f[] = {new Data(0, 2), new Data(1, 3), new Data(2, 12), new Data(5, 147)}; // Using the interpolate function to obtain // a data point corresponding to x=3 System.out.print("Value of f(3) is : " + (int)interpolate(f, 3, 4));}} // This code is contributed by 29AjayKumar
# Python3 program for implementation# of Lagrange's Interpolation # To represent a data point corresponding to x and y = f(x)class Data: def __init__(self, x, y): self.x = x self.y = y # function to interpolate the given data points# using Lagrange's formula# xi -> corresponds to the new data point# whose value is to be obtained# n -> represents the number of known data pointsdef interpolate(f: list, xi: int, n: int) -> float: # Initialize result result = 0.0 for i in range(n): # Compute individual terms of above formula term = f[i].y for j in range(n): if j != i: term = term * (xi - f[j].x) / (f[i].x - f[j].x) # Add current term to result result += term return result # Driver Codeif __name__ == "__main__": # creating an array of 4 known data points f = [Data(0, 2), Data(1, 3), Data(2, 12), Data(5, 147)] # Using the interpolate function to obtain a data point # corresponding to x=3 print("Value of f(3) is :", interpolate(f, 3, 4)) # This code is contributed by# sanjeev2552
// C# program for implementation// of Lagrange's Interpolationusing System; class GFG{ // To represent a data point// corresponding to x and y = f(x)class Data{ public int x, y; public Data(int x, int y) { this.x = x; this.y = y; }}; // function to interpolate the given// data points using Lagrange's formula// xi corresponds to the new data point// whose value is to be obtained n// represents the number of known data pointsstatic double interpolate(Data []f, int xi, int n){ double result = 0; // Initialize result for (int i = 0; i < n; i++) { // Compute individual terms // of above formula double term = f[i].y; for (int j = 0; j < n; j++) { if (j != i) term = term * (xi - f[j].x) / (f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // Driver codepublic static void Main(String[] args){ // creating an array of 4 known data points Data []f = {new Data(0, 2), new Data(1, 3), new Data(2, 12), new Data(5, 147)}; // Using the interpolate function to obtain // a data point corresponding to x=3 Console.Write("Value of f(3) is : " + (int)interpolate(f, 3, 4));}} // This code is contributed by PrinciRaj1992
<script>// Javascript program for implementation// of Lagrange's Interpolation // To represent a data point// corresponding to x and y = f(x)class Data{ constructor(x,y) { this.x=x; this.y=y; }} // function to interpolate the given// data points using Lagrange's formula// xi corresponds to the new data point// whose value is to be obtained n// represents the number of known data pointsfunction interpolate(f,xi,n){ let result = 0; // Initialize result for (let i = 0; i < n; i++) { // Compute individual terms of above formula let term = f[i].y; for (let j = 0; j < n; j++) { if (j != i) term = term*(xi - f[j].x) / (f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // Driver code // creating an array of 4 known data pointslet f=[new Data(0, 2), new Data(1, 3), new Data(2, 12), new Data(5, 147)]; // Using the interpolate function to obtain // a data point corresponding to x=3document.write("Value of f(3) is : " + interpolate(f, 3, 4)); // This code is contributed by rag2127</script>
Output:
Value of f(3) is : 35
Complexity: The time complexity of the above solution is O(n2) and auxiliary space is O(1).
References:
https://en.wikipedia.org/wiki/Lagrange_polynomial Higher Engineering Mathematics , Dr. B.S. Grewal
https://mat.iitm.ac.in/home/sryedida/public_html/caimna/interpolation/lagrange.html
This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
princiraj1992
sanjeev2552
rag2127
itskawal2000
surinderdawra388
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 460,
"s": 54,
"text": "What is Interpolation? Interpolation is a method of finding new data points within the range of a discrete set of known data points (Source Wiki). In other words interpolation is the technique to estimate the value of a mathematical function, for any intermediate value of the independent variable. For example, in the given table we’re given 4 set of discrete data points, for an unknown function f(x) : "
},
{
"code": null,
"e": 682,
"s": 462,
"text": "How to find? Here we can apply the Lagrange’s interpolation formula to get our solution. The Lagrange’s Interpolation formula: If, y = f(x) takes the values y0, y1, ... , yn corresponding to x = x0, x1 , ... , xn then, "
},
{
"code": null,
"e": 900,
"s": 682,
"text": "This method is preferred over its counterparts like Newton’s method because it is applicable even for unequally spaced values of x.We can use interpolation techniques to find an intermediate data point say at x = 3. "
},
{
"code": null,
"e": 938,
"s": 900,
"text": "Advantages of Lagrange Interpolation:"
},
{
"code": null,
"e": 1041,
"s": 938,
"text": "This formula is used to find the value of the function even when the arguments are not equally spaced."
},
{
"code": null,
"e": 1152,
"s": 1041,
"text": "This formula is used to find the value of independent variable x corresponding to a given value of a function."
},
{
"code": null,
"e": 1194,
"s": 1152,
"text": "Disadvantages of Lagrange Interpolation: "
},
{
"code": null,
"e": 1294,
"s": 1194,
"text": "A change of degree in Lagrangian polynomial involves a completely new computation of all the terms."
},
{
"code": null,
"e": 1417,
"s": 1294,
"text": "For a polynomial of high degree, the formula involves a large number of multiplications which make the process quite slow."
},
{
"code": null,
"e": 1617,
"s": 1417,
"text": "In the Lagrange Interpolation, the degree of polynomial is chosen at the outset. So it is difficult to find the degree of approximating polynomial which is suitable for given set of tabulated points."
},
{
"code": null,
"e": 1621,
"s": 1617,
"text": "C++"
},
{
"code": null,
"e": 1626,
"s": 1621,
"text": "Java"
},
{
"code": null,
"e": 1634,
"s": 1626,
"text": "Python3"
},
{
"code": null,
"e": 1637,
"s": 1634,
"text": "C#"
},
{
"code": null,
"e": 1648,
"s": 1637,
"text": "Javascript"
},
{
"code": "// C++ program for implementation of Lagrange's Interpolation#include<bits/stdc++.h>using namespace std; // To represent a data point corresponding to x and y = f(x)struct Data{ int x, y;}; // function to interpolate the given data points using Lagrange's formula// xi corresponds to the new data point whose value is to be obtained// n represents the number of known data pointsdouble interpolate(Data f[], int xi, int n){ double result = 0; // Initialize result for (int i=0; i<n; i++) { // Compute individual terms of above formula double term = f[i].y; for (int j=0;j<n;j++) { if (j!=i) term = term*(xi - f[j].x)/double(f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // driver function to check the programint main(){ // creating an array of 4 known data points Data f[] = {{0,2}, {1,3}, {2,12}, {5,147}}; // Using the interpolate function to obtain a data point // corresponding to x=3 cout << \"Value of f(3) is : \" << interpolate(f, 3, 5); return 0;}",
"e": 2758,
"s": 1648,
"text": null
},
{
"code": "// Java program for implementation// of Lagrange's Interpolation import java.util.*; class GFG{ // To represent a data point// corresponding to x and y = f(x)static class Data{ int x, y; public Data(int x, int y) { super(); this.x = x; this.y = y; } }; // function to interpolate the given// data points using Lagrange's formula// xi corresponds to the new data point// whose value is to be obtained n// represents the number of known data pointsstatic double interpolate(Data f[], int xi, int n){ double result = 0; // Initialize result for (int i = 0; i < n; i++) { // Compute individual terms of above formula double term = f[i].y; for (int j = 0; j < n; j++) { if (j != i) term = term*(xi - f[j].x) / (f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // Driver codepublic static void main(String[] args){ // creating an array of 4 known data points Data f[] = {new Data(0, 2), new Data(1, 3), new Data(2, 12), new Data(5, 147)}; // Using the interpolate function to obtain // a data point corresponding to x=3 System.out.print(\"Value of f(3) is : \" + (int)interpolate(f, 3, 4));}} // This code is contributed by 29AjayKumar",
"e": 4102,
"s": 2758,
"text": null
},
{
"code": "# Python3 program for implementation# of Lagrange's Interpolation # To represent a data point corresponding to x and y = f(x)class Data: def __init__(self, x, y): self.x = x self.y = y # function to interpolate the given data points# using Lagrange's formula# xi -> corresponds to the new data point# whose value is to be obtained# n -> represents the number of known data pointsdef interpolate(f: list, xi: int, n: int) -> float: # Initialize result result = 0.0 for i in range(n): # Compute individual terms of above formula term = f[i].y for j in range(n): if j != i: term = term * (xi - f[j].x) / (f[i].x - f[j].x) # Add current term to result result += term return result # Driver Codeif __name__ == \"__main__\": # creating an array of 4 known data points f = [Data(0, 2), Data(1, 3), Data(2, 12), Data(5, 147)] # Using the interpolate function to obtain a data point # corresponding to x=3 print(\"Value of f(3) is :\", interpolate(f, 3, 4)) # This code is contributed by# sanjeev2552",
"e": 5201,
"s": 4102,
"text": null
},
{
"code": "// C# program for implementation// of Lagrange's Interpolationusing System; class GFG{ // To represent a data point// corresponding to x and y = f(x)class Data{ public int x, y; public Data(int x, int y) { this.x = x; this.y = y; }}; // function to interpolate the given// data points using Lagrange's formula// xi corresponds to the new data point// whose value is to be obtained n// represents the number of known data pointsstatic double interpolate(Data []f, int xi, int n){ double result = 0; // Initialize result for (int i = 0; i < n; i++) { // Compute individual terms // of above formula double term = f[i].y; for (int j = 0; j < n; j++) { if (j != i) term = term * (xi - f[j].x) / (f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // Driver codepublic static void Main(String[] args){ // creating an array of 4 known data points Data []f = {new Data(0, 2), new Data(1, 3), new Data(2, 12), new Data(5, 147)}; // Using the interpolate function to obtain // a data point corresponding to x=3 Console.Write(\"Value of f(3) is : \" + (int)interpolate(f, 3, 4));}} // This code is contributed by PrinciRaj1992",
"e": 6602,
"s": 5201,
"text": null
},
{
"code": "<script>// Javascript program for implementation// of Lagrange's Interpolation // To represent a data point// corresponding to x and y = f(x)class Data{ constructor(x,y) { this.x=x; this.y=y; }} // function to interpolate the given// data points using Lagrange's formula// xi corresponds to the new data point// whose value is to be obtained n// represents the number of known data pointsfunction interpolate(f,xi,n){ let result = 0; // Initialize result for (let i = 0; i < n; i++) { // Compute individual terms of above formula let term = f[i].y; for (let j = 0; j < n; j++) { if (j != i) term = term*(xi - f[j].x) / (f[i].x - f[j].x); } // Add current term to result result += term; } return result;} // Driver code // creating an array of 4 known data pointslet f=[new Data(0, 2), new Data(1, 3), new Data(2, 12), new Data(5, 147)]; // Using the interpolate function to obtain // a data point corresponding to x=3document.write(\"Value of f(3) is : \" + interpolate(f, 3, 4)); // This code is contributed by rag2127</script>",
"e": 7789,
"s": 6602,
"text": null
},
{
"code": null,
"e": 7797,
"s": 7789,
"text": "Output:"
},
{
"code": null,
"e": 7819,
"s": 7797,
"text": "Value of f(3) is : 35"
},
{
"code": null,
"e": 7912,
"s": 7819,
"text": "Complexity: The time complexity of the above solution is O(n2) and auxiliary space is O(1). "
},
{
"code": null,
"e": 7925,
"s": 7912,
"text": "References: "
},
{
"code": null,
"e": 8024,
"s": 7925,
"text": "https://en.wikipedia.org/wiki/Lagrange_polynomial Higher Engineering Mathematics , Dr. B.S. Grewal"
},
{
"code": null,
"e": 8108,
"s": 8024,
"text": "https://mat.iitm.ac.in/home/sryedida/public_html/caimna/interpolation/lagrange.html"
},
{
"code": null,
"e": 8280,
"s": 8108,
"text": "This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8292,
"s": 8280,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8306,
"s": 8292,
"text": "princiraj1992"
},
{
"code": null,
"e": 8318,
"s": 8306,
"text": "sanjeev2552"
},
{
"code": null,
"e": 8326,
"s": 8318,
"text": "rag2127"
},
{
"code": null,
"e": 8339,
"s": 8326,
"text": "itskawal2000"
},
{
"code": null,
"e": 8356,
"s": 8339,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8369,
"s": 8356,
"text": "Mathematical"
},
{
"code": null,
"e": 8382,
"s": 8369,
"text": "Mathematical"
},
{
"code": null,
"e": 8480,
"s": 8382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8504,
"s": 8480,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 8525,
"s": 8504,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 8539,
"s": 8525,
"text": "Prime Numbers"
},
{
"code": null,
"e": 8581,
"s": 8539,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 8618,
"s": 8581,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 8671,
"s": 8618,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 8714,
"s": 8671,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 8746,
"s": 8714,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 8787,
"s": 8746,
"text": "Program for Decimal to Binary Conversion"
}
] |
Select a random number from stream, with O(1) space
|
21 Jan, 2022
Given a stream of numbers, generate a random number from the stream. You are allowed to use only O(1) space and the input is in the form of a stream, so can’t store the previously seen numbers. So how do we generate a random number from the whole stream such that the probability of picking any number is 1/n. with O(1) extra space? This problem is a variation of Reservoir Sampling. Here the value of k is 1.1) Initialize ‘count’ as 0, ‘count’ is used to store count of numbers seen so far in stream. 2) For each number ‘x’ from stream, do following .....a) Increment ‘count’ by 1. .....b) If count is 1, set result as x, and return result. .....c) Generate a random number from 0 to ‘count-1’. Let the generated random number be i. .....d) If i is equal to ‘count – 1’, update the result as x.
C++
C
Java
Python3
C#
PHP
Javascript
// An efficient C++ program to randomly select// a number from stream of numbers.#include <bits/stdc++.h>#include <time.h>using namespace std; // A function to randomly select a item// from stream[0], stream[1], .. stream[i-1]int selectRandom(int x){ static int res; // The resultant random number static int count = 0; // Count of numbers visited // so far in stream count++; // increment count of numbers seen so far // If this is the first element from stream, // return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 int i = rand() % count; // Replace the prev random number with // new number with 1/count probability if (i == count - 1) res = x; } return res;} // Driver Codeint main(){ int stream[] = {1, 2, 3, 4}; int n = sizeof(stream) / sizeof(stream[0]); // Use a different seed value for every run. srand(time(NULL)); for (int i = 0; i < n; ++i) cout << "Random number from first " << i + 1 << " numbers is " << selectRandom(stream[i]) << endl; return 0;} // This is code is contributed by rathbhupendra
// An efficient C program to randomly select a number from stream of numbers.#include <stdio.h>#include <stdlib.h>#include <time.h> // A function to randomly select a item from stream[0], stream[1], .. stream[i-1]int selectRandom(int x){ static int res; // The resultant random number static int count = 0; //Count of numbers visited so far in stream count++; // increment count of numbers seen so far // If this is the first element from stream, return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 int i = rand() % count; // Replace the prev random number with new number with 1/count probability if (i == count - 1) res = x; } return res;} // Driver program to test above function.int main(){ int stream[] = {1, 2, 3, 4}; int n = sizeof(stream)/sizeof(stream[0]); // Use a different seed value for every run. srand(time(NULL)); for (int i = 0; i < n; ++i) printf("Random number from first %d numbers is %d \n", i+1, selectRandom(stream[i])); return 0;}
//An efficient Java program to randomly select a number from stream of numbers. import java.util.Random; public class GFG{ static int res = 0; // The resultant random number static int count = 0; //Count of numbers visited so far in stream //A method to randomly select a item from stream[0], stream[1], .. stream[i-1] static int selectRandom(int x) { count++; // increment count of numbers seen so far // If this is the first element from stream, return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 Random r = new Random(); int i = r.nextInt(count); // Replace the prev random number with new number with 1/count probability if(i == count - 1) res = x; } return res; } // Driver program to test above function. public static void main(String[] args) { int stream[] = {1, 2, 3, 4}; int n = stream.length; for(int i = 0; i < n; i++) System.out.println("Random number from first " + (i+1) + " numbers is " + selectRandom(stream[i])); }}//This code is contributed by Sumit Ghosh
# An efficient python3 program# to randomly select a number# from stream of numbers.import random # A function to randomly select a item# from stream[0], stream[1], .. stream[i-1]# The resultant random numberres=0# Count of numbers visited# so far in streamcount=0def selectRandom(x): global res global count # increment count of numbers # seen so far count += 1; # If this is the first element # from stream, return it if (count == 1): res = x; else: # Generate a random number # from 0 to count - 1 i = random.randrange(count); # Replace the prev random number # with new number with 1/count # probability if (i == count - 1): res = x; return res; # Driver Codestream = [1, 2, 3, 4];n = len(stream); # Use a different seed value# for every run.for i in range (n): print("Random number from first", (i + 1), "numbers is", selectRandom(stream[i])); # This code is contributed by mits
// An efficient C# program to randomly// select a number from stream of numbers.using System; class GFG{ // The resultant random number static int res = 0; // Count of numbers visited // so far in stream static int count = 0; // A method to randomly select // a item from stream[0], // stream[1], .. stream[i-1] static int selectRandom(int x) { // increment count of // numbers seen so far count++; // If this is the first // element from stream, // return it if (count == 1) res = x; else { // Generate a random number // from 0 to count - 1 Random r = new Random(); int i = r.Next(count); // Replace the prev random // number with new number // with 1/count probability if(i == count - 1) res = x; } return res; } // Driver Codepublic static void Main(){ int[] stream = {1, 2, 3, 4}; int n = stream.Length; for(int i = 0; i < n; i++) Console.WriteLine("Random number from " + "first {0} numbers is {1}" , i + 1, selectRandom(stream[i])); }} // This code is contributed by mits
<?php// An efficient php program to randomly// select a number from stream of numbers. // A function to randomly select a item// from stream[0], stream[1], .. stream[i-1]function selectRandom($x){ // The resultant random number $res; // Count of numbers visited so far // in stream $count = 0; // increment count of numbers seen // so far $count++; // If this is the first element // from stream, return it if ($count == 1) $res = $x; else { // Generate a random number from // 0 to count - 1 $i = rand() % $count; // Replace the prev random number // with new number with 1/count // probability if (i == $count - 1) $res = $x; } return $res;} // Driver program to test above function. $stream = array(1, 2, 3, 4); $n = sizeof($stream)/sizeof($stream[0]); // Use a different seed value for // every run. srand(time(NULL)); for ($i = 0; $i < $n; ++$i) echo "Random number from first ", $i+1, "numbers is " , selectRandom($stream[$i]), "\n" ; // This code is contributed by nitin mittal.?>
<script>//An efficient Javascript program to randomly select a number from stream of numbers. let res = 0; // The resultant random numberlet count = 0; //Count of numbers visited so far in stream //A method to randomly select a item from stream[0], stream[1], .. stream[i-1]function selectRandom(x){ count++; // increment count of numbers seen so far // If this is the first element from stream, return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 let i = Math.floor(Math.random()*(count)); // Replace the prev random number with new number with 1/count probability if(i == count - 1) res = x; } return res;} // Driver program to test above function.let stream=[1, 2, 3, 4];let n = stream.length;for(let i = 0; i < n; i++) document.write("Random number from first " + (i+1) + " numbers is " + selectRandom(stream[i])+"<br>"); // This code is contributed by avanitrachhadiya2155</script>
Output:
Random number from first 1 numbers is 1
Random number from first 2 numbers is 1
Random number from first 3 numbers is 3
Random number from first 4 numbers is 4
Time Complexity: O(n)Auxiliary Space: O(1)How does this work We need to prove that every element is picked with 1/n probability where n is the number of items seen so far. For every new stream item x, we pick a random number from 0 to ‘count -1’, if the picked number is ‘count-1’, we replace the previous result with x.To simplify proof, let us first consider the last element, the last element replaces the previously-stored result with 1/n probability. So the probability of getting the last element as the result is 1/n.Let us now talk about the second last element. When the second last element processed the first time, the probability that it replaced the previous result is 1/(n-1). The probability that the previous result stays when the nth item is considered is (n-1)/n. So the probability that the second last element is picked in the last iteration is [1/(n-1)] * [(n-1)/n] which is 1/n. Similarly, we can prove for third last element and others.References: Reservoir Sampling
Method 2: generate a random number from the stream with numpy random.choice() method.
Python3
import numpy as np # initializing liststream = [1, 4, 5, 2, 7] # using random.choice() to# get a random numberrandom_num = np.random.choice(stream) # printing random numberprint("random number is ",random_num)
Output:
7
Time Complexity: O(n)
Auxiliary Space: O(1)
nitin mittal
Mithun Kumar
rathbhupendra
nidhi_biet
avanitrachhadiya2155
pulamolusaimohan
subhammahato348
prathamgoyal226
array-stream
Random Algorithms
Mathematical
Randomized
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
QuickSort using Random Pivoting
Shuffle or Randomize a list in Java
Generating Random String Using PHP
Primality Test | Set 2 (Fermat Method)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 850,
"s": 52,
"text": "Given a stream of numbers, generate a random number from the stream. You are allowed to use only O(1) space and the input is in the form of a stream, so can’t store the previously seen numbers. So how do we generate a random number from the whole stream such that the probability of picking any number is 1/n. with O(1) extra space? This problem is a variation of Reservoir Sampling. Here the value of k is 1.1) Initialize ‘count’ as 0, ‘count’ is used to store count of numbers seen so far in stream. 2) For each number ‘x’ from stream, do following .....a) Increment ‘count’ by 1. .....b) If count is 1, set result as x, and return result. .....c) Generate a random number from 0 to ‘count-1’. Let the generated random number be i. .....d) If i is equal to ‘count – 1’, update the result as x. "
},
{
"code": null,
"e": 854,
"s": 850,
"text": "C++"
},
{
"code": null,
"e": 856,
"s": 854,
"text": "C"
},
{
"code": null,
"e": 861,
"s": 856,
"text": "Java"
},
{
"code": null,
"e": 869,
"s": 861,
"text": "Python3"
},
{
"code": null,
"e": 872,
"s": 869,
"text": "C#"
},
{
"code": null,
"e": 876,
"s": 872,
"text": "PHP"
},
{
"code": null,
"e": 887,
"s": 876,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to randomly select// a number from stream of numbers.#include <bits/stdc++.h>#include <time.h>using namespace std; // A function to randomly select a item// from stream[0], stream[1], .. stream[i-1]int selectRandom(int x){ static int res; // The resultant random number static int count = 0; // Count of numbers visited // so far in stream count++; // increment count of numbers seen so far // If this is the first element from stream, // return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 int i = rand() % count; // Replace the prev random number with // new number with 1/count probability if (i == count - 1) res = x; } return res;} // Driver Codeint main(){ int stream[] = {1, 2, 3, 4}; int n = sizeof(stream) / sizeof(stream[0]); // Use a different seed value for every run. srand(time(NULL)); for (int i = 0; i < n; ++i) cout << \"Random number from first \" << i + 1 << \" numbers is \" << selectRandom(stream[i]) << endl; return 0;} // This is code is contributed by rathbhupendra",
"e": 2088,
"s": 887,
"text": null
},
{
"code": "// An efficient C program to randomly select a number from stream of numbers.#include <stdio.h>#include <stdlib.h>#include <time.h> // A function to randomly select a item from stream[0], stream[1], .. stream[i-1]int selectRandom(int x){ static int res; // The resultant random number static int count = 0; //Count of numbers visited so far in stream count++; // increment count of numbers seen so far // If this is the first element from stream, return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 int i = rand() % count; // Replace the prev random number with new number with 1/count probability if (i == count - 1) res = x; } return res;} // Driver program to test above function.int main(){ int stream[] = {1, 2, 3, 4}; int n = sizeof(stream)/sizeof(stream[0]); // Use a different seed value for every run. srand(time(NULL)); for (int i = 0; i < n; ++i) printf(\"Random number from first %d numbers is %d \\n\", i+1, selectRandom(stream[i])); return 0;}",
"e": 3220,
"s": 2088,
"text": null
},
{
"code": "//An efficient Java program to randomly select a number from stream of numbers. import java.util.Random; public class GFG{ static int res = 0; // The resultant random number static int count = 0; //Count of numbers visited so far in stream //A method to randomly select a item from stream[0], stream[1], .. stream[i-1] static int selectRandom(int x) { count++; // increment count of numbers seen so far // If this is the first element from stream, return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 Random r = new Random(); int i = r.nextInt(count); // Replace the prev random number with new number with 1/count probability if(i == count - 1) res = x; } return res; } // Driver program to test above function. public static void main(String[] args) { int stream[] = {1, 2, 3, 4}; int n = stream.length; for(int i = 0; i < n; i++) System.out.println(\"Random number from first \" + (i+1) + \" numbers is \" + selectRandom(stream[i])); }}//This code is contributed by Sumit Ghosh",
"e": 4493,
"s": 3220,
"text": null
},
{
"code": "# An efficient python3 program# to randomly select a number# from stream of numbers.import random # A function to randomly select a item# from stream[0], stream[1], .. stream[i-1]# The resultant random numberres=0# Count of numbers visited# so far in streamcount=0def selectRandom(x): global res global count # increment count of numbers # seen so far count += 1; # If this is the first element # from stream, return it if (count == 1): res = x; else: # Generate a random number # from 0 to count - 1 i = random.randrange(count); # Replace the prev random number # with new number with 1/count # probability if (i == count - 1): res = x; return res; # Driver Codestream = [1, 2, 3, 4];n = len(stream); # Use a different seed value# for every run.for i in range (n): print(\"Random number from first\", (i + 1), \"numbers is\", selectRandom(stream[i])); # This code is contributed by mits",
"e": 5511,
"s": 4493,
"text": null
},
{
"code": "// An efficient C# program to randomly// select a number from stream of numbers.using System; class GFG{ // The resultant random number static int res = 0; // Count of numbers visited // so far in stream static int count = 0; // A method to randomly select // a item from stream[0], // stream[1], .. stream[i-1] static int selectRandom(int x) { // increment count of // numbers seen so far count++; // If this is the first // element from stream, // return it if (count == 1) res = x; else { // Generate a random number // from 0 to count - 1 Random r = new Random(); int i = r.Next(count); // Replace the prev random // number with new number // with 1/count probability if(i == count - 1) res = x; } return res; } // Driver Codepublic static void Main(){ int[] stream = {1, 2, 3, 4}; int n = stream.Length; for(int i = 0; i < n; i++) Console.WriteLine(\"Random number from \" + \"first {0} numbers is {1}\" , i + 1, selectRandom(stream[i])); }} // This code is contributed by mits",
"e": 6839,
"s": 5511,
"text": null
},
{
"code": "<?php// An efficient php program to randomly// select a number from stream of numbers. // A function to randomly select a item// from stream[0], stream[1], .. stream[i-1]function selectRandom($x){ // The resultant random number $res; // Count of numbers visited so far // in stream $count = 0; // increment count of numbers seen // so far $count++; // If this is the first element // from stream, return it if ($count == 1) $res = $x; else { // Generate a random number from // 0 to count - 1 $i = rand() % $count; // Replace the prev random number // with new number with 1/count // probability if (i == $count - 1) $res = $x; } return $res;} // Driver program to test above function. $stream = array(1, 2, 3, 4); $n = sizeof($stream)/sizeof($stream[0]); // Use a different seed value for // every run. srand(time(NULL)); for ($i = 0; $i < $n; ++$i) echo \"Random number from first \", $i+1, \"numbers is \" , selectRandom($stream[$i]), \"\\n\" ; // This code is contributed by nitin mittal.?>",
"e": 8017,
"s": 6839,
"text": null
},
{
"code": "<script>//An efficient Javascript program to randomly select a number from stream of numbers. let res = 0; // The resultant random numberlet count = 0; //Count of numbers visited so far in stream //A method to randomly select a item from stream[0], stream[1], .. stream[i-1]function selectRandom(x){ count++; // increment count of numbers seen so far // If this is the first element from stream, return it if (count == 1) res = x; else { // Generate a random number from 0 to count - 1 let i = Math.floor(Math.random()*(count)); // Replace the prev random number with new number with 1/count probability if(i == count - 1) res = x; } return res;} // Driver program to test above function.let stream=[1, 2, 3, 4];let n = stream.length;for(let i = 0; i < n; i++) document.write(\"Random number from first \" + (i+1) + \" numbers is \" + selectRandom(stream[i])+\"<br>\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 9105,
"s": 8017,
"text": null
},
{
"code": null,
"e": 9115,
"s": 9105,
"text": "Output: "
},
{
"code": null,
"e": 9275,
"s": 9115,
"text": "Random number from first 1 numbers is 1\nRandom number from first 2 numbers is 1\nRandom number from first 3 numbers is 3\nRandom number from first 4 numbers is 4"
},
{
"code": null,
"e": 10266,
"s": 9275,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)How does this work We need to prove that every element is picked with 1/n probability where n is the number of items seen so far. For every new stream item x, we pick a random number from 0 to ‘count -1’, if the picked number is ‘count-1’, we replace the previous result with x.To simplify proof, let us first consider the last element, the last element replaces the previously-stored result with 1/n probability. So the probability of getting the last element as the result is 1/n.Let us now talk about the second last element. When the second last element processed the first time, the probability that it replaced the previous result is 1/(n-1). The probability that the previous result stays when the nth item is considered is (n-1)/n. So the probability that the second last element is picked in the last iteration is [1/(n-1)] * [(n-1)/n] which is 1/n. Similarly, we can prove for third last element and others.References: Reservoir Sampling "
},
{
"code": null,
"e": 10353,
"s": 10266,
"text": "Method 2: generate a random number from the stream with numpy random.choice() method."
},
{
"code": null,
"e": 10361,
"s": 10353,
"text": "Python3"
},
{
"code": "import numpy as np # initializing liststream = [1, 4, 5, 2, 7] # using random.choice() to# get a random numberrandom_num = np.random.choice(stream) # printing random numberprint(\"random number is \",random_num)",
"e": 10571,
"s": 10361,
"text": null
},
{
"code": null,
"e": 10579,
"s": 10571,
"text": "Output:"
},
{
"code": null,
"e": 10581,
"s": 10579,
"text": "7"
},
{
"code": null,
"e": 10603,
"s": 10581,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 10625,
"s": 10603,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10638,
"s": 10625,
"text": "nitin mittal"
},
{
"code": null,
"e": 10651,
"s": 10638,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10665,
"s": 10651,
"text": "rathbhupendra"
},
{
"code": null,
"e": 10676,
"s": 10665,
"text": "nidhi_biet"
},
{
"code": null,
"e": 10697,
"s": 10676,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 10714,
"s": 10697,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 10730,
"s": 10714,
"text": "subhammahato348"
},
{
"code": null,
"e": 10746,
"s": 10730,
"text": "prathamgoyal226"
},
{
"code": null,
"e": 10759,
"s": 10746,
"text": "array-stream"
},
{
"code": null,
"e": 10777,
"s": 10759,
"text": "Random Algorithms"
},
{
"code": null,
"e": 10790,
"s": 10777,
"text": "Mathematical"
},
{
"code": null,
"e": 10801,
"s": 10790,
"text": "Randomized"
},
{
"code": null,
"e": 10814,
"s": 10801,
"text": "Mathematical"
},
{
"code": null,
"e": 10912,
"s": 10814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10936,
"s": 10912,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 10957,
"s": 10936,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 10979,
"s": 10957,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 10993,
"s": 10979,
"text": "Prime Numbers"
},
{
"code": null,
"e": 11035,
"s": 10993,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 11114,
"s": 11035,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 11146,
"s": 11114,
"text": "QuickSort using Random Pivoting"
},
{
"code": null,
"e": 11182,
"s": 11146,
"text": "Shuffle or Randomize a list in Java"
},
{
"code": null,
"e": 11217,
"s": 11182,
"text": "Generating Random String Using PHP"
}
] |
Python | Parse a website with regex and urllib
|
23 Jan, 2019
Let’s discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages.
Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will give you the output as the bulk of HTML content that you can’t understand. Let’s see the demonstration with an explanation to let you understand more about parsing.
Code #1: Libraries needed
# importing librariesimport urllib.requestimport urllib.parseimport re
Code #2:
url = 'https://www.geeksforgeeks.org/'values = {'s':'python programming', 'submit':'search'}
We have defined a url and some related values that we want to search. Remember that we define values as a dictionary and in this key value pair we define python programming to search on the defined url.
Code #3:
data = urllib.parse.urlencode(values) data = data.encode('utf-8') req = urllib.request.Request(url, data) resp = urllib.request.urlopen(req) respData = resp.read()
In the first line we encode the values that we have defined earlier, then (line 2) we encode the same data that is understand by machine.In 3rd line of code we request for values in the defined url, then use the module urlopen() to open the web document that HTML.In the last line read() will help read the document line by line and assign it to respData named variable.
Code #4:
paragraphs = re.findall(r'<p>(.*?)</p>', str(respData)) for eachP in paragraphs: print(eachP)
In order to extract the relevant data we apply regular expression. Second argument must be type string and if we want to print the data we apply simple print function. Below are few examples:
Example #1:
import urllib.requestimport urllib.parseimport re url = 'https://www.geeksforgeeks.org/'values = {'s':'python programming', 'submit':'search'} data = urllib.parse.urlencode(values)data = data.encode('utf-8')req = urllib.request.Request(url, data)resp = urllib.request.urlopen(req)respData = resp.read() paragraphs = re.findall(r'<p>(.*?)</p>',str(respData)) for eachP in paragraphs: print(eachP)
Output:
Example #2:
import urllib.requestimport urllib.parseimport re url = 'https://www.geeksforgeeks.org/'values = {'s':'pandas', 'submit':'search'} data = urllib.parse.urlencode(values)data = data.encode('utf-8')req = urllib.request.Request(url, data)resp = urllib.request.urlopen(req)respData = resp.read() paragraphs = re.findall(r'<p>(.*?)</p>',str(respData)) for eachP in paragraphs: print(eachP)
Output:
python-utility
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 272,
"s": 52,
"text": "Let’s discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages."
},
{
"code": null,
"e": 565,
"s": 272,
"text": "Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will give you the output as the bulk of HTML content that you can’t understand. Let’s see the demonstration with an explanation to let you understand more about parsing."
},
{
"code": null,
"e": 591,
"s": 565,
"text": "Code #1: Libraries needed"
},
{
"code": "# importing librariesimport urllib.requestimport urllib.parseimport re",
"e": 662,
"s": 591,
"text": null
},
{
"code": null,
"e": 671,
"s": 662,
"text": "Code #2:"
},
{
"code": "url = 'https://www.geeksforgeeks.org/'values = {'s':'python programming', 'submit':'search'}",
"e": 773,
"s": 671,
"text": null
},
{
"code": null,
"e": 976,
"s": 773,
"text": "We have defined a url and some related values that we want to search. Remember that we define values as a dictionary and in this key value pair we define python programming to search on the defined url."
},
{
"code": null,
"e": 985,
"s": 976,
"text": "Code #3:"
},
{
"code": "data = urllib.parse.urlencode(values) data = data.encode('utf-8') req = urllib.request.Request(url, data) resp = urllib.request.urlopen(req) respData = resp.read() ",
"e": 1212,
"s": 985,
"text": null
},
{
"code": null,
"e": 1583,
"s": 1212,
"text": "In the first line we encode the values that we have defined earlier, then (line 2) we encode the same data that is understand by machine.In 3rd line of code we request for values in the defined url, then use the module urlopen() to open the web document that HTML.In the last line read() will help read the document line by line and assign it to respData named variable."
},
{
"code": null,
"e": 1592,
"s": 1583,
"text": "Code #4:"
},
{
"code": "paragraphs = re.findall(r'<p>(.*?)</p>', str(respData)) for eachP in paragraphs: print(eachP)",
"e": 1690,
"s": 1592,
"text": null
},
{
"code": null,
"e": 1882,
"s": 1690,
"text": "In order to extract the relevant data we apply regular expression. Second argument must be type string and if we want to print the data we apply simple print function. Below are few examples:"
},
{
"code": null,
"e": 1894,
"s": 1882,
"text": "Example #1:"
},
{
"code": "import urllib.requestimport urllib.parseimport re url = 'https://www.geeksforgeeks.org/'values = {'s':'python programming', 'submit':'search'} data = urllib.parse.urlencode(values)data = data.encode('utf-8')req = urllib.request.Request(url, data)resp = urllib.request.urlopen(req)respData = resp.read() paragraphs = re.findall(r'<p>(.*?)</p>',str(respData)) for eachP in paragraphs: print(eachP)",
"e": 2310,
"s": 1894,
"text": null
},
{
"code": null,
"e": 2319,
"s": 2310,
"text": "Output: "
},
{
"code": null,
"e": 2331,
"s": 2319,
"text": "Example #2:"
},
{
"code": "import urllib.requestimport urllib.parseimport re url = 'https://www.geeksforgeeks.org/'values = {'s':'pandas', 'submit':'search'} data = urllib.parse.urlencode(values)data = data.encode('utf-8')req = urllib.request.Request(url, data)resp = urllib.request.urlopen(req)respData = resp.read() paragraphs = re.findall(r'<p>(.*?)</p>',str(respData)) for eachP in paragraphs: print(eachP)",
"e": 2735,
"s": 2331,
"text": null
},
{
"code": null,
"e": 2744,
"s": 2735,
"text": "Output: "
},
{
"code": null,
"e": 2759,
"s": 2744,
"text": "python-utility"
},
{
"code": null,
"e": 2766,
"s": 2759,
"text": "Python"
},
{
"code": null,
"e": 2783,
"s": 2766,
"text": "Web Technologies"
}
] |
Swing Examples - Using Buttons
|
Following example showcase how to use standard buttons in a Java Swing application.
We are using the following APIs.
JButton − To create a standard button.
JButton − To create a standard button.
JButton.setEnabled(false); − To disable a button.
JButton.setEnabled(false); − To disable a button.
getRootPane().setDefaultButton(submitButton); − To make a button as default button to be clicked when enter key is pressed.
getRootPane().setDefaultButton(submitButton); − To make a button as default button to be clicked when enter key is pressed.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
JButton okButton = new JButton("Ok");
JButton cancelButton = new JButton("Cancel");
cancelButton.setEnabled(false);
JButton submitButton = new JButton("Submit");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Ok Button clicked.");
}
});
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Submit Button clicked.");
}
});
frame.getRootPane().setDefaultButton(submitButton);
panel.add(okButton);
panel.add(cancelButton);
panel.add(submitButton);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2123,
"s": 2039,
"text": "Following example showcase how to use standard buttons in a Java Swing application."
},
{
"code": null,
"e": 2156,
"s": 2123,
"text": "We are using the following APIs."
},
{
"code": null,
"e": 2195,
"s": 2156,
"text": "JButton − To create a standard button."
},
{
"code": null,
"e": 2234,
"s": 2195,
"text": "JButton − To create a standard button."
},
{
"code": null,
"e": 2284,
"s": 2234,
"text": "JButton.setEnabled(false); − To disable a button."
},
{
"code": null,
"e": 2334,
"s": 2284,
"text": "JButton.setEnabled(false); − To disable a button."
},
{
"code": null,
"e": 2458,
"s": 2334,
"text": "getRootPane().setDefaultButton(submitButton); − To make a button as default button to be clicked when enter key is pressed."
},
{
"code": null,
"e": 2582,
"s": 2458,
"text": "getRootPane().setDefaultButton(submitButton); − To make a button as default button to be clicked when enter key is pressed."
},
{
"code": null,
"e": 4255,
"s": 2582,
"text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n\n JButton okButton = new JButton(\"Ok\");\n JButton cancelButton = new JButton(\"Cancel\");\n cancelButton.setEnabled(false);\n JButton submitButton = new JButton(\"Submit\");\n\n okButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n JOptionPane.showMessageDialog(frame, \"Ok Button clicked.\");\n }\n });\n\n submitButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n JOptionPane.showMessageDialog(frame, \"Submit Button clicked.\");\n }\n });\n\n frame.getRootPane().setDefaultButton(submitButton);\n\n panel.add(okButton);\n panel.add(cancelButton);\n panel.add(submitButton);\n\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n}"
},
{
"code": null,
"e": 4262,
"s": 4255,
"text": " Print"
},
{
"code": null,
"e": 4273,
"s": 4262,
"text": " Add Notes"
}
] |
How to Concatenate tuples to nested tuples in Python
|
When it is required to concatenate tuples to nested tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.
The '+' operator is used for addition or concatenation operation.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = ( 7, 8, 3, 4, 3, 2),
my_tuple_2 = (9, 6, 8, 2, 1, 4),
print ("The first tuple is : " )
print(my_tuple_1)
print ("The second tuple is : " )
print(my_tuple_2)
my_result = my_tuple_1 + my_tuple_2
print("The tuple after concatenation is : " )
print(my_result)
The first tuple is :
((7, 8, 3, 4, 3, 2),)
The second tuple is :
((9, 6, 8, 2, 1, 4),)
The tuple after concatenation is :
((7, 8, 3, 4, 3, 2), (9, 6, 8, 2, 1, 4))
Two tuples are defined, and are displayed on the console.
The '+' operator is used to concatenate the values.
This result is assigned to a variable.
It is displayed as output on the console.
|
[
{
"code": null,
"e": 1391,
"s": 1062,
"text": "When it is required to concatenate tuples to nested tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access."
},
{
"code": null,
"e": 1457,
"s": 1391,
"text": "The '+' operator is used for addition or concatenation operation."
},
{
"code": null,
"e": 1496,
"s": 1457,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1506,
"s": 1496,
"text": "Live Demo"
},
{
"code": null,
"e": 1778,
"s": 1506,
"text": "my_tuple_1 = ( 7, 8, 3, 4, 3, 2),\nmy_tuple_2 = (9, 6, 8, 2, 1, 4),\n\nprint (\"The first tuple is : \" )\nprint(my_tuple_1)\nprint (\"The second tuple is : \" )\nprint(my_tuple_2)\n\nmy_result = my_tuple_1 + my_tuple_2\n\nprint(\"The tuple after concatenation is : \" )\nprint(my_result)"
},
{
"code": null,
"e": 1941,
"s": 1778,
"text": "The first tuple is :\n((7, 8, 3, 4, 3, 2),)\nThe second tuple is :\n((9, 6, 8, 2, 1, 4),)\nThe tuple after concatenation is :\n((7, 8, 3, 4, 3, 2), (9, 6, 8, 2, 1, 4))"
},
{
"code": null,
"e": 1999,
"s": 1941,
"text": "Two tuples are defined, and are displayed on the console."
},
{
"code": null,
"e": 2051,
"s": 1999,
"text": "The '+' operator is used to concatenate the values."
},
{
"code": null,
"e": 2090,
"s": 2051,
"text": "This result is assigned to a variable."
},
{
"code": null,
"e": 2132,
"s": 2090,
"text": "It is displayed as output on the console."
}
] |
Contractive Autoencoder (CAE) - GeeksforGeeks
|
18 Jan, 2022
Contractive Autoencoder was proposed by the researchers at the University of Toronto in 2011 in the paper Contractive auto-encoders: Explicit invariance during feature extraction. The idea behind that is to make the autoencoders robust of small changes in the training dataset.
To deal with the above challenge that is posed in basic autoencoders, the authors proposed to add another penalty term to the loss function of autoencoders. We will discuss this loss function in details.
Contractive autoencoder adds an extra term in the loss function of autoencoder, it is given as:
i.e the above penalty term is the Frobinious Norm of the encoder, the frobinious norm is just a generalization of Euclidean norm.
In the above penalty term, we first need to calculate the Jacobian matrix of the hidden layer, calculating a jacobian of the hidden layer with respect to input is similar to gradient calculation. Let’s first calculate the Jacobian of hidden layer:
where, \phi is non-linearity. Now, to get the jth hidden unit, we need to get the dot product of ith feature vector and the corresponding weight. For this, we need to apply the chain rule.
The above method is similar to how we calculate the gradient descent, but there is one major difference, that is we take h(X) as a vector-valued function, each as a separate output. Intuitively, For example, we have 64 hidden units, then we have 64 function outputs, and so we will have a gradient vector for each of that 64 hidden unit.
Let diag(x) is the diagonal matrix, the matrix from the above derivative is as follows:
Now, we place the diag(x) equation to the above equation and simplify:
In sparse autoencoder, our goal is to have the majority of components of representation close to 0, for this to happen, they must be lying in the left saturated part of the sigmoid function, where their corresponding sigmoid value is close to 0 with a very small first derivative, which in turn leads to the very small entries in the Jacobian matrix. This leads to highly contractive mapping in the sparse autoencoder, even though this is not the goal in sparse Autoencoder.
The idea behind denoising autoencoder is just to increase the robustness of the encoder to the small changes in the training data which is quite similar to the motivation of Contractive Autoencoder. However, there is some difference:
CAEs encourage robustness of representation f(x), whereas DAEs encourage robustness of reconstruction, which only partially increases the robustness of representation.
DAE increases its robustness by stochastically training the model for the reconstruction, whereas CAE increases the robustness of the first derivative of Jacobian matrix.
Python3
# codeimport tensorflow as tf class AutoEncoder(tf.keras.Model): def __init__(self): super(FullyConnectedAutoEncoder, self).__init__() self.flatten_layer =tf.keras.layers.Flatten() self.dense1 = tf.keras.layers.Dense(64, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(32, activation=tf.nn.relu) self.bottleneck = tf.keras.layers.Dense(16, activation=tf.nn.relu) self.dense4 = tf.keras.layers.Dense(32, activation=tf.nn.relu) self.dense5 = tf.keras.layers.Dense(64, activation=tf.nn.relu) self.dense_final = tf.keras.layers.Dense(784) def call(self, inp): x_reshaped = self.flatten_layer(inp) print(x_reshaped.shape) x = self.dense1(x_reshaped) x = self.dense2(x) x = self.bottleneck(x) x_hid= x x = self.dense4(x) x = self.dense5(x) x = self.dense_final(x) return x, x_reshaped,x_hid # define loss function and gradientlambda =100def loss(x, x_bar, h, model): reconstruction_loss = tf.reduce_mean( tf.keras.losses.mse(x, x_bar) ) reconstruction_loss *= 28 * 28 W= tf.Variable(model.bottleneck.weights[0]) dh = h * (1 - h) # N_batch x N_hidden W = tf.transpose(W) contractive = lambda * tf.reduce_sum(tf.linalg.matmul(dh**2 ,tf.square(W)), axis=1) total_loss = reconstruction_loss + contractive return total_lossdef grad(model, inputs): with tf.GradientTape() as tape: reconstruction, inputs_reshaped,hidden = model(inputs) loss_value = loss(inputs_reshaped, reconstruction, hidden, model) return loss_value, tape.gradient(loss_value, model.trainable_variables), inputs_reshaped, reconstruction # load dataset(x_train, _), (x_test, _) = tf.keras.datasets.fashion_mnist.load_data()x_train = x_train.astype('float32') / 255.x_test = x_test.astype('float32') / 255.# train the modelmodel = FullyConnectedAutoEncoder()optimizer = tf.optimizers.Adam(learning_rate=0.001)global_step = tf.Variable(0)num_epochs = 200batch_size = 128for epoch in range(num_epochs): print("Epoch: ", epoch) for x in range(0, len(x_train), batch_size): x_inp = x_train[x : x + batch_size] loss_value, grads, inputs_reshaped, reconstruction = grad(model, x_inp) optimizer.apply_gradients(zip(grads, model.trainable_variables), global_step) print("Step: {}, Loss: {}".format(global_step.numpy(),tf.reduce_sum(loss_value))) # generate resultsn = 10import matplotlib.pyplot as pltplt.figure(figsize=(20, 4))for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i]) plt.title("original") plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + 1 + n) reconstruction, inputs_reshaped,hidden = model(x_test[i].reshape((1,784))) plt.imshow(reconstruction.numpy().reshape((28,28))) plt.title("reconstructed") plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)plt.show()
References:
Contractive Autoencoder
nnr223442
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Informed and Uninformed Search in AI
Deploy Machine Learning Model using Flask
Support Vector Machine Algorithm
Types of Environments in AI
k-nearest neighbor algorithm in Python
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": 23953,
"s": 23925,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 24231,
"s": 23953,
"text": "Contractive Autoencoder was proposed by the researchers at the University of Toronto in 2011 in the paper Contractive auto-encoders: Explicit invariance during feature extraction. The idea behind that is to make the autoencoders robust of small changes in the training dataset."
},
{
"code": null,
"e": 24435,
"s": 24231,
"text": "To deal with the above challenge that is posed in basic autoencoders, the authors proposed to add another penalty term to the loss function of autoencoders. We will discuss this loss function in details."
},
{
"code": null,
"e": 24531,
"s": 24435,
"text": "Contractive autoencoder adds an extra term in the loss function of autoencoder, it is given as:"
},
{
"code": null,
"e": 24661,
"s": 24531,
"text": "i.e the above penalty term is the Frobinious Norm of the encoder, the frobinious norm is just a generalization of Euclidean norm."
},
{
"code": null,
"e": 24909,
"s": 24661,
"text": "In the above penalty term, we first need to calculate the Jacobian matrix of the hidden layer, calculating a jacobian of the hidden layer with respect to input is similar to gradient calculation. Let’s first calculate the Jacobian of hidden layer:"
},
{
"code": null,
"e": 25098,
"s": 24909,
"text": "where, \\phi is non-linearity. Now, to get the jth hidden unit, we need to get the dot product of ith feature vector and the corresponding weight. For this, we need to apply the chain rule."
},
{
"code": null,
"e": 25436,
"s": 25098,
"text": "The above method is similar to how we calculate the gradient descent, but there is one major difference, that is we take h(X) as a vector-valued function, each as a separate output. Intuitively, For example, we have 64 hidden units, then we have 64 function outputs, and so we will have a gradient vector for each of that 64 hidden unit."
},
{
"code": null,
"e": 25524,
"s": 25436,
"text": "Let diag(x) is the diagonal matrix, the matrix from the above derivative is as follows:"
},
{
"code": null,
"e": 25595,
"s": 25524,
"text": "Now, we place the diag(x) equation to the above equation and simplify:"
},
{
"code": null,
"e": 26070,
"s": 25595,
"text": "In sparse autoencoder, our goal is to have the majority of components of representation close to 0, for this to happen, they must be lying in the left saturated part of the sigmoid function, where their corresponding sigmoid value is close to 0 with a very small first derivative, which in turn leads to the very small entries in the Jacobian matrix. This leads to highly contractive mapping in the sparse autoencoder, even though this is not the goal in sparse Autoencoder."
},
{
"code": null,
"e": 26304,
"s": 26070,
"text": "The idea behind denoising autoencoder is just to increase the robustness of the encoder to the small changes in the training data which is quite similar to the motivation of Contractive Autoencoder. However, there is some difference:"
},
{
"code": null,
"e": 26472,
"s": 26304,
"text": "CAEs encourage robustness of representation f(x), whereas DAEs encourage robustness of reconstruction, which only partially increases the robustness of representation."
},
{
"code": null,
"e": 26643,
"s": 26472,
"text": "DAE increases its robustness by stochastically training the model for the reconstruction, whereas CAE increases the robustness of the first derivative of Jacobian matrix."
},
{
"code": null,
"e": 26651,
"s": 26643,
"text": "Python3"
},
{
"code": "# codeimport tensorflow as tf class AutoEncoder(tf.keras.Model): def __init__(self): super(FullyConnectedAutoEncoder, self).__init__() self.flatten_layer =tf.keras.layers.Flatten() self.dense1 = tf.keras.layers.Dense(64, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(32, activation=tf.nn.relu) self.bottleneck = tf.keras.layers.Dense(16, activation=tf.nn.relu) self.dense4 = tf.keras.layers.Dense(32, activation=tf.nn.relu) self.dense5 = tf.keras.layers.Dense(64, activation=tf.nn.relu) self.dense_final = tf.keras.layers.Dense(784) def call(self, inp): x_reshaped = self.flatten_layer(inp) print(x_reshaped.shape) x = self.dense1(x_reshaped) x = self.dense2(x) x = self.bottleneck(x) x_hid= x x = self.dense4(x) x = self.dense5(x) x = self.dense_final(x) return x, x_reshaped,x_hid # define loss function and gradientlambda =100def loss(x, x_bar, h, model): reconstruction_loss = tf.reduce_mean( tf.keras.losses.mse(x, x_bar) ) reconstruction_loss *= 28 * 28 W= tf.Variable(model.bottleneck.weights[0]) dh = h * (1 - h) # N_batch x N_hidden W = tf.transpose(W) contractive = lambda * tf.reduce_sum(tf.linalg.matmul(dh**2 ,tf.square(W)), axis=1) total_loss = reconstruction_loss + contractive return total_lossdef grad(model, inputs): with tf.GradientTape() as tape: reconstruction, inputs_reshaped,hidden = model(inputs) loss_value = loss(inputs_reshaped, reconstruction, hidden, model) return loss_value, tape.gradient(loss_value, model.trainable_variables), inputs_reshaped, reconstruction # load dataset(x_train, _), (x_test, _) = tf.keras.datasets.fashion_mnist.load_data()x_train = x_train.astype('float32') / 255.x_test = x_test.astype('float32') / 255.# train the modelmodel = FullyConnectedAutoEncoder()optimizer = tf.optimizers.Adam(learning_rate=0.001)global_step = tf.Variable(0)num_epochs = 200batch_size = 128for epoch in range(num_epochs): print(\"Epoch: \", epoch) for x in range(0, len(x_train), batch_size): x_inp = x_train[x : x + batch_size] loss_value, grads, inputs_reshaped, reconstruction = grad(model, x_inp) optimizer.apply_gradients(zip(grads, model.trainable_variables), global_step) print(\"Step: {}, Loss: {}\".format(global_step.numpy(),tf.reduce_sum(loss_value))) # generate resultsn = 10import matplotlib.pyplot as pltplt.figure(figsize=(20, 4))for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i]) plt.title(\"original\") plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + 1 + n) reconstruction, inputs_reshaped,hidden = model(x_test[i].reshape((1,784))) plt.imshow(reconstruction.numpy().reshape((28,28))) plt.title(\"reconstructed\") plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)plt.show()",
"e": 29789,
"s": 26651,
"text": null
},
{
"code": null,
"e": 29801,
"s": 29789,
"text": "References:"
},
{
"code": null,
"e": 29825,
"s": 29801,
"text": "Contractive Autoencoder"
},
{
"code": null,
"e": 29835,
"s": 29825,
"text": "nnr223442"
},
{
"code": null,
"e": 29850,
"s": 29835,
"text": "Neural Network"
},
{
"code": null,
"e": 29867,
"s": 29850,
"text": "Machine Learning"
},
{
"code": null,
"e": 29874,
"s": 29867,
"text": "Python"
},
{
"code": null,
"e": 29891,
"s": 29874,
"text": "Machine Learning"
},
{
"code": null,
"e": 29989,
"s": 29891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29998,
"s": 29989,
"text": "Comments"
},
{
"code": null,
"e": 30011,
"s": 29998,
"text": "Old Comments"
},
{
"code": null,
"e": 30067,
"s": 30011,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 30109,
"s": 30067,
"text": "Deploy Machine Learning Model using Flask"
},
{
"code": null,
"e": 30142,
"s": 30109,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 30170,
"s": 30142,
"text": "Types of Environments in AI"
},
{
"code": null,
"e": 30209,
"s": 30170,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 30237,
"s": 30209,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30287,
"s": 30237,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30309,
"s": 30287,
"text": "Python map() function"
}
] |
What are C++ Floating-Point Constants?
|
Floating-point constants specify values that must have a fractional part.
Floating-point constants have a "mantissa," which specifies the value of the number, an "exponent," which specifies the magnitude of the number, and an optional suffix that specifies the constant's type(double or float).
The mantissa is specified as a sequence of digits followed by a period, followed by an optional sequence of digits representing the fractional part of the number. For example −
24.25
12.00
These values can also contain exponents. For example,
24.25e3 which is equivalent to 24250
In C++ you can use the following code to create a floating point constant −
Live Demo
#include<iostream>
using namespace std;
int main() {
const float PI = 3.141; // 3.141 is floating point constant while PI is a constant float.
cout << PI;
return 0;
}
This will give the output −
3.141
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "Floating-point constants specify values that must have a fractional part."
},
{
"code": null,
"e": 1357,
"s": 1136,
"text": "Floating-point constants have a \"mantissa,\" which specifies the value of the number, an \"exponent,\" which specifies the magnitude of the number, and an optional suffix that specifies the constant's type(double or float)."
},
{
"code": null,
"e": 1534,
"s": 1357,
"text": "The mantissa is specified as a sequence of digits followed by a period, followed by an optional sequence of digits representing the fractional part of the number. For example −"
},
{
"code": null,
"e": 1546,
"s": 1534,
"text": "24.25\n12.00"
},
{
"code": null,
"e": 1600,
"s": 1546,
"text": "These values can also contain exponents. For example,"
},
{
"code": null,
"e": 1637,
"s": 1600,
"text": "24.25e3 which is equivalent to 24250"
},
{
"code": null,
"e": 1713,
"s": 1637,
"text": "In C++ you can use the following code to create a floating point constant −"
},
{
"code": null,
"e": 1723,
"s": 1713,
"text": "Live Demo"
},
{
"code": null,
"e": 1900,
"s": 1723,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n const float PI = 3.141; // 3.141 is floating point constant while PI is a constant float.\n cout << PI;\n return 0;\n}"
},
{
"code": null,
"e": 1928,
"s": 1900,
"text": "This will give the output −"
},
{
"code": null,
"e": 1934,
"s": 1928,
"text": "3.141"
}
] |
JavaScript - Array constructor Property
|
JavaScript array constructor property returns a reference to the array function that created the instance's prototype.
Its syntax is as follows −
array.constructor
Returns the function that created this object's instance.
Try the following example.
<html>
<head>
<title>JavaScript Array constructor Property</title>
</head>
<body>
<script type = "text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("arr.constructor is:" + arr.constructor);
</script>
</body>
</html>
arr.constructor is: function Array() { [native code] }
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2585,
"s": 2466,
"text": "JavaScript array constructor property returns a reference to the array function that created the instance's prototype."
},
{
"code": null,
"e": 2612,
"s": 2585,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2631,
"s": 2612,
"text": "array.constructor\n"
},
{
"code": null,
"e": 2689,
"s": 2631,
"text": "Returns the function that created this object's instance."
},
{
"code": null,
"e": 2716,
"s": 2689,
"text": "Try the following example."
},
{
"code": null,
"e": 3012,
"s": 2716,
"text": "<html>\n <head>\n <title>JavaScript Array constructor Property</title>\n </head>\n \n <body>\n \n <script type = \"text/javascript\">\n var arr = new Array( 10, 20, 30 );\n document.write(\"arr.constructor is:\" + arr.constructor); \n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3069,
"s": 3012,
"text": "arr.constructor is: function Array() { [native code] } \n"
},
{
"code": null,
"e": 3104,
"s": 3069,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3118,
"s": 3104,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3152,
"s": 3118,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3166,
"s": 3152,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3201,
"s": 3166,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3218,
"s": 3201,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3253,
"s": 3218,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3270,
"s": 3253,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3303,
"s": 3270,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3331,
"s": 3303,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3365,
"s": 3331,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3393,
"s": 3365,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3400,
"s": 3393,
"text": " Print"
},
{
"code": null,
"e": 3411,
"s": 3400,
"text": " Add Notes"
}
] |
How to convert a data frame to data.table in R?
|
Since operations with data.table are sometimes faster than the data frames, we might want to convert a data frame to a data.table object. The main difference between data frame and data.table is that data frame is available in the base R but to use data.table we have to install the package data.table. We can do this with the help setDT function in the data.table package.
Consider the below data frame −
> set.seed(1)
> x1<-rnorm(20,0.5)
> x2<-rnorm(20,0.8)
> x3<-rpois(20,2)
> x4<-rpois(20,5)
> x5<-runif(20,5,10)
> df<-data.frame(x1,x2,x3,x4,x5)
> df
x1 x2 x3 x4 x5
1 -0.1264538 1.7189774 2 6 9.959193
2 0.6836433 1.5821363 3 4 7.477968
3 -0.3356286 0.8745650 1 4 7.421748
4 2.0952808 -1.1893517 1 11 5.867212
5 0.8295078 1.4198257 3 6 8.774105
6 -0.3204684 0.7438713 1 3 7.269477
7 0.9874291 0.6442045 3 3 7.555849
8 1.2383247 -0.6707524 0 5 6.037726
9 1.0757814 0.3218499 1 8 6.143291
10 0.1946116 1.2179416 1 5 7.978560
11 2.0117812 2.1586796 1 10 7.874361
12 0.8898432 0.6972123 0 6 5.385322
13 -0.1212406 1.1876716 2 4 5.177703
14 -1.7146999 0.7461950 4 4 8.213977
15 1.6249309 -0.5770596 3 3 9.643076
16 0.4550664 0.3850054 3 1 7.990462
17 0.4838097 0.4057100 2 6 7.804504
18 1.4438362 0.7406866 2 2 7.630139
19 1.3212212 1.9000254 3 5 9.925476
20 1.0939013 1.5631757 2 6 7.538209
Loading data.table package −
> library(data.table)
Converting data frame df to data.table?
> setDT(df)
Checking whether df is a data.table or not −
> is.data.table(df)
[1] TRUE
Let’s have a look at one more example −
> y1<-letters[1:20]
> y2<-rep(c("Group1","Group2","Group3","Group4"),times=5)
> y3<-1:20
> df_new<-data.frame(y1,y2,y3)
> df_new
y1 y2 y3
1 a Group1 1
2 b Group2 2
3 c Group3 3
4 d Group4 4
5 e Group1 5
6 f Group2 6
7 g Group3 7
8 h Group4 8
9 i Group1 9
10 j Group2 10
11 k Group3 11
12 l Group4 12
13 m Group1 13
14 n Group2 14
15 o Group3 15
16 p Group4 16
17 q Group1 17
18 r Group2 18
19 s Group3 19
20 t Group4 20
> setDT(df_new)
> is.data.table(df_new)
[1] TRUE
|
[
{
"code": null,
"e": 1436,
"s": 1062,
"text": "Since operations with data.table are sometimes faster than the data frames, we might want to convert a data frame to a data.table object. The main difference between data frame and data.table is that data frame is available in the base R but to use data.table we have to install the package data.table. We can do this with the help setDT function in the data.table package."
},
{
"code": null,
"e": 1468,
"s": 1436,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 2394,
"s": 1468,
"text": "> set.seed(1)\n> x1<-rnorm(20,0.5)\n> x2<-rnorm(20,0.8)\n> x3<-rpois(20,2)\n> x4<-rpois(20,5)\n> x5<-runif(20,5,10)\n> df<-data.frame(x1,x2,x3,x4,x5)\n> df\nx1 x2 x3 x4 x5\n1 -0.1264538 1.7189774 2 6 9.959193\n2 0.6836433 1.5821363 3 4 7.477968\n3 -0.3356286 0.8745650 1 4 7.421748\n4 2.0952808 -1.1893517 1 11 5.867212\n5 0.8295078 1.4198257 3 6 8.774105\n6 -0.3204684 0.7438713 1 3 7.269477\n7 0.9874291 0.6442045 3 3 7.555849\n8 1.2383247 -0.6707524 0 5 6.037726\n9 1.0757814 0.3218499 1 8 6.143291\n10 0.1946116 1.2179416 1 5 7.978560\n11 2.0117812 2.1586796 1 10 7.874361\n12 0.8898432 0.6972123 0 6 5.385322\n13 -0.1212406 1.1876716 2 4 5.177703\n14 -1.7146999 0.7461950 4 4 8.213977\n15 1.6249309 -0.5770596 3 3 9.643076\n16 0.4550664 0.3850054 3 1 7.990462\n17 0.4838097 0.4057100 2 6 7.804504\n18 1.4438362 0.7406866 2 2 7.630139\n19 1.3212212 1.9000254 3 5 9.925476\n20 1.0939013 1.5631757 2 6 7.538209"
},
{
"code": null,
"e": 2423,
"s": 2394,
"text": "Loading data.table package −"
},
{
"code": null,
"e": 2445,
"s": 2423,
"text": "> library(data.table)"
},
{
"code": null,
"e": 2485,
"s": 2445,
"text": "Converting data frame df to data.table?"
},
{
"code": null,
"e": 2497,
"s": 2485,
"text": "> setDT(df)"
},
{
"code": null,
"e": 2542,
"s": 2497,
"text": "Checking whether df is a data.table or not −"
},
{
"code": null,
"e": 2571,
"s": 2542,
"text": "> is.data.table(df)\n[1] TRUE"
},
{
"code": null,
"e": 2611,
"s": 2571,
"text": "Let’s have a look at one more example −"
},
{
"code": null,
"e": 3105,
"s": 2611,
"text": "> y1<-letters[1:20]\n> y2<-rep(c(\"Group1\",\"Group2\",\"Group3\",\"Group4\"),times=5)\n> y3<-1:20\n> df_new<-data.frame(y1,y2,y3)\n> df_new\n y1 y2 y3\n1 a Group1 1\n2 b Group2 2\n3 c Group3 3\n4 d Group4 4\n5 e Group1 5\n6 f Group2 6\n7 g Group3 7\n8 h Group4 8\n9 i Group1 9\n10 j Group2 10\n11 k Group3 11\n12 l Group4 12\n13 m Group1 13\n14 n Group2 14\n15 o Group3 15\n16 p Group4 16\n17 q Group1 17\n18 r Group2 18\n19 s Group3 19\n20 t Group4 20\n> setDT(df_new)\n> is.data.table(df_new)\n[1] TRUE"
}
] |
CAST function in Cassandra - GeeksforGeeks
|
30 Oct, 2019
CAST function helps in Converts data from one data type to another data type in Cassandra.
In Cassandra CAST function Supported in SELECT statements. lets have a look how we can used CAST function in select statement.
SELECT CAST([fieldname] AS [data type])
FROM [table name]
Basic function of CAST:
It Converts From any native data type to text data type in formats such that ASCII and UTF-8.
It Converts Between numeric data types such that from `int` to `smallint`, `smallint` to `int`, etc.
By using the CAST function we can Converts the Most common use case.
It is very helpful in case of optimization where we have the need to frequent change from one data type to another.
By using the CAST function we can converts timestamp to text for display purposes in Cassandra.
This is a table for reference in which all native data type which can convert from one data type to another.
Lets have a look,
Table: CAST conversion tableThe following table describes the conversions supported by the cast function. Cassandra will silently ignore any cast converting a datatype into its own datatype.
Source – Cassandra.Apache.org
CQL query for CAST function:Let’s take an example: movies is a table name in which we want to change its native data type such that movie_date is field name which have timestamp data type and if we want to convert it into another native data type such that in text data type.
To create table used the following CQL query.
CREATE TABLE movies
(
movie_id int,
movie_date timestamp,
PRIMARY KEY (movie_id)
);
Insert the following data into the table:
movie_id : 7c3cffb8-0dc4-1d27-af24-c007b5fc5643
movie_date : 2019-10-15 01:11:50.000000+0000
INSERT INTO movies (movie_id, movie_date)
VALUES (7c3cffb8-0dc4-1d27-af24-c007b5fc5643,
'2019-10-15 01:11:50.000000+0000 ');
So, here is the format of how we can convert from one data type to another by using the CAST function. The below-given statement means that we are going to convert movie_date timestamp to movie_date text.
SELECT CAST(movie_date AS text)
Result: Without CASTSELECT movie_date
FROM movies
WHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643; Output:2019-10-15 01:11:50.000000+0000 (time stamp format)
SELECT movie_date
FROM movies
WHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643;
Output:
2019-10-15 01:11:50.000000+0000 (time stamp format)
Result: With CASTSELECT CAST(movie_date AS text)
FROM movies
WHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643; Output:2019-10-15 01:11:50.000Z (Coordinated Universal Time, or UTC)
SELECT CAST(movie_date AS text)
FROM movies
WHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643;
Output:
2019-10-15 01:11:50.000Z (Coordinated Universal Time, or UTC)
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Data Preprocessing in Data Mining
Cosine Similarity
Deadlock in DBMS
Introduction of B-Tree
Second Normal Form (2NF)
Introduction of Relational Algebra in DBMS
Boyce-Codd Normal Form (BCNF)
Advantages of Database Management System
SQL | GROUP BY
KDD Process in Data Mining
|
[
{
"code": null,
"e": 23647,
"s": 23619,
"text": "\n30 Oct, 2019"
},
{
"code": null,
"e": 23738,
"s": 23647,
"text": "CAST function helps in Converts data from one data type to another data type in Cassandra."
},
{
"code": null,
"e": 23865,
"s": 23738,
"text": "In Cassandra CAST function Supported in SELECT statements. lets have a look how we can used CAST function in select statement."
},
{
"code": null,
"e": 23925,
"s": 23865,
"text": "SELECT CAST([fieldname] AS [data type]) \nFROM [table name] "
},
{
"code": null,
"e": 23949,
"s": 23925,
"text": "Basic function of CAST:"
},
{
"code": null,
"e": 24043,
"s": 23949,
"text": "It Converts From any native data type to text data type in formats such that ASCII and UTF-8."
},
{
"code": null,
"e": 24144,
"s": 24043,
"text": "It Converts Between numeric data types such that from `int` to `smallint`, `smallint` to `int`, etc."
},
{
"code": null,
"e": 24213,
"s": 24144,
"text": "By using the CAST function we can Converts the Most common use case."
},
{
"code": null,
"e": 24329,
"s": 24213,
"text": "It is very helpful in case of optimization where we have the need to frequent change from one data type to another."
},
{
"code": null,
"e": 24425,
"s": 24329,
"text": "By using the CAST function we can converts timestamp to text for display purposes in Cassandra."
},
{
"code": null,
"e": 24534,
"s": 24425,
"text": "This is a table for reference in which all native data type which can convert from one data type to another."
},
{
"code": null,
"e": 24552,
"s": 24534,
"text": "Lets have a look,"
},
{
"code": null,
"e": 24743,
"s": 24552,
"text": "Table: CAST conversion tableThe following table describes the conversions supported by the cast function. Cassandra will silently ignore any cast converting a datatype into its own datatype."
},
{
"code": null,
"e": 24773,
"s": 24743,
"text": "Source – Cassandra.Apache.org"
},
{
"code": null,
"e": 25049,
"s": 24773,
"text": "CQL query for CAST function:Let’s take an example: movies is a table name in which we want to change its native data type such that movie_date is field name which have timestamp data type and if we want to convert it into another native data type such that in text data type."
},
{
"code": null,
"e": 25095,
"s": 25049,
"text": "To create table used the following CQL query."
},
{
"code": null,
"e": 25188,
"s": 25095,
"text": "CREATE TABLE movies\n (\n movie_id int,\n movie_date timestamp,\n PRIMARY KEY (movie_id)\n ); "
},
{
"code": null,
"e": 25230,
"s": 25188,
"text": "Insert the following data into the table:"
},
{
"code": null,
"e": 25478,
"s": 25230,
"text": "movie_id : 7c3cffb8-0dc4-1d27-af24-c007b5fc5643\nmovie_date : 2019-10-15 01:11:50.000000+0000 \n\nINSERT INTO movies (movie_id, movie_date) \n VALUES (7c3cffb8-0dc4-1d27-af24-c007b5fc5643, \n '2019-10-15 01:11:50.000000+0000 '); "
},
{
"code": null,
"e": 25683,
"s": 25478,
"text": "So, here is the format of how we can convert from one data type to another by using the CAST function. The below-given statement means that we are going to convert movie_date timestamp to movie_date text."
},
{
"code": null,
"e": 25716,
"s": 25683,
"text": "SELECT CAST(movie_date AS text) "
},
{
"code": null,
"e": 25881,
"s": 25716,
"text": "Result: Without CASTSELECT movie_date\nFROM movies\nWHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643; Output:2019-10-15 01:11:50.000000+0000 (time stamp format) "
},
{
"code": null,
"e": 25967,
"s": 25881,
"text": "SELECT movie_date\nFROM movies\nWHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643; "
},
{
"code": null,
"e": 25975,
"s": 25967,
"text": "Output:"
},
{
"code": null,
"e": 26028,
"s": 25975,
"text": "2019-10-15 01:11:50.000000+0000 (time stamp format) "
},
{
"code": null,
"e": 26214,
"s": 26028,
"text": "Result: With CASTSELECT CAST(movie_date AS text)\nFROM movies\nWHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643; Output:2019-10-15 01:11:50.000Z (Coordinated Universal Time, or UTC) "
},
{
"code": null,
"e": 26314,
"s": 26214,
"text": "SELECT CAST(movie_date AS text)\nFROM movies\nWHERE movie_id = 7c3cffb8-0dc4-1d27-af24-c007b5fc5643; "
},
{
"code": null,
"e": 26322,
"s": 26314,
"text": "Output:"
},
{
"code": null,
"e": 26385,
"s": 26322,
"text": "2019-10-15 01:11:50.000Z (Coordinated Universal Time, or UTC) "
},
{
"code": null,
"e": 26392,
"s": 26385,
"text": "Apache"
},
{
"code": null,
"e": 26397,
"s": 26392,
"text": "DBMS"
},
{
"code": null,
"e": 26402,
"s": 26397,
"text": "DBMS"
},
{
"code": null,
"e": 26500,
"s": 26402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26509,
"s": 26500,
"text": "Comments"
},
{
"code": null,
"e": 26522,
"s": 26509,
"text": "Old Comments"
},
{
"code": null,
"e": 26556,
"s": 26522,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 26574,
"s": 26556,
"text": "Cosine Similarity"
},
{
"code": null,
"e": 26591,
"s": 26574,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 26614,
"s": 26591,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 26639,
"s": 26614,
"text": "Second Normal Form (2NF)"
},
{
"code": null,
"e": 26682,
"s": 26639,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 26712,
"s": 26682,
"text": "Boyce-Codd Normal Form (BCNF)"
},
{
"code": null,
"e": 26753,
"s": 26712,
"text": "Advantages of Database Management System"
},
{
"code": null,
"e": 26768,
"s": 26753,
"text": "SQL | GROUP BY"
}
] |
AVRO - Deserialization Using Parsers
|
As mentioned earlier, one can read an Avro schema into a program either by generating a class corresponding to a schema or by using the parsers library. In Avro, data is always stored with its corresponding schema. Therefore, we can always read a serialized item without code generation.
This chapter describes how to read the schema using parsers library and Deserializing the data using Avro.
The serialized data is stored in the file mydata.txt. You can deserialize and read it using Avro.
Follow the procedure given below to deserialize the serialized data from a file.
First of all, read the schema from the file. To do so, use Schema.Parser class. This class provides methods to parse the schema in different formats.
Instantiate the Schema.Parser class by passing the file path where the schema is stored.
Schema schema = new Schema.Parser().parse(new File("/path/to/emp.avsc"));
Create an object of DatumReader interface using SpecificDatumReader class.
DatumReader<emp>empDatumReader = new SpecificDatumReader<emp>(emp.class);
Instantiate DataFileReader class. This class reads serialized data from a file. It requires the DatumReader object, and path of the file where the serialized data exists, as a parameters to the constructor.
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File("/path/to/mydata.txt"), datumReader);
Print the deserialized data, using the methods of DataFileReader.
The hasNext() method returns a boolean if there are any elements in the Reader
.
The hasNext() method returns a boolean if there are any elements in the Reader
.
The next() method of DataFileReader returns the data in the Reader.
The next() method of DataFileReader returns the data in the Reader.
while(dataFileReader.hasNext()){
em=dataFileReader.next(em);
System.out.println(em);
}
The following complete program shows how to deserialize the serialized data using Parsers library −
public class Deserialize {
public static void main(String args[]) throws Exception{
//Instantiating the Schema.Parser class.
Schema schema = new Schema.Parser().parse(new File("/home/Hadoop/Avro/schema/emp.avsc"));
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File("/home/Hadoop/Avro_Work/without_code_gen/mydata.txt"), datumReader);
GenericRecord emp = null;
while (dataFileReader.hasNext()) {
emp = dataFileReader.next(emp);
System.out.println(emp);
}
System.out.println("hello");
}
}
Browse into the directory where the generated code is placed. In this case, it is at home/Hadoop/Avro_work/without_code_gen.
$ cd home/Hadoop/Avro_work/without_code_gen/
Now copy and save the above program in the file named DeSerialize.java. Compile and execute it as shown below −
$ javac Deserialize.java
$ java Deserialize
{"name": "ramu", "id": 1, "salary": 30000, "age": 25, "address": "chennai"}
{"name": "rahman", "id": 2, "salary": 35000, "age": 30, "address": "Delhi"}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2149,
"s": 1861,
"text": "As mentioned earlier, one can read an Avro schema into a program either by generating a class corresponding to a schema or by using the parsers library. In Avro, data is always stored with its corresponding schema. Therefore, we can always read a serialized item without code generation."
},
{
"code": null,
"e": 2256,
"s": 2149,
"text": "This chapter describes how to read the schema using parsers library and Deserializing the data using Avro."
},
{
"code": null,
"e": 2354,
"s": 2256,
"text": "The serialized data is stored in the file mydata.txt. You can deserialize and read it using Avro."
},
{
"code": null,
"e": 2435,
"s": 2354,
"text": "Follow the procedure given below to deserialize the serialized data from a file."
},
{
"code": null,
"e": 2585,
"s": 2435,
"text": "First of all, read the schema from the file. To do so, use Schema.Parser class. This class provides methods to parse the schema in different formats."
},
{
"code": null,
"e": 2674,
"s": 2585,
"text": "Instantiate the Schema.Parser class by passing the file path where the schema is stored."
},
{
"code": null,
"e": 2749,
"s": 2674,
"text": "Schema schema = new Schema.Parser().parse(new File(\"/path/to/emp.avsc\"));\n"
},
{
"code": null,
"e": 2824,
"s": 2749,
"text": "Create an object of DatumReader interface using SpecificDatumReader class."
},
{
"code": null,
"e": 2899,
"s": 2824,
"text": "DatumReader<emp>empDatumReader = new SpecificDatumReader<emp>(emp.class);\n"
},
{
"code": null,
"e": 3106,
"s": 2899,
"text": "Instantiate DataFileReader class. This class reads serialized data from a file. It requires the DatumReader object, and path of the file where the serialized data exists, as a parameters to the constructor."
},
{
"code": null,
"e": 3235,
"s": 3106,
"text": "DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File(\"/path/to/mydata.txt\"), datumReader);\n"
},
{
"code": null,
"e": 3301,
"s": 3235,
"text": "Print the deserialized data, using the methods of DataFileReader."
},
{
"code": null,
"e": 3382,
"s": 3301,
"text": "The hasNext() method returns a boolean if there are any elements in the Reader\n."
},
{
"code": null,
"e": 3463,
"s": 3382,
"text": "The hasNext() method returns a boolean if there are any elements in the Reader\n."
},
{
"code": null,
"e": 3531,
"s": 3463,
"text": "The next() method of DataFileReader returns the data in the Reader."
},
{
"code": null,
"e": 3599,
"s": 3531,
"text": "The next() method of DataFileReader returns the data in the Reader."
},
{
"code": null,
"e": 3693,
"s": 3599,
"text": "while(dataFileReader.hasNext()){\n\n em=dataFileReader.next(em);\n System.out.println(em);\n}"
},
{
"code": null,
"e": 3793,
"s": 3693,
"text": "The following complete program shows how to deserialize the serialized data using Parsers library −"
},
{
"code": null,
"e": 4485,
"s": 3793,
"text": "public class Deserialize {\n public static void main(String args[]) throws Exception{\n\t\n //Instantiating the Schema.Parser class.\n Schema schema = new Schema.Parser().parse(new File(\"/home/Hadoop/Avro/schema/emp.avsc\"));\n DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);\n DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File(\"/home/Hadoop/Avro_Work/without_code_gen/mydata.txt\"), datumReader);\n GenericRecord emp = null;\n\t\t\n while (dataFileReader.hasNext()) {\n emp = dataFileReader.next(emp);\n System.out.println(emp);\n }\n System.out.println(\"hello\");\n }\n}"
},
{
"code": null,
"e": 4610,
"s": 4485,
"text": "Browse into the directory where the generated code is placed. In this case, it is at home/Hadoop/Avro_work/without_code_gen."
},
{
"code": null,
"e": 4656,
"s": 4610,
"text": "$ cd home/Hadoop/Avro_work/without_code_gen/\n"
},
{
"code": null,
"e": 4768,
"s": 4656,
"text": "Now copy and save the above program in the file named DeSerialize.java. Compile and execute it as shown below −"
},
{
"code": null,
"e": 4813,
"s": 4768,
"text": "$ javac Deserialize.java\n$ java Deserialize\n"
},
{
"code": null,
"e": 4966,
"s": 4813,
"text": "{\"name\": \"ramu\", \"id\": 1, \"salary\": 30000, \"age\": 25, \"address\": \"chennai\"}\n{\"name\": \"rahman\", \"id\": 2, \"salary\": 35000, \"age\": 30, \"address\": \"Delhi\"}\n"
},
{
"code": null,
"e": 4973,
"s": 4966,
"text": " Print"
},
{
"code": null,
"e": 4984,
"s": 4973,
"text": " Add Notes"
}
] |
C# | Creating a read-only wrapper for the List - GeeksforGeeks
|
27 Jan, 2019
List<T>.AsReadOnly Method is used to get a read-only ReadOnlyCollection<T> wrapper for the current collection.
Syntax:
public System.Collections.ObjectModel.ReadOnlyCollection AsReadOnly ();
Return Value: It returns an object that acts as a read-only wrapper around the current List<T>.
Example:
// C# code to create a read-only// wrapper for the List<T>using System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); firstlist.Add(5); firstlist.Add(6); firstlist.Add(7); Console.WriteLine("Before Wrapping: "); // Displaying the elements in the List foreach(int i in firstlist) { Console.WriteLine(i); } // Creating a Read-Only packing // around the List<T> IList<int> mylist2 = firstlist.AsReadOnly(); Console.WriteLine("After Wrapping: "); // Displaying the elements foreach(int m in mylist2) { Console.WriteLine(m); } Console.WriteLine("Trying to add new element into mylist2:"); // it will give error mylist2.Add(8); }}
Output:
Before Wrapping:
1
2
3
4
5
6
7
After Wrapping:
1
2
3
4
5
6
7
Trying to add new element into mylist2:
Runtime Error:
Unhandled Exception:System.NotSupportedException: Collection is read-only.
Note:
A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection. If changes are made to the underlying collection, the read-only collection reflects those changes.
This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.asreadonly?view=netframework-4.7.2
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Method Overriding
Destructors in C#
Difference between Ref and Out keywords in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
Introduction to .NET Framework
C# | Class and Object
C# | Abstract Classes
HashSet in C# with Examples
|
[
{
"code": null,
"e": 23994,
"s": 23966,
"text": "\n27 Jan, 2019"
},
{
"code": null,
"e": 24105,
"s": 23994,
"text": "List<T>.AsReadOnly Method is used to get a read-only ReadOnlyCollection<T> wrapper for the current collection."
},
{
"code": null,
"e": 24113,
"s": 24105,
"text": "Syntax:"
},
{
"code": null,
"e": 24185,
"s": 24113,
"text": "public System.Collections.ObjectModel.ReadOnlyCollection AsReadOnly ();"
},
{
"code": null,
"e": 24281,
"s": 24185,
"text": "Return Value: It returns an object that acts as a read-only wrapper around the current List<T>."
},
{
"code": null,
"e": 24290,
"s": 24281,
"text": "Example:"
},
{
"code": "// C# code to create a read-only// wrapper for the List<T>using System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); firstlist.Add(5); firstlist.Add(6); firstlist.Add(7); Console.WriteLine(\"Before Wrapping: \"); // Displaying the elements in the List foreach(int i in firstlist) { Console.WriteLine(i); } // Creating a Read-Only packing // around the List<T> IList<int> mylist2 = firstlist.AsReadOnly(); Console.WriteLine(\"After Wrapping: \"); // Displaying the elements foreach(int m in mylist2) { Console.WriteLine(m); } Console.WriteLine(\"Trying to add new element into mylist2:\"); // it will give error mylist2.Add(8); }}",
"e": 25392,
"s": 24290,
"text": null
},
{
"code": null,
"e": 25400,
"s": 25392,
"text": "Output:"
},
{
"code": null,
"e": 25504,
"s": 25400,
"text": "Before Wrapping: \n1\n2\n3\n4\n5\n6\n7\nAfter Wrapping: \n1\n2\n3\n4\n5\n6\n7\nTrying to add new element into mylist2:\n"
},
{
"code": null,
"e": 25519,
"s": 25504,
"text": "Runtime Error:"
},
{
"code": null,
"e": 25594,
"s": 25519,
"text": "Unhandled Exception:System.NotSupportedException: Collection is read-only."
},
{
"code": null,
"e": 25600,
"s": 25594,
"text": "Note:"
},
{
"code": null,
"e": 25808,
"s": 25600,
"text": "A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection. If changes are made to the underlying collection, the read-only collection reflects those changes."
},
{
"code": null,
"e": 25842,
"s": 25808,
"text": "This method is an O(1) operation."
},
{
"code": null,
"e": 25853,
"s": 25842,
"text": "Reference:"
},
{
"code": null,
"e": 25966,
"s": 25853,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.asreadonly?view=netframework-4.7.2"
},
{
"code": null,
"e": 25986,
"s": 25966,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 26011,
"s": 25986,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 26025,
"s": 26011,
"text": "CSharp-method"
},
{
"code": null,
"e": 26028,
"s": 26025,
"text": "C#"
},
{
"code": null,
"e": 26126,
"s": 26028,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26154,
"s": 26126,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26177,
"s": 26154,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 26195,
"s": 26177,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26241,
"s": 26195,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26281,
"s": 26241,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 26299,
"s": 26281,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26330,
"s": 26299,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26352,
"s": 26330,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26374,
"s": 26352,
"text": "C# | Abstract Classes"
}
] |
Operating System - Processes
|
A process is basically a program in execution. The execution of a process must progress in a sequential fashion.
To put it in simple terms, we write our computer programs in a text file and when we execute this program, it becomes a process which performs all the tasks mentioned in the program.
When a program is loaded into the memory and it becomes a process, it can be divided into four sections ─ stack, heap, text and data. The following image shows a simplified layout of a process inside main memory −
Stack
The process Stack contains the temporary data such as method/function parameters, return address and local variables.
Heap
This is dynamically allocated memory to a process during its run time.
Text
This includes the current activity represented by the value of Program Counter and the contents of the processor's registers.
Data
This section contains the global and static variables.
A program is a piece of code which may be a single line or millions of lines. A computer program is usually written by a computer programmer in a programming language. For example, here is a simple program written in C programming language −
#include <stdio.h>
int main() {
printf("Hello, World! \n");
return 0;
}
A computer program is a collection of instructions that performs a specific task when executed by a computer. When we compare a program with a process, we can conclude that a process is a dynamic instance of a computer program.
A part of a computer program that performs a well-defined task is known as an algorithm. A collection of computer programs, libraries and related data are referred to as a software.
When a process executes, it passes through different states. These stages may differ in different operating systems, and the names of these states are also not standardized.
In general, a process can have one of the following five states at a time.
Start
This is the initial state when a process is first started/created.
Ready
The process is waiting to be assigned to a processor. Ready processes are waiting to have the processor allocated to them by the operating system so that they can run. Process may come into this state after Start state or while running it by but interrupted by the scheduler to assign CPU to some other process.
Running
Once the process has been assigned to a processor by the OS scheduler, the process state is set to running and the processor executes its instructions.
Waiting
Process moves into the waiting state if it needs to wait for a resource, such as waiting for user input, or waiting for a file to become available.
Terminated or Exit
Once the process finishes its execution, or it is terminated by the operating system, it is moved to the terminated state where it waits to be removed from main memory.
A Process Control Block is a data structure maintained by the Operating System for every process. The PCB is identified by an integer process ID (PID). A PCB keeps all the information needed to keep track of a process as listed below in the table −
Process State
The current state of the process i.e., whether it is ready, running, waiting, or whatever.
Process privileges
This is required to allow/disallow access to system resources.
Process ID
Unique identification for each of the process in the operating system.
Pointer
A pointer to parent process.
Program Counter
Program Counter is a pointer to the address of the next instruction to be executed for this process.
CPU registers
Various CPU registers where process need to be stored for execution for running state.
CPU Scheduling Information
Process priority and other scheduling information which is required to schedule the process.
Memory management information
This includes the information of page table, memory limits, Segment table depending on memory used by the operating system.
Accounting information
This includes the amount of CPU used for process execution, time limits, execution ID etc.
IO status information
This includes a list of I/O devices allocated to the process.
The architecture of a PCB is completely dependent on Operating System and may contain different information in different operating systems. Here is a simplified diagram of a PCB −
The PCB is maintained for a process throughout its lifetime, and is deleted once the process terminates.
86 Lectures
10 hours
Arnab Chakraborty
5 Lectures
4.5 hours
Frahaan Hussain
8 Lectures
43 mins
Harshit Srivastava
29 Lectures
2.5 hours
Ashraf Said
43 Lectures
20 hours
ILANCHEZHIAN K
45 Lectures
20 hours
ILANCHEZHIAN K
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2027,
"s": 1914,
"text": "A process is basically a program in execution. The execution of a process must progress in a sequential fashion."
},
{
"code": null,
"e": 2210,
"s": 2027,
"text": "To put it in simple terms, we write our computer programs in a text file and when we execute this program, it becomes a process which performs all the tasks mentioned in the program."
},
{
"code": null,
"e": 2424,
"s": 2210,
"text": "When a program is loaded into the memory and it becomes a process, it can be divided into four sections ─ stack, heap, text and data. The following image shows a simplified layout of a process inside main memory −"
},
{
"code": null,
"e": 2430,
"s": 2424,
"text": "Stack"
},
{
"code": null,
"e": 2548,
"s": 2430,
"text": "The process Stack contains the temporary data such as method/function parameters, return address and local variables."
},
{
"code": null,
"e": 2553,
"s": 2548,
"text": "Heap"
},
{
"code": null,
"e": 2624,
"s": 2553,
"text": "This is dynamically allocated memory to a process during its run time."
},
{
"code": null,
"e": 2629,
"s": 2624,
"text": "Text"
},
{
"code": null,
"e": 2755,
"s": 2629,
"text": "This includes the current activity represented by the value of Program Counter and the contents of the processor's registers."
},
{
"code": null,
"e": 2760,
"s": 2755,
"text": "Data"
},
{
"code": null,
"e": 2815,
"s": 2760,
"text": "This section contains the global and static variables."
},
{
"code": null,
"e": 3057,
"s": 2815,
"text": "A program is a piece of code which may be a single line or millions of lines. A computer program is usually written by a computer programmer in a programming language. For example, here is a simple program written in C programming language −"
},
{
"code": null,
"e": 3136,
"s": 3057,
"text": "#include <stdio.h>\n\nint main() {\n printf(\"Hello, World! \\n\");\n return 0;\n}"
},
{
"code": null,
"e": 3364,
"s": 3136,
"text": "A computer program is a collection of instructions that performs a specific task when executed by a computer. When we compare a program with a process, we can conclude that a process is a dynamic instance of a computer program."
},
{
"code": null,
"e": 3546,
"s": 3364,
"text": "A part of a computer program that performs a well-defined task is known as an algorithm. A collection of computer programs, libraries and related data are referred to as a software."
},
{
"code": null,
"e": 3721,
"s": 3546,
"text": " When a process executes, it passes through different states. These stages may differ in different operating systems, and the names of these states are also not standardized."
},
{
"code": null,
"e": 3796,
"s": 3721,
"text": "In general, a process can have one of the following five states at a time."
},
{
"code": null,
"e": 3802,
"s": 3796,
"text": "Start"
},
{
"code": null,
"e": 3869,
"s": 3802,
"text": "This is the initial state when a process is first started/created."
},
{
"code": null,
"e": 3875,
"s": 3869,
"text": "Ready"
},
{
"code": null,
"e": 4187,
"s": 3875,
"text": "The process is waiting to be assigned to a processor. Ready processes are waiting to have the processor allocated to them by the operating system so that they can run. Process may come into this state after Start state or while running it by but interrupted by the scheduler to assign CPU to some other process."
},
{
"code": null,
"e": 4195,
"s": 4187,
"text": "Running"
},
{
"code": null,
"e": 4347,
"s": 4195,
"text": "Once the process has been assigned to a processor by the OS scheduler, the process state is set to running and the processor executes its instructions."
},
{
"code": null,
"e": 4355,
"s": 4347,
"text": "Waiting"
},
{
"code": null,
"e": 4503,
"s": 4355,
"text": "Process moves into the waiting state if it needs to wait for a resource, such as waiting for user input, or waiting for a file to become available."
},
{
"code": null,
"e": 4522,
"s": 4503,
"text": "Terminated or Exit"
},
{
"code": null,
"e": 4691,
"s": 4522,
"text": "Once the process finishes its execution, or it is terminated by the operating system, it is moved to the terminated state where it waits to be removed from main memory."
},
{
"code": null,
"e": 4940,
"s": 4691,
"text": "A Process Control Block is a data structure maintained by the Operating System for every process. The PCB is identified by an integer process ID (PID). A PCB keeps all the information needed to keep track of a process as listed below in the table −"
},
{
"code": null,
"e": 4954,
"s": 4940,
"text": "Process State"
},
{
"code": null,
"e": 5045,
"s": 4954,
"text": "The current state of the process i.e., whether it is ready, running, waiting, or whatever."
},
{
"code": null,
"e": 5064,
"s": 5045,
"text": "Process privileges"
},
{
"code": null,
"e": 5127,
"s": 5064,
"text": "This is required to allow/disallow access to system resources."
},
{
"code": null,
"e": 5138,
"s": 5127,
"text": "Process ID"
},
{
"code": null,
"e": 5209,
"s": 5138,
"text": "Unique identification for each of the process in the operating system."
},
{
"code": null,
"e": 5217,
"s": 5209,
"text": "Pointer"
},
{
"code": null,
"e": 5246,
"s": 5217,
"text": "A pointer to parent process."
},
{
"code": null,
"e": 5262,
"s": 5246,
"text": "Program Counter"
},
{
"code": null,
"e": 5363,
"s": 5262,
"text": "Program Counter is a pointer to the address of the next instruction to be executed for this process."
},
{
"code": null,
"e": 5377,
"s": 5363,
"text": "CPU registers"
},
{
"code": null,
"e": 5464,
"s": 5377,
"text": "Various CPU registers where process need to be stored for execution for running state."
},
{
"code": null,
"e": 5491,
"s": 5464,
"text": "CPU Scheduling Information"
},
{
"code": null,
"e": 5585,
"s": 5491,
"text": "Process priority and other scheduling information which is required to schedule the process."
},
{
"code": null,
"e": 5615,
"s": 5585,
"text": "Memory management information"
},
{
"code": null,
"e": 5739,
"s": 5615,
"text": "This includes the information of page table, memory limits, Segment table depending on memory used by the operating system."
},
{
"code": null,
"e": 5762,
"s": 5739,
"text": "Accounting information"
},
{
"code": null,
"e": 5854,
"s": 5762,
"text": "This includes the amount of CPU used for process execution, time limits, execution ID etc."
},
{
"code": null,
"e": 5876,
"s": 5854,
"text": "IO status information"
},
{
"code": null,
"e": 5938,
"s": 5876,
"text": "This includes a list of I/O devices allocated to the process."
},
{
"code": null,
"e": 6118,
"s": 5938,
"text": "The architecture of a PCB is completely dependent on Operating System and may contain different information in different operating systems. Here is a simplified diagram of a PCB −"
},
{
"code": null,
"e": 6223,
"s": 6118,
"text": "The PCB is maintained for a process throughout its lifetime, and is deleted once the process terminates."
},
{
"code": null,
"e": 6257,
"s": 6223,
"text": "\n 86 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6276,
"s": 6257,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6310,
"s": 6276,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6327,
"s": 6310,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6358,
"s": 6327,
"text": "\n 8 Lectures \n 43 mins\n"
},
{
"code": null,
"e": 6378,
"s": 6358,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 6413,
"s": 6378,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6426,
"s": 6413,
"text": " Ashraf Said"
},
{
"code": null,
"e": 6460,
"s": 6426,
"text": "\n 43 Lectures \n 20 hours \n"
},
{
"code": null,
"e": 6476,
"s": 6460,
"text": " ILANCHEZHIAN K"
},
{
"code": null,
"e": 6510,
"s": 6476,
"text": "\n 45 Lectures \n 20 hours \n"
},
{
"code": null,
"e": 6526,
"s": 6510,
"text": " ILANCHEZHIAN K"
},
{
"code": null,
"e": 6533,
"s": 6526,
"text": " Print"
},
{
"code": null,
"e": 6544,
"s": 6533,
"text": " Add Notes"
}
] |
How to check the existence of key in an object using AngularJS ? - GeeksforGeeks
|
14 Oct, 2020
Given an object containing (key, value) pair and the task is to check whether a key exists in an object or not using AngularJS.
Approach: The approach is to use the in operator to check whether a key exists in object or not. In first example the key “Prop_1” is input and it exists in the object. In the second example the user can check which key they want to check for existence.
Example 1:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.obj1 = { "Prop_1": 1, "Prop_2": 2, "Prop_3": 3 }; $scope.res = ''; $scope.textval = "Prop_1"; $scope.checkK = function () { var txtVal = $scope.textval; if (!(txtVal in $scope.obj1)) { $scope.res = "Key not Exists."; } else { $scope.res = "Key Exists"; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Check if a key exists in an object in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Object - {{obj1}}<br><br> Enter the key: <input type="text" ng-model="textval"> <br><br> <button ng-click="checkK()"> Check here</button> <br><br> {{res}}<br> </div> </div></body> </html>
Output:
Example 2:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.obj1 = { "Prop_1": 1, "Prop_2": 2, "Prop_3": 3 }; $scope.res = ''; $scope.textval = ""; $scope.checkK = function () { var txtVal = $scope.textval; if (!(txtVal in $scope.obj1)) { $scope.res = "Key not Exists."; } else { $scope.res = "Key Exists"; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Check if a key exists in an object in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Object - {{obj1}}<br><br> Enter the key: <input type="text" ng-model="textval"> <br><br> <button ng-click="checkK()"> Check here</button> <br><br> {{res}}<br> </div> </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.
AngularJS-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 25237,
"s": 25109,
"text": "Given an object containing (key, value) pair and the task is to check whether a key exists in an object or not using AngularJS."
},
{
"code": null,
"e": 25491,
"s": 25237,
"text": "Approach: The approach is to use the in operator to check whether a key exists in object or not. In first example the key “Prop_1” is input and it exists in the object. In the second example the user can check which key they want to check for existence."
},
{
"code": null,
"e": 25502,
"s": 25491,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.obj1 = { \"Prop_1\": 1, \"Prop_2\": 2, \"Prop_3\": 3 }; $scope.res = ''; $scope.textval = \"Prop_1\"; $scope.checkK = function () { var txtVal = $scope.textval; if (!(txtVal in $scope.obj1)) { $scope.res = \"Key not Exists.\"; } else { $scope.res = \"Key Exists\"; } } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Check if a key exists in an object in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Object - {{obj1}}<br><br> Enter the key: <input type=\"text\" ng-model=\"textval\"> <br><br> <button ng-click=\"checkK()\"> Check here</button> <br><br> {{res}}<br> </div> </div></body> </html> ",
"e": 26743,
"s": 25502,
"text": null
},
{
"code": null,
"e": 26751,
"s": 26743,
"text": "Output:"
},
{
"code": null,
"e": 26762,
"s": 26751,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.obj1 = { \"Prop_1\": 1, \"Prop_2\": 2, \"Prop_3\": 3 }; $scope.res = ''; $scope.textval = \"\"; $scope.checkK = function () { var txtVal = $scope.textval; if (!(txtVal in $scope.obj1)) { $scope.res = \"Key not Exists.\"; } else { $scope.res = \"Key Exists\"; } } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Check if a key exists in an object in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Object - {{obj1}}<br><br> Enter the key: <input type=\"text\" ng-model=\"textval\"> <br><br> <button ng-click=\"checkK()\"> Check here</button> <br><br> {{res}}<br> </div> </div></body> </html> ",
"e": 27999,
"s": 26762,
"text": null
},
{
"code": null,
"e": 28007,
"s": 27999,
"text": "Output:"
},
{
"code": null,
"e": 28144,
"s": 28007,
"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": 28159,
"s": 28144,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 28169,
"s": 28159,
"text": "AngularJS"
},
{
"code": null,
"e": 28174,
"s": 28169,
"text": "HTML"
},
{
"code": null,
"e": 28191,
"s": 28174,
"text": "Web Technologies"
},
{
"code": null,
"e": 28196,
"s": 28191,
"text": "HTML"
},
{
"code": null,
"e": 28294,
"s": 28196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28338,
"s": 28294,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28362,
"s": 28338,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28397,
"s": 28362,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28450,
"s": 28397,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28499,
"s": 28450,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 28561,
"s": 28499,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28611,
"s": 28561,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28671,
"s": 28611,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28719,
"s": 28671,
"text": "How to update Node.js and NPM to next version ?"
}
] |
\mapsto - Tex Command
|
\mapsto - Used to draw mapsto symbol.
{ \mapsto }
\mapsto command is used to draw mapsto symbol.
\mapsto
↦
\mapsto
↦
\mapsto
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8024,
"s": 7986,
"text": "\\mapsto - Used to draw mapsto symbol."
},
{
"code": null,
"e": 8036,
"s": 8024,
"text": "{ \\mapsto }"
},
{
"code": null,
"e": 8083,
"s": 8036,
"text": "\\mapsto command is used to draw mapsto symbol."
},
{
"code": null,
"e": 8098,
"s": 8083,
"text": "\n\\mapsto\n\n↦\n\n\n"
},
{
"code": null,
"e": 8111,
"s": 8098,
"text": "\\mapsto\n\n↦\n\n"
},
{
"code": null,
"e": 8119,
"s": 8111,
"text": "\\mapsto"
},
{
"code": null,
"e": 8151,
"s": 8119,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8164,
"s": 8151,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8197,
"s": 8164,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8210,
"s": 8197,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8242,
"s": 8210,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8278,
"s": 8242,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8313,
"s": 8278,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8330,
"s": 8313,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8363,
"s": 8330,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8377,
"s": 8363,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8409,
"s": 8377,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8424,
"s": 8409,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8431,
"s": 8424,
"text": " Print"
},
{
"code": null,
"e": 8442,
"s": 8431,
"text": " Add Notes"
}
] |
Topic Modeling in Python: Latent Dirichlet Allocation (LDA) | by Shashank Kapadia | Towards Data Science
|
Preface: This article aims to provide consolidated information on the underlying topic and is not to be considered as the original work. The information and the code are repurposed through several online articles, research papers, books, and open-source code
Topic Models, in a nutshell, are a type of statistical language models used for uncovering hidden structure in a collection of texts. In a practical and more intuitively, you can think of it as a task of:
Dimensionality Reduction, where rather than representing a text T in its feature space as {Word_i: count(Word_i, T) for Word_i in Vocabulary}, you can represent it in a topic space as {Topic_i: Weight(Topic_i, T) for Topic_i in Topics}
Unsupervised Learning, where it can be compared to clustering, as in the case of clustering, the number of topics, like the number of clusters, is an output parameter. By doing topic modeling, we build clusters of words rather than clusters of texts. A text is thus a mixture of all the topics, each having a specific weight
Tagging, abstract “topics” that occur in a collection of documents that best represents the information in them.
There are several existing algorithms you can use to perform the topic modeling. The most common of it are, Latent Semantic Analysis (LSA/LSI), Probabilistic Latent Semantic Analysis (pLSA), and Latent Dirichlet Allocation (LDA)
In this article, we’ll take a closer look at LDA, and implement our first topic model using the sklearn implementation in python 2.7
LDA is a generative probabilistic model that assumes each topic is a mixture over an underlying set of words, and each document is a mixture of over a set of topic probabilities.
We can describe the generative process of LDA as, given the M number of documents, N number of words, and prior K number of topics, the model trains to output:
psi, the distribution of words for each topic K
phi, the distribution of topics for each document i
Alpha parameter is Dirichlet prior concentration parameter that represents document-topic density — with a higher alpha, documents are assumed to be made up of more topics and result in more specific topic distribution per document.
Beta parameter is the same prior concentration parameter that represents topic-word density — with high beta, topics are assumed to made of up most of the words and result in a more specific word distribution per topic.
The complete code is available as a Jupyter Notebook on GitHub
Loading dataData cleaningExploratory analysisPreparing data for LDA analysisLDA model trainingAnalyzing LDA model results
Loading data
Data cleaning
Exploratory analysis
Preparing data for LDA analysis
LDA model training
Analyzing LDA model results
For this tutorial, we’ll use the dataset of papers published in NeurIPS (NIPS) conference which is one of the most prestigious yearly events in the machine learning community. The CSV data file contains information on the different NeurIPS papers that were published from 1987 until 2016 (29 years!). These papers discuss a wide variety of topics in machine learning, from neural networks to optimization methods, and many more.
Let’s start by looking at the content of the file
# Importing modulesimport pandas as pdimport osos.chdir('..')# Read data into paperspapers = pd.read_csv('./data/NIPS Papers/papers.csv')# Print headpapers.head()
Since the goal of this analysis is to perform topic modeling, let’s focus only on the text data from each paper, and drop other metadata columns. Also, for the demonstration, we’ll only look at 100 papers
# Remove the columnspapers = papers.drop(columns=['id', 'event_type', 'pdf_name'], axis=1).sample(100)# Print out the first rows of paperspapers.head()
Remove punctuation/lower casing
Next, let’s perform a simple preprocessing on the content of paper_text column to make them more amenable for analysis, and reliable results. To do that, we’ll use a regular expression to remove any punctuation, and then lowercase the text
# Load the regular expression libraryimport re# Remove punctuationpapers['paper_text_processed'] = \papers['paper_text'].map(lambda x: re.sub('[,\.!?]', '', x))# Convert the titles to lowercasepapers['paper_text_processed'] = \papers['paper_text_processed'].map(lambda x: x.lower())# Print out the first rows of paperspapers['paper_text_processed'].head()
To verify whether the preprocessing, we’ll make a word cloud using the wordcloud package to get a visual representation of most common words. It is key to understanding the data and ensuring we are on the right track, and if any more preprocessing is necessary before training the model.
# Import the wordcloud libraryfrom wordcloud import WordCloud# Join the different processed titles together.long_string = ','.join(list(papers['paper_text_processed'].values))# Create a WordCloud objectwordcloud = WordCloud(background_color="white", max_words=5000, contour_width=3, contour_color='steelblue')# Generate a word cloudwordcloud.generate(long_string)# Visualize the word cloudwordcloud.to_image()
Next, let’s work to transform the textual data in a format that will serve as an input for training LDA model. We start by tokenizing the text and removing stopwords. Next, we convert the tokenized object into a corpus and dictionary.
import gensimfrom gensim.utils import simple_preprocessimport nltknltk.download('stopwords')from nltk.corpus import stopwordsstop_words = stopwords.words('english')stop_words.extend(['from', 'subject', 're', 'edu', 'use'])def sent_to_words(sentences): for sentence in sentences: # deacc=True removes punctuations yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))def remove_stopwords(texts): return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]data = papers.paper_text_processed.values.tolist()data_words = list(sent_to_words(data))# remove stop wordsdata_words = remove_stopwords(data_words)print(data_words[:1][0][:30])
import gensim.corpora as corpora# Create Dictionaryid2word = corpora.Dictionary(data_words)# Create Corpustexts = data_words# Term Document Frequencycorpus = [id2word.doc2bow(text) for text in texts]# Viewprint(corpus[:1][0][:30])
To keep things simple, we’ll keep all the parameters to default except for inputting the number of topics. For this tutorial, we will build a model with 10 topics where each topic is a combination of keywords, and each keyword contributes a certain weightage to the topic.
from pprint import pprint# number of topicsnum_topics = 10# Build LDA modellda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=id2word, num_topics=num_topics)# Print the Keyword in the 10 topicspprint(lda_model.print_topics())doc_lda = lda_model[corpus]
Now that we have a trained model let’s visualize the topics for interpretability. To do so, we’ll use a popular visualization package, pyLDAvis which is designed to help interactively with:
Better understanding and interpreting individual topics, andBetter understanding the relationships between the topics.
Better understanding and interpreting individual topics, and
Better understanding the relationships between the topics.
For (1), you can manually select each topic to view its top most frequent and/or “relevant” terms, using different values of the λ parameter. This can help when you’re trying to assign a human interpretable name or “meaning” to each topic.
For (2), exploring the Intertopic Distance Plot can help you learn about how topics relate to each other, including potential higher-level structure between groups of topics.
import pyLDAvis.gensimimport pickle import pyLDAvis# Visualize the topicspyLDAvis.enable_notebook()LDAvis_data_filepath = os.path.join('./results/ldavis_prepared_'+str(num_topics))# # this is a bit time consuming - make the if statement True# # if you want to execute visualization prep yourselfif 1 == 1: LDAvis_prepared = pyLDAvis.gensim.prepare(lda_model, corpus, id2word) with open(LDAvis_data_filepath, 'wb') as f: pickle.dump(LDAvis_prepared, f)# load the pre-prepared pyLDAvis data from diskwith open(LDAvis_data_filepath, 'rb') as f: LDAvis_prepared = pickle.load(f)pyLDAvis.save_html(LDAvis_prepared, './results/ldavis_prepared_'+ str(num_topics) +'.html')LDAvis_prepared
Machine learning has become increasingly popular over the past decade, and recent advances in computational availability have led to exponential growth to people looking for ways how new methods can be incorporated to advance the field of Natural Language Processing.
Often, we treat topic models as black-box algorithms, but hopefully, this article addressed to shed light on the underlying math, and intuitions behind it, and high-level code to get you started with any textual data.
In the next article, we’ll go one step deeper into understanding how you can evaluate the performance of topic models, tune its hyper-parameters to get more intuitive and reliable results.
References:
[1] Topic model — Wikipedia. https://en.wikipedia.org/wiki/Topic_model
[2] Distributed Strategies for Topic Modeling. https://www.ideals.illinois.edu/bitstream/handle/2142/46405/ParallelTopicModels.pdf?sequence=2&isAllowed=y
[3] Topic Mapping — Software — Resources — Amaral Lab. https://amaral.northwestern.edu/resources/software/topic-mapping
[4] A Survey of Topic Modeling in Text Mining. https://thesai.org/Downloads/Volume6No1/Paper_21-A_Survey_of_Topic_Modeling_in_Text_Mining.pdf
Thanks for reading. If you have any feedback, please feel to reach out by commenting on this post, messaging me on LinkedIn, or shooting me an email (shmkapadia[at]gmail.com)
If you liked this article, visit my other articles on NLP
|
[
{
"code": null,
"e": 431,
"s": 172,
"text": "Preface: This article aims to provide consolidated information on the underlying topic and is not to be considered as the original work. The information and the code are repurposed through several online articles, research papers, books, and open-source code"
},
{
"code": null,
"e": 636,
"s": 431,
"text": "Topic Models, in a nutshell, are a type of statistical language models used for uncovering hidden structure in a collection of texts. In a practical and more intuitively, you can think of it as a task of:"
},
{
"code": null,
"e": 872,
"s": 636,
"text": "Dimensionality Reduction, where rather than representing a text T in its feature space as {Word_i: count(Word_i, T) for Word_i in Vocabulary}, you can represent it in a topic space as {Topic_i: Weight(Topic_i, T) for Topic_i in Topics}"
},
{
"code": null,
"e": 1197,
"s": 872,
"text": "Unsupervised Learning, where it can be compared to clustering, as in the case of clustering, the number of topics, like the number of clusters, is an output parameter. By doing topic modeling, we build clusters of words rather than clusters of texts. A text is thus a mixture of all the topics, each having a specific weight"
},
{
"code": null,
"e": 1310,
"s": 1197,
"text": "Tagging, abstract “topics” that occur in a collection of documents that best represents the information in them."
},
{
"code": null,
"e": 1539,
"s": 1310,
"text": "There are several existing algorithms you can use to perform the topic modeling. The most common of it are, Latent Semantic Analysis (LSA/LSI), Probabilistic Latent Semantic Analysis (pLSA), and Latent Dirichlet Allocation (LDA)"
},
{
"code": null,
"e": 1672,
"s": 1539,
"text": "In this article, we’ll take a closer look at LDA, and implement our first topic model using the sklearn implementation in python 2.7"
},
{
"code": null,
"e": 1851,
"s": 1672,
"text": "LDA is a generative probabilistic model that assumes each topic is a mixture over an underlying set of words, and each document is a mixture of over a set of topic probabilities."
},
{
"code": null,
"e": 2011,
"s": 1851,
"text": "We can describe the generative process of LDA as, given the M number of documents, N number of words, and prior K number of topics, the model trains to output:"
},
{
"code": null,
"e": 2059,
"s": 2011,
"text": "psi, the distribution of words for each topic K"
},
{
"code": null,
"e": 2111,
"s": 2059,
"text": "phi, the distribution of topics for each document i"
},
{
"code": null,
"e": 2344,
"s": 2111,
"text": "Alpha parameter is Dirichlet prior concentration parameter that represents document-topic density — with a higher alpha, documents are assumed to be made up of more topics and result in more specific topic distribution per document."
},
{
"code": null,
"e": 2564,
"s": 2344,
"text": "Beta parameter is the same prior concentration parameter that represents topic-word density — with high beta, topics are assumed to made of up most of the words and result in a more specific word distribution per topic."
},
{
"code": null,
"e": 2627,
"s": 2564,
"text": "The complete code is available as a Jupyter Notebook on GitHub"
},
{
"code": null,
"e": 2749,
"s": 2627,
"text": "Loading dataData cleaningExploratory analysisPreparing data for LDA analysisLDA model trainingAnalyzing LDA model results"
},
{
"code": null,
"e": 2762,
"s": 2749,
"text": "Loading data"
},
{
"code": null,
"e": 2776,
"s": 2762,
"text": "Data cleaning"
},
{
"code": null,
"e": 2797,
"s": 2776,
"text": "Exploratory analysis"
},
{
"code": null,
"e": 2829,
"s": 2797,
"text": "Preparing data for LDA analysis"
},
{
"code": null,
"e": 2848,
"s": 2829,
"text": "LDA model training"
},
{
"code": null,
"e": 2876,
"s": 2848,
"text": "Analyzing LDA model results"
},
{
"code": null,
"e": 3305,
"s": 2876,
"text": "For this tutorial, we’ll use the dataset of papers published in NeurIPS (NIPS) conference which is one of the most prestigious yearly events in the machine learning community. The CSV data file contains information on the different NeurIPS papers that were published from 1987 until 2016 (29 years!). These papers discuss a wide variety of topics in machine learning, from neural networks to optimization methods, and many more."
},
{
"code": null,
"e": 3355,
"s": 3305,
"text": "Let’s start by looking at the content of the file"
},
{
"code": null,
"e": 3518,
"s": 3355,
"text": "# Importing modulesimport pandas as pdimport osos.chdir('..')# Read data into paperspapers = pd.read_csv('./data/NIPS Papers/papers.csv')# Print headpapers.head()"
},
{
"code": null,
"e": 3723,
"s": 3518,
"text": "Since the goal of this analysis is to perform topic modeling, let’s focus only on the text data from each paper, and drop other metadata columns. Also, for the demonstration, we’ll only look at 100 papers"
},
{
"code": null,
"e": 3875,
"s": 3723,
"text": "# Remove the columnspapers = papers.drop(columns=['id', 'event_type', 'pdf_name'], axis=1).sample(100)# Print out the first rows of paperspapers.head()"
},
{
"code": null,
"e": 3907,
"s": 3875,
"text": "Remove punctuation/lower casing"
},
{
"code": null,
"e": 4147,
"s": 3907,
"text": "Next, let’s perform a simple preprocessing on the content of paper_text column to make them more amenable for analysis, and reliable results. To do that, we’ll use a regular expression to remove any punctuation, and then lowercase the text"
},
{
"code": null,
"e": 4503,
"s": 4147,
"text": "# Load the regular expression libraryimport re# Remove punctuationpapers['paper_text_processed'] = \\papers['paper_text'].map(lambda x: re.sub('[,\\.!?]', '', x))# Convert the titles to lowercasepapers['paper_text_processed'] = \\papers['paper_text_processed'].map(lambda x: x.lower())# Print out the first rows of paperspapers['paper_text_processed'].head()"
},
{
"code": null,
"e": 4791,
"s": 4503,
"text": "To verify whether the preprocessing, we’ll make a word cloud using the wordcloud package to get a visual representation of most common words. It is key to understanding the data and ensuring we are on the right track, and if any more preprocessing is necessary before training the model."
},
{
"code": null,
"e": 5201,
"s": 4791,
"text": "# Import the wordcloud libraryfrom wordcloud import WordCloud# Join the different processed titles together.long_string = ','.join(list(papers['paper_text_processed'].values))# Create a WordCloud objectwordcloud = WordCloud(background_color=\"white\", max_words=5000, contour_width=3, contour_color='steelblue')# Generate a word cloudwordcloud.generate(long_string)# Visualize the word cloudwordcloud.to_image()"
},
{
"code": null,
"e": 5436,
"s": 5201,
"text": "Next, let’s work to transform the textual data in a format that will serve as an input for training LDA model. We start by tokenizing the text and removing stopwords. Next, we convert the tokenized object into a corpus and dictionary."
},
{
"code": null,
"e": 6151,
"s": 5436,
"text": "import gensimfrom gensim.utils import simple_preprocessimport nltknltk.download('stopwords')from nltk.corpus import stopwordsstop_words = stopwords.words('english')stop_words.extend(['from', 'subject', 're', 'edu', 'use'])def sent_to_words(sentences): for sentence in sentences: # deacc=True removes punctuations yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))def remove_stopwords(texts): return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]data = papers.paper_text_processed.values.tolist()data_words = list(sent_to_words(data))# remove stop wordsdata_words = remove_stopwords(data_words)print(data_words[:1][0][:30])"
},
{
"code": null,
"e": 6382,
"s": 6151,
"text": "import gensim.corpora as corpora# Create Dictionaryid2word = corpora.Dictionary(data_words)# Create Corpustexts = data_words# Term Document Frequencycorpus = [id2word.doc2bow(text) for text in texts]# Viewprint(corpus[:1][0][:30])"
},
{
"code": null,
"e": 6655,
"s": 6382,
"text": "To keep things simple, we’ll keep all the parameters to default except for inputting the number of topics. For this tutorial, we will build a model with 10 topics where each topic is a combination of keywords, and each keyword contributes a certain weightage to the topic."
},
{
"code": null,
"e": 6995,
"s": 6655,
"text": "from pprint import pprint# number of topicsnum_topics = 10# Build LDA modellda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=id2word, num_topics=num_topics)# Print the Keyword in the 10 topicspprint(lda_model.print_topics())doc_lda = lda_model[corpus]"
},
{
"code": null,
"e": 7185,
"s": 6995,
"text": "Now that we have a trained model let’s visualize the topics for interpretability. To do so, we’ll use a popular visualization package, pyLDAvis which is designed to help interactively with:"
},
{
"code": null,
"e": 7304,
"s": 7185,
"text": "Better understanding and interpreting individual topics, andBetter understanding the relationships between the topics."
},
{
"code": null,
"e": 7365,
"s": 7304,
"text": "Better understanding and interpreting individual topics, and"
},
{
"code": null,
"e": 7424,
"s": 7365,
"text": "Better understanding the relationships between the topics."
},
{
"code": null,
"e": 7664,
"s": 7424,
"text": "For (1), you can manually select each topic to view its top most frequent and/or “relevant” terms, using different values of the λ parameter. This can help when you’re trying to assign a human interpretable name or “meaning” to each topic."
},
{
"code": null,
"e": 7839,
"s": 7664,
"text": "For (2), exploring the Intertopic Distance Plot can help you learn about how topics relate to each other, including potential higher-level structure between groups of topics."
},
{
"code": null,
"e": 8536,
"s": 7839,
"text": "import pyLDAvis.gensimimport pickle import pyLDAvis# Visualize the topicspyLDAvis.enable_notebook()LDAvis_data_filepath = os.path.join('./results/ldavis_prepared_'+str(num_topics))# # this is a bit time consuming - make the if statement True# # if you want to execute visualization prep yourselfif 1 == 1: LDAvis_prepared = pyLDAvis.gensim.prepare(lda_model, corpus, id2word) with open(LDAvis_data_filepath, 'wb') as f: pickle.dump(LDAvis_prepared, f)# load the pre-prepared pyLDAvis data from diskwith open(LDAvis_data_filepath, 'rb') as f: LDAvis_prepared = pickle.load(f)pyLDAvis.save_html(LDAvis_prepared, './results/ldavis_prepared_'+ str(num_topics) +'.html')LDAvis_prepared"
},
{
"code": null,
"e": 8804,
"s": 8536,
"text": "Machine learning has become increasingly popular over the past decade, and recent advances in computational availability have led to exponential growth to people looking for ways how new methods can be incorporated to advance the field of Natural Language Processing."
},
{
"code": null,
"e": 9022,
"s": 8804,
"text": "Often, we treat topic models as black-box algorithms, but hopefully, this article addressed to shed light on the underlying math, and intuitions behind it, and high-level code to get you started with any textual data."
},
{
"code": null,
"e": 9211,
"s": 9022,
"text": "In the next article, we’ll go one step deeper into understanding how you can evaluate the performance of topic models, tune its hyper-parameters to get more intuitive and reliable results."
},
{
"code": null,
"e": 9223,
"s": 9211,
"text": "References:"
},
{
"code": null,
"e": 9294,
"s": 9223,
"text": "[1] Topic model — Wikipedia. https://en.wikipedia.org/wiki/Topic_model"
},
{
"code": null,
"e": 9448,
"s": 9294,
"text": "[2] Distributed Strategies for Topic Modeling. https://www.ideals.illinois.edu/bitstream/handle/2142/46405/ParallelTopicModels.pdf?sequence=2&isAllowed=y"
},
{
"code": null,
"e": 9568,
"s": 9448,
"text": "[3] Topic Mapping — Software — Resources — Amaral Lab. https://amaral.northwestern.edu/resources/software/topic-mapping"
},
{
"code": null,
"e": 9710,
"s": 9568,
"text": "[4] A Survey of Topic Modeling in Text Mining. https://thesai.org/Downloads/Volume6No1/Paper_21-A_Survey_of_Topic_Modeling_in_Text_Mining.pdf"
},
{
"code": null,
"e": 9885,
"s": 9710,
"text": "Thanks for reading. If you have any feedback, please feel to reach out by commenting on this post, messaging me on LinkedIn, or shooting me an email (shmkapadia[at]gmail.com)"
}
] |
How to join tables using SQL to combine datasets | by Kate Marie Lewis | Towards Data Science
|
For the last 4 weeks my friends and I have been helping each other learn new skills while social distancing. We are learning data science as an online study group. We are nearly finished the SQL portion. I am so proud of everyone’s efforts and how willing they have been to have a go at something new.
In the last couple weeks my parents have even decided to give my lessons a go. They only have a few weeks to catch up on, so it will be interesting to hear what they think.
Last week we used data on the three albums released by the Spice Girls to determine which of the albums was the best. We did this using the GROUP BY keyword so that we could aggregate the statistics for each album.
Now that we know how to group and aggregate data in the table, this week we will learn how to join tables together.
It is helpful to be able to combine data sets. Particularly if there are different details in each table. By joining them together you are able to do some calculations. Alternatively, you can create a new table that contains all the different details together in one dataset.
To combine tables we will use the UNION, UNION ALL, INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN keywords.
use the keyword UNION to stack datasets without duplicate values
use the keyword UNION ALL to stack datasets with duplicate values
use the keyword INNER JOIN to join two tables together and only get the overlapping values
use the keyword LEFT OUTER JOIN to join two tables together and not loose any data from the left table, even those records that do not have a match in the right table
use the keyword RIGHT OUTER JOIN to join two tables together and not loose any data from the right table, even those records that do not have a match in the left table
understand the difference between the UNION and UNION ALL keywords
understand the difference between an INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN.
Everybody knows that Australia is full of dangerous animals. However, one of the lesser known predators is the magpie. This bird swoops down on unsuspecting victims, with sharp beaks well equiped to take out an eye. We want to find out how common magpie attacks are in each of the Australian states. Where do we have to wear protective headgear? 😜
To solve our problem we have several tables of data.
The first is a table contains the number of magpie attacks reported from each Australian state according to the website magpie alert. It is important to note that the data on this site is crowdsourced. People self-report when they have been swooped by a magpie. Therefore there may be some biases based on where the website is most popular.
Our second set of data is a table of dropbear attacks. Dropbears are another ferocious Australian animal. We can use this table as a comparison to the magpie attacks data.
Disclaimer: dropbears are not real and so the data is made up by me 😃
In addition to the two tables on animal attacks, we also have data on the Australian states that I got from Wikipedia. We can use this table to normalise our animal attack tables for population or area differences between the states.
The simplest way to combine two tables together is using the keywords UNION or UNION ALL. These two methods pile one lot of selected data on top of the other.
SELECT name_column_one, name_column_three FROM name_of_table_oneUNION SELECT name_column_one, name_column_three FROM name_of_table_two;
The difference between the two keywords is that UNION only takes distinct values, but UNION ALL keeps all of the values selected. Both are used with the same syntax.
SELECT name_column_one, name_column_three FROM name_of_table_oneUNION ALL SELECT name_column_one, name_column_three FROM name_of_table_two;
There are several different ways we can combine tables based on value matching. They include the INNER JOIN, FULL OUTER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN.
Available joins are slightly different in different versions of SQL language. We have been learning MySQL. Therefore we will focus only on the joins available in MySQL. INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN, but not FULL OUTER JOIN are the ones that may be used in MySQL.
If you would like to learn how to do a FULL OUTER JOIN that is covered in one of my other articles on the difference between inner and outer joins in SQL.
If you want to perform a join where you only include data where both tables contain matching values in a specified column, then you would use an INNER JOIN.
Inner joins return only the parts of two datasets that overlap. So that records will be returned only where there is a matching value in the column you are joining on in both tables. The syntax for an INNER JOIN is shown below:
SELECT *FROM name_of_table_oneINNER JOIN name_of_table_twoON name_of_table_one.name_column_one = name_of_table_two.name_column_one
In the example above, the records from table one and table two would both be returned, but only if the values in column one of table one match the values in column one of table two. Any records that do not have matching values would not be returned by an INNER JOIN.
One part of the join syntax that we have not come across in our lessons before, is referring to a column by both table and column name. This is important when joining tables because both tables could have a column with the same name. If you don’t include the table name when selecting columns with the same name, the program will not know which one you are referring to.
To avoid confusion, we use the table name and the column name separated by a full stop to create a unique identifier for each column.
To join two tables based on a column match without loosing any of the data from the left table, you would use a LEFT OUTER JOIN.
Left outer joins are used when you want to get all the values from one table but only the records that match the left table from the right table.
SELECT *FROM name_of_table_oneLEFT OUTER JOIN name_of_table_twoON name_of_table_one.name_column_one = name_of_table_two.name_column_one
In our LEFT OUTER JOIN example above, all rows from table one will be returned plus the rows that table two had in common with table one based on column one in each table.
The syntax for a RIGHT OUTER JOIN is the same as for a LEFT OUTER JOIN. The only difference between the two is that the right table, in our example table two, will retain all of its records. Whilst the left table, table one will only keep its records where there is a match between its column one and table two’s column one.
SELECT *FROM name_of_table_oneRIGHT OUTER JOIN name_of_table_twoON name_of_table_one.name_column_one = name_of_table_two.name_column_one
Go to https://www.db-fiddle.com/In the left hand column put the CREATE TABLE and INSERT INTO queries below
Go to https://www.db-fiddle.com/
In the left hand column put the CREATE TABLE and INSERT INTO queries below
CREATE TABLE magpie_attacks( state_code varchar(255), state_name varchar(255), animal varchar(255), number_of_attacks int(255));INSERT INTO magpie_attacks( state_code, state_name, animal, number_of_attacks)VALUES ('SA', 'South Australia', 'magpie', 154), ('VIC', 'Victoria', 'magpie', 972), ('TAS', 'Tasmania', 'magpie', 0), ('NSW', 'New South Whales', 'magpie', 823), ('QLD', 'Queensland', 'magpie', 1141), ('WA', 'Western Australia', 'magpie', 287), ('ACT', 'Australian Capital Territory', 'magpie', 668);CREATE TABLE dropbear_attacks( state_code varchar(255), state_name varchar(255), animal varchar(255), number_of_attacks int(255));INSERT INTO dropbear_attacks( state_code, state_name, animal, number_of_attacks)VALUES ('SA', 'South Australia', 'dropbear', 21), ('VIC', 'Victoria', 'dropbear', 67), ('TAS', 'Tasmania', 'dropbear', 30), ('NSW', 'New South Whales', 'dropbear', 19), ('QLD', 'Queensland', 'dropbear', 40), ('WA', 'Western Australia', 'dropbear', 37);CREATE TABLE australian_states( state_code varchar(255), state_name varchar(255), population int(255), area_km2 int(255));INSERT INTO australian_states( state_code, state_name, population, area_km2)VALUES ('SA', 'South Australia', 1751693, 1044353), ('VIC', 'Victoria', 6594804, 237657), ('TAS', 'Tasmania', 534281, 90758), ('NSW', 'New South Whales', 8089526, 809952), ('QLD', 'Queensland', 5095100, 1851736), ('WA', 'Western Australia', 2621680, 2642753), ('ACT', 'Australian Capital Territory', 426709, 2358), ('NT', 'Northern Territory', 245869, 1419630);
3. In the right hand column put your queries and run them using the ‘Run’ button in the top left
4. Run the query below and see if it returns what you would expect it to:
SELECT * FROM magpie_attacksUNION SELECT * FROM dropbear_attacks;
5. Run the query below and see if it returns what you would expect it to:
SELECT state_code, state_name FROM magpie_attacksUNION SELECT state_code, state_name FROM dropbear_attacks;
6. Run the query below and compare the results to what you got from the previous query:
SELECT state_code, state_name FROM magpie_attacksUNION ALL SELECT state_code, state_name FROM dropbear_attacks;
7. Run the query below and see if it returns what you would expect it to:
SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacksFROM magpie_attacksINNER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;
8. Run the query below and compare the results to the previous query:
SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacksFROM magpie_attacksLEFT OUTER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;
9. Run the query below and compare the results to the previous two queries:
SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacksFROM magpie_attacksRIGHT OUTER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;
10. Run the query below and compare the results to the previous two queries:
SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacks, dropbear_attacks.number_of_attacks / magpie_attacks.number_of_attacks * 100 AS 'dropbear_attacks_as_percentage_of_magpie_attacks'FROM magpie_attacksINNER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;
Exercise 1: Combine the magpie_attacks table and the australian_states table using each of the different union and join methods that we have learned in this lesson. Feel free to select as many or as few columns as you need to in order to make your queries run.
Exercise 2: Write a query to find out which Australian state has the greatest number of magpie attacks as a percentage of the population in that state. Hint: you can use the query in step 10 as a reference if needed.
After completing this lesson you should know:
how to use the keyword UNION to stack datasets without duplicate values
how to use the keyword UNION ALL to stack datasets with duplicate values
how to use the keyword INNER JOIN to join two tables together and only get the overlapping values
how to use the keyword LEFT OUTER JOIN to join two tables together and not loose any data from the left table that does not have a match in the right table
how to use the keyword RIGHT OUTER JOIN to join two tables together and not loose any data from the right table that does not have a match in the left table
understand the difference between the UNION and UNION ALL KEYWORDS
understand the difference between an INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN.
Next lesson will be a review of all we have learned in the last 5 lessons on SQL. I always think it is a good idea to practice new skills to consolidate the lessons. Hopefully the review lesson will also let us use all the skills learned over the lessons in a more independent way. Up till now the exercises have been fairly similar to the examples that preceded them. However, I am hoping that part of what we will learn next lesson is how to choose what methods to use in order to solve the problems.
In addition to data, my other passion is painting. You can find my wildlife art at www.katemarielewis.com
|
[
{
"code": null,
"e": 474,
"s": 172,
"text": "For the last 4 weeks my friends and I have been helping each other learn new skills while social distancing. We are learning data science as an online study group. We are nearly finished the SQL portion. I am so proud of everyone’s efforts and how willing they have been to have a go at something new."
},
{
"code": null,
"e": 647,
"s": 474,
"text": "In the last couple weeks my parents have even decided to give my lessons a go. They only have a few weeks to catch up on, so it will be interesting to hear what they think."
},
{
"code": null,
"e": 862,
"s": 647,
"text": "Last week we used data on the three albums released by the Spice Girls to determine which of the albums was the best. We did this using the GROUP BY keyword so that we could aggregate the statistics for each album."
},
{
"code": null,
"e": 978,
"s": 862,
"text": "Now that we know how to group and aggregate data in the table, this week we will learn how to join tables together."
},
{
"code": null,
"e": 1254,
"s": 978,
"text": "It is helpful to be able to combine data sets. Particularly if there are different details in each table. By joining them together you are able to do some calculations. Alternatively, you can create a new table that contains all the different details together in one dataset."
},
{
"code": null,
"e": 1365,
"s": 1254,
"text": "To combine tables we will use the UNION, UNION ALL, INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN keywords."
},
{
"code": null,
"e": 1430,
"s": 1365,
"text": "use the keyword UNION to stack datasets without duplicate values"
},
{
"code": null,
"e": 1496,
"s": 1430,
"text": "use the keyword UNION ALL to stack datasets with duplicate values"
},
{
"code": null,
"e": 1587,
"s": 1496,
"text": "use the keyword INNER JOIN to join two tables together and only get the overlapping values"
},
{
"code": null,
"e": 1754,
"s": 1587,
"text": "use the keyword LEFT OUTER JOIN to join two tables together and not loose any data from the left table, even those records that do not have a match in the right table"
},
{
"code": null,
"e": 1922,
"s": 1754,
"text": "use the keyword RIGHT OUTER JOIN to join two tables together and not loose any data from the right table, even those records that do not have a match in the left table"
},
{
"code": null,
"e": 1989,
"s": 1922,
"text": "understand the difference between the UNION and UNION ALL keywords"
},
{
"code": null,
"e": 2076,
"s": 1989,
"text": "understand the difference between an INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN."
},
{
"code": null,
"e": 2424,
"s": 2076,
"text": "Everybody knows that Australia is full of dangerous animals. However, one of the lesser known predators is the magpie. This bird swoops down on unsuspecting victims, with sharp beaks well equiped to take out an eye. We want to find out how common magpie attacks are in each of the Australian states. Where do we have to wear protective headgear? 😜"
},
{
"code": null,
"e": 2477,
"s": 2424,
"text": "To solve our problem we have several tables of data."
},
{
"code": null,
"e": 2818,
"s": 2477,
"text": "The first is a table contains the number of magpie attacks reported from each Australian state according to the website magpie alert. It is important to note that the data on this site is crowdsourced. People self-report when they have been swooped by a magpie. Therefore there may be some biases based on where the website is most popular."
},
{
"code": null,
"e": 2990,
"s": 2818,
"text": "Our second set of data is a table of dropbear attacks. Dropbears are another ferocious Australian animal. We can use this table as a comparison to the magpie attacks data."
},
{
"code": null,
"e": 3060,
"s": 2990,
"text": "Disclaimer: dropbears are not real and so the data is made up by me 😃"
},
{
"code": null,
"e": 3294,
"s": 3060,
"text": "In addition to the two tables on animal attacks, we also have data on the Australian states that I got from Wikipedia. We can use this table to normalise our animal attack tables for population or area differences between the states."
},
{
"code": null,
"e": 3453,
"s": 3294,
"text": "The simplest way to combine two tables together is using the keywords UNION or UNION ALL. These two methods pile one lot of selected data on top of the other."
},
{
"code": null,
"e": 3647,
"s": 3453,
"text": " SELECT name_column_one, name_column_three FROM name_of_table_oneUNION SELECT name_column_one, name_column_three FROM name_of_table_two;"
},
{
"code": null,
"e": 3813,
"s": 3647,
"text": "The difference between the two keywords is that UNION only takes distinct values, but UNION ALL keeps all of the values selected. Both are used with the same syntax."
},
{
"code": null,
"e": 4011,
"s": 3813,
"text": " SELECT name_column_one, name_column_three FROM name_of_table_oneUNION ALL SELECT name_column_one, name_column_three FROM name_of_table_two;"
},
{
"code": null,
"e": 4175,
"s": 4011,
"text": "There are several different ways we can combine tables based on value matching. They include the INNER JOIN, FULL OUTER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN."
},
{
"code": null,
"e": 4458,
"s": 4175,
"text": "Available joins are slightly different in different versions of SQL language. We have been learning MySQL. Therefore we will focus only on the joins available in MySQL. INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN, but not FULL OUTER JOIN are the ones that may be used in MySQL."
},
{
"code": null,
"e": 4613,
"s": 4458,
"text": "If you would like to learn how to do a FULL OUTER JOIN that is covered in one of my other articles on the difference between inner and outer joins in SQL."
},
{
"code": null,
"e": 4770,
"s": 4613,
"text": "If you want to perform a join where you only include data where both tables contain matching values in a specified column, then you would use an INNER JOIN."
},
{
"code": null,
"e": 4998,
"s": 4770,
"text": "Inner joins return only the parts of two datasets that overlap. So that records will be returned only where there is a matching value in the column you are joining on in both tables. The syntax for an INNER JOIN is shown below:"
},
{
"code": null,
"e": 5138,
"s": 4998,
"text": "SELECT *FROM name_of_table_oneINNER JOIN name_of_table_twoON name_of_table_one.name_column_one = name_of_table_two.name_column_one"
},
{
"code": null,
"e": 5405,
"s": 5138,
"text": "In the example above, the records from table one and table two would both be returned, but only if the values in column one of table one match the values in column one of table two. Any records that do not have matching values would not be returned by an INNER JOIN."
},
{
"code": null,
"e": 5776,
"s": 5405,
"text": "One part of the join syntax that we have not come across in our lessons before, is referring to a column by both table and column name. This is important when joining tables because both tables could have a column with the same name. If you don’t include the table name when selecting columns with the same name, the program will not know which one you are referring to."
},
{
"code": null,
"e": 5910,
"s": 5776,
"text": "To avoid confusion, we use the table name and the column name separated by a full stop to create a unique identifier for each column."
},
{
"code": null,
"e": 6039,
"s": 5910,
"text": "To join two tables based on a column match without loosing any of the data from the left table, you would use a LEFT OUTER JOIN."
},
{
"code": null,
"e": 6185,
"s": 6039,
"text": "Left outer joins are used when you want to get all the values from one table but only the records that match the left table from the right table."
},
{
"code": null,
"e": 6330,
"s": 6185,
"text": "SELECT *FROM name_of_table_oneLEFT OUTER JOIN name_of_table_twoON name_of_table_one.name_column_one = name_of_table_two.name_column_one"
},
{
"code": null,
"e": 6502,
"s": 6330,
"text": "In our LEFT OUTER JOIN example above, all rows from table one will be returned plus the rows that table two had in common with table one based on column one in each table."
},
{
"code": null,
"e": 6827,
"s": 6502,
"text": "The syntax for a RIGHT OUTER JOIN is the same as for a LEFT OUTER JOIN. The only difference between the two is that the right table, in our example table two, will retain all of its records. Whilst the left table, table one will only keep its records where there is a match between its column one and table two’s column one."
},
{
"code": null,
"e": 6973,
"s": 6827,
"text": "SELECT *FROM name_of_table_oneRIGHT OUTER JOIN name_of_table_twoON name_of_table_one.name_column_one = name_of_table_two.name_column_one"
},
{
"code": null,
"e": 7080,
"s": 6973,
"text": "Go to https://www.db-fiddle.com/In the left hand column put the CREATE TABLE and INSERT INTO queries below"
},
{
"code": null,
"e": 7113,
"s": 7080,
"text": "Go to https://www.db-fiddle.com/"
},
{
"code": null,
"e": 7188,
"s": 7113,
"text": "In the left hand column put the CREATE TABLE and INSERT INTO queries below"
},
{
"code": null,
"e": 8852,
"s": 7188,
"text": "CREATE TABLE magpie_attacks( state_code varchar(255), state_name varchar(255), animal varchar(255), number_of_attacks int(255));INSERT INTO magpie_attacks( state_code, state_name, animal, number_of_attacks)VALUES ('SA', 'South Australia', 'magpie', 154), ('VIC', 'Victoria', 'magpie', 972), ('TAS', 'Tasmania', 'magpie', 0), ('NSW', 'New South Whales', 'magpie', 823), ('QLD', 'Queensland', 'magpie', 1141), ('WA', 'Western Australia', 'magpie', 287), ('ACT', 'Australian Capital Territory', 'magpie', 668);CREATE TABLE dropbear_attacks( state_code varchar(255), state_name varchar(255), animal varchar(255), number_of_attacks int(255));INSERT INTO dropbear_attacks( state_code, state_name, animal, number_of_attacks)VALUES ('SA', 'South Australia', 'dropbear', 21), ('VIC', 'Victoria', 'dropbear', 67), ('TAS', 'Tasmania', 'dropbear', 30), ('NSW', 'New South Whales', 'dropbear', 19), ('QLD', 'Queensland', 'dropbear', 40), ('WA', 'Western Australia', 'dropbear', 37);CREATE TABLE australian_states( state_code varchar(255), state_name varchar(255), population int(255), area_km2 int(255));INSERT INTO australian_states( state_code, state_name, population, area_km2)VALUES ('SA', 'South Australia', 1751693, 1044353), ('VIC', 'Victoria', 6594804, 237657), ('TAS', 'Tasmania', 534281, 90758), ('NSW', 'New South Whales', 8089526, 809952), ('QLD', 'Queensland', 5095100, 1851736), ('WA', 'Western Australia', 2621680, 2642753), ('ACT', 'Australian Capital Territory', 426709, 2358), ('NT', 'Northern Territory', 245869, 1419630);"
},
{
"code": null,
"e": 8949,
"s": 8852,
"text": "3. In the right hand column put your queries and run them using the ‘Run’ button in the top left"
},
{
"code": null,
"e": 9023,
"s": 8949,
"text": "4. Run the query below and see if it returns what you would expect it to:"
},
{
"code": null,
"e": 9134,
"s": 9023,
"text": " SELECT * FROM magpie_attacksUNION SELECT * FROM dropbear_attacks;"
},
{
"code": null,
"e": 9208,
"s": 9134,
"text": "5. Run the query below and see if it returns what you would expect it to:"
},
{
"code": null,
"e": 9376,
"s": 9208,
"text": " SELECT state_code, state_name FROM magpie_attacksUNION SELECT state_code, state_name FROM dropbear_attacks;"
},
{
"code": null,
"e": 9464,
"s": 9376,
"text": "6. Run the query below and compare the results to what you got from the previous query:"
},
{
"code": null,
"e": 9636,
"s": 9464,
"text": " SELECT state_code, state_name FROM magpie_attacksUNION ALL SELECT state_code, state_name FROM dropbear_attacks;"
},
{
"code": null,
"e": 9710,
"s": 9636,
"text": "7. Run the query below and see if it returns what you would expect it to:"
},
{
"code": null,
"e": 9976,
"s": 9710,
"text": "SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacksFROM magpie_attacksINNER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;"
},
{
"code": null,
"e": 10046,
"s": 9976,
"text": "8. Run the query below and compare the results to the previous query:"
},
{
"code": null,
"e": 10317,
"s": 10046,
"text": "SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacksFROM magpie_attacksLEFT OUTER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;"
},
{
"code": null,
"e": 10393,
"s": 10317,
"text": "9. Run the query below and compare the results to the previous two queries:"
},
{
"code": null,
"e": 10665,
"s": 10393,
"text": "SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacksFROM magpie_attacksRIGHT OUTER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;"
},
{
"code": null,
"e": 10742,
"s": 10665,
"text": "10. Run the query below and compare the results to the previous two queries:"
},
{
"code": null,
"e": 11144,
"s": 10742,
"text": "SELECT magpie_attacks.state_code, magpie_attacks.number_of_attacks AS magpie_attacks, dropbear_attacks.number_of_attacks AS dropbear_attacks, dropbear_attacks.number_of_attacks / magpie_attacks.number_of_attacks * 100 AS 'dropbear_attacks_as_percentage_of_magpie_attacks'FROM magpie_attacksINNER JOIN dropbear_attacksON magpie_attacks.state_code = dropbear_attacks.state_code;"
},
{
"code": null,
"e": 11405,
"s": 11144,
"text": "Exercise 1: Combine the magpie_attacks table and the australian_states table using each of the different union and join methods that we have learned in this lesson. Feel free to select as many or as few columns as you need to in order to make your queries run."
},
{
"code": null,
"e": 11622,
"s": 11405,
"text": "Exercise 2: Write a query to find out which Australian state has the greatest number of magpie attacks as a percentage of the population in that state. Hint: you can use the query in step 10 as a reference if needed."
},
{
"code": null,
"e": 11668,
"s": 11622,
"text": "After completing this lesson you should know:"
},
{
"code": null,
"e": 11740,
"s": 11668,
"text": "how to use the keyword UNION to stack datasets without duplicate values"
},
{
"code": null,
"e": 11813,
"s": 11740,
"text": "how to use the keyword UNION ALL to stack datasets with duplicate values"
},
{
"code": null,
"e": 11911,
"s": 11813,
"text": "how to use the keyword INNER JOIN to join two tables together and only get the overlapping values"
},
{
"code": null,
"e": 12067,
"s": 11911,
"text": "how to use the keyword LEFT OUTER JOIN to join two tables together and not loose any data from the left table that does not have a match in the right table"
},
{
"code": null,
"e": 12224,
"s": 12067,
"text": "how to use the keyword RIGHT OUTER JOIN to join two tables together and not loose any data from the right table that does not have a match in the left table"
},
{
"code": null,
"e": 12291,
"s": 12224,
"text": "understand the difference between the UNION and UNION ALL KEYWORDS"
},
{
"code": null,
"e": 12378,
"s": 12291,
"text": "understand the difference between an INNER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN."
},
{
"code": null,
"e": 12881,
"s": 12378,
"text": "Next lesson will be a review of all we have learned in the last 5 lessons on SQL. I always think it is a good idea to practice new skills to consolidate the lessons. Hopefully the review lesson will also let us use all the skills learned over the lessons in a more independent way. Up till now the exercises have been fairly similar to the examples that preceded them. However, I am hoping that part of what we will learn next lesson is how to choose what methods to use in order to solve the problems."
}
] |
How to replace values of a Python dictionary?
|
You can assign a dictionary value to a variable in Python using the access operator []. For example,
my_dict = {
'foo': 42,
'bar': 12.5
}
new_var = my_dict['foo']
print(new_var)
This will give the output −
42
This syntax can also be used to reassign the value associated with this key. For example,
my_dict = {
'foo': 42,
'bar': 12.5
}
my_dict['foo'] = "Hello"
print(my_dict['foo'])
This will give the output −
Hello
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "You can assign a dictionary value to a variable in Python using the access operator []. For example,"
},
{
"code": null,
"e": 1246,
"s": 1163,
"text": "my_dict = {\n 'foo': 42,\n 'bar': 12.5\n}\nnew_var = my_dict['foo']\nprint(new_var)"
},
{
"code": null,
"e": 1274,
"s": 1246,
"text": "This will give the output −"
},
{
"code": null,
"e": 1277,
"s": 1274,
"text": "42"
},
{
"code": null,
"e": 1367,
"s": 1277,
"text": "This syntax can also be used to reassign the value associated with this key. For example,"
},
{
"code": null,
"e": 1461,
"s": 1367,
"text": "my_dict = {\n 'foo': 42,\n 'bar': 12.5\n}\nmy_dict['foo'] = \"Hello\"\nprint(my_dict['foo'])"
},
{
"code": null,
"e": 1489,
"s": 1461,
"text": "This will give the output −"
},
{
"code": null,
"e": 1495,
"s": 1489,
"text": "Hello"
}
] |
How to disable action bar permanently in Android?
|
This example demonstrate about How to disable action bar permanently in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.java
<? xml version= "1.0" encoding= "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :orientation= "vertical"
tools :context= ".MainActivity" >
<TextView
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :layout_centerInParent= "true"
android :gravity= "center"
android :text= "No Action Bar"
android :textAppearance= "@style/Base.TextAppearance.AppCompat.Large" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
}
}
Step 4 − Add the following code to res/values/styles.xml
<resources>
<!-- Base application theme. -->
<style name= "AppTheme" parent= "Theme.AppCompat.Light.DarkActionBar" >
<!-- Customize your theme here. -->
<item name= "colorPrimary" > @color/colorPrimary </item>
<item name= "colorPrimaryDark" > @color/colorPrimaryDark </item>
<item name= "colorAccent" > @color/colorAccent </item>
</style>
<style name= "AppTheme.NoActionBar" >
<item name= "windowActionBar" > false </item>
<item name= "windowNoTitle" > true </item>
</style>
</resources>
Step 5 − 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= "app.tutorialspoint.com.sample" >
<uses-permission android :name= "android.permission.VIBRATE" />
<application
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android:label= "@string/app_name"
android:roundIcon= "@mipmap/ic_launcher_round"
android:supportsRtl= "true"
android:theme= "@style/AppTheme" >
<activity android:name= ".MainActivity" >
<intent-filter>
<action android:name= "android.intent.action.MAIN" />
<category android:name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "This example demonstrate about How to disable action bar permanently in Android."
},
{
"code": null,
"e": 1272,
"s": 1143,
"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": 1337,
"s": 1272,
"text": "Step 2 − Add the following code to res/layout/activity_main.java"
},
{
"code": null,
"e": 1981,
"s": 1337,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :orientation= \"vertical\"\n tools :context= \".MainActivity\" >\n <TextView\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :layout_centerInParent= \"true\"\n android :gravity= \"center\"\n android :text= \"No Action Bar\"\n android :textAppearance= \"@style/Base.TextAppearance.AppCompat.Large\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2038,
"s": 1981,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2379,
"s": 2038,
"text": "package app.tutorialspoint.com.sample ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n}"
},
{
"code": null,
"e": 2436,
"s": 2379,
"text": "Step 4 − Add the following code to res/values/styles.xml"
},
{
"code": null,
"e": 2975,
"s": 2436,
"text": "<resources>\n <!-- Base application theme. -->\n <style name= \"AppTheme\" parent= \"Theme.AppCompat.Light.DarkActionBar\" >\n <!-- Customize your theme here. -->\n <item name= \"colorPrimary\" > @color/colorPrimary </item>\n <item name= \"colorPrimaryDark\" > @color/colorPrimaryDark </item>\n <item name= \"colorAccent\" > @color/colorAccent </item>\n </style>\n <style name= \"AppTheme.NoActionBar\" >\n <item name= \"windowActionBar\" > false </item>\n <item name= \"windowNoTitle\" > true </item>\n </style>\n</resources>"
},
{
"code": null,
"e": 3030,
"s": 2975,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3807,
"s": 3030,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.VIBRATE\" />\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": 4154,
"s": 3807,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
Sorting algorithm visualization : Heap Sort - GeeksforGeeks
|
28 Dec, 2021
An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented.
The Graphical User Interface(GUI) is implemented in Python using pygame library.
Generate random array and fill the pygame window with bars. Bars are straight vertical lines, which represents array elements.
Set all bars to green color (unsorted).
Heapify the array to perform sorting.
After Heapify, large bars are at the beginning followed by smaller bars.
Use pygame.time.delay() to slow down the algorithm, so that we can see the sorting process.
Implement a timer to see how the algorithm performs.
The actions are performed using ‘pygame.event.get()’ method, which stores all the events which user performs, such as start, reset.
Blue color is used to highlight bars that are involved in sorting at a particular time.
Orange color highlights the bars sorted.
We can clearly see from the Heap Sort visualization, that Heap Sort is very fast compared to other sorting algorithms like Insertion sort or Selection sort and similar in speed with Merge sort.
Press “Enter” key to Perform Visualization.
Press “R” key to generate new array.
Please make sure to install the pygame library before running the below program.
Below is the implementation of the above visualizer:
Python3
# Python implementation of the
# Sorting visualiser: Heap Sort
# Imports
import pygame
import random
import time
pygame.font.init()
startTime = time.time()
# Total window
screen = pygame.display.set_mode(
(900, 650)
)
# Title and Icon
pygame.display.set_caption(
"SORTING VISUALISER"
)
# Uncomment below lines for setting
# up the icon for the visuliser
# img = pygame.image.load('sorticon.png')
# pygame.display.set_icon(img)
# Boolean variable to run
# the program in while loop
run = True
# Window size and some initials
width = 900
length = 600
array = [0]*151
arr_clr = [(0, 204, 102)]*151
clr_ind = 0
clr = [(0, 204, 102), (255, 0, 0),
(0, 0, 153), (255, 102, 0)]
fnt = pygame.font.SysFont("comicsans", 30)
fnt1 = pygame.font.SysFont("comicsans", 20)
# Function to generate new Array
def generate_arr():
for i in range(1, 151):
arr_clr[i] = clr[0]
array[i] = random.randrange(1, 100)
# Initially generate a array
generate_arr()
# Function to refill the
# updates on the window
def refill():
screen.fill((255, 255, 255))
draw()
pygame.display.update()
pygame.time.delay(10)
# Sorting Algorithm: Heap Sort
def heapSort(array):
n = len(array)
for i in range(n//2-1, -1, -1):
pygame.event.pump()
heapify(array, i, n)
for i in range(n-1, 0, -1):
array[i], array[0] = array[0], array[i]
arr_clr[i] = clr[1]
refill()
heapify(array, 0, i)
def heapify(array, root, size):
left = root * 2 + 1
right = root * 2 + 2
largest = root
if left < size and array[left] > array[largest]:
largest = left
if right < size and array[right] > array[largest]:
largest = right
if largest != root:
arr_clr[largest] = clr[2]
arr_clr[root] = clr[2]
array[largest],\
array[root] = array[root],\
array[largest]
refill()
arr_clr[largest] = clr[0]
arr_clr[root] = clr[0]
heapify(array, largest, size)
refill()
# Function to Draw the array values
def draw():
# Text should be rendered
txt = fnt.render("SORT: PRESS 'ENTER'",
1, (0, 0, 0))
# Position where text is placed
screen.blit(txt, (20, 20))
txt1 = fnt.render("NEW ARRAY: PRESS 'R'",
1, (0, 0, 0))
screen.blit(txt1, (20, 40))
txt2 = fnt1.render("ALGORITHM USED:" +
"HEAP SORT", 1, (0, 0, 0))
screen.blit(txt2, (600, 60))
text3 = fnt1.render("Running Time(sec): " +
str(int(time.time() - startTime)),
1, (0, 0, 0))
screen.blit(text3, (600, 20))
element_width = (width-150)//150
boundry_arr = 900 / 150
boundry_grp = 550 / 100
pygame.draw.line(screen, (0, 0, 0), (0, 95),
(900, 95), 6)
# Drawing the array values as lines
for i in range(1, 151):
pygame.draw.line(screen, arr_clr[i],
(boundry_arr * i-3, 100),
(boundry_arr * i-3,
array[i]*boundry_grp + 100),\
element_width)
# Program should be run
# continuously to keep the window open
while run:
# background
screen.fill((255, 255, 255))
# Event handler stores all event
for event in pygame.event.get():
# If we click Close button in window
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
generate_arr()
if event.key == pygame.K_RETURN:
heapSort(array)
draw()
pygame.display.update()
pygame.quit()
amartyaghoshgfg
Data Visualization
Heap Sort
Python-gui
Python-PyGame
Algorithms
Analysis
Heap
Project
Python
Python Programs
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
Difference between Informed and Uninformed Search in AI
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
K means Clustering - Introduction
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Practice Questions on Time Complexity Analysis
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Analysis of Algorithms | Set 3 (Asymptotic Notations)
|
[
{
"code": null,
"e": 24347,
"s": 24316,
"text": " \n28 Dec, 2021\n"
},
{
"code": null,
"e": 24505,
"s": 24347,
"text": "An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented."
},
{
"code": null,
"e": 24586,
"s": 24505,
"text": "The Graphical User Interface(GUI) is implemented in Python using pygame library."
},
{
"code": null,
"e": 24713,
"s": 24586,
"text": "Generate random array and fill the pygame window with bars. Bars are straight vertical lines, which represents array elements."
},
{
"code": null,
"e": 24753,
"s": 24713,
"text": "Set all bars to green color (unsorted)."
},
{
"code": null,
"e": 24791,
"s": 24753,
"text": "Heapify the array to perform sorting."
},
{
"code": null,
"e": 24864,
"s": 24791,
"text": "After Heapify, large bars are at the beginning followed by smaller bars."
},
{
"code": null,
"e": 24956,
"s": 24864,
"text": "Use pygame.time.delay() to slow down the algorithm, so that we can see the sorting process."
},
{
"code": null,
"e": 25009,
"s": 24956,
"text": "Implement a timer to see how the algorithm performs."
},
{
"code": null,
"e": 25141,
"s": 25009,
"text": "The actions are performed using ‘pygame.event.get()’ method, which stores all the events which user performs, such as start, reset."
},
{
"code": null,
"e": 25229,
"s": 25141,
"text": "Blue color is used to highlight bars that are involved in sorting at a particular time."
},
{
"code": null,
"e": 25270,
"s": 25229,
"text": "Orange color highlights the bars sorted."
},
{
"code": null,
"e": 25464,
"s": 25270,
"text": "We can clearly see from the Heap Sort visualization, that Heap Sort is very fast compared to other sorting algorithms like Insertion sort or Selection sort and similar in speed with Merge sort."
},
{
"code": null,
"e": 25508,
"s": 25464,
"text": "Press “Enter” key to Perform Visualization."
},
{
"code": null,
"e": 25545,
"s": 25508,
"text": "Press “R” key to generate new array."
},
{
"code": null,
"e": 25626,
"s": 25545,
"text": "Please make sure to install the pygame library before running the below program."
},
{
"code": null,
"e": 25679,
"s": 25626,
"text": "Below is the implementation of the above visualizer:"
},
{
"code": null,
"e": 25687,
"s": 25679,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Python implementation of the\n# Sorting visualiser: Heap Sort\n \n# Imports\nimport pygame\nimport random\nimport time\npygame.font.init()\nstartTime = time.time()\n \n# Total window\nscreen = pygame.display.set_mode(\n (900, 650)\n)\n \n# Title and Icon\npygame.display.set_caption(\n \"SORTING VISUALISER\"\n)\n \n# Uncomment below lines for setting\n# up the icon for the visuliser\n# img = pygame.image.load('sorticon.png')\n# pygame.display.set_icon(img)\n \n# Boolean variable to run\n# the program in while loop\nrun = True\n \n# Window size and some initials\nwidth = 900\nlength = 600\narray = [0]*151\narr_clr = [(0, 204, 102)]*151\nclr_ind = 0\nclr = [(0, 204, 102), (255, 0, 0),\n (0, 0, 153), (255, 102, 0)]\nfnt = pygame.font.SysFont(\"comicsans\", 30)\nfnt1 = pygame.font.SysFont(\"comicsans\", 20)\n \n# Function to generate new Array\ndef generate_arr():\n for i in range(1, 151):\n arr_clr[i] = clr[0]\n array[i] = random.randrange(1, 100)\n \n \n# Initially generate a array\ngenerate_arr()\n \n# Function to refill the\n# updates on the window\ndef refill():\n screen.fill((255, 255, 255))\n draw()\n pygame.display.update()\n pygame.time.delay(10)\n \n \n# Sorting Algorithm: Heap Sort\ndef heapSort(array):\n n = len(array)\n for i in range(n//2-1, -1, -1):\n pygame.event.pump()\n heapify(array, i, n)\n for i in range(n-1, 0, -1):\n array[i], array[0] = array[0], array[i]\n arr_clr[i] = clr[1]\n refill()\n heapify(array, 0, i)\n \n \ndef heapify(array, root, size):\n left = root * 2 + 1\n right = root * 2 + 2\n largest = root\n if left < size and array[left] > array[largest]:\n largest = left\n if right < size and array[right] > array[largest]:\n largest = right\n if largest != root:\n arr_clr[largest] = clr[2]\n arr_clr[root] = clr[2]\n array[largest],\\\n array[root] = array[root],\\\n array[largest]\n refill()\n arr_clr[largest] = clr[0]\n arr_clr[root] = clr[0]\n heapify(array, largest, size)\n refill()\n \n# Function to Draw the array values\ndef draw():\n \n # Text should be rendered\n txt = fnt.render(\"SORT: PRESS 'ENTER'\",\n 1, (0, 0, 0))\n # Position where text is placed\n screen.blit(txt, (20, 20))\n txt1 = fnt.render(\"NEW ARRAY: PRESS 'R'\",\n 1, (0, 0, 0))\n screen.blit(txt1, (20, 40))\n txt2 = fnt1.render(\"ALGORITHM USED:\" +\n \"HEAP SORT\", 1, (0, 0, 0))\n screen.blit(txt2, (600, 60))\n text3 = fnt1.render(\"Running Time(sec): \" +\n str(int(time.time() - startTime)),\n 1, (0, 0, 0))\n screen.blit(text3, (600, 20))\n element_width = (width-150)//150\n boundry_arr = 900 / 150\n boundry_grp = 550 / 100\n pygame.draw.line(screen, (0, 0, 0), (0, 95),\n (900, 95), 6)\n \n # Drawing the array values as lines\n for i in range(1, 151):\n pygame.draw.line(screen, arr_clr[i],\n (boundry_arr * i-3, 100),\n (boundry_arr * i-3,\n array[i]*boundry_grp + 100),\\\n element_width)\n \n \n# Program should be run\n# continuously to keep the window open\nwhile run:\n # background\n screen.fill((255, 255, 255))\n \n # Event handler stores all event\n for event in pygame.event.get():\n \n # If we click Close button in window\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n generate_arr()\n if event.key == pygame.K_RETURN:\n heapSort(array)\n draw()\n pygame.display.update()\n \npygame.quit()\n\n\n\n\n\n",
"e": 29439,
"s": 25697,
"text": null
},
{
"code": null,
"e": 29455,
"s": 29439,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 29476,
"s": 29455,
"text": "\nData Visualization\n"
},
{
"code": null,
"e": 29488,
"s": 29476,
"text": "\nHeap Sort\n"
},
{
"code": null,
"e": 29501,
"s": 29488,
"text": "\nPython-gui\n"
},
{
"code": null,
"e": 29517,
"s": 29501,
"text": "\nPython-PyGame\n"
},
{
"code": null,
"e": 29530,
"s": 29517,
"text": "\nAlgorithms\n"
},
{
"code": null,
"e": 29541,
"s": 29530,
"text": "\nAnalysis\n"
},
{
"code": null,
"e": 29548,
"s": 29541,
"text": "\nHeap\n"
},
{
"code": null,
"e": 29558,
"s": 29548,
"text": "\nProject\n"
},
{
"code": null,
"e": 29567,
"s": 29558,
"text": "\nPython\n"
},
{
"code": null,
"e": 29585,
"s": 29567,
"text": "\nPython Programs\n"
},
{
"code": null,
"e": 29595,
"s": 29585,
"text": "\nSorting\n"
},
{
"code": null,
"e": 29800,
"s": 29595,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 29825,
"s": 29800,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29881,
"s": 29825,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 29924,
"s": 29881,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 29953,
"s": 29924,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 29987,
"s": 29953,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 30040,
"s": 29987,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 30087,
"s": 30040,
"text": "Practice Questions on Time Complexity Analysis"
},
{
"code": null,
"e": 30138,
"s": 30087,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 30175,
"s": 30138,
"text": "Time Complexity and Space Complexity"
}
] |
Creating Word Embeddings for Out-Of-Vocabulary (OOV) words such as Singlish | by Timothy Tan | Towards Data Science
|
In this article, I will share how I created Singlish Word Embeddings to be used for downstream Natural Language Processing (NLP) tasks.
But why you might ask?
To understand my motivation for such a task, you first need to understand what word embeddings are and their importance in NLP.
When it comes to Natural Language Understanding (NLU), this requires a machine to comprehend the human language. To perform such a feat, the machine requires the language (written in words) to be converted into numerical values that best represents the meaning, relationship and context a particular word falls into.
These “numerical values” can be seen as Word Embeddings in NLP — words mapped to vectors of real numbers in n-dimensional space.
To put it simply, imagine a scatter plot on a 3-dimensional pane (x-axis, y-axis and z-axis). Each point on this plot represents a word in English i.e. “King”, “Queen”. You also notice that these points are pretty close (distance-wise) to each other. In addition, these points are also pretty far away from words like “Cat” or “Dog”.
To achieve such a plot, the words “King”, “Queen”, “Cat” and “Dog” had been given word embeddings (X, Y and Z numerical values) that best represent the relationship between them.
In Figure 1, we can see that words related to humans are grouped together (red) while words relating to animals are grouped together (blue). Why? Because the machine that generated these word embeddings has learned these complex relationships through multiple iterations of going through a large text corpus. It had given numeric representations to all words it has seen and trained upon.
It is like a machine saying:
“Hey! I’ve read through your text corpus multiple times over and here are the numeric values I think best represent each word!”
As a human, we need to verify such a claim yes? One way to do it is to visualise these words in vector space i.e. a scatter plot, to see where these words fall within that pane.
If the related words fall somewhat near each other as in Figure 1, then we can kind of validate that the machine has indeed learned enough to represent the words as numbers.
In short...
Word embeddings are the values that allow the machine to understand the relationships or meaning between words base on context. i.e. “King” and “Queen” were similar to one another (closer) and dissimilar (further) to words like “Cat” and “Dog”.
Of course there are more to word embeddings than the example I gave above but...
The point I want to drive across is this.
Machines work with numbers not words. Word embeddings are important because they are the numeric representations of words and this is the first step needed before conducting any downstream NLP tasks.
NLP tasks like Entity Extraction, Text Summarisation, Sentiment Analysis, Text Classification, Voice to Text, Image Captioning, Speech to Text and many more downstream tasks all require good word embeddings to get accurate results.
Making sense so far?
Now that we understand word embeddings and why they are important, let’s briefly talk about Singlish.
For my non-Singaporean readers, “Singlish” is essentially colloquial Singaporean English. It is a hybrid of English, Malay, Tamil, Mandarin and many other dialects like Hokkien, mixed and mashed together.
One of the best examples I’ve found on the internet is this.
Another of my all time favourite example of Singlish is this.
You see, Singlish isn’t just mix of different languages. Adapted from Mandarin, the use of Singlish words can change the meaning of the previous word base on the intonation of the Singlish term. i.e. “Can meh?” vs “Can bo?”
In English, the word “Can” is just that — to be able. In Singlish, that meaning changes depending on the subsequent Singlish term said with a certain intonation.
You can how see why working with Singlish is going to be a pain in NLP.
Alright then!
Now that introductions are out of the way, let’s get down to business to defeat the Huns... just kidding! (I hope you got that reference from Mulan...)
The next few sections below are the nitty gritty details on what I’ve done. It may or may not get technical but I will try my best to explain what I’ve done in simple terms.
But first, a summary.
Machines can’t understand text, but they understand numbers. Therefore, word embeddings are important as they are the numeric representations of text.It is from word embeddings that many downstream NLP tasks are performed.Singlish is a very localised language. There isn’t any out-of-the-box word embeddings for Singlish as far as I know. There is a need to create Singlish word embeddings for any future NLP works.
Machines can’t understand text, but they understand numbers. Therefore, word embeddings are important as they are the numeric representations of text.
It is from word embeddings that many downstream NLP tasks are performed.
Singlish is a very localised language. There isn’t any out-of-the-box word embeddings for Singlish as far as I know. There is a need to create Singlish word embeddings for any future NLP works.
In this section, I will first explain where I got the data from. Then I will talk about the model used to create the Singlish word embeddings. After which, I will go through my initial findings, the problems I realised from these findings, how I rectified the problem before finally revealing my finalised result from this.
The data was scrapped from our all time favourite Singapore forum called “Hardware Zone” ( https://forums.hardwarezone.com.sg/). It was a forum initially made to be IT-oriented but as with all forums, it has deviated to being a place many Singaporeans go to to talk about anything and everything under the sun.
The best part?
They mostly use Singlish in the forum. Perfect for any deep learning task. Here is an example of how a thread comment would look like.
['got high ses lifestyle also no use treat chw like a dog if me i sure vote her she low ses man take people breakfast ask people buy ckt already dw pay up tsk tsk tsk\n', ' children big liao no need scare tio pok\n', 'she low ses man take people breakfast ask people buy ckt already dw pay up tsk tsk tsk i dont get her thinking actually if she is rich she could even fly over to kl to eat buffet and then fly back in 1 hour dunno why want to save over this kind of small thing to ppl like her like food\n']
It may seem like just bad and broken English but actually, to a Singaporean reading this, we understand all the implicit meanings from the slangs and English used here.
Data collection-wise, 46 main threads were scrapped with a total of 7,471,930 entries. Below is the breakdown of number of threads by entry.
Eat-Drink-Man-Woman 1640025Travel and Accommodation 688253Mobile Communication Technology 582447Mass Order Corner 574927MovieMania 451531Gaming Arena 426976Campus Zone 322146General Merchandise Bazaar 286604Money Mind 264523Internet Bandwidth & Networking Clinic 243543Music SiG 227198Hobby Lovers 224994Headphones, Earphones and Portable Media Devices 206141Notebook Clinic 184116HomeSeekers and HomeMakers 153683Apple Clinic 139810Hardware Clinic 133421Cars & Cars 115286The Tablet Den 108793Fashion & Grooming 98211Electronics Bazaar 75192Degree Programs and Courses 49734Football and Sports Arena 47769Software Clinic 43553Health & Fitness Corner 21665The "Makan" Zone 21358National Service Knowledge-Base 16545Current Affairs Lounge 16259Home Theatre & Audiophiles 14888The House of Displays 13987Employment Office 12146Other Academic Concerns 9927Tech Show Central (IT Show 2018) 9895Parenting, Kids & Early Learning 9756Pets Inner Circle 6525Wearable Gadgets and IoT 5735The Book Nook 5238Digital Cameras & Photography 4714Ratings Board 3858IT Garage Sales 3549Diploma Programs and Courses 2348Certified Systems, IT Security and Network Training 1798Post-Degree Programs & Courses 1724Online Services & Basic Membership Support/Feedback 876Design & Visual Art Gallery SiG 246HardwareZone.com Reviews Lab (online publication) 18
Having manually reviewed the data quality from each thread, some threads like “Travel and Accommodation” were used for mainly sales and thus, rejected from the analysis.
I ended up only using data from “MovieMania” which did not include any form of advertisements nor sales within the thread. I also deemed 451,532 entries a large enough set to train decent word embeddings.
The average length of each entry in this thread was 27.08 words. This gave me a corpus of 12,675,524 words. In terms of number of unique vocabulary words used, the number came down to 201,766. I kept the top 50,000 words based on frequency and labelled the remainder with an “unknown” token for training.
There is no point keeping infrequent words for training. If the word only appears a couple of times, there is no learning that can take place. Hence, the reason why I replaced all infrequent words with an“unknown” token.
I also cleaned the data by simply removing all forms of punctuation and standardising the cases by lower casing them.
Technical Summary:
No. of words: 12,675,524No. of sentences: 427,735Avg. No. words per sentence: 27.05No. of unique vocabulary words used: 50,000
Now that the data is out of the way, the next segment will talk about the actual model used to train word embeddings.
The skip-gram model is an unsupervised machine learning technique that is used to find the most relevant words for a given word.
Take this phrase for example,
The skip-gram model tries to predict the context words given an input word. In this case, given the word “Fox”, predict “quick”, “brown”, “jumps” and “over”.
Now imagine the model scanning through my entire training corpus from Hardware Zone. For each sentence (427,735 sentences), loop through each word, extract out it’s context words and use the input word to predict those context words.
An error function is also calculated per sentence. The goal of the model is to minimise this error function through multiple iterations by slowly adapting the weights within the model.
I iterate this “learning” until the error function starts to stabilise before extracting the weights with the model as my word embeddings.
What I attempted to explain above, is essentially how neural networks work. Architecturally, it will look something like this:
Following so far?
Great! Before I get to the results, let’s review some technical specifications in the model building process.
Technical Specifications:Context size = 3Learning Rate = 0.025Learning Rate Decay = 0.001No. of Epochs = 25No. of word dimensions = 100No. of Negative Samples = 3Total Training Time = 17 hrs 05 mins (~= 41 mins per Epoch)
For those who are wondering what these technical jargon refers to, context size refers to the number of words to predict i.e. “quick”, “brown”, “jumps”, “over” was a context size of 2 — Two words before the input word, “Fox” and two words after.
Learning rate and decay refers to how the model adapts it weights over the iterations. i.e. how much it learns per iteration.
Epoch refers to how many iterations of the entire training set to loop through. For example, I had 427,735 sentences in my training set, I am looping through this 25 times.
Word dimensions refers to the number of numerical values to best represent a word. In my example in the introduction, I used 3 dimensions to keep it simple and easy to understand. In actual fact, we can actually go up to 300 dimensions.
Negative sample size is a parameter that comes from Negative sampling — a technique used to train machine learning models that generally have more negative observations compared to positive ones. Recall I kept 50,000 vocabulary words to use.
If I were to use “Fox” to predict “Quick”, there will only be 1 correct answer, versus 49,999 wrong answers. The probability to get the prediction of “Quick” correct would be insanely low.
Hence to speed up the learning process, negative sampling is used to reduce to number of negative levels. i.e. Instead of looking at 49,999 wrong answers, I only look at 3 random wrong answers. Hence, No. of Negative Samples = 3.
Still with me yeah? Fantastic! Let’s carry on!
Here are the results of the first run of the trying to generate word embeddings for Singlish.
What you see below are similarity scores (0 to 1) between word-pairs and the top 10 words that tend to be closest to the word of interest. The higher the number, the more similar the words are in terms of context.
As an initial test before even looking into Singlish words, I decided to look at the scores for words like “her” vs “she” and “his” vs “he”. If these scores were not high, I would have deemed that the model has not trained well enough.
Thankfully, the scores are pretty high and decent.
Similarity between 'her' & 'she': 0.9317842308059494Closest 10:her 0.9999999999999994she 0.9317842308059496who 0.8088322989667506face 0.7685887293574792and 0.731550465085091hair 0.7196624736651458shes 0.7191209881379563when 0.7119862209278394his 0.7107795929496181that 0.7091856776526962********************************************************Similarity between 'his' & 'he': 0.897577672968669Closest 10:his 1.0he 0.8975776729686689him 0.8446763202218628who 0.775987111217783was 0.7667867138663951that 0.7528368024154157father 0.749632881268601son 0.7281268393201477become 0.7264880215455141wife 0.711578758349141********************************************************Similarity between 'jialat' & 'unlucky': 0.011948430628978856Closest 10:jialat 1.0sia 0.8384455155248727riao 0.8266230148176981liao 0.8242816925791344sibei 0.814415592977946hahaha 0.8064565592682809ya 0.8045512611232027meh 0.7954521439129846lol 0.7936809689607456leh 0.7920613014175707********************************************************Similarity between 'jialat' & 'bad': 0.6371130561508843Closest 10:bad 1.0quite 0.8823291887959687good 0.8762035559199239really 0.8758630577100476very 0.8731856141554037like 0.8728014312651295too 0.8656864898051815damn 0.8599010325212141so 0.8486273610657793actually 0.8392110977957886********************************************************Similarity between 'bodoh' & 'stupid': 0.1524869239423864Closest 10:bodoh 0.9999999999999998628 0.4021945681425326u4e3au56fdu5148u75af 0.3993291424102916beck 0.39461861903538475recieve 0.39110839516564666otto 0.3839416132228821gaki 0.34783948936473097fapppppp 0.3418846453140858bentley 0.3344963328126833hagoromo 0.3331640207541007********************************************************Similarity between 'bah' & 'ba': 0.5447425470420932Closest 10:bah 0.9999999999999998lei 0.7051290703273838nowadays 0.698360482336586dun 0.6968374466521237alot 0.6767383433113785type 0.6745085658120278cos 0.6711909808612231wat 0.6682283480973521ppl 0.6675756452507112lah 0.6671682261049516********************************************************Similarity between 'lah' & 'la': 0.8876189066755961Closest 10:lah 1.0meh 0.8877331822636787la 0.8876189066755962dun 0.8865821519839381mah 0.8793885175949425leh 0.8723455556110296cannot 0.8686775338961492ya 0.8661596706378043u 0.8549447964449902wat 0.8542029625856831********************************************************Similarity between 'lah' & 'leh': 0.8723455556110294********************************************************Similarity between 'lah' & 'ba': 0.6857482674200363********************************************************Similarity between 'lah' & 'lor': 0.8447135421839688********************************************************Similarity between 'lah' & 'hor': 0.722923046216034********************************************************Similarity between 'lor' & 'hor': 0.6876132025458188Closest 10:lor 1.0u 0.8925715547690672cannot 0.865412324252327dun 0.8509787619825337leh 0.8508639376357423lah 0.8447135421839689ya 0.8438741042009468la 0.8403252240817168meh 0.8356571743730847mah 0.8314177487183335********************************************************Similarity between 'walau' & 'walao': 0.4186234210208167Closest 10:walau 1.0nv 0.6617041802872807pple 0.6285030787914123nb 0.6248358788358526la 0.6207062961324734knn 0.6206045544509986lah 0.6158839994483083lo 0.6102554356797499jialat 0.6079250154571741sibei 0.6076622192051193********************************************************Similarity between 'makan' & 'eat': 0.6577461668802116Closest 10:makan 1.0jiak 0.7007467882204779go 0.6911439090088933pple 0.65857421561786eat 0.6577461668802115food 0.6575154915623017kr 0.6545185140294344sg 0.6473315303433985heng 0.6422265572697313beo 0.6354614594882941********************************************************Similarity between 'makan' & 'food': 0.6575154915623018********************************************************Similarity between 'tw' & 'sg': 0.7339666801539345Closest 10:tw 0.9999999999999997tiong 0.7723149794376185sg 0.7339666801539344lidat 0.7330705496009475hk 0.7258329008490501taiwan 0.7195021043855226tiongland 0.7171170137971364pple 0.7130953678674011yr 0.7017495747955986mediacorpse 0.6954931933921777********************************************************Similarity between 'kr' & 'sg': 0.7889688950703608Closest 10:sg 1.0go 0.7940974860875252kr 0.7889688950703608tiongland 0.7675846859894958ongware 0.7674045119824121yr 0.7584581119582794pple 0.7536492976456339time 0.7533848231714694buy 0.751509500730294tix 0.743339654154326********************************************************
There are some interesting findings from the above results that I’d like to point out.
Overall, I would say the model has learned and performed decently well on understanding Singlish words.
Not the best, but decent.
It’s no surprise that the model has learned that “Makan” (Malay for “Eat”), “Food” and “Eat” were found to be similar. But what’s interesting is the word “Jiak” — dialect for “Eat” and commonly used in Singlish sentences, was picked up and deemed similar to “Food”, “Makan” and “Eat” as well.
This looks to me that the model has indeed learned some Singlish words well.
The next interesting result comes from the abbreviations of country names. As humans reading the result, we know “sg” refers to “Singapore”, “kr” — “Korean”, “tw” — “Taiwan” & “hk” — “Hong Kong”. To a machine however, it is not that simple, the model did not have prior knowledge of these. Yet, it has managed to group these terms together.
Very interesting indeed!
This is another validation point that tells me the model has trained decently well on Singlish words.
Now, instead of just staring at numbers, there is a method that helps us visualise words in vector space. This is called T-distributed Stochastic Neighbor Embedding (TSNE).
TSNE can be loosely seen as a dimensionality reduction technique to visualise high-dimensional data. i.e. word embeddings of 100 dimensions. The idea is to embed high-dimensional points in low dimensions in a way that respects similarities between points.
In English, convert 100 dimensions into 2 or 3 dimensions and retain the embedded information as much as possible.
If I were to run TSNE (n=2 dimensions) on some of my results above and display it on a scatter plot, it will look like this:
Not too shabby a result.
While the results above looked promising, there were some issues that needed addressing.
I only realised this when I was reviewing the results. The following section will explain further.
First off, as you can see, Singlish words like “lah”, “lor”, “meh” seem to be similar to each other but...
So what? What does it actually mean?!
After thinking about it, it is not exactly useful.
Singlish phrases usually appear as bigrams (2 words) that really encapsulates the meaning of the context in which it was used. A good example is Figure 3 — The power of “Can”. The bigrams “can meh?” vs “can lah!” have very different meanings.
If we were to look at the words independently, “can” and “meh”, that meaning is lost.
Therefore, having a vector representation of the words “meh” vs “lah”alone is not entirely useful here.
To remedy this issue, I needed a way to keep these words together. Skip-Gram trains on unigrams, yes. But what if I could convert these bigrams to unigrams first? i.e. “Can meh” -> “Can_meh” *note the underscore.
The second problem is not as serious as the first, but worth some air time.
It is the inherent problem with dimensionality reduction techniques like TSNE. You see, information loss by downsizing from 100 dimensions to 2 dimensions is inevitable. As much as I love visuals, I realised that I could only get the true understanding of the results by looking at numbers and not the visual.
Nothing to solve here.
Just food for thought.
Now let’s take a look at my attempt to solve the first problem.
After realising the issue with Singlish, I needed a way to convert my bigrams to unigram and yet keep the information or meaning of those words.
The way I could do that was by calculating the PMI of all possible bigrams in the corpus.
For example, the formula in Figure 7 reads, take the log of the probability of the occurrence of pair of words (i.e. “can meh”), divided by the probabilities of the occurrences of each individual words.
The breakdown of my process is as such:
If x = “can” and y = “meh”,
Count the number of times “can meh” appears together.Count the number of times “can” appears alone.Count the number of times “meh” appears alone.Apply PMI and get a score.Set some threshold parameter. If score is above threshold convert all occurrences of “can meh” into “can_meh” i.e. bigram to unigram.Retrain the entire skip-gram model.
Count the number of times “can meh” appears together.
Count the number of times “can” appears alone.
Count the number of times “meh” appears alone.
Apply PMI and get a score.
Set some threshold parameter. If score is above threshold convert all occurrences of “can meh” into “can_meh” i.e. bigram to unigram.
Retrain the entire skip-gram model.
The steps from 1 to 5 is actually known as building a phrase model.
And so... the quest to retrain my 17 hour model ensued...
I calculated the PMI scores for all possible bigrams and set a threshold variable. I actually used the normalised version of the PMI formula above for calculation, but the concept is the same.
Technical Specifications of Normalised PMI phrase model:
Minimum count of word = 5Threshold = 0.5 (range from -1 to 1)
Minimum count of word = 5
Threshold = 0.5 (range from -1 to 1)
['as we are left with just 2 days of 2017 hereu2019s a song for everyone here edit to weewee especially lol', 'good_morning click here to download the hardwarezone_forums app']['wah_piang . why every time lidat one . siao liao can meh . wah_lau . can lah . can la . of course medicated_oil . can anot']
As you can see, the threshold affects how many bigrams gets converted to unigrams. I did not manage to get bigrams of “can meh” to be converted to unigrams because if I were to set the threshold any lower, many other non-bigram related words will start to be converted into unigrams.
Sadly, there is a trade-off to make here.
After accounting for the bigrams, I retrained the model (which now took me 18 hours to train) and received the results below.
Notice how many non-related bigrams became unigrams? i.e. “for_her”, “with_her”. This is what I meant as trade-off in the phrase modelling step.
Because of all these non-related bigram, a number of the scores have fallen.
Similarity between 'her' & 'she': 0.8960039000509769Closest 10:her 1.0she 0.8960039000509765when_she 0.7756011613106286she_is 0.7612506774261273with_her 0.7449142184510621who 0.7348657494449988for_her 0.7306419631887822shes 0.7279985577059225face 0.7192153872317455look_like 0.718696491400789********************************************************Similarity between 'his' & 'he': 0.8129410509281912Closest 10:his 1.0he 0.8129410509281914him 0.804565895231623he_was 0.7816885610401878when_he 0.7747444761501758that_he 0.7724774086496818in_the 0.7622871291423432himself 0.7611962890490288was 0.7492507482663726with_his 0.7241458127853628********************************************************Similarity between 'jialat' & 'unlucky': 0.1258840952579276Closest 10:jialat 0.9999999999999996den 0.7104029620075444liao 0.7050826631244886chiu 0.6967369805196841heng 0.686838291277863hahaha 0.6860075650732084riao 0.6810071447192776la 0.6804775540889827le 0.676416467456822can_go 0.6756005150502169********************************************************Similarity between 'jialat' & 'bad': 0.4089547762801133Closest 10:bad 1.0but 0.8388423345999712good 0.8244038298175955really 0.8192112848219635i_think 0.7970842555698856very 0.7965053100959192like 0.785966214367795feel 0.783452344516318too 0.7788218726013071i_feel 0.7721110713307375********************************************************Similarity between 'bah' & 'ba': 0.5793487566624044Closest 10:bah 1.0say 0.6595798529633369lah 0.6451347547752344dun 0.6449884617104611sure 0.627629971037843bo_bian 0.6251418244527653this_kind 0.6223631439973716ppl 0.6196652346594724coz 0.61880214034487mah 0.6146197262236697********************************************************Similarity between 'lah' & 'la': 0.8863959901557994Closest 10:lah 0.9999999999999998la 0.8863959901557996meh 0.8739974021915318mah 0.8641084304399245say 0.8589606487232055lor 0.8535623035418399u 0.8304372234546418leh 0.8275930224011575loh 0.8189639505064721like_that 0.8170752533330873********************************************************Similarity between 'lah' & 'leh': 0.8275930224011575********************************************************Similarity between 'lah' & 'ba': 0.7298744482101323********************************************************Similarity between 'lah' & 'lor': 0.8535623035418399********************************************************Similarity between 'lah' & 'hor': 0.7787062026673155********************************************************Similarity between 'lor' & 'hor': 0.7283051932769404Closest 10:lor 1.0u 0.8706158009584564lah 0.8535623035418399mah 0.8300722350347082meh 0.8271088070439694or_not 0.8212467976061046can 0.8202962002027998la 0.8136970310629428say 0.8119961813856317no_need 0.8113510524754526********************************************************Similarity between 'walau' & 'walao': 0.37910878579551655Closest 10:walau 0.9999999999999998liao_lor 0.595008714889509last_time 0.5514972888957848riao 0.5508554544237825no_wonder 0.5449206686992254bttorn_wrote 0.5434895860379704hayley 0.5418542538935931y 0.5415132654837992meh 0.5397241464489063dunno 0.5377254112246059********************************************************Similarity between 'makan' & 'eat': 0.6600454451976521Closest 10:makan 0.9999999999999998go 0.7208286785168599den 0.697169918153346pple 0.6897361126052199got_pple 0.6756029930429751must 0.6677701662661563somemore 0.6675667631139202eat 0.6600454451976518lo 0.6524129092703767there 0.649481411415345********************************************************Similarity between 'makan' & 'food': 0.4861726118637594********************************************************Similarity between 'tw' & 'sg': 0.6679227949310249Closest 10:tw 1.0tiong 0.7219240075555984taiwan 0.7034844664255471hk 0.7028979577505058tiongland 0.6828634228902605mediacock 0.6751283466015426last_time 0.6732280724879228sg 0.6679227949310248this_yr 0.6384487035493662every_year 0.6284237559586139********************************************************Similarity between 'kr' & 'sg': 0.7700608852122885Closest 10:sg 1.0in_sg 0.8465612812762291kr 0.7700608852122885pple 0.7599772116504516laio 0.7520684090232901go 0.7509260306136896sure 0.7156635106866068come 0.7116443785982034tiongland 0.7015439847091592ongware_wrote 0.6974645318958415********************************************************Closest 10:wah_piang 1.0tsm 0.4967581460786865scourge_wrote 0.4923443232403448aikiboy_wrote 0.4887014894882954sian 0.4871567208941815ah_ma 0.48058368153798403lms 0.4790804214522433ruien 0.47420796750340777xln 0.46973552365710514myolie 0.4682823729806439********************************************************
In short, the results above was worst off than the previous results.
I think that the this issue came from the lack of data. If I had more examples of people using “can meh” or “can lah”, the phrase model would have picked up these bigrams without having me set a low threshold. 0.5 threshold is really low in my opinion.
I caught too many false positives.
Rubbish in, rubbish out right? This was exactly what happened here.
As you can imagine, I still have ways to go in tuning my model to get decent Singlish word embeddings for my future works.
What I would do differently is this:
Recode my scripts to run distributed. Or better yet, code to run in a GPU. This will allow me to run on a much larger corpus i.e. the whole of Hardware Zone and not just one thread of it.Train a better phrase model. i.e. the PMI portion.
Recode my scripts to run distributed. Or better yet, code to run in a GPU. This will allow me to run on a much larger corpus i.e. the whole of Hardware Zone and not just one thread of it.
Train a better phrase model. i.e. the PMI portion.
For now, I will keep the word embeddings for the first model.
Edit: If you’re interested in finding out about how to deal with misspellings, abbreviations or other OOV words in your corpus, I’ve written another article about it here!
I’ve definitely learned a lot from this exercise and I hope that by me sharing my methodologies, thought processes and results, you’d be able to do the same in your respective local languages.
With that, adios amigos!
Hope that you’ve enjoyed reading this as much as I’ve enjoyed doing it!
Feel free to share the article if it helps anyone out there!
If you are looking for NLP datasets to work with, click here for a curated list I created! :)
LinkedIn Profile: Timothy Tan
|
[
{
"code": null,
"e": 308,
"s": 172,
"text": "In this article, I will share how I created Singlish Word Embeddings to be used for downstream Natural Language Processing (NLP) tasks."
},
{
"code": null,
"e": 331,
"s": 308,
"text": "But why you might ask?"
},
{
"code": null,
"e": 459,
"s": 331,
"text": "To understand my motivation for such a task, you first need to understand what word embeddings are and their importance in NLP."
},
{
"code": null,
"e": 776,
"s": 459,
"text": "When it comes to Natural Language Understanding (NLU), this requires a machine to comprehend the human language. To perform such a feat, the machine requires the language (written in words) to be converted into numerical values that best represents the meaning, relationship and context a particular word falls into."
},
{
"code": null,
"e": 905,
"s": 776,
"text": "These “numerical values” can be seen as Word Embeddings in NLP — words mapped to vectors of real numbers in n-dimensional space."
},
{
"code": null,
"e": 1239,
"s": 905,
"text": "To put it simply, imagine a scatter plot on a 3-dimensional pane (x-axis, y-axis and z-axis). Each point on this plot represents a word in English i.e. “King”, “Queen”. You also notice that these points are pretty close (distance-wise) to each other. In addition, these points are also pretty far away from words like “Cat” or “Dog”."
},
{
"code": null,
"e": 1418,
"s": 1239,
"text": "To achieve such a plot, the words “King”, “Queen”, “Cat” and “Dog” had been given word embeddings (X, Y and Z numerical values) that best represent the relationship between them."
},
{
"code": null,
"e": 1807,
"s": 1418,
"text": "In Figure 1, we can see that words related to humans are grouped together (red) while words relating to animals are grouped together (blue). Why? Because the machine that generated these word embeddings has learned these complex relationships through multiple iterations of going through a large text corpus. It had given numeric representations to all words it has seen and trained upon."
},
{
"code": null,
"e": 1836,
"s": 1807,
"text": "It is like a machine saying:"
},
{
"code": null,
"e": 1964,
"s": 1836,
"text": "“Hey! I’ve read through your text corpus multiple times over and here are the numeric values I think best represent each word!”"
},
{
"code": null,
"e": 2142,
"s": 1964,
"text": "As a human, we need to verify such a claim yes? One way to do it is to visualise these words in vector space i.e. a scatter plot, to see where these words fall within that pane."
},
{
"code": null,
"e": 2316,
"s": 2142,
"text": "If the related words fall somewhat near each other as in Figure 1, then we can kind of validate that the machine has indeed learned enough to represent the words as numbers."
},
{
"code": null,
"e": 2328,
"s": 2316,
"text": "In short..."
},
{
"code": null,
"e": 2573,
"s": 2328,
"text": "Word embeddings are the values that allow the machine to understand the relationships or meaning between words base on context. i.e. “King” and “Queen” were similar to one another (closer) and dissimilar (further) to words like “Cat” and “Dog”."
},
{
"code": null,
"e": 2654,
"s": 2573,
"text": "Of course there are more to word embeddings than the example I gave above but..."
},
{
"code": null,
"e": 2696,
"s": 2654,
"text": "The point I want to drive across is this."
},
{
"code": null,
"e": 2896,
"s": 2696,
"text": "Machines work with numbers not words. Word embeddings are important because they are the numeric representations of words and this is the first step needed before conducting any downstream NLP tasks."
},
{
"code": null,
"e": 3128,
"s": 2896,
"text": "NLP tasks like Entity Extraction, Text Summarisation, Sentiment Analysis, Text Classification, Voice to Text, Image Captioning, Speech to Text and many more downstream tasks all require good word embeddings to get accurate results."
},
{
"code": null,
"e": 3149,
"s": 3128,
"text": "Making sense so far?"
},
{
"code": null,
"e": 3251,
"s": 3149,
"text": "Now that we understand word embeddings and why they are important, let’s briefly talk about Singlish."
},
{
"code": null,
"e": 3456,
"s": 3251,
"text": "For my non-Singaporean readers, “Singlish” is essentially colloquial Singaporean English. It is a hybrid of English, Malay, Tamil, Mandarin and many other dialects like Hokkien, mixed and mashed together."
},
{
"code": null,
"e": 3517,
"s": 3456,
"text": "One of the best examples I’ve found on the internet is this."
},
{
"code": null,
"e": 3579,
"s": 3517,
"text": "Another of my all time favourite example of Singlish is this."
},
{
"code": null,
"e": 3803,
"s": 3579,
"text": "You see, Singlish isn’t just mix of different languages. Adapted from Mandarin, the use of Singlish words can change the meaning of the previous word base on the intonation of the Singlish term. i.e. “Can meh?” vs “Can bo?”"
},
{
"code": null,
"e": 3965,
"s": 3803,
"text": "In English, the word “Can” is just that — to be able. In Singlish, that meaning changes depending on the subsequent Singlish term said with a certain intonation."
},
{
"code": null,
"e": 4037,
"s": 3965,
"text": "You can how see why working with Singlish is going to be a pain in NLP."
},
{
"code": null,
"e": 4051,
"s": 4037,
"text": "Alright then!"
},
{
"code": null,
"e": 4203,
"s": 4051,
"text": "Now that introductions are out of the way, let’s get down to business to defeat the Huns... just kidding! (I hope you got that reference from Mulan...)"
},
{
"code": null,
"e": 4377,
"s": 4203,
"text": "The next few sections below are the nitty gritty details on what I’ve done. It may or may not get technical but I will try my best to explain what I’ve done in simple terms."
},
{
"code": null,
"e": 4399,
"s": 4377,
"text": "But first, a summary."
},
{
"code": null,
"e": 4815,
"s": 4399,
"text": "Machines can’t understand text, but they understand numbers. Therefore, word embeddings are important as they are the numeric representations of text.It is from word embeddings that many downstream NLP tasks are performed.Singlish is a very localised language. There isn’t any out-of-the-box word embeddings for Singlish as far as I know. There is a need to create Singlish word embeddings for any future NLP works."
},
{
"code": null,
"e": 4966,
"s": 4815,
"text": "Machines can’t understand text, but they understand numbers. Therefore, word embeddings are important as they are the numeric representations of text."
},
{
"code": null,
"e": 5039,
"s": 4966,
"text": "It is from word embeddings that many downstream NLP tasks are performed."
},
{
"code": null,
"e": 5233,
"s": 5039,
"text": "Singlish is a very localised language. There isn’t any out-of-the-box word embeddings for Singlish as far as I know. There is a need to create Singlish word embeddings for any future NLP works."
},
{
"code": null,
"e": 5557,
"s": 5233,
"text": "In this section, I will first explain where I got the data from. Then I will talk about the model used to create the Singlish word embeddings. After which, I will go through my initial findings, the problems I realised from these findings, how I rectified the problem before finally revealing my finalised result from this."
},
{
"code": null,
"e": 5868,
"s": 5557,
"text": "The data was scrapped from our all time favourite Singapore forum called “Hardware Zone” ( https://forums.hardwarezone.com.sg/). It was a forum initially made to be IT-oriented but as with all forums, it has deviated to being a place many Singaporeans go to to talk about anything and everything under the sun."
},
{
"code": null,
"e": 5883,
"s": 5868,
"text": "The best part?"
},
{
"code": null,
"e": 6018,
"s": 5883,
"text": "They mostly use Singlish in the forum. Perfect for any deep learning task. Here is an example of how a thread comment would look like."
},
{
"code": null,
"e": 16480,
"s": 6018,
"text": "['got high ses lifestyle also no use treat chw like a dog if me i sure vote her she low ses man take people breakfast ask people buy ckt already dw pay up tsk tsk tsk\\n', ' children big liao no need scare tio pok\\n', 'she low ses man take people breakfast ask people buy ckt already dw pay up tsk tsk tsk i dont get her thinking actually if she is rich she could even fly over to kl to eat buffet and then fly back in 1 hour dunno why want to save over this kind of small thing to ppl like her like food\\n']"
},
{
"code": null,
"e": 16649,
"s": 16480,
"text": "It may seem like just bad and broken English but actually, to a Singaporean reading this, we understand all the implicit meanings from the slangs and English used here."
},
{
"code": null,
"e": 16790,
"s": 16649,
"text": "Data collection-wise, 46 main threads were scrapped with a total of 7,471,930 entries. Below is the breakdown of number of threads by entry."
},
{
"code": null,
"e": 19643,
"s": 16790,
"text": "Eat-Drink-Man-Woman 1640025Travel and Accommodation 688253Mobile Communication Technology 582447Mass Order Corner 574927MovieMania 451531Gaming Arena 426976Campus Zone 322146General Merchandise Bazaar 286604Money Mind 264523Internet Bandwidth & Networking Clinic 243543Music SiG 227198Hobby Lovers 224994Headphones, Earphones and Portable Media Devices 206141Notebook Clinic 184116HomeSeekers and HomeMakers 153683Apple Clinic 139810Hardware Clinic 133421Cars & Cars 115286The Tablet Den 108793Fashion & Grooming 98211Electronics Bazaar 75192Degree Programs and Courses 49734Football and Sports Arena 47769Software Clinic 43553Health & Fitness Corner 21665The \"Makan\" Zone 21358National Service Knowledge-Base 16545Current Affairs Lounge 16259Home Theatre & Audiophiles 14888The House of Displays 13987Employment Office 12146Other Academic Concerns 9927Tech Show Central (IT Show 2018) 9895Parenting, Kids & Early Learning 9756Pets Inner Circle 6525Wearable Gadgets and IoT 5735The Book Nook 5238Digital Cameras & Photography 4714Ratings Board 3858IT Garage Sales 3549Diploma Programs and Courses 2348Certified Systems, IT Security and Network Training 1798Post-Degree Programs & Courses 1724Online Services & Basic Membership Support/Feedback 876Design & Visual Art Gallery SiG 246HardwareZone.com Reviews Lab (online publication) 18"
},
{
"code": null,
"e": 19813,
"s": 19643,
"text": "Having manually reviewed the data quality from each thread, some threads like “Travel and Accommodation” were used for mainly sales and thus, rejected from the analysis."
},
{
"code": null,
"e": 20018,
"s": 19813,
"text": "I ended up only using data from “MovieMania” which did not include any form of advertisements nor sales within the thread. I also deemed 451,532 entries a large enough set to train decent word embeddings."
},
{
"code": null,
"e": 20323,
"s": 20018,
"text": "The average length of each entry in this thread was 27.08 words. This gave me a corpus of 12,675,524 words. In terms of number of unique vocabulary words used, the number came down to 201,766. I kept the top 50,000 words based on frequency and labelled the remainder with an “unknown” token for training."
},
{
"code": null,
"e": 20544,
"s": 20323,
"text": "There is no point keeping infrequent words for training. If the word only appears a couple of times, there is no learning that can take place. Hence, the reason why I replaced all infrequent words with an“unknown” token."
},
{
"code": null,
"e": 20662,
"s": 20544,
"text": "I also cleaned the data by simply removing all forms of punctuation and standardising the cases by lower casing them."
},
{
"code": null,
"e": 20681,
"s": 20662,
"text": "Technical Summary:"
},
{
"code": null,
"e": 20808,
"s": 20681,
"text": "No. of words: 12,675,524No. of sentences: 427,735Avg. No. words per sentence: 27.05No. of unique vocabulary words used: 50,000"
},
{
"code": null,
"e": 20926,
"s": 20808,
"text": "Now that the data is out of the way, the next segment will talk about the actual model used to train word embeddings."
},
{
"code": null,
"e": 21055,
"s": 20926,
"text": "The skip-gram model is an unsupervised machine learning technique that is used to find the most relevant words for a given word."
},
{
"code": null,
"e": 21085,
"s": 21055,
"text": "Take this phrase for example,"
},
{
"code": null,
"e": 21243,
"s": 21085,
"text": "The skip-gram model tries to predict the context words given an input word. In this case, given the word “Fox”, predict “quick”, “brown”, “jumps” and “over”."
},
{
"code": null,
"e": 21477,
"s": 21243,
"text": "Now imagine the model scanning through my entire training corpus from Hardware Zone. For each sentence (427,735 sentences), loop through each word, extract out it’s context words and use the input word to predict those context words."
},
{
"code": null,
"e": 21662,
"s": 21477,
"text": "An error function is also calculated per sentence. The goal of the model is to minimise this error function through multiple iterations by slowly adapting the weights within the model."
},
{
"code": null,
"e": 21801,
"s": 21662,
"text": "I iterate this “learning” until the error function starts to stabilise before extracting the weights with the model as my word embeddings."
},
{
"code": null,
"e": 21928,
"s": 21801,
"text": "What I attempted to explain above, is essentially how neural networks work. Architecturally, it will look something like this:"
},
{
"code": null,
"e": 21946,
"s": 21928,
"text": "Following so far?"
},
{
"code": null,
"e": 22056,
"s": 21946,
"text": "Great! Before I get to the results, let’s review some technical specifications in the model building process."
},
{
"code": null,
"e": 22278,
"s": 22056,
"text": "Technical Specifications:Context size = 3Learning Rate = 0.025Learning Rate Decay = 0.001No. of Epochs = 25No. of word dimensions = 100No. of Negative Samples = 3Total Training Time = 17 hrs 05 mins (~= 41 mins per Epoch)"
},
{
"code": null,
"e": 22524,
"s": 22278,
"text": "For those who are wondering what these technical jargon refers to, context size refers to the number of words to predict i.e. “quick”, “brown”, “jumps”, “over” was a context size of 2 — Two words before the input word, “Fox” and two words after."
},
{
"code": null,
"e": 22650,
"s": 22524,
"text": "Learning rate and decay refers to how the model adapts it weights over the iterations. i.e. how much it learns per iteration."
},
{
"code": null,
"e": 22823,
"s": 22650,
"text": "Epoch refers to how many iterations of the entire training set to loop through. For example, I had 427,735 sentences in my training set, I am looping through this 25 times."
},
{
"code": null,
"e": 23060,
"s": 22823,
"text": "Word dimensions refers to the number of numerical values to best represent a word. In my example in the introduction, I used 3 dimensions to keep it simple and easy to understand. In actual fact, we can actually go up to 300 dimensions."
},
{
"code": null,
"e": 23302,
"s": 23060,
"text": "Negative sample size is a parameter that comes from Negative sampling — a technique used to train machine learning models that generally have more negative observations compared to positive ones. Recall I kept 50,000 vocabulary words to use."
},
{
"code": null,
"e": 23491,
"s": 23302,
"text": "If I were to use “Fox” to predict “Quick”, there will only be 1 correct answer, versus 49,999 wrong answers. The probability to get the prediction of “Quick” correct would be insanely low."
},
{
"code": null,
"e": 23721,
"s": 23491,
"text": "Hence to speed up the learning process, negative sampling is used to reduce to number of negative levels. i.e. Instead of looking at 49,999 wrong answers, I only look at 3 random wrong answers. Hence, No. of Negative Samples = 3."
},
{
"code": null,
"e": 23768,
"s": 23721,
"text": "Still with me yeah? Fantastic! Let’s carry on!"
},
{
"code": null,
"e": 23862,
"s": 23768,
"text": "Here are the results of the first run of the trying to generate word embeddings for Singlish."
},
{
"code": null,
"e": 24076,
"s": 23862,
"text": "What you see below are similarity scores (0 to 1) between word-pairs and the top 10 words that tend to be closest to the word of interest. The higher the number, the more similar the words are in terms of context."
},
{
"code": null,
"e": 24312,
"s": 24076,
"text": "As an initial test before even looking into Singlish words, I decided to look at the scores for words like “her” vs “she” and “his” vs “he”. If these scores were not high, I would have deemed that the model has not trained well enough."
},
{
"code": null,
"e": 24363,
"s": 24312,
"text": "Thankfully, the scores are pretty high and decent."
},
{
"code": null,
"e": 28972,
"s": 24363,
"text": "Similarity between 'her' & 'she': 0.9317842308059494Closest 10:her 0.9999999999999994she 0.9317842308059496who 0.8088322989667506face 0.7685887293574792and 0.731550465085091hair 0.7196624736651458shes 0.7191209881379563when 0.7119862209278394his 0.7107795929496181that 0.7091856776526962********************************************************Similarity between 'his' & 'he': 0.897577672968669Closest 10:his 1.0he 0.8975776729686689him 0.8446763202218628who 0.775987111217783was 0.7667867138663951that 0.7528368024154157father 0.749632881268601son 0.7281268393201477become 0.7264880215455141wife 0.711578758349141********************************************************Similarity between 'jialat' & 'unlucky': 0.011948430628978856Closest 10:jialat 1.0sia 0.8384455155248727riao 0.8266230148176981liao 0.8242816925791344sibei 0.814415592977946hahaha 0.8064565592682809ya 0.8045512611232027meh 0.7954521439129846lol 0.7936809689607456leh 0.7920613014175707********************************************************Similarity between 'jialat' & 'bad': 0.6371130561508843Closest 10:bad 1.0quite 0.8823291887959687good 0.8762035559199239really 0.8758630577100476very 0.8731856141554037like 0.8728014312651295too 0.8656864898051815damn 0.8599010325212141so 0.8486273610657793actually 0.8392110977957886********************************************************Similarity between 'bodoh' & 'stupid': 0.1524869239423864Closest 10:bodoh 0.9999999999999998628 0.4021945681425326u4e3au56fdu5148u75af 0.3993291424102916beck 0.39461861903538475recieve 0.39110839516564666otto 0.3839416132228821gaki 0.34783948936473097fapppppp 0.3418846453140858bentley 0.3344963328126833hagoromo 0.3331640207541007********************************************************Similarity between 'bah' & 'ba': 0.5447425470420932Closest 10:bah 0.9999999999999998lei 0.7051290703273838nowadays 0.698360482336586dun 0.6968374466521237alot 0.6767383433113785type 0.6745085658120278cos 0.6711909808612231wat 0.6682283480973521ppl 0.6675756452507112lah 0.6671682261049516********************************************************Similarity between 'lah' & 'la': 0.8876189066755961Closest 10:lah 1.0meh 0.8877331822636787la 0.8876189066755962dun 0.8865821519839381mah 0.8793885175949425leh 0.8723455556110296cannot 0.8686775338961492ya 0.8661596706378043u 0.8549447964449902wat 0.8542029625856831********************************************************Similarity between 'lah' & 'leh': 0.8723455556110294********************************************************Similarity between 'lah' & 'ba': 0.6857482674200363********************************************************Similarity between 'lah' & 'lor': 0.8447135421839688********************************************************Similarity between 'lah' & 'hor': 0.722923046216034********************************************************Similarity between 'lor' & 'hor': 0.6876132025458188Closest 10:lor 1.0u 0.8925715547690672cannot 0.865412324252327dun 0.8509787619825337leh 0.8508639376357423lah 0.8447135421839689ya 0.8438741042009468la 0.8403252240817168meh 0.8356571743730847mah 0.8314177487183335********************************************************Similarity between 'walau' & 'walao': 0.4186234210208167Closest 10:walau 1.0nv 0.6617041802872807pple 0.6285030787914123nb 0.6248358788358526la 0.6207062961324734knn 0.6206045544509986lah 0.6158839994483083lo 0.6102554356797499jialat 0.6079250154571741sibei 0.6076622192051193********************************************************Similarity between 'makan' & 'eat': 0.6577461668802116Closest 10:makan 1.0jiak 0.7007467882204779go 0.6911439090088933pple 0.65857421561786eat 0.6577461668802115food 0.6575154915623017kr 0.6545185140294344sg 0.6473315303433985heng 0.6422265572697313beo 0.6354614594882941********************************************************Similarity between 'makan' & 'food': 0.6575154915623018********************************************************Similarity between 'tw' & 'sg': 0.7339666801539345Closest 10:tw 0.9999999999999997tiong 0.7723149794376185sg 0.7339666801539344lidat 0.7330705496009475hk 0.7258329008490501taiwan 0.7195021043855226tiongland 0.7171170137971364pple 0.7130953678674011yr 0.7017495747955986mediacorpse 0.6954931933921777********************************************************Similarity between 'kr' & 'sg': 0.7889688950703608Closest 10:sg 1.0go 0.7940974860875252kr 0.7889688950703608tiongland 0.7675846859894958ongware 0.7674045119824121yr 0.7584581119582794pple 0.7536492976456339time 0.7533848231714694buy 0.751509500730294tix 0.743339654154326********************************************************"
},
{
"code": null,
"e": 29059,
"s": 28972,
"text": "There are some interesting findings from the above results that I’d like to point out."
},
{
"code": null,
"e": 29163,
"s": 29059,
"text": "Overall, I would say the model has learned and performed decently well on understanding Singlish words."
},
{
"code": null,
"e": 29189,
"s": 29163,
"text": "Not the best, but decent."
},
{
"code": null,
"e": 29482,
"s": 29189,
"text": "It’s no surprise that the model has learned that “Makan” (Malay for “Eat”), “Food” and “Eat” were found to be similar. But what’s interesting is the word “Jiak” — dialect for “Eat” and commonly used in Singlish sentences, was picked up and deemed similar to “Food”, “Makan” and “Eat” as well."
},
{
"code": null,
"e": 29559,
"s": 29482,
"text": "This looks to me that the model has indeed learned some Singlish words well."
},
{
"code": null,
"e": 29900,
"s": 29559,
"text": "The next interesting result comes from the abbreviations of country names. As humans reading the result, we know “sg” refers to “Singapore”, “kr” — “Korean”, “tw” — “Taiwan” & “hk” — “Hong Kong”. To a machine however, it is not that simple, the model did not have prior knowledge of these. Yet, it has managed to group these terms together."
},
{
"code": null,
"e": 29925,
"s": 29900,
"text": "Very interesting indeed!"
},
{
"code": null,
"e": 30027,
"s": 29925,
"text": "This is another validation point that tells me the model has trained decently well on Singlish words."
},
{
"code": null,
"e": 30200,
"s": 30027,
"text": "Now, instead of just staring at numbers, there is a method that helps us visualise words in vector space. This is called T-distributed Stochastic Neighbor Embedding (TSNE)."
},
{
"code": null,
"e": 30456,
"s": 30200,
"text": "TSNE can be loosely seen as a dimensionality reduction technique to visualise high-dimensional data. i.e. word embeddings of 100 dimensions. The idea is to embed high-dimensional points in low dimensions in a way that respects similarities between points."
},
{
"code": null,
"e": 30571,
"s": 30456,
"text": "In English, convert 100 dimensions into 2 or 3 dimensions and retain the embedded information as much as possible."
},
{
"code": null,
"e": 30696,
"s": 30571,
"text": "If I were to run TSNE (n=2 dimensions) on some of my results above and display it on a scatter plot, it will look like this:"
},
{
"code": null,
"e": 30721,
"s": 30696,
"text": "Not too shabby a result."
},
{
"code": null,
"e": 30810,
"s": 30721,
"text": "While the results above looked promising, there were some issues that needed addressing."
},
{
"code": null,
"e": 30909,
"s": 30810,
"text": "I only realised this when I was reviewing the results. The following section will explain further."
},
{
"code": null,
"e": 31016,
"s": 30909,
"text": "First off, as you can see, Singlish words like “lah”, “lor”, “meh” seem to be similar to each other but..."
},
{
"code": null,
"e": 31054,
"s": 31016,
"text": "So what? What does it actually mean?!"
},
{
"code": null,
"e": 31105,
"s": 31054,
"text": "After thinking about it, it is not exactly useful."
},
{
"code": null,
"e": 31348,
"s": 31105,
"text": "Singlish phrases usually appear as bigrams (2 words) that really encapsulates the meaning of the context in which it was used. A good example is Figure 3 — The power of “Can”. The bigrams “can meh?” vs “can lah!” have very different meanings."
},
{
"code": null,
"e": 31434,
"s": 31348,
"text": "If we were to look at the words independently, “can” and “meh”, that meaning is lost."
},
{
"code": null,
"e": 31538,
"s": 31434,
"text": "Therefore, having a vector representation of the words “meh” vs “lah”alone is not entirely useful here."
},
{
"code": null,
"e": 31751,
"s": 31538,
"text": "To remedy this issue, I needed a way to keep these words together. Skip-Gram trains on unigrams, yes. But what if I could convert these bigrams to unigrams first? i.e. “Can meh” -> “Can_meh” *note the underscore."
},
{
"code": null,
"e": 31827,
"s": 31751,
"text": "The second problem is not as serious as the first, but worth some air time."
},
{
"code": null,
"e": 32137,
"s": 31827,
"text": "It is the inherent problem with dimensionality reduction techniques like TSNE. You see, information loss by downsizing from 100 dimensions to 2 dimensions is inevitable. As much as I love visuals, I realised that I could only get the true understanding of the results by looking at numbers and not the visual."
},
{
"code": null,
"e": 32160,
"s": 32137,
"text": "Nothing to solve here."
},
{
"code": null,
"e": 32183,
"s": 32160,
"text": "Just food for thought."
},
{
"code": null,
"e": 32247,
"s": 32183,
"text": "Now let’s take a look at my attempt to solve the first problem."
},
{
"code": null,
"e": 32392,
"s": 32247,
"text": "After realising the issue with Singlish, I needed a way to convert my bigrams to unigram and yet keep the information or meaning of those words."
},
{
"code": null,
"e": 32482,
"s": 32392,
"text": "The way I could do that was by calculating the PMI of all possible bigrams in the corpus."
},
{
"code": null,
"e": 32685,
"s": 32482,
"text": "For example, the formula in Figure 7 reads, take the log of the probability of the occurrence of pair of words (i.e. “can meh”), divided by the probabilities of the occurrences of each individual words."
},
{
"code": null,
"e": 32725,
"s": 32685,
"text": "The breakdown of my process is as such:"
},
{
"code": null,
"e": 32753,
"s": 32725,
"text": "If x = “can” and y = “meh”,"
},
{
"code": null,
"e": 33093,
"s": 32753,
"text": "Count the number of times “can meh” appears together.Count the number of times “can” appears alone.Count the number of times “meh” appears alone.Apply PMI and get a score.Set some threshold parameter. If score is above threshold convert all occurrences of “can meh” into “can_meh” i.e. bigram to unigram.Retrain the entire skip-gram model."
},
{
"code": null,
"e": 33147,
"s": 33093,
"text": "Count the number of times “can meh” appears together."
},
{
"code": null,
"e": 33194,
"s": 33147,
"text": "Count the number of times “can” appears alone."
},
{
"code": null,
"e": 33241,
"s": 33194,
"text": "Count the number of times “meh” appears alone."
},
{
"code": null,
"e": 33268,
"s": 33241,
"text": "Apply PMI and get a score."
},
{
"code": null,
"e": 33402,
"s": 33268,
"text": "Set some threshold parameter. If score is above threshold convert all occurrences of “can meh” into “can_meh” i.e. bigram to unigram."
},
{
"code": null,
"e": 33438,
"s": 33402,
"text": "Retrain the entire skip-gram model."
},
{
"code": null,
"e": 33506,
"s": 33438,
"text": "The steps from 1 to 5 is actually known as building a phrase model."
},
{
"code": null,
"e": 33564,
"s": 33506,
"text": "And so... the quest to retrain my 17 hour model ensued..."
},
{
"code": null,
"e": 33757,
"s": 33564,
"text": "I calculated the PMI scores for all possible bigrams and set a threshold variable. I actually used the normalised version of the PMI formula above for calculation, but the concept is the same."
},
{
"code": null,
"e": 33814,
"s": 33757,
"text": "Technical Specifications of Normalised PMI phrase model:"
},
{
"code": null,
"e": 33876,
"s": 33814,
"text": "Minimum count of word = 5Threshold = 0.5 (range from -1 to 1)"
},
{
"code": null,
"e": 33902,
"s": 33876,
"text": "Minimum count of word = 5"
},
{
"code": null,
"e": 33939,
"s": 33902,
"text": "Threshold = 0.5 (range from -1 to 1)"
},
{
"code": null,
"e": 34242,
"s": 33939,
"text": "['as we are left with just 2 days of 2017 hereu2019s a song for everyone here edit to weewee especially lol', 'good_morning click here to download the hardwarezone_forums app']['wah_piang . why every time lidat one . siao liao can meh . wah_lau . can lah . can la . of course medicated_oil . can anot']"
},
{
"code": null,
"e": 34526,
"s": 34242,
"text": "As you can see, the threshold affects how many bigrams gets converted to unigrams. I did not manage to get bigrams of “can meh” to be converted to unigrams because if I were to set the threshold any lower, many other non-bigram related words will start to be converted into unigrams."
},
{
"code": null,
"e": 34568,
"s": 34526,
"text": "Sadly, there is a trade-off to make here."
},
{
"code": null,
"e": 34694,
"s": 34568,
"text": "After accounting for the bigrams, I retrained the model (which now took me 18 hours to train) and received the results below."
},
{
"code": null,
"e": 34839,
"s": 34694,
"text": "Notice how many non-related bigrams became unigrams? i.e. “for_her”, “with_her”. This is what I meant as trade-off in the phrase modelling step."
},
{
"code": null,
"e": 34916,
"s": 34839,
"text": "Because of all these non-related bigram, a number of the scores have fallen."
},
{
"code": null,
"e": 39576,
"s": 34916,
"text": "Similarity between 'her' & 'she': 0.8960039000509769Closest 10:her 1.0she 0.8960039000509765when_she 0.7756011613106286she_is 0.7612506774261273with_her 0.7449142184510621who 0.7348657494449988for_her 0.7306419631887822shes 0.7279985577059225face 0.7192153872317455look_like 0.718696491400789********************************************************Similarity between 'his' & 'he': 0.8129410509281912Closest 10:his 1.0he 0.8129410509281914him 0.804565895231623he_was 0.7816885610401878when_he 0.7747444761501758that_he 0.7724774086496818in_the 0.7622871291423432himself 0.7611962890490288was 0.7492507482663726with_his 0.7241458127853628********************************************************Similarity between 'jialat' & 'unlucky': 0.1258840952579276Closest 10:jialat 0.9999999999999996den 0.7104029620075444liao 0.7050826631244886chiu 0.6967369805196841heng 0.686838291277863hahaha 0.6860075650732084riao 0.6810071447192776la 0.6804775540889827le 0.676416467456822can_go 0.6756005150502169********************************************************Similarity between 'jialat' & 'bad': 0.4089547762801133Closest 10:bad 1.0but 0.8388423345999712good 0.8244038298175955really 0.8192112848219635i_think 0.7970842555698856very 0.7965053100959192like 0.785966214367795feel 0.783452344516318too 0.7788218726013071i_feel 0.7721110713307375********************************************************Similarity between 'bah' & 'ba': 0.5793487566624044Closest 10:bah 1.0say 0.6595798529633369lah 0.6451347547752344dun 0.6449884617104611sure 0.627629971037843bo_bian 0.6251418244527653this_kind 0.6223631439973716ppl 0.6196652346594724coz 0.61880214034487mah 0.6146197262236697********************************************************Similarity between 'lah' & 'la': 0.8863959901557994Closest 10:lah 0.9999999999999998la 0.8863959901557996meh 0.8739974021915318mah 0.8641084304399245say 0.8589606487232055lor 0.8535623035418399u 0.8304372234546418leh 0.8275930224011575loh 0.8189639505064721like_that 0.8170752533330873********************************************************Similarity between 'lah' & 'leh': 0.8275930224011575********************************************************Similarity between 'lah' & 'ba': 0.7298744482101323********************************************************Similarity between 'lah' & 'lor': 0.8535623035418399********************************************************Similarity between 'lah' & 'hor': 0.7787062026673155********************************************************Similarity between 'lor' & 'hor': 0.7283051932769404Closest 10:lor 1.0u 0.8706158009584564lah 0.8535623035418399mah 0.8300722350347082meh 0.8271088070439694or_not 0.8212467976061046can 0.8202962002027998la 0.8136970310629428say 0.8119961813856317no_need 0.8113510524754526********************************************************Similarity between 'walau' & 'walao': 0.37910878579551655Closest 10:walau 0.9999999999999998liao_lor 0.595008714889509last_time 0.5514972888957848riao 0.5508554544237825no_wonder 0.5449206686992254bttorn_wrote 0.5434895860379704hayley 0.5418542538935931y 0.5415132654837992meh 0.5397241464489063dunno 0.5377254112246059********************************************************Similarity between 'makan' & 'eat': 0.6600454451976521Closest 10:makan 0.9999999999999998go 0.7208286785168599den 0.697169918153346pple 0.6897361126052199got_pple 0.6756029930429751must 0.6677701662661563somemore 0.6675667631139202eat 0.6600454451976518lo 0.6524129092703767there 0.649481411415345********************************************************Similarity between 'makan' & 'food': 0.4861726118637594********************************************************Similarity between 'tw' & 'sg': 0.6679227949310249Closest 10:tw 1.0tiong 0.7219240075555984taiwan 0.7034844664255471hk 0.7028979577505058tiongland 0.6828634228902605mediacock 0.6751283466015426last_time 0.6732280724879228sg 0.6679227949310248this_yr 0.6384487035493662every_year 0.6284237559586139********************************************************Similarity between 'kr' & 'sg': 0.7700608852122885Closest 10:sg 1.0in_sg 0.8465612812762291kr 0.7700608852122885pple 0.7599772116504516laio 0.7520684090232901go 0.7509260306136896sure 0.7156635106866068come 0.7116443785982034tiongland 0.7015439847091592ongware_wrote 0.6974645318958415********************************************************Closest 10:wah_piang 1.0tsm 0.4967581460786865scourge_wrote 0.4923443232403448aikiboy_wrote 0.4887014894882954sian 0.4871567208941815ah_ma 0.48058368153798403lms 0.4790804214522433ruien 0.47420796750340777xln 0.46973552365710514myolie 0.4682823729806439********************************************************"
},
{
"code": null,
"e": 39645,
"s": 39576,
"text": "In short, the results above was worst off than the previous results."
},
{
"code": null,
"e": 39898,
"s": 39645,
"text": "I think that the this issue came from the lack of data. If I had more examples of people using “can meh” or “can lah”, the phrase model would have picked up these bigrams without having me set a low threshold. 0.5 threshold is really low in my opinion."
},
{
"code": null,
"e": 39933,
"s": 39898,
"text": "I caught too many false positives."
},
{
"code": null,
"e": 40001,
"s": 39933,
"text": "Rubbish in, rubbish out right? This was exactly what happened here."
},
{
"code": null,
"e": 40124,
"s": 40001,
"text": "As you can imagine, I still have ways to go in tuning my model to get decent Singlish word embeddings for my future works."
},
{
"code": null,
"e": 40161,
"s": 40124,
"text": "What I would do differently is this:"
},
{
"code": null,
"e": 40399,
"s": 40161,
"text": "Recode my scripts to run distributed. Or better yet, code to run in a GPU. This will allow me to run on a much larger corpus i.e. the whole of Hardware Zone and not just one thread of it.Train a better phrase model. i.e. the PMI portion."
},
{
"code": null,
"e": 40587,
"s": 40399,
"text": "Recode my scripts to run distributed. Or better yet, code to run in a GPU. This will allow me to run on a much larger corpus i.e. the whole of Hardware Zone and not just one thread of it."
},
{
"code": null,
"e": 40638,
"s": 40587,
"text": "Train a better phrase model. i.e. the PMI portion."
},
{
"code": null,
"e": 40700,
"s": 40638,
"text": "For now, I will keep the word embeddings for the first model."
},
{
"code": null,
"e": 40872,
"s": 40700,
"text": "Edit: If you’re interested in finding out about how to deal with misspellings, abbreviations or other OOV words in your corpus, I’ve written another article about it here!"
},
{
"code": null,
"e": 41065,
"s": 40872,
"text": "I’ve definitely learned a lot from this exercise and I hope that by me sharing my methodologies, thought processes and results, you’d be able to do the same in your respective local languages."
},
{
"code": null,
"e": 41090,
"s": 41065,
"text": "With that, adios amigos!"
},
{
"code": null,
"e": 41162,
"s": 41090,
"text": "Hope that you’ve enjoyed reading this as much as I’ve enjoyed doing it!"
},
{
"code": null,
"e": 41223,
"s": 41162,
"text": "Feel free to share the article if it helps anyone out there!"
},
{
"code": null,
"e": 41317,
"s": 41223,
"text": "If you are looking for NLP datasets to work with, click here for a curated list I created! :)"
}
] |
Train a Neural Network to classify images and optimize CPU inferencing in 10mins | by Ojas Dileep Sawant | Towards Data Science
|
There are tons of resources out there on simplified Training and optimized pre-trained Inferencing models. However, training something custom to optimize performance on readily available hardware with minimal effort still seemed far fetched!
In this article we will leverage the concept of transfer learning where a model trained to classify images is used to train our custom use-case (e.g. items in your pantry) in your device browser with Teachable Machine (GUI) and optimize CPU inferencing with Intel® OpenVINOTM Toolkit without any painful SW installation (in 10mins of-course!).
Is optimization necessary? Skip to the performance comparison at the end.
What setup do I need beforehand?
6th to 10th generation Intel Core or Intel Xeon processors (i.e. if you purchased an Intel device released 2016 onwards)
Docker installed on a Linux System with internet access to hub.docker.com
Access to a camera device (e.g. webcam)
On your camera-enabled laptop or desktop device navigate to https://teachablemachine.withgoogle.com/train/imageEdit Class labels (e.g. cereal box, cookies) and add as many as you wishUse Hold to Record button to capture a few frames from the live previewRepeat this for each class, and finally hit the Train Model buttonNote: Don’t switch your browser Tabs and let the training finishTest in the Preview Panel on the far right and hit Export ModelOn the Export your model.. pop-up click the second tab TensorflowWith Keras already selected, click the Download my model
On your camera-enabled laptop or desktop device navigate to https://teachablemachine.withgoogle.com/train/image
Edit Class labels (e.g. cereal box, cookies) and add as many as you wish
Use Hold to Record button to capture a few frames from the live preview
Repeat this for each class, and finally hit the Train Model buttonNote: Don’t switch your browser Tabs and let the training finish
Test in the Preview Panel on the far right and hit Export Model
On the Export your model.. pop-up click the second tab Tensorflow
With Keras already selected, click the Download my model
It might take some time but a file named converted_keras.zip will be downloaded eventually.
I have created a repo with utilities to automate this, so you don’t have to! Make sure to have docker, internet access, unzip, and git installed on the system.
Clone or download/extract the repo:
git clone https://github.com/ojjsaw/teachable-machine-openvino.git
Replace your custom converted_keras.zip file in the repo directory and run the below script from the repo root directory. It might take a few minutes while downloading docker images the very first time.
./util_conv_teachable_to_openvino.sh
Make sure to capture your test images pertaining to your custom trained model and run the code below.
Just 4ms with OpenVINO inference on the test.jpg after the TF Keras v1.15.0 model to OpenVINO IR conversion (includes removal of training nodes).
docker run --rm -it -v ${PWD}:/workdir openvino/ubuntu18_dev:latest /bin/bashcd /workdirpython3 teachable_img_openvino_classify.py frozen_model.xml frozen_model.bin labels.txt test.jpg
Teachable Machine website provides TF Keras python code for inferencing locally.
In my case, it took 804ms (~1.2fps) for the predict function with the default example code and model, while it took mere 4ms (~250fps) with OpenVINO python code on the same test.jpg image from previous section.
docker run --rm -it -v ${PWD}:/workdir tensorflow/tensorflow:1.15.0 bashcd /workdirpip install Pillowpython teachable_img_keras_orig_classify.py keras_model.h5 test.jpg
The first command enables rendering the OpenCV preview window from docker.
xhost + docker run --rm -it --privileged -v ${PWD}:/workdir -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix -v /dev/video0:/dev/video0 openvino/ubuntu18_dev:latest /bin/bash cd /workdir python3 teachable_livecam_openvino_classify.py frozen_model.xml frozen_model.bin labels.txt
There does exist a flow to quickly train custom image classification model with everyday hardware locally.
No code modification was required, just a few clicks away.
It is also totally worth going that extra mile for cutting down (800ms to 4ms) with OpenVINO inferencing on Intel CPU considering there was no extra effort required what-so-ever!
|
[
{
"code": null,
"e": 414,
"s": 172,
"text": "There are tons of resources out there on simplified Training and optimized pre-trained Inferencing models. However, training something custom to optimize performance on readily available hardware with minimal effort still seemed far fetched!"
},
{
"code": null,
"e": 758,
"s": 414,
"text": "In this article we will leverage the concept of transfer learning where a model trained to classify images is used to train our custom use-case (e.g. items in your pantry) in your device browser with Teachable Machine (GUI) and optimize CPU inferencing with Intel® OpenVINOTM Toolkit without any painful SW installation (in 10mins of-course!)."
},
{
"code": null,
"e": 832,
"s": 758,
"text": "Is optimization necessary? Skip to the performance comparison at the end."
},
{
"code": null,
"e": 865,
"s": 832,
"text": "What setup do I need beforehand?"
},
{
"code": null,
"e": 986,
"s": 865,
"text": "6th to 10th generation Intel Core or Intel Xeon processors (i.e. if you purchased an Intel device released 2016 onwards)"
},
{
"code": null,
"e": 1060,
"s": 986,
"text": "Docker installed on a Linux System with internet access to hub.docker.com"
},
{
"code": null,
"e": 1100,
"s": 1060,
"text": "Access to a camera device (e.g. webcam)"
},
{
"code": null,
"e": 1669,
"s": 1100,
"text": "On your camera-enabled laptop or desktop device navigate to https://teachablemachine.withgoogle.com/train/imageEdit Class labels (e.g. cereal box, cookies) and add as many as you wishUse Hold to Record button to capture a few frames from the live previewRepeat this for each class, and finally hit the Train Model buttonNote: Don’t switch your browser Tabs and let the training finishTest in the Preview Panel on the far right and hit Export ModelOn the Export your model.. pop-up click the second tab TensorflowWith Keras already selected, click the Download my model"
},
{
"code": null,
"e": 1781,
"s": 1669,
"text": "On your camera-enabled laptop or desktop device navigate to https://teachablemachine.withgoogle.com/train/image"
},
{
"code": null,
"e": 1854,
"s": 1781,
"text": "Edit Class labels (e.g. cereal box, cookies) and add as many as you wish"
},
{
"code": null,
"e": 1926,
"s": 1854,
"text": "Use Hold to Record button to capture a few frames from the live preview"
},
{
"code": null,
"e": 2057,
"s": 1926,
"text": "Repeat this for each class, and finally hit the Train Model buttonNote: Don’t switch your browser Tabs and let the training finish"
},
{
"code": null,
"e": 2121,
"s": 2057,
"text": "Test in the Preview Panel on the far right and hit Export Model"
},
{
"code": null,
"e": 2187,
"s": 2121,
"text": "On the Export your model.. pop-up click the second tab Tensorflow"
},
{
"code": null,
"e": 2244,
"s": 2187,
"text": "With Keras already selected, click the Download my model"
},
{
"code": null,
"e": 2336,
"s": 2244,
"text": "It might take some time but a file named converted_keras.zip will be downloaded eventually."
},
{
"code": null,
"e": 2496,
"s": 2336,
"text": "I have created a repo with utilities to automate this, so you don’t have to! Make sure to have docker, internet access, unzip, and git installed on the system."
},
{
"code": null,
"e": 2532,
"s": 2496,
"text": "Clone or download/extract the repo:"
},
{
"code": null,
"e": 2599,
"s": 2532,
"text": "git clone https://github.com/ojjsaw/teachable-machine-openvino.git"
},
{
"code": null,
"e": 2802,
"s": 2599,
"text": "Replace your custom converted_keras.zip file in the repo directory and run the below script from the repo root directory. It might take a few minutes while downloading docker images the very first time."
},
{
"code": null,
"e": 2839,
"s": 2802,
"text": "./util_conv_teachable_to_openvino.sh"
},
{
"code": null,
"e": 2941,
"s": 2839,
"text": "Make sure to capture your test images pertaining to your custom trained model and run the code below."
},
{
"code": null,
"e": 3087,
"s": 2941,
"text": "Just 4ms with OpenVINO inference on the test.jpg after the TF Keras v1.15.0 model to OpenVINO IR conversion (includes removal of training nodes)."
},
{
"code": null,
"e": 3272,
"s": 3087,
"text": "docker run --rm -it -v ${PWD}:/workdir openvino/ubuntu18_dev:latest /bin/bashcd /workdirpython3 teachable_img_openvino_classify.py frozen_model.xml frozen_model.bin labels.txt test.jpg"
},
{
"code": null,
"e": 3353,
"s": 3272,
"text": "Teachable Machine website provides TF Keras python code for inferencing locally."
},
{
"code": null,
"e": 3564,
"s": 3353,
"text": "In my case, it took 804ms (~1.2fps) for the predict function with the default example code and model, while it took mere 4ms (~250fps) with OpenVINO python code on the same test.jpg image from previous section."
},
{
"code": null,
"e": 3733,
"s": 3564,
"text": "docker run --rm -it -v ${PWD}:/workdir tensorflow/tensorflow:1.15.0 bashcd /workdirpip install Pillowpython teachable_img_keras_orig_classify.py keras_model.h5 test.jpg"
},
{
"code": null,
"e": 3808,
"s": 3733,
"text": "The first command enables rendering the OpenCV preview window from docker."
},
{
"code": null,
"e": 4091,
"s": 3808,
"text": "xhost + docker run --rm -it --privileged -v ${PWD}:/workdir -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix -v /dev/video0:/dev/video0 openvino/ubuntu18_dev:latest /bin/bash cd /workdir python3 teachable_livecam_openvino_classify.py frozen_model.xml frozen_model.bin labels.txt"
},
{
"code": null,
"e": 4198,
"s": 4091,
"text": "There does exist a flow to quickly train custom image classification model with everyday hardware locally."
},
{
"code": null,
"e": 4257,
"s": 4198,
"text": "No code modification was required, just a few clicks away."
}
] |
Design Patterns for MongoDB. Design decisions every full stack... | by Semi Koen | Towards Data Science
|
Since the dawn of computing, data is ever growing — this has a direct impact on the needs for storage, processing and analytics technologies. The past decade, developers have moved from SQL to NoSQL databases, with MongoDB being dominant in terms of popularity, as an operational data store in the world of enterprise applications.
If you have read any of my recent articles or know me in person you may realise how much I value software architecture and patterns. Most people think that they are only applicable on the server side. I truly believe though that the backend design should not be an afterthought, but a key part of the architecture. Bad design choices are explicitly affecting the solution’s scalability and performance.
As such today I will introduce you to a few practical MongoDB design patterns that any full stack developer should aim to understand, when using the MERN/MEAN collection of technologies:
Polymorphic Schema
Aggregate Data Model
❗️Assumption: Basic familiarity with MongoDB is necessary, so is some understanding of relational modelling (because we will refer to SQL as a contrasting approach).
Often, we think about MongoDB as a schema-less database, but this is not quite true! It does have schema, but it is dynamic i.e. the schema is not enforced on documents of the same collection, but contrary it has the ability to change and morph; that is why it is called polymorphic schema. What it means is that diverse datasets can be stored together, which is a competitive advantage for the booming unstructured big data.
Especially when it comes to Object Oriented Programming (OOP) and inheritance, the polymorphic capability of MongoDB becomes very handy, as developers can serialise instances of varying classes of the same hierarchy (parent-child) to the same collection, and then deserialise them back to objects.
This is not very straight forward in relational databases as tables have fixed schemas. For example, consider a trading system: A Security base class can be derived as Stock, Equity, Option etc.
While in MongoDB we can store the derived types in a single collection called Security and add on each document a discriminator (_t), in a relational database we have these modelling choices:
Single table with the union of the fields for Stock, Equity, Option, resulting in a sparsely populated schema.
Three tables, one for each concrete implementation of Stock, Equity, Option, resulting in redundancy (as there is repetitive base information of the Security attributes), as well as complicated queries to retrieve all types of securities.
One table for Security for the common content, and three tables for Stock, Equity, Option that will have a SecurityID and will only contain the respective attributes. This option solves the redundancy issue, but still the query can get complex.
As you can see there is a lot more code involved than in a polymorphic MongoDb collection!
The only thing constant in life is change — this certainly holds true to a database schema and it often poses challenges and a few headaches when it comes to traditional relational database systems. The Achilles heel of a tabular schema that has been carefully engineered to be normalised by eliminating redundancy is that a small change to one table can cause a ripple of changes across the database and can spill into the server-side application code too.
A typical approach is to stop the application, take a backup, run complex migration scripts to support the new schema, release the new version of the application to support the new schema and restart the application. With continuous deployment (CD) taking care of the application side of the release, the most time consuming task, requiring lengthy downtime, is pinned down to the database migration. Some ALTER commands executed on large tables can even take days to complete...
In MongoDB however, backwards compatibility comes out of the box, so developers account for these changes in the server-side code itself. Once the application is updated to handle the absence of a field, we can migrate the collection in question in the background while the application is still running (assuming there is more than a single node involved). When the entire collection is migrated, we can replace our application code to truly forget the old field.
Database design is not something that is written in stone and schema changes can be vexing (if not paralysing) in legacy tabular databases, so the polymorphic feature of MongoDB is very powerful indeed.
If you have any OOP experience, you must have come across in your career, Eric Evan’s classic book Domain Driven Design that introduces the aggregate models. An aggregate is a collection of data that we interact with as a unit, and normally has more complex structure than a traditional row/record i.e. it can hold nested lists, dictionaries or other composite types.
Atomicity is only supported within the contents of a single aggregate; in other words the aggregate forms the boundary of an ACID operation (read more on the MongoDB manual). Handling inter-aggregate relationships is more difficult than intra-aggregate ones: joins are not supported directly inside the kernel, but are managed in the application code or with the somewhat complex aggregation pipeline framework.
In essence there is a fine balance on whether to embed related objects within one another or reference them by ID, and as most things in modelling there is not a one-stop solution on how to make this decision. It is very much context specific as it depends on how the application interacts with the data.
Before we proceed, we need to understand what the advantages of embedding are:
🔴 The main reason for embedding documents is read performance which is connected to the very nature of the way computer disks are built: when looking for a particular record, they may take a while to locate it (high latency); but once they do, accessing any additional bytes happens fast (high bandwidth). So collocating related information makes sense as it can be retrieved in one go.🔴 Another aspect is that it reduces the round trips to the database that we had to program in order to query separate collections.
Now let’s explore some points to ponder when designing our MongoDB schema, based on the type of relationship that two entities have:
A One-to-One relationship is a type of cardinality that describes the relationship between two entities where one record from entity A is associated with one record in entity B. It can be modelled in two ways: either embedding the relationship as a sub-document, or linking to a document in a separate collection (no foreign key constraints are enforced so the relation only exists in the application level schema). It all depends upon how the data is being accessed by the application, how frequently and also the lifecycle of the dataset (i.e. if entity A is deleted, does entity B still have to exist?)
Golden Rule #1: If an object B needs to be accessed on its own (i.e. outside the context of the parent object A) then use reference, otherwise embed.
A One-to-Many relationship refers to the relationship between two entities A and B, where one side can have one or more links to the other, while the reverse is single sided. Like a 1:1 relationship, it can also be modelled by leveraging embedding or referencing.Here are the main considerations to take into account:
If a nested array of objects is to increase uncontrollably, embedding is not recommended as:
Each document cannot exceed 16MB.
New space needs to be allocated for the growing document and also indices need to be updated which impacts the write performance.
In this case referencing is preferred and entities A and B are modelled as stand-alone collections. However one trade off is that we will need to perform a second query to get the details of entity B, so read performance might be impacted. An application-level join comes to the rescue: with the correct indexing (for memory optimisation) and the usage of projections (for network bandwidth reduction) the server-side joins are slightly more expensive than the ones pushed to the DB engine. The $lookup operator should be required infrequently. If we need it a lot, there is a schema-smell!
Another option is to use pre-aggregated collections (acting as OLAP cubes) to simplify some of these joins.
Golden Rule # 2: Arrays should not grow without bound.- If there are less than a couple of hundred narrow documents on the B side, it is safe to embed them;— If there are more than a couple of hundred documents on the B side, we don’t embed the whole document; we link them by having an array of B objectID references;— If there are more than a few thousand documents on the B side, we use a parent-reference to the A-side in the B objects.
and
Golden Rule # 3: Application-level joins are common practice and not to be frowned upon; in these cases indexing selection makes or breaks the querying performance.
❗️Denormalisation: Two contributing factors to denormalise our documents are:
Updates will not be atomic any more;
High read-to-write ratio (i.e. a field that is mostly read and rarely updated is a good candidate for denormalisation).
A Many-to-Many relationship refers to the relationship between two entities A and B, where both sides can have one or more links to the other. In relational databases, these cases are modelled with a junction-table, however in MongoDB we can use bi-directional embedding, so we query A to search for the embedded references of the B objects, and then query B with an$in operator to find these returned references (the reverse is also possible). And vice versa.
Here the complexity arises from establishing an even balance between A and B, as the 16MB threshold can also be broken. In these instances, one-way embedding is recommended.
NoSQL Distilled
MongoDB University: Building with Patterns
MongoDB Antipatterns (MongoDb World 2019)
Domain Driven Design
The upshot of all of this is that MongoDB gives us the ability to design our schema to match the needs of our applications so we can get the most out of them. This flexibility is incredibly powerful but that power needs to be harnessed in terms of patterns we use in the application. — We need to remember that performance issues are frequently traced to poor schema design, as such it is essential to get it right, first time round.
Thanks for reading!
I regularly write about Leadership, Technology & Data on Medium — if you would like to read my future posts then please ‘Follow’ me!
|
[
{
"code": null,
"e": 504,
"s": 172,
"text": "Since the dawn of computing, data is ever growing — this has a direct impact on the needs for storage, processing and analytics technologies. The past decade, developers have moved from SQL to NoSQL databases, with MongoDB being dominant in terms of popularity, as an operational data store in the world of enterprise applications."
},
{
"code": null,
"e": 907,
"s": 504,
"text": "If you have read any of my recent articles or know me in person you may realise how much I value software architecture and patterns. Most people think that they are only applicable on the server side. I truly believe though that the backend design should not be an afterthought, but a key part of the architecture. Bad design choices are explicitly affecting the solution’s scalability and performance."
},
{
"code": null,
"e": 1094,
"s": 907,
"text": "As such today I will introduce you to a few practical MongoDB design patterns that any full stack developer should aim to understand, when using the MERN/MEAN collection of technologies:"
},
{
"code": null,
"e": 1113,
"s": 1094,
"text": "Polymorphic Schema"
},
{
"code": null,
"e": 1134,
"s": 1113,
"text": "Aggregate Data Model"
},
{
"code": null,
"e": 1300,
"s": 1134,
"text": "❗️Assumption: Basic familiarity with MongoDB is necessary, so is some understanding of relational modelling (because we will refer to SQL as a contrasting approach)."
},
{
"code": null,
"e": 1726,
"s": 1300,
"text": "Often, we think about MongoDB as a schema-less database, but this is not quite true! It does have schema, but it is dynamic i.e. the schema is not enforced on documents of the same collection, but contrary it has the ability to change and morph; that is why it is called polymorphic schema. What it means is that diverse datasets can be stored together, which is a competitive advantage for the booming unstructured big data."
},
{
"code": null,
"e": 2024,
"s": 1726,
"text": "Especially when it comes to Object Oriented Programming (OOP) and inheritance, the polymorphic capability of MongoDB becomes very handy, as developers can serialise instances of varying classes of the same hierarchy (parent-child) to the same collection, and then deserialise them back to objects."
},
{
"code": null,
"e": 2219,
"s": 2024,
"text": "This is not very straight forward in relational databases as tables have fixed schemas. For example, consider a trading system: A Security base class can be derived as Stock, Equity, Option etc."
},
{
"code": null,
"e": 2411,
"s": 2219,
"text": "While in MongoDB we can store the derived types in a single collection called Security and add on each document a discriminator (_t), in a relational database we have these modelling choices:"
},
{
"code": null,
"e": 2522,
"s": 2411,
"text": "Single table with the union of the fields for Stock, Equity, Option, resulting in a sparsely populated schema."
},
{
"code": null,
"e": 2761,
"s": 2522,
"text": "Three tables, one for each concrete implementation of Stock, Equity, Option, resulting in redundancy (as there is repetitive base information of the Security attributes), as well as complicated queries to retrieve all types of securities."
},
{
"code": null,
"e": 3006,
"s": 2761,
"text": "One table for Security for the common content, and three tables for Stock, Equity, Option that will have a SecurityID and will only contain the respective attributes. This option solves the redundancy issue, but still the query can get complex."
},
{
"code": null,
"e": 3097,
"s": 3006,
"text": "As you can see there is a lot more code involved than in a polymorphic MongoDb collection!"
},
{
"code": null,
"e": 3555,
"s": 3097,
"text": "The only thing constant in life is change — this certainly holds true to a database schema and it often poses challenges and a few headaches when it comes to traditional relational database systems. The Achilles heel of a tabular schema that has been carefully engineered to be normalised by eliminating redundancy is that a small change to one table can cause a ripple of changes across the database and can spill into the server-side application code too."
},
{
"code": null,
"e": 4035,
"s": 3555,
"text": "A typical approach is to stop the application, take a backup, run complex migration scripts to support the new schema, release the new version of the application to support the new schema and restart the application. With continuous deployment (CD) taking care of the application side of the release, the most time consuming task, requiring lengthy downtime, is pinned down to the database migration. Some ALTER commands executed on large tables can even take days to complete..."
},
{
"code": null,
"e": 4499,
"s": 4035,
"text": "In MongoDB however, backwards compatibility comes out of the box, so developers account for these changes in the server-side code itself. Once the application is updated to handle the absence of a field, we can migrate the collection in question in the background while the application is still running (assuming there is more than a single node involved). When the entire collection is migrated, we can replace our application code to truly forget the old field."
},
{
"code": null,
"e": 4702,
"s": 4499,
"text": "Database design is not something that is written in stone and schema changes can be vexing (if not paralysing) in legacy tabular databases, so the polymorphic feature of MongoDB is very powerful indeed."
},
{
"code": null,
"e": 5070,
"s": 4702,
"text": "If you have any OOP experience, you must have come across in your career, Eric Evan’s classic book Domain Driven Design that introduces the aggregate models. An aggregate is a collection of data that we interact with as a unit, and normally has more complex structure than a traditional row/record i.e. it can hold nested lists, dictionaries or other composite types."
},
{
"code": null,
"e": 5482,
"s": 5070,
"text": "Atomicity is only supported within the contents of a single aggregate; in other words the aggregate forms the boundary of an ACID operation (read more on the MongoDB manual). Handling inter-aggregate relationships is more difficult than intra-aggregate ones: joins are not supported directly inside the kernel, but are managed in the application code or with the somewhat complex aggregation pipeline framework."
},
{
"code": null,
"e": 5787,
"s": 5482,
"text": "In essence there is a fine balance on whether to embed related objects within one another or reference them by ID, and as most things in modelling there is not a one-stop solution on how to make this decision. It is very much context specific as it depends on how the application interacts with the data."
},
{
"code": null,
"e": 5866,
"s": 5787,
"text": "Before we proceed, we need to understand what the advantages of embedding are:"
},
{
"code": null,
"e": 6383,
"s": 5866,
"text": "🔴 The main reason for embedding documents is read performance which is connected to the very nature of the way computer disks are built: when looking for a particular record, they may take a while to locate it (high latency); but once they do, accessing any additional bytes happens fast (high bandwidth). So collocating related information makes sense as it can be retrieved in one go.🔴 Another aspect is that it reduces the round trips to the database that we had to program in order to query separate collections."
},
{
"code": null,
"e": 6516,
"s": 6383,
"text": "Now let’s explore some points to ponder when designing our MongoDB schema, based on the type of relationship that two entities have:"
},
{
"code": null,
"e": 7122,
"s": 6516,
"text": "A One-to-One relationship is a type of cardinality that describes the relationship between two entities where one record from entity A is associated with one record in entity B. It can be modelled in two ways: either embedding the relationship as a sub-document, or linking to a document in a separate collection (no foreign key constraints are enforced so the relation only exists in the application level schema). It all depends upon how the data is being accessed by the application, how frequently and also the lifecycle of the dataset (i.e. if entity A is deleted, does entity B still have to exist?)"
},
{
"code": null,
"e": 7273,
"s": 7122,
"text": "Golden Rule #1: If an object B needs to be accessed on its own (i.e. outside the context of the parent object A) then use reference, otherwise embed."
},
{
"code": null,
"e": 7591,
"s": 7273,
"text": "A One-to-Many relationship refers to the relationship between two entities A and B, where one side can have one or more links to the other, while the reverse is single sided. Like a 1:1 relationship, it can also be modelled by leveraging embedding or referencing.Here are the main considerations to take into account:"
},
{
"code": null,
"e": 7684,
"s": 7591,
"text": "If a nested array of objects is to increase uncontrollably, embedding is not recommended as:"
},
{
"code": null,
"e": 7718,
"s": 7684,
"text": "Each document cannot exceed 16MB."
},
{
"code": null,
"e": 7848,
"s": 7718,
"text": "New space needs to be allocated for the growing document and also indices need to be updated which impacts the write performance."
},
{
"code": null,
"e": 8439,
"s": 7848,
"text": "In this case referencing is preferred and entities A and B are modelled as stand-alone collections. However one trade off is that we will need to perform a second query to get the details of entity B, so read performance might be impacted. An application-level join comes to the rescue: with the correct indexing (for memory optimisation) and the usage of projections (for network bandwidth reduction) the server-side joins are slightly more expensive than the ones pushed to the DB engine. The $lookup operator should be required infrequently. If we need it a lot, there is a schema-smell!"
},
{
"code": null,
"e": 8547,
"s": 8439,
"text": "Another option is to use pre-aggregated collections (acting as OLAP cubes) to simplify some of these joins."
},
{
"code": null,
"e": 8988,
"s": 8547,
"text": "Golden Rule # 2: Arrays should not grow without bound.- If there are less than a couple of hundred narrow documents on the B side, it is safe to embed them;— If there are more than a couple of hundred documents on the B side, we don’t embed the whole document; we link them by having an array of B objectID references;— If there are more than a few thousand documents on the B side, we use a parent-reference to the A-side in the B objects."
},
{
"code": null,
"e": 8992,
"s": 8988,
"text": "and"
},
{
"code": null,
"e": 9157,
"s": 8992,
"text": "Golden Rule # 3: Application-level joins are common practice and not to be frowned upon; in these cases indexing selection makes or breaks the querying performance."
},
{
"code": null,
"e": 9235,
"s": 9157,
"text": "❗️Denormalisation: Two contributing factors to denormalise our documents are:"
},
{
"code": null,
"e": 9272,
"s": 9235,
"text": "Updates will not be atomic any more;"
},
{
"code": null,
"e": 9392,
"s": 9272,
"text": "High read-to-write ratio (i.e. a field that is mostly read and rarely updated is a good candidate for denormalisation)."
},
{
"code": null,
"e": 9853,
"s": 9392,
"text": "A Many-to-Many relationship refers to the relationship between two entities A and B, where both sides can have one or more links to the other. In relational databases, these cases are modelled with a junction-table, however in MongoDB we can use bi-directional embedding, so we query A to search for the embedded references of the B objects, and then query B with an$in operator to find these returned references (the reverse is also possible). And vice versa."
},
{
"code": null,
"e": 10027,
"s": 9853,
"text": "Here the complexity arises from establishing an even balance between A and B, as the 16MB threshold can also be broken. In these instances, one-way embedding is recommended."
},
{
"code": null,
"e": 10043,
"s": 10027,
"text": "NoSQL Distilled"
},
{
"code": null,
"e": 10086,
"s": 10043,
"text": "MongoDB University: Building with Patterns"
},
{
"code": null,
"e": 10128,
"s": 10086,
"text": "MongoDB Antipatterns (MongoDb World 2019)"
},
{
"code": null,
"e": 10149,
"s": 10128,
"text": "Domain Driven Design"
},
{
"code": null,
"e": 10583,
"s": 10149,
"text": "The upshot of all of this is that MongoDB gives us the ability to design our schema to match the needs of our applications so we can get the most out of them. This flexibility is incredibly powerful but that power needs to be harnessed in terms of patterns we use in the application. — We need to remember that performance issues are frequently traced to poor schema design, as such it is essential to get it right, first time round."
},
{
"code": null,
"e": 10603,
"s": 10583,
"text": "Thanks for reading!"
}
] |
Data Visualization Using Pandas Bokeh | by Raji Rai | Towards Data Science
|
Exploratory data analysis is the foundation for understanding and building effective ML models. Data visualization is a key part of EDA, and there are many tools available for this. Bokeh is an interactive visualization library. It provides intuitive and versatile graphics. Bokeh can help to quickly and easily make interactive plots and dashboards. Pandas Bokeh provides a Bokeh plotting backend for Pandas.
Integrating Pandas Bokeh with your Python code is very simple. You only need to install and import the pandas-bokeh library, and then you can use it like any other visual tool. You should import Pandas-Bokeh library after importing Pandas. Use the following command to download and import pandas-bokeh library:
#Load the pandas_bokeh library!pip install pandas_bokehimport pandas as pdimport pandas_bokeh
You can set the plotting output as HTML or Notebook. To set the output to notebook use the command, pandas_bokeh.output_notebook(). This will embed the plot in the notebook cell. To display the output as a HTML file use the command, pandas_bokeh.output_file(filename).
You can easily plot Pandas DataFrames using the command, df.plot_bokeh(). Pandas Bokeh offers a wide variety of plotting options such as line, scatter, bar, histogram, area, mapplot, step, point, and pie. All the plots are interactive, pannable, and zoomable. Here are some examples with the code of popular visualizations, plotted using pandas_bokeh that are commonly used in data analysis.
Bar Plot
#Vertical barchartcarhpbot.plot_bokeh( kind="bar", figsize =(1000,800), x="name", xlabel="Car Models", title="Bottom 10 Car Features", alpha=0.6, legend = "top_right", show_figure=True)#Stacked vertical barcarhpbot.plot_bokeh.bar( figsize =(1000,800), x="name", stacked=True, xlabel="Car Models", title="Bottom 10 Car Features", alpha=0.6, legend = "top_right", show_figure=True)
Line Plot
iris.plot_bokeh( kind='line', x='species', y=['sepal_length', 'sepal_width','petal_length','petal_width'], xlabel='Species', ylabel='Length and Width', title='Flowers',)
Histogram
iris.plot_bokeh(kind="hist",title ="Iris feature distribution", figsize =(1000,800), xlabel = "Features", ylabel="Measure" )
Scatter Plot
car.plot_bokeh.scatter( x='horsepower', y=['weight'], figsize=(1000, 700), zooming=False, panning=False)
Map Plot
mapplot["size"] = mapplot["pop_max"] / 1000000mapplot.plot_bokeh.map( x="longitude", y="latitude", hovertool_string="""<h2> @{name} </h2> <h3> Population: @{pop_max} </h3>""", tile_provider="STAMEN_TERRAIN_RETINA", size="size", figsize=(1200, 600), title="Cities with more than 1000K population")
Area Plot
carhp.plot_bokeh.area( x="name", stacked=True, figsize=(1300, 700), title="Compare Car Models", xlabel="Top 10 Car models", )
These were some basic plots plotted using pandas_bokeh. Each of these plots can be enhanced further using various optional parameters. Pandas Bokeh has provided a wonderful GitHub repository explaining all the plots with some great examples. The examples that I have shown above are all available with the data set in my Kaggle notebook.
|
[
{
"code": null,
"e": 582,
"s": 172,
"text": "Exploratory data analysis is the foundation for understanding and building effective ML models. Data visualization is a key part of EDA, and there are many tools available for this. Bokeh is an interactive visualization library. It provides intuitive and versatile graphics. Bokeh can help to quickly and easily make interactive plots and dashboards. Pandas Bokeh provides a Bokeh plotting backend for Pandas."
},
{
"code": null,
"e": 893,
"s": 582,
"text": "Integrating Pandas Bokeh with your Python code is very simple. You only need to install and import the pandas-bokeh library, and then you can use it like any other visual tool. You should import Pandas-Bokeh library after importing Pandas. Use the following command to download and import pandas-bokeh library:"
},
{
"code": null,
"e": 987,
"s": 893,
"text": "#Load the pandas_bokeh library!pip install pandas_bokehimport pandas as pdimport pandas_bokeh"
},
{
"code": null,
"e": 1256,
"s": 987,
"text": "You can set the plotting output as HTML or Notebook. To set the output to notebook use the command, pandas_bokeh.output_notebook(). This will embed the plot in the notebook cell. To display the output as a HTML file use the command, pandas_bokeh.output_file(filename)."
},
{
"code": null,
"e": 1648,
"s": 1256,
"text": "You can easily plot Pandas DataFrames using the command, df.plot_bokeh(). Pandas Bokeh offers a wide variety of plotting options such as line, scatter, bar, histogram, area, mapplot, step, point, and pie. All the plots are interactive, pannable, and zoomable. Here are some examples with the code of popular visualizations, plotted using pandas_bokeh that are commonly used in data analysis."
},
{
"code": null,
"e": 1657,
"s": 1648,
"text": "Bar Plot"
},
{
"code": null,
"e": 2089,
"s": 1657,
"text": "#Vertical barchartcarhpbot.plot_bokeh( kind=\"bar\", figsize =(1000,800), x=\"name\", xlabel=\"Car Models\", title=\"Bottom 10 Car Features\", alpha=0.6, legend = \"top_right\", show_figure=True)#Stacked vertical barcarhpbot.plot_bokeh.bar( figsize =(1000,800), x=\"name\", stacked=True, xlabel=\"Car Models\", title=\"Bottom 10 Car Features\", alpha=0.6, legend = \"top_right\", show_figure=True)"
},
{
"code": null,
"e": 2099,
"s": 2089,
"text": "Line Plot"
},
{
"code": null,
"e": 2287,
"s": 2099,
"text": "iris.plot_bokeh( kind='line', x='species', y=['sepal_length', 'sepal_width','petal_length','petal_width'], xlabel='Species', ylabel='Length and Width', title='Flowers',)"
},
{
"code": null,
"e": 2297,
"s": 2287,
"text": "Histogram"
},
{
"code": null,
"e": 2491,
"s": 2297,
"text": "iris.plot_bokeh(kind=\"hist\",title =\"Iris feature distribution\", figsize =(1000,800), xlabel = \"Features\", ylabel=\"Measure\" )"
},
{
"code": null,
"e": 2504,
"s": 2491,
"text": "Scatter Plot"
},
{
"code": null,
"e": 2625,
"s": 2504,
"text": "car.plot_bokeh.scatter( x='horsepower', y=['weight'], figsize=(1000, 700), zooming=False, panning=False)"
},
{
"code": null,
"e": 2634,
"s": 2625,
"text": "Map Plot"
},
{
"code": null,
"e": 2981,
"s": 2634,
"text": "mapplot[\"size\"] = mapplot[\"pop_max\"] / 1000000mapplot.plot_bokeh.map( x=\"longitude\", y=\"latitude\", hovertool_string=\"\"\"<h2> @{name} </h2> <h3> Population: @{pop_max} </h3>\"\"\", tile_provider=\"STAMEN_TERRAIN_RETINA\", size=\"size\", figsize=(1200, 600), title=\"Cities with more than 1000K population\")"
},
{
"code": null,
"e": 2991,
"s": 2981,
"text": "Area Plot"
},
{
"code": null,
"e": 3135,
"s": 2991,
"text": "carhp.plot_bokeh.area( x=\"name\", stacked=True, figsize=(1300, 700), title=\"Compare Car Models\", xlabel=\"Top 10 Car models\", )"
}
] |
Zoho Interview | Set 4 - GeeksforGeeks
|
22 Jul, 2019
Round one:Note: They have two patterns, for me they asked programming pattern, which is really tough.Time: 2.15 hrs40 Questions full of programming, first 10 questions have half mark, next 30 Questions have 1 mark, no Compilation Errors.1) First 10 questions is to find the output of program which contains full of loops, loops inside loops.2) Next 30 Questions has five parts....a) To find the input of the program, output will be given.....b) To find the error in logic and correct it, to provide the expected output.....c) To find which two program gives the same result among given four programs.....d) To find the loop condition for the desired output.....e) To find the order of function in execution..
Round two:Level One:1) To find the odd numbers in between the range.Input:215Output:3,5,7,9,11,13
2) To find the factors of the numbers given in an array and to sort the numbers in descending order according to the factors present in it.Input:Given array : 8, 2, 3, 12, 16Output:12, 16, 8, 2, 3
3) To output the number in words (0-999)Input: 234Output: Two hundred and Thirty Four
4) To find the print the pattern:Ip: n=5Op:11 12 11 2 1 11 1 1 2 2 1
5) A man his driving car from home to office with X petrol. There are N number of petrol bunks in the city with only few capacities and each petrol is located in different places For one km one liter will consume. So he fill up petrol in his petrol tank in each petrol bunks. Output the remaining petrol if he has or tell him that he cannot travel if he is out of petrol.Input:Petrol in car: 2 LitersPetrol bunks: A B CDistance from petrol each petrol bunks: 1, 5, 3Capacities of each petrol bunk: 6, 4, 2Output:Remaining petrol in car is 5 liters
Level two:1) Print the given pattern:Input:N= 3, M=3Output:X X XX 0 XX X X
Input:N=4 M=5Output:X X X XX 0 0 XX 0 0 XX 0 0 XX X X X
Input:N=6 M=7X X X X X XX 0 0 0 0 XX 0 X X 0 XX 0 X X 0 XX 0 X X 0 XX 0 0 0 0 XX X X X X X
2) To find the number of groups and output the groups:Explanation: To find the sum of the elements in the groups and that sum should be divisible by input X and the groups should be limited to range with X numbers.If X is 3, then the group should have only 2 elements and 3 elements from the array whose sum is divisible by 3.Input:Array: 3, 9, 7, 4, 6, 8X: 3Output:3, 93, 69, 63, 9, 6No of groups: 4
Level three:1) To output the given string for the given input which is an integer.Input: 1Output: AInput: 26Output: ZInput : 27Output: AAInput: 28:Output: ABInput: 1000Output: ALL
2) Input:Number of elements in set1: 4Elements are: 9, 9, 9, 9Number of elements in set 2: 3Elements are: 1,1,1Output:1, 0, 1, 1, 0Input:Number of elements in set1: 11Elements are: 7,2,3,4,5,3,1,2,7,2,8Number of elements in set 2: 3Elements are: 1,2,3Output: 7,2,3,4,5,3,1,2,8,5,1
Round three:Real time programming and analysis:Note: Showing output does matter need to show the output as soon as possible. And also need to solve the constraints very fast, since you know what you have done in your program. After finishing the program always explain the logic behind it and the constraints about the processing and how you solved those constraints to the technical people.1) To form a structure which has few elements:
struct product {
char productname[20];
int product_price;
int product_id;
}
Get the product name, price and id and display the product name and price in descending of the price.
2) For the same above structure, now add another structure which is the category. That category will have products in it.
Struct category
{
char category_name[20];
int cat_id;
}
According the category get the product name, product price and id, then display all the products category wise in descending order.
3) For the same structure which as category and product, get the category id from the user in the product structure and save to the category list. Then display them all in category wise.
4) A sheet full of data will be given with inventory stock list, which as different categories and different products as input with category capacity and product availability in the structure. Now we need to add a new category or new product with capacity and availability. Need to check whether the product availability is exceeding the category capacity, if yes the output rack is full or else tell how much free space is available and add the product to list.
5) Constraints in the above in question will be given, need to solve all the constraints, so that the Technical HR gets satisfied.
After these rounds, if they get satisfied, they will call you for Technical HR, followed by General HR. If you solved every single question and you were really fast in problem solving, then HR interview will be easy. Or else HR interview will be very tough especially the Technical HR (The Technical HR round as lots of logical questions)
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience for SDE-1
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Microsoft Interview Experience for Internship (Via Engage)
Infosys DSE Interview Experience 2021
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience | Set 420 (For QAE)
|
[
{
"code": null,
"e": 24974,
"s": 24946,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 25683,
"s": 24974,
"text": "Round one:Note: They have two patterns, for me they asked programming pattern, which is really tough.Time: 2.15 hrs40 Questions full of programming, first 10 questions have half mark, next 30 Questions have 1 mark, no Compilation Errors.1) First 10 questions is to find the output of program which contains full of loops, loops inside loops.2) Next 30 Questions has five parts....a) To find the input of the program, output will be given.....b) To find the error in logic and correct it, to provide the expected output.....c) To find which two program gives the same result among given four programs.....d) To find the loop condition for the desired output.....e) To find the order of function in execution.."
},
{
"code": null,
"e": 25781,
"s": 25683,
"text": "Round two:Level One:1) To find the odd numbers in between the range.Input:215Output:3,5,7,9,11,13"
},
{
"code": null,
"e": 25978,
"s": 25781,
"text": "2) To find the factors of the numbers given in an array and to sort the numbers in descending order according to the factors present in it.Input:Given array : 8, 2, 3, 12, 16Output:12, 16, 8, 2, 3"
},
{
"code": null,
"e": 26064,
"s": 25978,
"text": "3) To output the number in words (0-999)Input: 234Output: Two hundred and Thirty Four"
},
{
"code": null,
"e": 26133,
"s": 26064,
"text": "4) To find the print the pattern:Ip: n=5Op:11 12 11 2 1 11 1 1 2 2 1"
},
{
"code": null,
"e": 26681,
"s": 26133,
"text": "5) A man his driving car from home to office with X petrol. There are N number of petrol bunks in the city with only few capacities and each petrol is located in different places For one km one liter will consume. So he fill up petrol in his petrol tank in each petrol bunks. Output the remaining petrol if he has or tell him that he cannot travel if he is out of petrol.Input:Petrol in car: 2 LitersPetrol bunks: A B CDistance from petrol each petrol bunks: 1, 5, 3Capacities of each petrol bunk: 6, 4, 2Output:Remaining petrol in car is 5 liters"
},
{
"code": null,
"e": 26756,
"s": 26681,
"text": "Level two:1) Print the given pattern:Input:N= 3, M=3Output:X X XX 0 XX X X"
},
{
"code": null,
"e": 26812,
"s": 26756,
"text": "Input:N=4 M=5Output:X X X XX 0 0 XX 0 0 XX 0 0 XX X X X"
},
{
"code": null,
"e": 26903,
"s": 26812,
"text": "Input:N=6 M=7X X X X X XX 0 0 0 0 XX 0 X X 0 XX 0 X X 0 XX 0 X X 0 XX 0 0 0 0 XX X X X X X"
},
{
"code": null,
"e": 27304,
"s": 26903,
"text": "2) To find the number of groups and output the groups:Explanation: To find the sum of the elements in the groups and that sum should be divisible by input X and the groups should be limited to range with X numbers.If X is 3, then the group should have only 2 elements and 3 elements from the array whose sum is divisible by 3.Input:Array: 3, 9, 7, 4, 6, 8X: 3Output:3, 93, 69, 63, 9, 6No of groups: 4"
},
{
"code": null,
"e": 27484,
"s": 27304,
"text": "Level three:1) To output the given string for the given input which is an integer.Input: 1Output: AInput: 26Output: ZInput : 27Output: AAInput: 28:Output: ABInput: 1000Output: ALL"
},
{
"code": null,
"e": 27765,
"s": 27484,
"text": "2) Input:Number of elements in set1: 4Elements are: 9, 9, 9, 9Number of elements in set 2: 3Elements are: 1,1,1Output:1, 0, 1, 1, 0Input:Number of elements in set1: 11Elements are: 7,2,3,4,5,3,1,2,7,2,8Number of elements in set 2: 3Elements are: 1,2,3Output: 7,2,3,4,5,3,1,2,8,5,1"
},
{
"code": null,
"e": 28203,
"s": 27765,
"text": "Round three:Real time programming and analysis:Note: Showing output does matter need to show the output as soon as possible. And also need to solve the constraints very fast, since you know what you have done in your program. After finishing the program always explain the logic behind it and the constraints about the processing and how you solved those constraints to the technical people.1) To form a structure which has few elements:"
},
{
"code": null,
"e": 28288,
"s": 28203,
"text": "struct product {\n char productname[20];\n int product_price;\n int product_id;\n}"
},
{
"code": null,
"e": 28390,
"s": 28288,
"text": "Get the product name, price and id and display the product name and price in descending of the price."
},
{
"code": null,
"e": 28512,
"s": 28390,
"text": "2) For the same above structure, now add another structure which is the category. That category will have products in it."
},
{
"code": null,
"e": 28575,
"s": 28512,
"text": "Struct category\n{\n char category_name[20];\n int cat_id;\n} "
},
{
"code": null,
"e": 28707,
"s": 28575,
"text": "According the category get the product name, product price and id, then display all the products category wise in descending order."
},
{
"code": null,
"e": 28894,
"s": 28707,
"text": "3) For the same structure which as category and product, get the category id from the user in the product structure and save to the category list. Then display them all in category wise."
},
{
"code": null,
"e": 29357,
"s": 28894,
"text": "4) A sheet full of data will be given with inventory stock list, which as different categories and different products as input with category capacity and product availability in the structure. Now we need to add a new category or new product with capacity and availability. Need to check whether the product availability is exceeding the category capacity, if yes the output rack is full or else tell how much free space is available and add the product to list."
},
{
"code": null,
"e": 29488,
"s": 29357,
"text": "5) Constraints in the above in question will be given, need to solve all the constraints, so that the Technical HR gets satisfied."
},
{
"code": null,
"e": 29827,
"s": 29488,
"text": "After these rounds, if they get satisfied, they will call you for Technical HR, followed by General HR. If you solved every single question and you were really fast in problem solving, then HR interview will be easy. Or else HR interview will be very tough especially the Technical HR (The Technical HR round as lots of logical questions)"
},
{
"code": null,
"e": 30048,
"s": 29827,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30053,
"s": 30048,
"text": "Zoho"
},
{
"code": null,
"e": 30075,
"s": 30053,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30080,
"s": 30075,
"text": "Zoho"
},
{
"code": null,
"e": 30178,
"s": 30080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30187,
"s": 30178,
"text": "Comments"
},
{
"code": null,
"e": 30200,
"s": 30187,
"text": "Old Comments"
},
{
"code": null,
"e": 30250,
"s": 30200,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 30288,
"s": 30250,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30334,
"s": 30288,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 30372,
"s": 30334,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30437,
"s": 30372,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 30496,
"s": 30437,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 30534,
"s": 30496,
"text": "Infosys DSE Interview Experience 2021"
},
{
"code": null,
"e": 30606,
"s": 30534,
"text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022"
},
{
"code": null,
"e": 30656,
"s": 30606,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
}
] |
Why does Python automatically exit a script when it’s done? - GeeksforGeeks
|
26 Nov, 2020
Python is a scripting language. This means that a Python code is executed line by line with the help of a Python interpreter. When a python interpreter encounters an end-of-file character, it is unable to retrieve any data from the script. This EOF(end-of-file) character is the same as the EOF that informs the end of the file while reading data from a file in Python.
There is an EOF character present at the end of each python script that instructs the interpreter to stop the execution of code. While working on a standard input connected to a tty device, we can produce a similar result with CTRL+D on UNIX and CTRL+Z, ENTER on Windows.
Consider this simple code that takes a number as user input and returns twice of that number.
Python3
a = int(input("Enter number: "))# waiting for user input... print("Twice of the number: ", 2 * a)
Try pressing the EOF character(depending on your os) while the program is waiting for user input. The program will terminate as soon as it encounters the EOF character like this:
Exiting Python Script
Notice that the program throws an EOFError Exception when it encounters EOF before the program completion.
We can use the atexit module to detect the script exit. The following code detects script exit using register() function of the atexit module.
Syntax: atexit.register(fun, *args, **kwargs)
Parameters: First the function name is mentioned and then any arguments for that function is passed. The parameters are separated using ‘, ‘.
Return: This function returns the called fun and hence the calling can be traced.
The atexit.register() method takes a function as an argument that is to be executed at script exit.
Python3
import atexit a = 5print("Twice of a:", a*2) atexit.register(print, "Exiting Python Script")
Output:
Twice of a: 10
Exiting Python Script
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24662,
"s": 24292,
"text": "Python is a scripting language. This means that a Python code is executed line by line with the help of a Python interpreter. When a python interpreter encounters an end-of-file character, it is unable to retrieve any data from the script. This EOF(end-of-file) character is the same as the EOF that informs the end of the file while reading data from a file in Python."
},
{
"code": null,
"e": 24935,
"s": 24662,
"text": "There is an EOF character present at the end of each python script that instructs the interpreter to stop the execution of code. While working on a standard input connected to a tty device, we can produce a similar result with CTRL+D on UNIX and CTRL+Z, ENTER on Windows. "
},
{
"code": null,
"e": 25029,
"s": 24935,
"text": "Consider this simple code that takes a number as user input and returns twice of that number."
},
{
"code": null,
"e": 25037,
"s": 25029,
"text": "Python3"
},
{
"code": "a = int(input(\"Enter number: \"))# waiting for user input... print(\"Twice of the number: \", 2 * a)",
"e": 25137,
"s": 25037,
"text": null
},
{
"code": null,
"e": 25316,
"s": 25137,
"text": "Try pressing the EOF character(depending on your os) while the program is waiting for user input. The program will terminate as soon as it encounters the EOF character like this:"
},
{
"code": null,
"e": 25338,
"s": 25316,
"text": "Exiting Python Script"
},
{
"code": null,
"e": 25445,
"s": 25338,
"text": "Notice that the program throws an EOFError Exception when it encounters EOF before the program completion."
},
{
"code": null,
"e": 25588,
"s": 25445,
"text": "We can use the atexit module to detect the script exit. The following code detects script exit using register() function of the atexit module."
},
{
"code": null,
"e": 25634,
"s": 25588,
"text": "Syntax: atexit.register(fun, *args, **kwargs)"
},
{
"code": null,
"e": 25776,
"s": 25634,
"text": "Parameters: First the function name is mentioned and then any arguments for that function is passed. The parameters are separated using ‘, ‘."
},
{
"code": null,
"e": 25858,
"s": 25776,
"text": "Return: This function returns the called fun and hence the calling can be traced."
},
{
"code": null,
"e": 25958,
"s": 25858,
"text": "The atexit.register() method takes a function as an argument that is to be executed at script exit."
},
{
"code": null,
"e": 25966,
"s": 25958,
"text": "Python3"
},
{
"code": "import atexit a = 5print(\"Twice of a:\", a*2) atexit.register(print, \"Exiting Python Script\")",
"e": 26061,
"s": 25966,
"text": null
},
{
"code": null,
"e": 26069,
"s": 26061,
"text": "Output:"
},
{
"code": null,
"e": 26107,
"s": 26069,
"text": "Twice of a: 10\nExiting Python Script\n"
},
{
"code": null,
"e": 26121,
"s": 26107,
"text": "python-basics"
},
{
"code": null,
"e": 26128,
"s": 26121,
"text": "Python"
},
{
"code": null,
"e": 26226,
"s": 26128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26235,
"s": 26226,
"text": "Comments"
},
{
"code": null,
"e": 26248,
"s": 26235,
"text": "Old Comments"
},
{
"code": null,
"e": 26280,
"s": 26248,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26336,
"s": 26280,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26391,
"s": 26336,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26433,
"s": 26391,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26475,
"s": 26433,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26506,
"s": 26475,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26545,
"s": 26506,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26574,
"s": 26545,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26596,
"s": 26574,
"text": "Defaultdict in Python"
}
] |
Handling errors in SAP GUI Scripting code
|
You can take reference from GUI Scripting help section and it can explain things in detail.
It provides you default property types as per requirement. If you want to perform next step, stop or abort user step, you can use the following properties.
See the below code that uses above property type to display different messages −
Public Sub get_status_bar_value_exit_if_Error()
Dim usr_resp AsString
If(session.findById("wnd[0]/sbar").messagetype = "E"Or
session.findById("wnd[0]/sbar").messagetype= "W") Then
usr_resp =MsgBox(session.findById("wnd[0]/sbar").Text & Chr(13) &"Show the Error in SAP ?",
vbYesNo)
If usr_resp =vbYes Then
Else
Callgo_to_Sap_home
End If
End
End If
End Sub
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "You can take reference from GUI Scripting help section and it can explain things in detail."
},
{
"code": null,
"e": 1310,
"s": 1154,
"text": "It provides you default property types as per requirement. If you want to perform next step, stop or abort user step, you can use the following properties."
},
{
"code": null,
"e": 1391,
"s": 1310,
"text": "See the below code that uses above property type to display different messages −"
},
{
"code": null,
"e": 1773,
"s": 1391,
"text": "Public Sub get_status_bar_value_exit_if_Error()\n Dim usr_resp AsString\n If(session.findById(\"wnd[0]/sbar\").messagetype = \"E\"Or\n session.findById(\"wnd[0]/sbar\").messagetype= \"W\") Then\n usr_resp =MsgBox(session.findById(\"wnd[0]/sbar\").Text & Chr(13) &\"Show the Error in SAP ?\",\nvbYesNo)\n If usr_resp =vbYes Then\n Else\n Callgo_to_Sap_home\n End If\n End\n End If\nEnd Sub"
}
] |
GATE | GATE-CS-2014-(Set-2) | Question 65 - GeeksforGeeks
|
10 Sep, 2021
Consider the grammar defined by the following production rules, with two operators ∗ and +
S --> T * P
T --> U | T * U
P --> Q + P | Q
Q --> Id
U --> Id
Which one of the following is TRUE?
(A) + is left associative, while ∗ is right associative(B) + is right associative, while ∗ is left associative(C) Both + and ∗ are right associative(D) Both + and ∗ are left associative
Answer: (B)Explanation: From the grammar we can find out associative by looking at grammar.
Let us consider the 2nd production
T -> T * U
T is generating T*U recursively (left recursive) so * is
left associative.
Similarly
P -> Q + P
Right recursion so + is right associative.
So option B is correct.
NOTE: Above is the shortcut trick that can be observed after drawingfew parse trees.One can also find out correct answer by drawing the parse tree.
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0028:48 / 52:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Sn5eIxvrNBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25693,
"s": 25665,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 25784,
"s": 25693,
"text": "Consider the grammar defined by the following production rules, with two operators ∗ and +"
},
{
"code": null,
"e": 25868,
"s": 25784,
"text": " S --> T * P \n T --> U | T * U\n P --> Q + P | Q\n Q --> Id\n U --> Id\n"
},
{
"code": null,
"e": 25904,
"s": 25868,
"text": "Which one of the following is TRUE?"
},
{
"code": null,
"e": 26090,
"s": 25904,
"text": "(A) + is left associative, while ∗ is right associative(B) + is right associative, while ∗ is left associative(C) Both + and ∗ are right associative(D) Both + and ∗ are left associative"
},
{
"code": null,
"e": 26182,
"s": 26090,
"text": "Answer: (B)Explanation: From the grammar we can find out associative by looking at grammar."
},
{
"code": null,
"e": 26394,
"s": 26182,
"text": "Let us consider the 2nd production\nT -> T * U\nT is generating T*U recursively (left recursive) so * is \nleft associative.\n\nSimilarly\nP -> Q + P\nRight recursion so + is right associative.\nSo option B is correct. "
},
{
"code": null,
"e": 26542,
"s": 26394,
"text": "NOTE: Above is the shortcut trick that can be observed after drawingfew parse trees.One can also find out correct answer by drawing the parse tree."
},
{
"code": null,
"e": 27439,
"s": 26542,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0028:48 / 52:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Sn5eIxvrNBc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 27460,
"s": 27439,
"text": "GATE-CS-2014-(Set-2)"
},
{
"code": null,
"e": 27486,
"s": 27460,
"text": "GATE-GATE-CS-2014-(Set-2)"
},
{
"code": null,
"e": 27491,
"s": 27486,
"text": "GATE"
},
{
"code": null,
"e": 27589,
"s": 27491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27623,
"s": 27589,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27657,
"s": 27623,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27691,
"s": 27657,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27724,
"s": 27691,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27760,
"s": 27724,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27794,
"s": 27760,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27830,
"s": 27794,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27864,
"s": 27830,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27898,
"s": 27864,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
7 libraries that help in time-series problems | by Pratik Gandhi | Towards Data Science
|
Time series problems are one of the toughest problems to solve in data science. Traditional methods that are time-aware like ARIMA, SARIMA are great but lately they have largely been accompanied by the non-time aware and robust machine learning algorithms like XGBoost, LigthGBM, and so forth because of need and proven successful track records. However, using these methods require extensive data preparation like removing periodicity, removing trend from the target and engineering features like rolling window features, lag features, etc. to prepare the final dataset.
To gain better accuracy we need to develop complex models and the work can be quite extensive. Therefore, it is better to leverage some of the automation that is already developed/creating by the Machine Learning community. Below are some of the packages which are really helpful in solving time series problems.
tsfresh is a fantastic python package that can automatically calculate a large number of time series features.
Let's understand how tsfresh can be implemented by taking a standard dataset of Airline passengers:
The data needs to/will be formatted in a format something like below:
From the output above we see that almost ~800 features are created. tsfresh also helps in feature selection based on p-value. Check out the documentation for more details.
There is an exhaustive list of all the features that are calculated using tsfresh which can found here.
Github: https://github.com/blue-yonder/tsfresh
Documentation: https://tsfresh.readthedocs.io/en/latest/index.html
AutoTS is an automated time series forecasting library that can train multiple time series models using straightforward code. AutoTS means Automatic Time Series.
Some of the best features of this library are:
It uses genetic programming optimization to find optimal time series forecasting model.
Provides lower and upper confidence interval forecast values.
It trains diverse models like naive, statistical, machine learning as well as deep learning models
It can also perform automatic ensembling of best models
It also has the ability to handle messy data by learning optimal NaN imputation and outlier removal
It can run both univariate and multivariate time series
Let us take Apple Stocks dataset and understand more in detail:
model = AutoTS(forecast_length=40, frequency='infer',
ensemble='simple', drop_data_older_than_periods=100)
model = model.fit(df, date_col='Date', value_col=' Close/Last', id_col=None)
This will run hundreds of models. You will see in the output pane the variety of models that run. Lets see how the model predicts :
prediction = model.predict()
forecast = prediction.forecast
print("Stock Price Prediction of Apple")
print(forecast)
Github: https://github.com/winedarksea/AutoTS
Documentation: https://winedarksea.github.io/AutoTS/build/html/source/tutorial.html
3. Prophet:
Prophet is a well-known time series package developed by the research team at Facebook with its first release in 2017. It works well with data that has strong seasonal effects and several seasons of historical data. It is highly user-friendly and customizable, with minimum efforts to set it up. It can handle the following things but not limited to:
daily seasonality,
holiday effects
input regressors
Lets take a look at a simple example:
We can also trend and the seasonality plots as below:
And finally, we can also see the predictions along with all the confidence intervals
Github: https://github.com/facebook/prophet
Documentation: https://facebook.github.io/prophet/
4. darts:
Darts is another Python package that helps in the manipulation and forecasting of time series. The syntax is “sklearn-friendly” using fit and predict functions to achieve your goals. In addition, it contains a variety of models from ARIMA to Neural Networks.
The best part of the package is that it supports not only univariate but also supports multivariate time series and models. The library also makes it easy to backtest models and combine the predictions of several models and external regressors. Lets take a simple example and understand its working:
Github: https://github.com/unit8co/darts
Documentation: https://unit8co.github.io/darts/README.html
5. AtsPy:
AtsPy stands for Automated Time Series Models in Python. The goal of the library is to forecast univariate time series. You can load the data and specify which models you would like to run as shown in the example below:
The package provides a diverse set of models totally automated. Below is the screenshot of the models available:
Github: https://github.com/firmai/atspy
6. kats:
Kats is another recent library developed by the research team at Facebook dedicated especially to handle time-series data. The goal of the framework is to provide a complete solution for solving time series problems. Using this library we can do the following:
time-series analysis
detection of patterns including seasonalities, outlier, trend changes
feature engineering module that produces 65 features
building forecasting models on time series data including Prophet, ARIMA, Holt-Winters, etc.
The library seems to be promising and it has just released its first version. Some tutorials can be found here.
Github: https://github.com/facebookresearch/Kats
Sktime library as the name suggests is a unified python library that works for time series data and is scikit-learn compatible. It has models for time series forecasting, regression, and classification. The main goal to develop was to interoperate with scikit-learn.
It can do several things but to mention few of them:
State of the art models
Ability to use sklearn’s Pipeline
Model tuning
Ensembling of models
The roadmap of sktime looks very promising and has a lot of developments coming down the pipeline:
Multivariate/panel forecasting,Time series clustering,Time series annotation (segmentation and anomaly detection),Probabilistic time series modeling, including survival and point processes.
Multivariate/panel forecasting,
Time series clustering,
Time series annotation (segmentation and anomaly detection),
Probabilistic time series modeling, including survival and point processes.
If there is a specific library/package you would like me to make a detailed tutorial please do comment and let me know. Also, if there are any other wonderful time series packages that can be added to this list, please do not hesitate to comment. Thank you for your time for reading!
My other articles related to Time-Series:
https://towardsdatascience.com/7-statistical-tests-to-validate-and-help-to-fit-arima-model-33c5853e2e93https://towardsdatascience.com/20-simple-yet-powerful-features-for-time-series-using-date-and-time-af9da649e5dc
https://towardsdatascience.com/7-statistical-tests-to-validate-and-help-to-fit-arima-model-33c5853e2e93
https://towardsdatascience.com/20-simple-yet-powerful-features-for-time-series-using-date-and-time-af9da649e5dc
Follow me on Twitter or LinkedIn. You may also reach out to me via pratikkgandhi@gmail.com
Please sign up for a membership if you want to become a Medium member and enjoy reading articles without any limits. Medium will share a portion with me for any members who sign up using the above link! Thanks.
|
[
{
"code": null,
"e": 744,
"s": 172,
"text": "Time series problems are one of the toughest problems to solve in data science. Traditional methods that are time-aware like ARIMA, SARIMA are great but lately they have largely been accompanied by the non-time aware and robust machine learning algorithms like XGBoost, LigthGBM, and so forth because of need and proven successful track records. However, using these methods require extensive data preparation like removing periodicity, removing trend from the target and engineering features like rolling window features, lag features, etc. to prepare the final dataset."
},
{
"code": null,
"e": 1057,
"s": 744,
"text": "To gain better accuracy we need to develop complex models and the work can be quite extensive. Therefore, it is better to leverage some of the automation that is already developed/creating by the Machine Learning community. Below are some of the packages which are really helpful in solving time series problems."
},
{
"code": null,
"e": 1168,
"s": 1057,
"text": "tsfresh is a fantastic python package that can automatically calculate a large number of time series features."
},
{
"code": null,
"e": 1268,
"s": 1168,
"text": "Let's understand how tsfresh can be implemented by taking a standard dataset of Airline passengers:"
},
{
"code": null,
"e": 1338,
"s": 1268,
"text": "The data needs to/will be formatted in a format something like below:"
},
{
"code": null,
"e": 1510,
"s": 1338,
"text": "From the output above we see that almost ~800 features are created. tsfresh also helps in feature selection based on p-value. Check out the documentation for more details."
},
{
"code": null,
"e": 1614,
"s": 1510,
"text": "There is an exhaustive list of all the features that are calculated using tsfresh which can found here."
},
{
"code": null,
"e": 1661,
"s": 1614,
"text": "Github: https://github.com/blue-yonder/tsfresh"
},
{
"code": null,
"e": 1728,
"s": 1661,
"text": "Documentation: https://tsfresh.readthedocs.io/en/latest/index.html"
},
{
"code": null,
"e": 1890,
"s": 1728,
"text": "AutoTS is an automated time series forecasting library that can train multiple time series models using straightforward code. AutoTS means Automatic Time Series."
},
{
"code": null,
"e": 1937,
"s": 1890,
"text": "Some of the best features of this library are:"
},
{
"code": null,
"e": 2025,
"s": 1937,
"text": "It uses genetic programming optimization to find optimal time series forecasting model."
},
{
"code": null,
"e": 2087,
"s": 2025,
"text": "Provides lower and upper confidence interval forecast values."
},
{
"code": null,
"e": 2186,
"s": 2087,
"text": "It trains diverse models like naive, statistical, machine learning as well as deep learning models"
},
{
"code": null,
"e": 2242,
"s": 2186,
"text": "It can also perform automatic ensembling of best models"
},
{
"code": null,
"e": 2342,
"s": 2242,
"text": "It also has the ability to handle messy data by learning optimal NaN imputation and outlier removal"
},
{
"code": null,
"e": 2398,
"s": 2342,
"text": "It can run both univariate and multivariate time series"
},
{
"code": null,
"e": 2462,
"s": 2398,
"text": "Let us take Apple Stocks dataset and understand more in detail:"
},
{
"code": null,
"e": 2517,
"s": 2462,
"text": "model = AutoTS(forecast_length=40, frequency='infer', "
},
{
"code": null,
"e": 2585,
"s": 2517,
"text": " ensemble='simple', drop_data_older_than_periods=100)"
},
{
"code": null,
"e": 2662,
"s": 2585,
"text": "model = model.fit(df, date_col='Date', value_col=' Close/Last', id_col=None)"
},
{
"code": null,
"e": 2794,
"s": 2662,
"text": "This will run hundreds of models. You will see in the output pane the variety of models that run. Lets see how the model predicts :"
},
{
"code": null,
"e": 2823,
"s": 2794,
"text": "prediction = model.predict()"
},
{
"code": null,
"e": 2854,
"s": 2823,
"text": "forecast = prediction.forecast"
},
{
"code": null,
"e": 2895,
"s": 2854,
"text": "print(\"Stock Price Prediction of Apple\")"
},
{
"code": null,
"e": 2911,
"s": 2895,
"text": "print(forecast)"
},
{
"code": null,
"e": 2957,
"s": 2911,
"text": "Github: https://github.com/winedarksea/AutoTS"
},
{
"code": null,
"e": 3041,
"s": 2957,
"text": "Documentation: https://winedarksea.github.io/AutoTS/build/html/source/tutorial.html"
},
{
"code": null,
"e": 3053,
"s": 3041,
"text": "3. Prophet:"
},
{
"code": null,
"e": 3404,
"s": 3053,
"text": "Prophet is a well-known time series package developed by the research team at Facebook with its first release in 2017. It works well with data that has strong seasonal effects and several seasons of historical data. It is highly user-friendly and customizable, with minimum efforts to set it up. It can handle the following things but not limited to:"
},
{
"code": null,
"e": 3423,
"s": 3404,
"text": "daily seasonality,"
},
{
"code": null,
"e": 3439,
"s": 3423,
"text": "holiday effects"
},
{
"code": null,
"e": 3456,
"s": 3439,
"text": "input regressors"
},
{
"code": null,
"e": 3494,
"s": 3456,
"text": "Lets take a look at a simple example:"
},
{
"code": null,
"e": 3548,
"s": 3494,
"text": "We can also trend and the seasonality plots as below:"
},
{
"code": null,
"e": 3633,
"s": 3548,
"text": "And finally, we can also see the predictions along with all the confidence intervals"
},
{
"code": null,
"e": 3677,
"s": 3633,
"text": "Github: https://github.com/facebook/prophet"
},
{
"code": null,
"e": 3728,
"s": 3677,
"text": "Documentation: https://facebook.github.io/prophet/"
},
{
"code": null,
"e": 3738,
"s": 3728,
"text": "4. darts:"
},
{
"code": null,
"e": 3997,
"s": 3738,
"text": "Darts is another Python package that helps in the manipulation and forecasting of time series. The syntax is “sklearn-friendly” using fit and predict functions to achieve your goals. In addition, it contains a variety of models from ARIMA to Neural Networks."
},
{
"code": null,
"e": 4297,
"s": 3997,
"text": "The best part of the package is that it supports not only univariate but also supports multivariate time series and models. The library also makes it easy to backtest models and combine the predictions of several models and external regressors. Lets take a simple example and understand its working:"
},
{
"code": null,
"e": 4338,
"s": 4297,
"text": "Github: https://github.com/unit8co/darts"
},
{
"code": null,
"e": 4397,
"s": 4338,
"text": "Documentation: https://unit8co.github.io/darts/README.html"
},
{
"code": null,
"e": 4407,
"s": 4397,
"text": "5. AtsPy:"
},
{
"code": null,
"e": 4627,
"s": 4407,
"text": "AtsPy stands for Automated Time Series Models in Python. The goal of the library is to forecast univariate time series. You can load the data and specify which models you would like to run as shown in the example below:"
},
{
"code": null,
"e": 4740,
"s": 4627,
"text": "The package provides a diverse set of models totally automated. Below is the screenshot of the models available:"
},
{
"code": null,
"e": 4780,
"s": 4740,
"text": "Github: https://github.com/firmai/atspy"
},
{
"code": null,
"e": 4789,
"s": 4780,
"text": "6. kats:"
},
{
"code": null,
"e": 5050,
"s": 4789,
"text": "Kats is another recent library developed by the research team at Facebook dedicated especially to handle time-series data. The goal of the framework is to provide a complete solution for solving time series problems. Using this library we can do the following:"
},
{
"code": null,
"e": 5071,
"s": 5050,
"text": "time-series analysis"
},
{
"code": null,
"e": 5141,
"s": 5071,
"text": "detection of patterns including seasonalities, outlier, trend changes"
},
{
"code": null,
"e": 5194,
"s": 5141,
"text": "feature engineering module that produces 65 features"
},
{
"code": null,
"e": 5287,
"s": 5194,
"text": "building forecasting models on time series data including Prophet, ARIMA, Holt-Winters, etc."
},
{
"code": null,
"e": 5399,
"s": 5287,
"text": "The library seems to be promising and it has just released its first version. Some tutorials can be found here."
},
{
"code": null,
"e": 5448,
"s": 5399,
"text": "Github: https://github.com/facebookresearch/Kats"
},
{
"code": null,
"e": 5715,
"s": 5448,
"text": "Sktime library as the name suggests is a unified python library that works for time series data and is scikit-learn compatible. It has models for time series forecasting, regression, and classification. The main goal to develop was to interoperate with scikit-learn."
},
{
"code": null,
"e": 5768,
"s": 5715,
"text": "It can do several things but to mention few of them:"
},
{
"code": null,
"e": 5792,
"s": 5768,
"text": "State of the art models"
},
{
"code": null,
"e": 5826,
"s": 5792,
"text": "Ability to use sklearn’s Pipeline"
},
{
"code": null,
"e": 5839,
"s": 5826,
"text": "Model tuning"
},
{
"code": null,
"e": 5860,
"s": 5839,
"text": "Ensembling of models"
},
{
"code": null,
"e": 5959,
"s": 5860,
"text": "The roadmap of sktime looks very promising and has a lot of developments coming down the pipeline:"
},
{
"code": null,
"e": 6149,
"s": 5959,
"text": "Multivariate/panel forecasting,Time series clustering,Time series annotation (segmentation and anomaly detection),Probabilistic time series modeling, including survival and point processes."
},
{
"code": null,
"e": 6181,
"s": 6149,
"text": "Multivariate/panel forecasting,"
},
{
"code": null,
"e": 6205,
"s": 6181,
"text": "Time series clustering,"
},
{
"code": null,
"e": 6266,
"s": 6205,
"text": "Time series annotation (segmentation and anomaly detection),"
},
{
"code": null,
"e": 6342,
"s": 6266,
"text": "Probabilistic time series modeling, including survival and point processes."
},
{
"code": null,
"e": 6626,
"s": 6342,
"text": "If there is a specific library/package you would like me to make a detailed tutorial please do comment and let me know. Also, if there are any other wonderful time series packages that can be added to this list, please do not hesitate to comment. Thank you for your time for reading!"
},
{
"code": null,
"e": 6668,
"s": 6626,
"text": "My other articles related to Time-Series:"
},
{
"code": null,
"e": 6883,
"s": 6668,
"text": "https://towardsdatascience.com/7-statistical-tests-to-validate-and-help-to-fit-arima-model-33c5853e2e93https://towardsdatascience.com/20-simple-yet-powerful-features-for-time-series-using-date-and-time-af9da649e5dc"
},
{
"code": null,
"e": 6987,
"s": 6883,
"text": "https://towardsdatascience.com/7-statistical-tests-to-validate-and-help-to-fit-arima-model-33c5853e2e93"
},
{
"code": null,
"e": 7099,
"s": 6987,
"text": "https://towardsdatascience.com/20-simple-yet-powerful-features-for-time-series-using-date-and-time-af9da649e5dc"
},
{
"code": null,
"e": 7190,
"s": 7099,
"text": "Follow me on Twitter or LinkedIn. You may also reach out to me via pratikkgandhi@gmail.com"
}
] |
DAX Filter - ALL function
|
Returns all the rows in a table or all the values in a column, ignoring any filters that might have been applied. This function is useful for clearing filters and creating calculations on all the rows in a table.
ALL ({<table> | <column>, [<column>], [<column>] ...})
table
The table that you want to clear filters on.
column
The column that you want to clear filters on.
The argument to the ALL function must be either a reference to a base table or one or more references to base columns. You cannot use table expressions or column expressions with the ALL function.
The table or column or columns with filters removed.
ALL function is not used by itself, but serves as an intermediate function that can be used to change the set of results over which some other calculation is performed.
= COUNTA (Results[Medal])/CALCULATE (COUNTA (Results[Medal], ALL (Results))
With this DAX formula, all the rows in the Results table are taken into account in the CALCULATE function with the filter containing the ALL function. This way, you have the total count in the denominator.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2214,
"s": 2001,
"text": "Returns all the rows in a table or all the values in a column, ignoring any filters that might have been applied. This function is useful for clearing filters and creating calculations on all the rows in a table."
},
{
"code": null,
"e": 2271,
"s": 2214,
"text": "ALL ({<table> | <column>, [<column>], [<column>] ...}) \n"
},
{
"code": null,
"e": 2277,
"s": 2271,
"text": "table"
},
{
"code": null,
"e": 2322,
"s": 2277,
"text": "The table that you want to clear filters on."
},
{
"code": null,
"e": 2329,
"s": 2322,
"text": "column"
},
{
"code": null,
"e": 2375,
"s": 2329,
"text": "The column that you want to clear filters on."
},
{
"code": null,
"e": 2572,
"s": 2375,
"text": "The argument to the ALL function must be either a reference to a base table or one or more references to base columns. You cannot use table expressions or column expressions with the ALL function."
},
{
"code": null,
"e": 2625,
"s": 2572,
"text": "The table or column or columns with filters removed."
},
{
"code": null,
"e": 2794,
"s": 2625,
"text": "ALL function is not used by itself, but serves as an intermediate function that can be used to change the set of results over which some other calculation is performed."
},
{
"code": null,
"e": 2871,
"s": 2794,
"text": "= COUNTA (Results[Medal])/CALCULATE (COUNTA (Results[Medal], ALL (Results)) "
},
{
"code": null,
"e": 3077,
"s": 2871,
"text": "With this DAX formula, all the rows in the Results table are taken into account in the CALCULATE function with the filter containing the ALL function. This way, you have the total count in the denominator."
},
{
"code": null,
"e": 3112,
"s": 3077,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3126,
"s": 3112,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3159,
"s": 3126,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3173,
"s": 3159,
"text": " Randy Minder"
},
{
"code": null,
"e": 3208,
"s": 3173,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3222,
"s": 3208,
"text": " Randy Minder"
},
{
"code": null,
"e": 3229,
"s": 3222,
"text": " Print"
},
{
"code": null,
"e": 3240,
"s": 3229,
"text": " Add Notes"
}
] |
Abstract Syntax Tree (AST) in Java - GeeksforGeeks
|
12 Aug, 2021
Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.
There is numerous importance of AST with application in compilers as abstract syntax trees are data structures widely used in compilers to represent the structure of program code. An AST is usually the result of the syntax analysis phase of a compiler. It often serves as an intermediate representation of the program through several stages that the compiler requires, and has a strong impact on the final output of the compiler.
Let us do discuss the use of AST before proceeding further to the implementation part. AST’s are mainly used in compilers to check code for their accuracy. If the generated tree has errors, the compiler prints an error message. Abstract Syntax Tree (AST) is used because some constructs cannot be represented in context-free grammar, such as implicit typing. They are highly specific to programming languages, but research is underway on universal syntax trees.
Flow Chart:
id + id * id would have the following syntax tree which is as follows:
Abstract syntax tree will be as follows:
Implementation:
Here we will be writing custom java source codes corresponding to which we will be providing the AST for the same java source code as in implementation.
Example 1(A) Java source code
Java
// Java Custom Source Code // Main classclass GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println("Hello World!"); }}
Example 1(B) AST of above source code
Java
CLASS_DEF -> CLASS_DEF [1:0]|--MODIFIERS -> MODIFIERS [1:0]| `--LITERAL_PUBLIC -> public [1:0]|--LITERAL_CLASS -> class [1:7]|--IDENT -> GFG [1:13]`--OBJBLOCK -> OBJBLOCK [1:17] |--LCURLY -> { [1:17] |--METHOD_DEF -> METHOD_DEF [2:4] | |--MODIFIERS -> MODIFIERS [2:4] | | |--LITERAL_PUBLIC -> public [2:4] | | `--LITERAL_STATIC -> static [2:11] | |--TYPE -> TYPE [2:18] | | `--LITERAL_VOID -> void [2:18] | |--IDENT -> main [2:23] | |--LPAREN -> ( [2:27] | |--PARAMETERS -> PARAMETERS [2:34] | | `--PARAMETER_DEF -> PARAMETER_DEF [2:34] | | |--MODIFIERS -> MODIFIERS [2:34] | | |--TYPE -> TYPE [2:34] | | | `--ARRAY_DECLARATOR -> [ [2:34] | | | |--IDENT -> String [2:28] | | | `--RBRACK -> ] [2:35] | | `--IDENT -> args [2:37] | |--RPAREN -> ) [2:41] | `--SLIST -> { [2:43] | |--EXPR -> EXPR [3:26] | | `--METHOD_CALL -> ( [3:26] | | |--DOT -> . [3:18] | | | |--DOT -> . [3:14] | | | | |--IDENT -> System [3:8] | | | | `--IDENT -> out [3:15] | | | `--IDENT -> println [3:19] | | |--ELIST -> ELIST [3:27] | | | `--EXPR -> EXPR [3:27] | | | `--STRING_LITERAL -> "Hello World!" [3:27] | | `--RPAREN -> ) [3:41] | |--SEMI -> ; [3:42] | `--RCURLY -> } [4:4] `--RCURLY -> } [5:0]
Now you must be wondering how to make an AST or how the above code is generated for that geek follow the simple steps as listed in the sequential order.
Run the Source Code in your local Environment.
Download the Checkstyle Command line
checkstyle-8.43-all.jar
Audit the Program with the help of Checkstyle in your Terminal:
java -jar checkstyle-8.43-all.jar -c /google_checks.xml YourFile.java
After Audit, Run this command in your terminal to get the AST of your preferred Code: java -jar checkstyle-8.43-all.jar -t YourFile.java
AST is now ready. But wait geeks,
Note: This is not an Updated AST
Remember: To update the AST, we have to do the following two steps
Step 1: We should replace
">" with ">" and "<" with "<"
Step 2: Remove the code lines
Example 1(C) Updated AST Examples of the above code is as follows:
Java
CLASS_DEF -> CLASS_DEF |--MODIFIERS -> MODIFIERS | `--LITERAL_PUBLIC -> public |--LITERAL_CLASS -> class |--IDENT -> GFG `--OBJBLOCK -> OBJBLOCK |--LCURLY -> { |--METHOD_DEF -> METHOD_DEF | |--MODIFIERS -> MODIFIERS | | |--LITERAL_PUBLIC -> public | | `--LITERAL_STATIC -> static | |--TYPE -> TYPE | | `--LITERAL_VOID -> void | |--IDENT -> main | |--LPAREN -> ( | |--PARAMETERS -> PARAMETERS | | `--PARAMETER_DEF -> PARAMETER_DEF | | |--MODIFIERS -> MODIFIERS | | |--TYPE -> TYPE | | | `--ARRAY_DECLARATOR -> [ | | | |--IDENT -> String | | | `--RBRACK -> ] | | `--IDENT -> args | |--RPAREN -> ) | `--SLIST -> { | |--EXPR -> EXPR | | `--METHOD_CALL -> ( | | |--DOT -> . | | | |--DOT -> . | | | | |--IDENT -> System | | | | `--IDENT -> out | | | `--IDENT -> println | | |--ELIST -> ELIST | | | `--EXPR -> EXPR | | | `--STRING_LITERAL -> "Hello World!" | | `--RPAREN -> ) | |--SEMI -> ; | `--RCURLY -> } `--RCURLY -> }
Example 2: Representing 1 + 2 can be represented in AST
Java
+ BinaryExpression - type: + - left_value: LiteralExpr: value: 1 - right_vaue: LiteralExpr: value: 2
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java
|
[
{
"code": null,
"e": 23892,
"s": 23864,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 24104,
"s": 23892,
"text": "Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code."
},
{
"code": null,
"e": 24534,
"s": 24104,
"text": "There is numerous importance of AST with application in compilers as abstract syntax trees are data structures widely used in compilers to represent the structure of program code. An AST is usually the result of the syntax analysis phase of a compiler. It often serves as an intermediate representation of the program through several stages that the compiler requires, and has a strong impact on the final output of the compiler."
},
{
"code": null,
"e": 24996,
"s": 24534,
"text": "Let us do discuss the use of AST before proceeding further to the implementation part. AST’s are mainly used in compilers to check code for their accuracy. If the generated tree has errors, the compiler prints an error message. Abstract Syntax Tree (AST) is used because some constructs cannot be represented in context-free grammar, such as implicit typing. They are highly specific to programming languages, but research is underway on universal syntax trees."
},
{
"code": null,
"e": 25010,
"s": 24996,
"text": "Flow Chart: "
},
{
"code": null,
"e": 25081,
"s": 25010,
"text": "id + id * id would have the following syntax tree which is as follows:"
},
{
"code": null,
"e": 25122,
"s": 25081,
"text": "Abstract syntax tree will be as follows:"
},
{
"code": null,
"e": 25138,
"s": 25122,
"text": "Implementation:"
},
{
"code": null,
"e": 25291,
"s": 25138,
"text": "Here we will be writing custom java source codes corresponding to which we will be providing the AST for the same java source code as in implementation."
},
{
"code": null,
"e": 25321,
"s": 25291,
"text": "Example 1(A) Java source code"
},
{
"code": null,
"e": 25326,
"s": 25321,
"text": "Java"
},
{
"code": "// Java Custom Source Code // Main classclass GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println(\"Hello World!\"); }}",
"e": 25530,
"s": 25326,
"text": null
},
{
"code": null,
"e": 25568,
"s": 25530,
"text": "Example 1(B) AST of above source code"
},
{
"code": null,
"e": 25573,
"s": 25568,
"text": "Java"
},
{
"code": "CLASS_DEF -> CLASS_DEF [1:0]|--MODIFIERS -> MODIFIERS [1:0]| `--LITERAL_PUBLIC -> public [1:0]|--LITERAL_CLASS -> class [1:7]|--IDENT -> GFG [1:13]`--OBJBLOCK -> OBJBLOCK [1:17] |--LCURLY -> { [1:17] |--METHOD_DEF -> METHOD_DEF [2:4] | |--MODIFIERS -> MODIFIERS [2:4] | | |--LITERAL_PUBLIC -> public [2:4] | | `--LITERAL_STATIC -> static [2:11] | |--TYPE -> TYPE [2:18] | | `--LITERAL_VOID -> void [2:18] | |--IDENT -> main [2:23] | |--LPAREN -> ( [2:27] | |--PARAMETERS -> PARAMETERS [2:34] | | `--PARAMETER_DEF -> PARAMETER_DEF [2:34] | | |--MODIFIERS -> MODIFIERS [2:34] | | |--TYPE -> TYPE [2:34] | | | `--ARRAY_DECLARATOR -> [ [2:34] | | | |--IDENT -> String [2:28] | | | `--RBRACK -> ] [2:35] | | `--IDENT -> args [2:37] | |--RPAREN -> ) [2:41] | `--SLIST -> { [2:43] | |--EXPR -> EXPR [3:26] | | `--METHOD_CALL -> ( [3:26] | | |--DOT -> . [3:18] | | | |--DOT -> . [3:14] | | | | |--IDENT -> System [3:8] | | | | `--IDENT -> out [3:15] | | | `--IDENT -> println [3:19] | | |--ELIST -> ELIST [3:27] | | | `--EXPR -> EXPR [3:27] | | | `--STRING_LITERAL -> \"Hello World!\" [3:27] | | `--RPAREN -> ) [3:41] | |--SEMI -> ; [3:42] | `--RCURLY -> } [4:4] `--RCURLY -> } [5:0]",
"e": 27094,
"s": 25573,
"text": null
},
{
"code": null,
"e": 27248,
"s": 27094,
"text": "Now you must be wondering how to make an AST or how the above code is generated for that geek follow the simple steps as listed in the sequential order. "
},
{
"code": null,
"e": 27295,
"s": 27248,
"text": "Run the Source Code in your local Environment."
},
{
"code": null,
"e": 27332,
"s": 27295,
"text": "Download the Checkstyle Command line"
},
{
"code": null,
"e": 27358,
"s": 27332,
"text": " checkstyle-8.43-all.jar "
},
{
"code": null,
"e": 27422,
"s": 27358,
"text": "Audit the Program with the help of Checkstyle in your Terminal:"
},
{
"code": null,
"e": 27492,
"s": 27422,
"text": "java -jar checkstyle-8.43-all.jar -c /google_checks.xml YourFile.java"
},
{
"code": null,
"e": 27630,
"s": 27492,
"text": "After Audit, Run this command in your terminal to get the AST of your preferred Code: java -jar checkstyle-8.43-all.jar -t YourFile.java"
},
{
"code": null,
"e": 27664,
"s": 27630,
"text": "AST is now ready. But wait geeks,"
},
{
"code": null,
"e": 27697,
"s": 27664,
"text": "Note: This is not an Updated AST"
},
{
"code": null,
"e": 27764,
"s": 27697,
"text": "Remember: To update the AST, we have to do the following two steps"
},
{
"code": null,
"e": 27791,
"s": 27764,
"text": "Step 1: We should replace "
},
{
"code": null,
"e": 27827,
"s": 27791,
"text": "\">\" with \">\" and \"<\" with \"<\""
},
{
"code": null,
"e": 27857,
"s": 27827,
"text": "Step 2: Remove the code lines"
},
{
"code": null,
"e": 27924,
"s": 27857,
"text": "Example 1(C) Updated AST Examples of the above code is as follows:"
},
{
"code": null,
"e": 27929,
"s": 27924,
"text": "Java"
},
{
"code": "CLASS_DEF -> CLASS_DEF |--MODIFIERS -> MODIFIERS | `--LITERAL_PUBLIC -> public |--LITERAL_CLASS -> class |--IDENT -> GFG `--OBJBLOCK -> OBJBLOCK |--LCURLY -> { |--METHOD_DEF -> METHOD_DEF | |--MODIFIERS -> MODIFIERS | | |--LITERAL_PUBLIC -> public | | `--LITERAL_STATIC -> static | |--TYPE -> TYPE | | `--LITERAL_VOID -> void | |--IDENT -> main | |--LPAREN -> ( | |--PARAMETERS -> PARAMETERS | | `--PARAMETER_DEF -> PARAMETER_DEF | | |--MODIFIERS -> MODIFIERS | | |--TYPE -> TYPE | | | `--ARRAY_DECLARATOR -> [ | | | |--IDENT -> String | | | `--RBRACK -> ] | | `--IDENT -> args | |--RPAREN -> ) | `--SLIST -> { | |--EXPR -> EXPR | | `--METHOD_CALL -> ( | | |--DOT -> . | | | |--DOT -> . | | | | |--IDENT -> System | | | | `--IDENT -> out | | | `--IDENT -> println | | |--ELIST -> ELIST | | | `--EXPR -> EXPR | | | `--STRING_LITERAL -> \"Hello World!\" | | `--RPAREN -> ) | |--SEMI -> ; | `--RCURLY -> } `--RCURLY -> } ",
"e": 29224,
"s": 27929,
"text": null
},
{
"code": null,
"e": 29281,
"s": 29224,
"text": "Example 2: Representing 1 + 2 can be represented in AST "
},
{
"code": null,
"e": 29286,
"s": 29281,
"text": "Java"
},
{
"code": "+ BinaryExpression - type: + - left_value: LiteralExpr: value: 1 - right_vaue: LiteralExpr: value: 2",
"e": 29394,
"s": 29286,
"text": null
},
{
"code": null,
"e": 29399,
"s": 29394,
"text": "Java"
},
{
"code": null,
"e": 29404,
"s": 29399,
"text": "Java"
},
{
"code": null,
"e": 29502,
"s": 29404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29511,
"s": 29502,
"text": "Comments"
},
{
"code": null,
"e": 29524,
"s": 29511,
"text": "Old Comments"
},
{
"code": null,
"e": 29570,
"s": 29524,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29591,
"s": 29570,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29606,
"s": 29591,
"text": "Stream In Java"
},
{
"code": null,
"e": 29625,
"s": 29606,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29667,
"s": 29625,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 29710,
"s": 29667,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29727,
"s": 29710,
"text": "Generics in Java"
},
{
"code": null,
"e": 29757,
"s": 29727,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29783,
"s": 29757,
"text": "Java Programming Examples"
}
] |
Supermarket Data Analysis with Pandas | by Soner Yıldırım | Towards Data Science
|
Pandas is the most widely-used data analysis and manipulation library for Python. Its intuitive and versatile functions make the data analysis process efficient, simple, and easy to understand.
In this article, we will practice pandas on a supermarket sales dataset available on Kaggle. It contains sales data of different branches of a supermarket chain during a 3-month-period.
Let’s start by importing the libraries and reading the dataset.
import numpy as npimport pandas as pddf = pd.read_csv("/content/supermarket.xls", parse_dates=['Date'])
We use the parse_dates parameter to store the date column with datetime data type so that we do not have to convert the data type later on. The datetime data type allows for using the functions under the dt accessor that are specific to dates and times.
There are some columns which are either redundant and irrelevant to our analysis.
Invoice ID: A unique invoice identification number. Does not possess any information for analsis.
Cogs: Product of the unit price and quantity columns.
Gross margin percentage: Consists of a single value which is 4.761905.
Gross income: Can be obtained from multiplying the total column with 0.04761905 (i.e. gross margin percentage).
City: Perfectly correlated with the branch column. There is one branch in each city.
In order to simplify the dataset, we drop these columns.
to_drop = ['Invoice ID', 'City','cogs', 'gross margin percentage', 'gross income']df.drop(to_drop, axis=1, inplace=True)df.head()
We should always check if there are missing values in the dataset.
df.isna().sum().sum()0
The isna function returns the dataframe indicating missing values with “True”. By chaining a sum function, we get the number of missing values in each column. The second sum function gives the number of missing values in the entire dataframe.
We might be interested in a general overview of the sales at each branch. The total amount of sales and average sales amount per invoice can be calculated with the groupby function.
df[['Branch', 'Total']]\.groupby('Branch').agg(['mean','sum','count'])
The average amount per invoice is higher in the C branch. As a result, the total sales amount of this branch is higher than the other branches although the number of invoices is less.
We can also check the average unit price of products in each product line. Let’s also sort them in descending order to get a more structured overview.
df[['Product line', 'Unit price']].groupby('Product line').mean()\.sort_values(by='Unit price', ascending=False).round(2)
Fashion accessories lead the list but the average unit prices are quite close to each other.
We can also check the trend in weekly sales amounts of this supermarket chain. The first step is to group the total sales amount by date.
dates = df[['Date','Total']].groupby('Date').sum()dates.head()
The dates dataframe contains daily sales amounts. In order to check the weekly sales, we need to resample it before plotting. A simple way is to use the resample function.
dates.resample('7D').sum().plot(figsize=(9,4))
The period for resampling is specified by ‘7D’ indicating 7 days. We also need a function to tell pandas how to aggregate values in the resampled periods (e.g. sum or mean).
Let’s also check the product preferences of females and males. One way is to calculate the total number of items purchased in each product line. We first use the groupby function to obtain the data and then create a bar plot to make a comparison.
gender = df[['Gender','Product line','Quantity']]\.groupby(['Gender','Product line'], as_index=False).sum()gender.head()
We now have the quantities in each category for both females and males. The next step is to plot them.
import seaborn as snssns.set(style='darkgrid')sns.catplot(data=gender, y='Product line', x='Quantity', kind='bar', hue='Gender', aspect=1.6, orient='h')
The catplot function is a figure-level interface to generate categorical plots. The type of plot is defined by the kind parameter.
Females purchase more products in the fashion accessories category which is expected. However, I’m a bit surprised to see males surpass females in the health and beauty category.
Filtering data based on a condition is a typical task in data analysis. Pandas is quite efficient in terms of how you can filter data. For instance, the query function accepts the condition as a string. There are, of course, some limitations but it comes in handy for many cases.
We can filter the purchases with total amount higher than 300 and quantity higher than 4 using the query function as below.
df.query('Total > 300 and Quantity > 4').shape(393, 12)
There are 393 purchases that fit these criteria.
The distribution of variables always provides valuable insight for data analysis. For instance, we can check the distribution of the total sales amount of purchases. One method is to plot a histogram which can easily be done with the plot function of pandas.
df.Total.plot(kind='hist', figsize=(8,5), title='Histogram of Total Sale Amounts')
Histogram divides the value range of a continuous variable into discrete bins and counts the number of data points (i.e. rows) in each bin. As a result, we get an overview of the distribution of values.
We can also analyze the sales based on time period of the day. For instance, we might be interested in finding out if people tend to spend more in the mornings than evenings.
In order to efficiently use date and time functionalities under dt accessor of pandas, we should convert the data type of the time column to datetime.
df.Time = pd.to_datetime(df.Time)
The hour method returns the hour of the time as a string. We need to convert it to integer to use for filtering.
df[df.Time.dt.hour.astype('int') >= 20]['Total'].mean().round(2)306.26df[df.Time.dt.hour.astype('int') <= 10]['Total'].mean().round(2)311.10
Let’s elaborate on what we have done above. The hour method of dt accessor extracts the hour as string. We convert it to an integer using the astype function and use it to filter purchased made after 20. The final operation is taking the mean of the purchases that fit the specified condition. Then we do the same for purchases made before 10.
The main purpose of this article to demonstrate various pandas functions that help us analyze tabular data. The parameters of pandas functions are highly important as they make the functions more powerful and versatile. Thus, it is very important to know what parameters achieve.
One of the things I like about pandas is that there are almost always more than one way to accomplish a task. For instance, what we have done in the examples can also be done in a different way. In fact, you may challenge yourself to do the same using different functions.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 366,
"s": 172,
"text": "Pandas is the most widely-used data analysis and manipulation library for Python. Its intuitive and versatile functions make the data analysis process efficient, simple, and easy to understand."
},
{
"code": null,
"e": 552,
"s": 366,
"text": "In this article, we will practice pandas on a supermarket sales dataset available on Kaggle. It contains sales data of different branches of a supermarket chain during a 3-month-period."
},
{
"code": null,
"e": 616,
"s": 552,
"text": "Let’s start by importing the libraries and reading the dataset."
},
{
"code": null,
"e": 720,
"s": 616,
"text": "import numpy as npimport pandas as pddf = pd.read_csv(\"/content/supermarket.xls\", parse_dates=['Date'])"
},
{
"code": null,
"e": 974,
"s": 720,
"text": "We use the parse_dates parameter to store the date column with datetime data type so that we do not have to convert the data type later on. The datetime data type allows for using the functions under the dt accessor that are specific to dates and times."
},
{
"code": null,
"e": 1056,
"s": 974,
"text": "There are some columns which are either redundant and irrelevant to our analysis."
},
{
"code": null,
"e": 1154,
"s": 1056,
"text": "Invoice ID: A unique invoice identification number. Does not possess any information for analsis."
},
{
"code": null,
"e": 1208,
"s": 1154,
"text": "Cogs: Product of the unit price and quantity columns."
},
{
"code": null,
"e": 1279,
"s": 1208,
"text": "Gross margin percentage: Consists of a single value which is 4.761905."
},
{
"code": null,
"e": 1391,
"s": 1279,
"text": "Gross income: Can be obtained from multiplying the total column with 0.04761905 (i.e. gross margin percentage)."
},
{
"code": null,
"e": 1476,
"s": 1391,
"text": "City: Perfectly correlated with the branch column. There is one branch in each city."
},
{
"code": null,
"e": 1533,
"s": 1476,
"text": "In order to simplify the dataset, we drop these columns."
},
{
"code": null,
"e": 1663,
"s": 1533,
"text": "to_drop = ['Invoice ID', 'City','cogs', 'gross margin percentage', 'gross income']df.drop(to_drop, axis=1, inplace=True)df.head()"
},
{
"code": null,
"e": 1730,
"s": 1663,
"text": "We should always check if there are missing values in the dataset."
},
{
"code": null,
"e": 1753,
"s": 1730,
"text": "df.isna().sum().sum()0"
},
{
"code": null,
"e": 1996,
"s": 1753,
"text": "The isna function returns the dataframe indicating missing values with “True”. By chaining a sum function, we get the number of missing values in each column. The second sum function gives the number of missing values in the entire dataframe."
},
{
"code": null,
"e": 2178,
"s": 1996,
"text": "We might be interested in a general overview of the sales at each branch. The total amount of sales and average sales amount per invoice can be calculated with the groupby function."
},
{
"code": null,
"e": 2249,
"s": 2178,
"text": "df[['Branch', 'Total']]\\.groupby('Branch').agg(['mean','sum','count'])"
},
{
"code": null,
"e": 2433,
"s": 2249,
"text": "The average amount per invoice is higher in the C branch. As a result, the total sales amount of this branch is higher than the other branches although the number of invoices is less."
},
{
"code": null,
"e": 2584,
"s": 2433,
"text": "We can also check the average unit price of products in each product line. Let’s also sort them in descending order to get a more structured overview."
},
{
"code": null,
"e": 2706,
"s": 2584,
"text": "df[['Product line', 'Unit price']].groupby('Product line').mean()\\.sort_values(by='Unit price', ascending=False).round(2)"
},
{
"code": null,
"e": 2799,
"s": 2706,
"text": "Fashion accessories lead the list but the average unit prices are quite close to each other."
},
{
"code": null,
"e": 2937,
"s": 2799,
"text": "We can also check the trend in weekly sales amounts of this supermarket chain. The first step is to group the total sales amount by date."
},
{
"code": null,
"e": 3000,
"s": 2937,
"text": "dates = df[['Date','Total']].groupby('Date').sum()dates.head()"
},
{
"code": null,
"e": 3172,
"s": 3000,
"text": "The dates dataframe contains daily sales amounts. In order to check the weekly sales, we need to resample it before plotting. A simple way is to use the resample function."
},
{
"code": null,
"e": 3219,
"s": 3172,
"text": "dates.resample('7D').sum().plot(figsize=(9,4))"
},
{
"code": null,
"e": 3393,
"s": 3219,
"text": "The period for resampling is specified by ‘7D’ indicating 7 days. We also need a function to tell pandas how to aggregate values in the resampled periods (e.g. sum or mean)."
},
{
"code": null,
"e": 3640,
"s": 3393,
"text": "Let’s also check the product preferences of females and males. One way is to calculate the total number of items purchased in each product line. We first use the groupby function to obtain the data and then create a bar plot to make a comparison."
},
{
"code": null,
"e": 3761,
"s": 3640,
"text": "gender = df[['Gender','Product line','Quantity']]\\.groupby(['Gender','Product line'], as_index=False).sum()gender.head()"
},
{
"code": null,
"e": 3864,
"s": 3761,
"text": "We now have the quantities in each category for both females and males. The next step is to plot them."
},
{
"code": null,
"e": 4028,
"s": 3864,
"text": "import seaborn as snssns.set(style='darkgrid')sns.catplot(data=gender, y='Product line', x='Quantity', kind='bar', hue='Gender', aspect=1.6, orient='h')"
},
{
"code": null,
"e": 4159,
"s": 4028,
"text": "The catplot function is a figure-level interface to generate categorical plots. The type of plot is defined by the kind parameter."
},
{
"code": null,
"e": 4338,
"s": 4159,
"text": "Females purchase more products in the fashion accessories category which is expected. However, I’m a bit surprised to see males surpass females in the health and beauty category."
},
{
"code": null,
"e": 4618,
"s": 4338,
"text": "Filtering data based on a condition is a typical task in data analysis. Pandas is quite efficient in terms of how you can filter data. For instance, the query function accepts the condition as a string. There are, of course, some limitations but it comes in handy for many cases."
},
{
"code": null,
"e": 4742,
"s": 4618,
"text": "We can filter the purchases with total amount higher than 300 and quantity higher than 4 using the query function as below."
},
{
"code": null,
"e": 4798,
"s": 4742,
"text": "df.query('Total > 300 and Quantity > 4').shape(393, 12)"
},
{
"code": null,
"e": 4847,
"s": 4798,
"text": "There are 393 purchases that fit these criteria."
},
{
"code": null,
"e": 5106,
"s": 4847,
"text": "The distribution of variables always provides valuable insight for data analysis. For instance, we can check the distribution of the total sales amount of purchases. One method is to plot a histogram which can easily be done with the plot function of pandas."
},
{
"code": null,
"e": 5203,
"s": 5106,
"text": "df.Total.plot(kind='hist', figsize=(8,5), title='Histogram of Total Sale Amounts')"
},
{
"code": null,
"e": 5406,
"s": 5203,
"text": "Histogram divides the value range of a continuous variable into discrete bins and counts the number of data points (i.e. rows) in each bin. As a result, we get an overview of the distribution of values."
},
{
"code": null,
"e": 5581,
"s": 5406,
"text": "We can also analyze the sales based on time period of the day. For instance, we might be interested in finding out if people tend to spend more in the mornings than evenings."
},
{
"code": null,
"e": 5732,
"s": 5581,
"text": "In order to efficiently use date and time functionalities under dt accessor of pandas, we should convert the data type of the time column to datetime."
},
{
"code": null,
"e": 5766,
"s": 5732,
"text": "df.Time = pd.to_datetime(df.Time)"
},
{
"code": null,
"e": 5879,
"s": 5766,
"text": "The hour method returns the hour of the time as a string. We need to convert it to integer to use for filtering."
},
{
"code": null,
"e": 6020,
"s": 5879,
"text": "df[df.Time.dt.hour.astype('int') >= 20]['Total'].mean().round(2)306.26df[df.Time.dt.hour.astype('int') <= 10]['Total'].mean().round(2)311.10"
},
{
"code": null,
"e": 6364,
"s": 6020,
"text": "Let’s elaborate on what we have done above. The hour method of dt accessor extracts the hour as string. We convert it to an integer using the astype function and use it to filter purchased made after 20. The final operation is taking the mean of the purchases that fit the specified condition. Then we do the same for purchases made before 10."
},
{
"code": null,
"e": 6644,
"s": 6364,
"text": "The main purpose of this article to demonstrate various pandas functions that help us analyze tabular data. The parameters of pandas functions are highly important as they make the functions more powerful and versatile. Thus, it is very important to know what parameters achieve."
},
{
"code": null,
"e": 6917,
"s": 6644,
"text": "One of the things I like about pandas is that there are almost always more than one way to accomplish a task. For instance, what we have done in the examples can also be done in a different way. In fact, you may challenge yourself to do the same using different functions."
}
] |
Find the version of the Pandas and its dependencies in Python
|
Pandas is the important package for data analysis in Python. There are different versions available for Pandas. Due to some version mismatch, it may create some problems. So we need to find the version numbers of the Pandas. We can see them easily using the following code.
We can use the command like below, to get the version −
pandas.__version__
>>> import pandas as pd
>>> print(pd.__version__)
0.25.2
>>>
We can also get the version of the dependencies using the function like below −
pandas.show_versions()
>>> pd.show_versions()
INSTALLED VERSIONS
------------------
commit : None
python : 3.7.1.final.0
python-bits : 64
OS : Windows
OS-release : 7
machine : AMD64
processor : Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.None
pandas : 0.25.2
numpy : 1.15.3
pytz : 2018.7
dateutil : 2.7.4
pip : 19.2.2
setuptools : 39.0.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.2.5
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : 4.6.3
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : 4.2.5
matplotlib : 3.0.1
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
>>>
|
[
{
"code": null,
"e": 1336,
"s": 1062,
"text": "Pandas is the important package for data analysis in Python. There are different versions available for Pandas. Due to some version mismatch, it may create some problems. So we need to find the version numbers of the Pandas. We can see them easily using the following code."
},
{
"code": null,
"e": 1392,
"s": 1336,
"text": "We can use the command like below, to get the version −"
},
{
"code": null,
"e": 1411,
"s": 1392,
"text": "pandas.__version__"
},
{
"code": null,
"e": 1472,
"s": 1411,
"text": ">>> import pandas as pd\n>>> print(pd.__version__)\n0.25.2\n>>>"
},
{
"code": null,
"e": 1552,
"s": 1472,
"text": "We can also get the version of the dependencies using the function like below −"
},
{
"code": null,
"e": 1576,
"s": 1552,
"text": "pandas.show_versions()\n"
},
{
"code": null,
"e": 2493,
"s": 1576,
"text": ">>> pd.show_versions()\nINSTALLED VERSIONS\n------------------\ncommit : None\npython : 3.7.1.final.0\npython-bits : 64\nOS : Windows\nOS-release : 7\nmachine : AMD64\nprocessor : Intel64 Family 6 Model 60 Stepping 3, GenuineIntel\nbyteorder : little\nLC_ALL : None\nLANG : None\nLOCALE : None.None\n\npandas : 0.25.2\nnumpy : 1.15.3\npytz : 2018.7\ndateutil : 2.7.4\npip : 19.2.2\nsetuptools : 39.0.1\nCython : None\npytest : None\nhypothesis : None\nsphinx : None\nblosc : None\nfeather : None\nxlsxwriter : None\nlxml.etree : 4.2.5\nhtml5lib : None\npymysql : None\npsycopg2 : None\njinja2 : None\nIPython : None\npandas_datareader: None\nbs4 : 4.6.3\nbottleneck : None\nfastparquet : None\ngcsfs : None\nlxml.etree : 4.2.5\nmatplotlib : 3.0.1\nnumexpr : None\nodfpy : None\nopenpyxl : None\npandas_gbq : None\npyarrow : None\npytables : None\ns3fs : None\nscipy : None\nsqlalchemy : None\ntables : None\nxarray : None\nxlrd : None\nxlwt : None\nxlsxwriter : None\n>>>"
}
] |
RxJS - Creation Operator iif
|
This operator will decide which Observable will be subscribed.
iif(condition: Function):Observable
condition − The condition is a function if its return true the observable will be subscribed.
An observable will be returned based on the condition.
import { iif, of } from 'rxjs';
import { mergeMap, first, last } from 'rxjs/operators';
let task1 = iif(
() => (Math.random() + 1) % 2 === 0,
of("Even Case"),
of("Odd Case")
);
task1.subscribe(value => console.log(value));
iff() operator acts like a ternary operator and mostly used for if-else condition cases.
Odd Case
51 Lectures
4 hours
Daniel Stern
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1887,
"s": 1824,
"text": "This operator will decide which Observable will be subscribed."
},
{
"code": null,
"e": 1924,
"s": 1887,
"text": "iif(condition: Function):Observable\n"
},
{
"code": null,
"e": 2018,
"s": 1924,
"text": "condition − The condition is a function if its return true the observable will be subscribed."
},
{
"code": null,
"e": 2073,
"s": 2018,
"text": "An observable will be returned based on the condition."
},
{
"code": null,
"e": 2306,
"s": 2073,
"text": "import { iif, of } from 'rxjs';\nimport { mergeMap, first, last } from 'rxjs/operators';\n\nlet task1 = iif(\n () => (Math.random() + 1) % 2 === 0,\n of(\"Even Case\"),\n of(\"Odd Case\")\n);\ntask1.subscribe(value => console.log(value));"
},
{
"code": null,
"e": 2395,
"s": 2306,
"text": "iff() operator acts like a ternary operator and mostly used for if-else condition cases."
},
{
"code": null,
"e": 2405,
"s": 2395,
"text": "Odd Case\n"
},
{
"code": null,
"e": 2438,
"s": 2405,
"text": "\n 51 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2452,
"s": 2438,
"text": " Daniel Stern"
},
{
"code": null,
"e": 2459,
"s": 2452,
"text": " Print"
},
{
"code": null,
"e": 2470,
"s": 2459,
"text": " Add Notes"
}
] |
Find minimum number of coins that make a given value - GeeksforGeeks
|
18 Oct, 2021
Given a value V, if we want to make a change for V cents, and we have an infinite supply of each of C = { C1, C2, .., Cm} valued coins, what is the minimum number of coins to make the change? If it’s not possible to make a change, print -1.
Examples:
Input: coins[] = {25, 10, 5}, V = 30
Output: Minimum 2 coins required
We can use one coin of 25 cents and one of 5 cents
Input: coins[] = {9, 6, 5, 1}, V = 11
Output: Minimum 2 coins required
We can use one coin of 6 cents and 1 coin of 5 cents
This problem is a variation of the problem discussed Coin Change Problem. Here instead of finding the total number of possible solutions, we need to find the solution with the minimum number of coins.
The minimum number of coins for a value V can be computed using the below recursive formula.
If V == 0, then 0 coins required.
If V > 0
minCoins(coins[0..m-1], V) = min {1 + minCoins(V-coin[i])}
where i varies from 0 to m-1
and coin[i] <= V
Below is a recursive solution based on the above recursive formula.
C++
Java
Python3
C#
PHP
Javascript
// A Naive recursive C++ program to find minimum of coins// to make a given change V#include<bits/stdc++.h>using namespace std; // m is size of coins array (number of different coins)int minCoins(int coins[], int m, int V){ // base case if (V == 0) return 0; // Initialize result int res = INT_MAX; // Try every coin that has smaller value than V for (int i=0; i<m; i++) { if (coins[i] <= V) { int sub_res = minCoins(coins, m, V-coins[i]); // Check for INT_MAX to avoid overflow and see if // result can minimized if (sub_res != INT_MAX && sub_res + 1 < res) res = sub_res + 1; } } return res;} // Driver program to test above functionint main(){ int coins[] = {9, 6, 5, 1}; int m = sizeof(coins)/sizeof(coins[0]); int V = 11; cout << "Minimum coins required is " << minCoins(coins, m, V); return 0;}
// A Naive recursive JAVA program to find minimum of coins// to make a given change Vclass coin{ // m is size of coins array (number of different coins) static int minCoins(int coins[], int m, int V) { // base case if (V == 0) return 0; // Initialize result int res = Integer.MAX_VALUE; // Try every coin that has smaller value than V for (int i=0; i<m; i++) { if (coins[i] <= V) { int sub_res = minCoins(coins, m, V-coins[i]); // Check for INT_MAX to avoid overflow and see if // result can minimized if (sub_res != Integer.MAX_VALUE && sub_res + 1 < res) res = sub_res + 1; } } return res; } public static void main(String args[]) { int coins[] = {9, 6, 5, 1}; int m = coins.length; int V = 11; System.out.println("Minimum coins required is "+ minCoins(coins, m, V) ); }}/* This code is contributed by Rajat Mishra */
# A Naive recursive python program to find minimum of coins# to make a given change V import sys # m is size of coins array (number of different coins)def minCoins(coins, m, V): # base case if (V == 0): return 0 # Initialize result res = sys.maxsize # Try every coin that has smaller value than V for i in range(0, m): if (coins[i] <= V): sub_res = minCoins(coins, m, V-coins[i]) # Check for INT_MAX to avoid overflow and see if # result can minimized if (sub_res != sys.maxsize and sub_res + 1 < res): res = sub_res + 1 return res # Driver program to test above functioncoins = [9, 6, 5, 1]m = len(coins)V = 11print("Minimum coins required is",minCoins(coins, m, V)) # This code is contributed by# Smitha Dinesh Semwal
// A Naive recursive C# program// to find minimum of coins// to make a given change Vusing System;class coin{ // m is size of coins array // (number of different coins) static int minCoins(int []coins, int m, int V) { // base case if (V == 0) return 0; // Initialize result int res = int.MaxValue; // Try every coin that has // smaller value than V for (int i = 0; i < m; i++) { if (coins[i] <= V) { int sub_res = minCoins(coins, m, V - coins[i]); // Check for INT_MAX to // avoid overflow and see // if result can minimized if (sub_res != int.MaxValue && sub_res + 1 < res) res = sub_res + 1; } } return res; } // Driver Code public static void Main() { int []coins = {9, 6, 5, 1}; int m = coins.Length; int V = 11; Console.Write("Minimum coins required is "+ minCoins(coins, m, V)); }} // This code is contributed by nitin mittal.
<?php// A Naive recursive PHP// program to find minimum// of coins to make a given// change V // m is size of coins array// (number of different coins)function minCoins($coins, $m, $V){ // base caseif ($V == 0) return 0; // Initialize result$res = PHP_INT_MAX; // Try every coin that has// smaller value than Vfor ($i = 0; $i < $m; $i++){ if ($coins[$i] <= $V) { $sub_res = minCoins($coins, $m, $V - $coins[$i]); // Check for INT_MAX to // avoid overflow and see // if result can minimized if ($sub_res != PHP_INT_MAX && $sub_res + 1 < $res) $res = $sub_res + 1; }}return $res;} // Driver Code$coins = array(9, 6, 5, 1);$m = sizeof($coins);$V = 11;echo "Minimum coins required is ", minCoins($coins, $m, $V); // This code is contributed by ajit?>
<script> // A Naive recursive Javascript program to// find minimum of coins to make a given// change V // m is size of coins array// (number of different coins)function minCoins(coins, m, V){ // Base case if (V == 0) return 0; // Initialize result let res = Number.MAX_VALUE; // Try every coin that has smaller // value than V for(let i = 0; i < m; i++) { if (coins[i] <= V) { let sub_res = minCoins(coins, m, V - coins[i]); // Check for INT_MAX to avoid overflow and // see if result can minimized if (sub_res != Number.MAX_VALUE && sub_res + 1 < res) res = sub_res + 1; } } return res;} // Driver codelet coins = [ 9, 6, 5, 1 ];let m = coins.length;let V = 11; document.write("Minimum coins required is " + minCoins(coins, m, V) ); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Minimum coins required is 2
The time complexity of the above solution is exponential. If we draw the complete recursion tree, we can observe that many subproblems are solved again and again. For example, when we start from V = 11, we can reach 6 by subtracting one 5 times and by subtracting 5 one time. So the subproblem for 6 is called twice.
Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the min coins problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array table[][] in a bottom-up manner. Below is Dynamic Programming based solution.
C++
Java
Python3
C#
PHP
Javascript
// A Dynamic Programming based C++ program to find minimum of coins// to make a given change V#include<bits/stdc++.h>using namespace std; // m is size of coins array (number of different coins)int minCoins(int coins[], int m, int V){ // table[i] will be storing the minimum number of coins // required for i value. So table[V] will have result int table[V+1]; // Base case (If given value V is 0) table[0] = 0; // Initialize all table values as Infinite for (int i=1; i<=V; i++) table[i] = INT_MAX; // Compute minimum coins required for all // values from 1 to V for (int i=1; i<=V; i++) { // Go through all coins smaller than i for (int j=0; j<m; j++) if (coins[j] <= i) { int sub_res = table[i-coins[j]]; if (sub_res != INT_MAX && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } if(table[V]==INT_MAX) return -1; return table[V];} // Driver program to test above functionint main(){ int coins[] = {9, 6, 5, 1}; int m = sizeof(coins)/sizeof(coins[0]); int V = 11; cout << "Minimum coins required is " << minCoins(coins, m, V); return 0;}
// A Dynamic Programming based Java// program to find minimum of coins// to make a given change Vimport java.io.*; class GFG{ // m is size of coins array // (number of different coins) static int minCoins(int coins[], int m, int V) { // table[i] will be storing // the minimum number of coins // required for i value. So // table[V] will have result int table[] = new int[V + 1]; // Base case (If given value V is 0) table[0] = 0; // Initialize all table values as Infinite for (int i = 1; i <= V; i++) table[i] = Integer.MAX_VALUE; // Compute minimum coins required for all // values from 1 to V for (int i = 1; i <= V; i++) { // Go through all coins smaller than i for (int j = 0; j < m; j++) if (coins[j] <= i) { int sub_res = table[i - coins[j]]; if (sub_res != Integer.MAX_VALUE && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } if(table[V]==Integer.MAX_VALUE) return -1; return table[V]; } // Driver program public static void main (String[] args) { int coins[] = {9, 6, 5, 1}; int m = coins.length; int V = 11; System.out.println ( "Minimum coins required is " + minCoins(coins, m, V)); }} //This Code is contributed by vt_m.
# A Dynamic Programming based Python3 program to# find minimum of coins to make a given change Vimport sys # m is size of coins array (number of# different coins)def minCoins(coins, m, V): # table[i] will be storing the minimum # number of coins required for i value. # So table[V] will have result table = [0 for i in range(V + 1)] # Base case (If given value V is 0) table[0] = 0 # Initialize all table values as Infinite for i in range(1, V + 1): table[i] = sys.maxsize # Compute minimum coins required # for all values from 1 to V for i in range(1, V + 1): # Go through all coins smaller than i for j in range(m): if (coins[j] <= i): sub_res = table[i - coins[j]] if (sub_res != sys.maxsize and sub_res + 1 < table[i]): table[i] = sub_res + 1 if table[V] == sys.maxsize: return -1 return table[V] # Driver Codeif __name__ == "__main__": coins = [9, 6, 5, 1] m = len(coins) V = 11 print("Minimum coins required is ", minCoins(coins, m, V)) # This code is contributed by ita_c
// A Dynamic Programming based// Java program to find minimum// of coins to make a given// change Vusing System; class GFG{ // m is size of coins array// (number of different coins)static int minCoins(int []coins, int m, int V){ // table[i] will be storing // the minimum number of coins // required for i value. So // table[V] will have result int []table = new int[V + 1]; // Base case (If given // value V is 0) table[0] = 0; // Initialize all table // values as Infinite for (int i = 1; i <= V; i++) table[i] = int.MaxValue; // Compute minimum coins // required for all // values from 1 to V for (int i = 1; i <= V; i++) { // Go through all coins // smaller than i for (int j = 0; j < m; j++) if (coins[j] <= i) { int sub_res = table[i - coins[j]]; if (sub_res != int.MaxValue && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } return table[V]; } // Driver Codestatic public void Main (){ int []coins = {9, 6, 5, 1}; int m = coins.Length; int V = 11; Console.WriteLine("Minimum coins required is " + minCoins(coins, m, V));}} // This code is contributed// by akt_mit
<?php// A Dynamic Programming based// PHP program to find minimum// of coins to make a given// change V. // m is size of coins// array (number of different coins)function minCoins($coins, $m, $V){ // table[i] will be storing the // minimum number of coins // required for i value. So // table[V] will have result $table[$V + 1] = array(); // Base case (If given // value V is 0) $table[0] = 0; // Initialize all table // values as Infinite for ($i = 1; $i <= $V; $i++) $table[$i] = PHP_INT_MAX; // Compute minimum coins // required for all // values from 1 to V for ($i = 1; $i <= $V; $i++) { // Go through all coins // smaller than i for ($j = 0; $j < $m; $j++) if ($coins[$j] <= $i) { $sub_res = $table[$i - $coins[$j]]; if ($sub_res != PHP_INT_MAX && $sub_res + 1 < $table[$i]) $table[$i] = $sub_res + 1; } } if ($table[$V] == PHP_INT_MAX) return -1; return $table[$V];} // Driver Code$coins = array(9, 6, 5, 1);$m = sizeof($coins);$V = 11;echo "Minimum coins required is ", minCoins($coins, $m, $V); // This code is contributed by ajit?>
<script>// A Dynamic Programming based Javascript// program to find minimum of coins// to make a given change V // m is size of coins array // (number of different coins) function minCoins(coins,m,v) { // table[i] will be storing // the minimum number of coins // required for i value. So // table[V] will have result let table = new Array(V+1); for(let i = 0; i < V + 1; i++) { table[i] = 0; } // Initialize all table values as Infinite for (let i = 1; i <= V; i++) { table[i] = Number.MAX_VALUE; } // Compute minimum coins required for all // values from 1 to V for (let i = 1; i <= V; i++) { // Go through all coins smaller than i for (let j = 0; j < m; j++) if (coins[j] <= i) { let sub_res = table[i - coins[j]]; if (sub_res != Number.MAX_VALUE && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } if(table[V] == Number.MAX_VALUE) return -1; return table[V]; } // Driver program let coins = [9, 6, 5, 1]; let m = coins.length; let V = 11; document.write( "Minimum coins required is " + minCoins(coins, m, V)) // This code is contributed by rag2127</script>
Output:
Minimum coins required is 2
The time complexity of the above solution is O(mV).
Thanks to Goku for suggesting the above solution in a comment here and thanks to Vignesh Mohan for suggesting this problem and initial solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
jit_t
ukasp
Lens0021
kushanksriraj
snape_here
avanitrachhadiya2155
rag2127
sweetyty
punamsingh628700
Accolite
Amazon
dp-coin-change
Morgan Stanley
Oracle
Paytm
Samsung
Snapdeal
Synopsys
Dynamic Programming
Mathematical
Paytm
Morgan Stanley
Accolite
Amazon
Samsung
Snapdeal
Oracle
Synopsys
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Overlapping Subproblems Property in Dynamic Programming | DP-1
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 25927,
"s": 25899,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 26168,
"s": 25927,
"text": "Given a value V, if we want to make a change for V cents, and we have an infinite supply of each of C = { C1, C2, .., Cm} valued coins, what is the minimum number of coins to make the change? If it’s not possible to make a change, print -1."
},
{
"code": null,
"e": 26180,
"s": 26168,
"text": "Examples: "
},
{
"code": null,
"e": 26427,
"s": 26180,
"text": "Input: coins[] = {25, 10, 5}, V = 30\nOutput: Minimum 2 coins required\nWe can use one coin of 25 cents and one of 5 cents \n\nInput: coins[] = {9, 6, 5, 1}, V = 11\nOutput: Minimum 2 coins required\nWe can use one coin of 6 cents and 1 coin of 5 cents"
},
{
"code": null,
"e": 26628,
"s": 26427,
"text": "This problem is a variation of the problem discussed Coin Change Problem. Here instead of finding the total number of possible solutions, we need to find the solution with the minimum number of coins."
},
{
"code": null,
"e": 26722,
"s": 26628,
"text": "The minimum number of coins for a value V can be computed using the below recursive formula. "
},
{
"code": null,
"e": 26937,
"s": 26722,
"text": "If V == 0, then 0 coins required.\nIf V > 0\n minCoins(coins[0..m-1], V) = min {1 + minCoins(V-coin[i])} \n where i varies from 0 to m-1 \n and coin[i] <= V"
},
{
"code": null,
"e": 27006,
"s": 26937,
"text": "Below is a recursive solution based on the above recursive formula. "
},
{
"code": null,
"e": 27010,
"s": 27006,
"text": "C++"
},
{
"code": null,
"e": 27015,
"s": 27010,
"text": "Java"
},
{
"code": null,
"e": 27023,
"s": 27015,
"text": "Python3"
},
{
"code": null,
"e": 27026,
"s": 27023,
"text": "C#"
},
{
"code": null,
"e": 27030,
"s": 27026,
"text": "PHP"
},
{
"code": null,
"e": 27041,
"s": 27030,
"text": "Javascript"
},
{
"code": "// A Naive recursive C++ program to find minimum of coins// to make a given change V#include<bits/stdc++.h>using namespace std; // m is size of coins array (number of different coins)int minCoins(int coins[], int m, int V){ // base case if (V == 0) return 0; // Initialize result int res = INT_MAX; // Try every coin that has smaller value than V for (int i=0; i<m; i++) { if (coins[i] <= V) { int sub_res = minCoins(coins, m, V-coins[i]); // Check for INT_MAX to avoid overflow and see if // result can minimized if (sub_res != INT_MAX && sub_res + 1 < res) res = sub_res + 1; } } return res;} // Driver program to test above functionint main(){ int coins[] = {9, 6, 5, 1}; int m = sizeof(coins)/sizeof(coins[0]); int V = 11; cout << \"Minimum coins required is \" << minCoins(coins, m, V); return 0;}",
"e": 27942,
"s": 27041,
"text": null
},
{
"code": "// A Naive recursive JAVA program to find minimum of coins// to make a given change Vclass coin{ // m is size of coins array (number of different coins) static int minCoins(int coins[], int m, int V) { // base case if (V == 0) return 0; // Initialize result int res = Integer.MAX_VALUE; // Try every coin that has smaller value than V for (int i=0; i<m; i++) { if (coins[i] <= V) { int sub_res = minCoins(coins, m, V-coins[i]); // Check for INT_MAX to avoid overflow and see if // result can minimized if (sub_res != Integer.MAX_VALUE && sub_res + 1 < res) res = sub_res + 1; } } return res; } public static void main(String args[]) { int coins[] = {9, 6, 5, 1}; int m = coins.length; int V = 11; System.out.println(\"Minimum coins required is \"+ minCoins(coins, m, V) ); }}/* This code is contributed by Rajat Mishra */",
"e": 28967,
"s": 27942,
"text": null
},
{
"code": "# A Naive recursive python program to find minimum of coins# to make a given change V import sys # m is size of coins array (number of different coins)def minCoins(coins, m, V): # base case if (V == 0): return 0 # Initialize result res = sys.maxsize # Try every coin that has smaller value than V for i in range(0, m): if (coins[i] <= V): sub_res = minCoins(coins, m, V-coins[i]) # Check for INT_MAX to avoid overflow and see if # result can minimized if (sub_res != sys.maxsize and sub_res + 1 < res): res = sub_res + 1 return res # Driver program to test above functioncoins = [9, 6, 5, 1]m = len(coins)V = 11print(\"Minimum coins required is\",minCoins(coins, m, V)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 29790,
"s": 28967,
"text": null
},
{
"code": "// A Naive recursive C# program// to find minimum of coins// to make a given change Vusing System;class coin{ // m is size of coins array // (number of different coins) static int minCoins(int []coins, int m, int V) { // base case if (V == 0) return 0; // Initialize result int res = int.MaxValue; // Try every coin that has // smaller value than V for (int i = 0; i < m; i++) { if (coins[i] <= V) { int sub_res = minCoins(coins, m, V - coins[i]); // Check for INT_MAX to // avoid overflow and see // if result can minimized if (sub_res != int.MaxValue && sub_res + 1 < res) res = sub_res + 1; } } return res; } // Driver Code public static void Main() { int []coins = {9, 6, 5, 1}; int m = coins.Length; int V = 11; Console.Write(\"Minimum coins required is \"+ minCoins(coins, m, V)); }} // This code is contributed by nitin mittal.",
"e": 31009,
"s": 29790,
"text": null
},
{
"code": "<?php// A Naive recursive PHP// program to find minimum// of coins to make a given// change V // m is size of coins array// (number of different coins)function minCoins($coins, $m, $V){ // base caseif ($V == 0) return 0; // Initialize result$res = PHP_INT_MAX; // Try every coin that has// smaller value than Vfor ($i = 0; $i < $m; $i++){ if ($coins[$i] <= $V) { $sub_res = minCoins($coins, $m, $V - $coins[$i]); // Check for INT_MAX to // avoid overflow and see // if result can minimized if ($sub_res != PHP_INT_MAX && $sub_res + 1 < $res) $res = $sub_res + 1; }}return $res;} // Driver Code$coins = array(9, 6, 5, 1);$m = sizeof($coins);$V = 11;echo \"Minimum coins required is \", minCoins($coins, $m, $V); // This code is contributed by ajit?>",
"e": 31883,
"s": 31009,
"text": null
},
{
"code": "<script> // A Naive recursive Javascript program to// find minimum of coins to make a given// change V // m is size of coins array// (number of different coins)function minCoins(coins, m, V){ // Base case if (V == 0) return 0; // Initialize result let res = Number.MAX_VALUE; // Try every coin that has smaller // value than V for(let i = 0; i < m; i++) { if (coins[i] <= V) { let sub_res = minCoins(coins, m, V - coins[i]); // Check for INT_MAX to avoid overflow and // see if result can minimized if (sub_res != Number.MAX_VALUE && sub_res + 1 < res) res = sub_res + 1; } } return res;} // Driver codelet coins = [ 9, 6, 5, 1 ];let m = coins.length;let V = 11; document.write(\"Minimum coins required is \" + minCoins(coins, m, V) ); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 32887,
"s": 31883,
"text": null
},
{
"code": null,
"e": 32896,
"s": 32887,
"text": "Output: "
},
{
"code": null,
"e": 32924,
"s": 32896,
"text": "Minimum coins required is 2"
},
{
"code": null,
"e": 33242,
"s": 32924,
"text": "The time complexity of the above solution is exponential. If we draw the complete recursion tree, we can observe that many subproblems are solved again and again. For example, when we start from V = 11, we can reach 6 by subtracting one 5 times and by subtracting 5 one time. So the subproblem for 6 is called twice. "
},
{
"code": null,
"e": 33661,
"s": 33242,
"text": "Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the min coins problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array table[][] in a bottom-up manner. Below is Dynamic Programming based solution. "
},
{
"code": null,
"e": 33665,
"s": 33661,
"text": "C++"
},
{
"code": null,
"e": 33670,
"s": 33665,
"text": "Java"
},
{
"code": null,
"e": 33678,
"s": 33670,
"text": "Python3"
},
{
"code": null,
"e": 33681,
"s": 33678,
"text": "C#"
},
{
"code": null,
"e": 33685,
"s": 33681,
"text": "PHP"
},
{
"code": null,
"e": 33696,
"s": 33685,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based C++ program to find minimum of coins// to make a given change V#include<bits/stdc++.h>using namespace std; // m is size of coins array (number of different coins)int minCoins(int coins[], int m, int V){ // table[i] will be storing the minimum number of coins // required for i value. So table[V] will have result int table[V+1]; // Base case (If given value V is 0) table[0] = 0; // Initialize all table values as Infinite for (int i=1; i<=V; i++) table[i] = INT_MAX; // Compute minimum coins required for all // values from 1 to V for (int i=1; i<=V; i++) { // Go through all coins smaller than i for (int j=0; j<m; j++) if (coins[j] <= i) { int sub_res = table[i-coins[j]]; if (sub_res != INT_MAX && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } if(table[V]==INT_MAX) return -1; return table[V];} // Driver program to test above functionint main(){ int coins[] = {9, 6, 5, 1}; int m = sizeof(coins)/sizeof(coins[0]); int V = 11; cout << \"Minimum coins required is \" << minCoins(coins, m, V); return 0;}",
"e": 34914,
"s": 33696,
"text": null
},
{
"code": "// A Dynamic Programming based Java// program to find minimum of coins// to make a given change Vimport java.io.*; class GFG{ // m is size of coins array // (number of different coins) static int minCoins(int coins[], int m, int V) { // table[i] will be storing // the minimum number of coins // required for i value. So // table[V] will have result int table[] = new int[V + 1]; // Base case (If given value V is 0) table[0] = 0; // Initialize all table values as Infinite for (int i = 1; i <= V; i++) table[i] = Integer.MAX_VALUE; // Compute minimum coins required for all // values from 1 to V for (int i = 1; i <= V; i++) { // Go through all coins smaller than i for (int j = 0; j < m; j++) if (coins[j] <= i) { int sub_res = table[i - coins[j]]; if (sub_res != Integer.MAX_VALUE && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } if(table[V]==Integer.MAX_VALUE) return -1; return table[V]; } // Driver program public static void main (String[] args) { int coins[] = {9, 6, 5, 1}; int m = coins.length; int V = 11; System.out.println ( \"Minimum coins required is \" + minCoins(coins, m, V)); }} //This Code is contributed by vt_m.",
"e": 36476,
"s": 34914,
"text": null
},
{
"code": "# A Dynamic Programming based Python3 program to# find minimum of coins to make a given change Vimport sys # m is size of coins array (number of# different coins)def minCoins(coins, m, V): # table[i] will be storing the minimum # number of coins required for i value. # So table[V] will have result table = [0 for i in range(V + 1)] # Base case (If given value V is 0) table[0] = 0 # Initialize all table values as Infinite for i in range(1, V + 1): table[i] = sys.maxsize # Compute minimum coins required # for all values from 1 to V for i in range(1, V + 1): # Go through all coins smaller than i for j in range(m): if (coins[j] <= i): sub_res = table[i - coins[j]] if (sub_res != sys.maxsize and sub_res + 1 < table[i]): table[i] = sub_res + 1 if table[V] == sys.maxsize: return -1 return table[V] # Driver Codeif __name__ == \"__main__\": coins = [9, 6, 5, 1] m = len(coins) V = 11 print(\"Minimum coins required is \", minCoins(coins, m, V)) # This code is contributed by ita_c",
"e": 37659,
"s": 36476,
"text": null
},
{
"code": "// A Dynamic Programming based// Java program to find minimum// of coins to make a given// change Vusing System; class GFG{ // m is size of coins array// (number of different coins)static int minCoins(int []coins, int m, int V){ // table[i] will be storing // the minimum number of coins // required for i value. So // table[V] will have result int []table = new int[V + 1]; // Base case (If given // value V is 0) table[0] = 0; // Initialize all table // values as Infinite for (int i = 1; i <= V; i++) table[i] = int.MaxValue; // Compute minimum coins // required for all // values from 1 to V for (int i = 1; i <= V; i++) { // Go through all coins // smaller than i for (int j = 0; j < m; j++) if (coins[j] <= i) { int sub_res = table[i - coins[j]]; if (sub_res != int.MaxValue && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } return table[V]; } // Driver Codestatic public void Main (){ int []coins = {9, 6, 5, 1}; int m = coins.Length; int V = 11; Console.WriteLine(\"Minimum coins required is \" + minCoins(coins, m, V));}} // This code is contributed// by akt_mit",
"e": 38957,
"s": 37659,
"text": null
},
{
"code": "<?php// A Dynamic Programming based// PHP program to find minimum// of coins to make a given// change V. // m is size of coins// array (number of different coins)function minCoins($coins, $m, $V){ // table[i] will be storing the // minimum number of coins // required for i value. So // table[V] will have result $table[$V + 1] = array(); // Base case (If given // value V is 0) $table[0] = 0; // Initialize all table // values as Infinite for ($i = 1; $i <= $V; $i++) $table[$i] = PHP_INT_MAX; // Compute minimum coins // required for all // values from 1 to V for ($i = 1; $i <= $V; $i++) { // Go through all coins // smaller than i for ($j = 0; $j < $m; $j++) if ($coins[$j] <= $i) { $sub_res = $table[$i - $coins[$j]]; if ($sub_res != PHP_INT_MAX && $sub_res + 1 < $table[$i]) $table[$i] = $sub_res + 1; } } if ($table[$V] == PHP_INT_MAX) return -1; return $table[$V];} // Driver Code$coins = array(9, 6, 5, 1);$m = sizeof($coins);$V = 11;echo \"Minimum coins required is \", minCoins($coins, $m, $V); // This code is contributed by ajit?>",
"e": 40179,
"s": 38957,
"text": null
},
{
"code": "<script>// A Dynamic Programming based Javascript// program to find minimum of coins// to make a given change V // m is size of coins array // (number of different coins) function minCoins(coins,m,v) { // table[i] will be storing // the minimum number of coins // required for i value. So // table[V] will have result let table = new Array(V+1); for(let i = 0; i < V + 1; i++) { table[i] = 0; } // Initialize all table values as Infinite for (let i = 1; i <= V; i++) { table[i] = Number.MAX_VALUE; } // Compute minimum coins required for all // values from 1 to V for (let i = 1; i <= V; i++) { // Go through all coins smaller than i for (let j = 0; j < m; j++) if (coins[j] <= i) { let sub_res = table[i - coins[j]]; if (sub_res != Number.MAX_VALUE && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } if(table[V] == Number.MAX_VALUE) return -1; return table[V]; } // Driver program let coins = [9, 6, 5, 1]; let m = coins.length; let V = 11; document.write( \"Minimum coins required is \" + minCoins(coins, m, V)) // This code is contributed by rag2127</script>",
"e": 41615,
"s": 40179,
"text": null
},
{
"code": null,
"e": 41624,
"s": 41615,
"text": "Output: "
},
{
"code": null,
"e": 41652,
"s": 41624,
"text": "Minimum coins required is 2"
},
{
"code": null,
"e": 41705,
"s": 41652,
"text": "The time complexity of the above solution is O(mV). "
},
{
"code": null,
"e": 41974,
"s": 41705,
"text": "Thanks to Goku for suggesting the above solution in a comment here and thanks to Vignesh Mohan for suggesting this problem and initial solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 41987,
"s": 41974,
"text": "nitin mittal"
},
{
"code": null,
"e": 41993,
"s": 41987,
"text": "jit_t"
},
{
"code": null,
"e": 41999,
"s": 41993,
"text": "ukasp"
},
{
"code": null,
"e": 42008,
"s": 41999,
"text": "Lens0021"
},
{
"code": null,
"e": 42022,
"s": 42008,
"text": "kushanksriraj"
},
{
"code": null,
"e": 42033,
"s": 42022,
"text": "snape_here"
},
{
"code": null,
"e": 42054,
"s": 42033,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 42062,
"s": 42054,
"text": "rag2127"
},
{
"code": null,
"e": 42071,
"s": 42062,
"text": "sweetyty"
},
{
"code": null,
"e": 42088,
"s": 42071,
"text": "punamsingh628700"
},
{
"code": null,
"e": 42097,
"s": 42088,
"text": "Accolite"
},
{
"code": null,
"e": 42104,
"s": 42097,
"text": "Amazon"
},
{
"code": null,
"e": 42119,
"s": 42104,
"text": "dp-coin-change"
},
{
"code": null,
"e": 42134,
"s": 42119,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 42141,
"s": 42134,
"text": "Oracle"
},
{
"code": null,
"e": 42147,
"s": 42141,
"text": "Paytm"
},
{
"code": null,
"e": 42155,
"s": 42147,
"text": "Samsung"
},
{
"code": null,
"e": 42164,
"s": 42155,
"text": "Snapdeal"
},
{
"code": null,
"e": 42173,
"s": 42164,
"text": "Synopsys"
},
{
"code": null,
"e": 42193,
"s": 42173,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42206,
"s": 42193,
"text": "Mathematical"
},
{
"code": null,
"e": 42212,
"s": 42206,
"text": "Paytm"
},
{
"code": null,
"e": 42227,
"s": 42212,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 42236,
"s": 42227,
"text": "Accolite"
},
{
"code": null,
"e": 42243,
"s": 42236,
"text": "Amazon"
},
{
"code": null,
"e": 42251,
"s": 42243,
"text": "Samsung"
},
{
"code": null,
"e": 42260,
"s": 42251,
"text": "Snapdeal"
},
{
"code": null,
"e": 42267,
"s": 42260,
"text": "Oracle"
},
{
"code": null,
"e": 42276,
"s": 42267,
"text": "Synopsys"
},
{
"code": null,
"e": 42296,
"s": 42276,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42309,
"s": 42296,
"text": "Mathematical"
},
{
"code": null,
"e": 42407,
"s": 42309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42440,
"s": 42407,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 42475,
"s": 42440,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 42543,
"s": 42475,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 42564,
"s": 42543,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 42627,
"s": 42564,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 42687,
"s": 42627,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 42702,
"s": 42687,
"text": "C++ Data Types"
},
{
"code": null,
"e": 42745,
"s": 42702,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 42769,
"s": 42745,
"text": "Merge two sorted arrays"
}
] |
How to create a ColorPicker using JavaFX?
|
A color picker gives you a standard color palette fro which you can select a required color. You can create a color picker by instantiating the javafx.scene.control.ColorPicker class.
The following Example demonstrates the creation of a ColorPicker.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class ColorPickerExample extends Application {
public void start(Stage stage) {
//Setting the label
Label label = new Label("Select Desired Color:");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
//Creating a Color picker
ColorPicker picker = new ColorPicker();
//Creating a hbox to hold the pagination
HBox hbox = new HBox();
hbox.setSpacing(20);
hbox.setPadding(new Insets(25, 50, 50, 60));
hbox.getChildren().addAll(label, picker);
//Setting the stage
Group root = new Group(hbox);
Scene scene = new Scene(root, 595, 300, Color.BEIGE);
stage.setTitle("Color Picker");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1246,
"s": 1062,
"text": "A color picker gives you a standard color palette fro which you can select a required color. You can create a color picker by instantiating the javafx.scene.control.ColorPicker class."
},
{
"code": null,
"e": 1312,
"s": 1246,
"text": "The following Example demonstrates the creation of a ColorPicker."
},
{
"code": null,
"e": 2557,
"s": 1312,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ColorPicker;\nimport javafx.scene.control.Label;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.stage.Stage;\npublic class ColorPickerExample extends Application {\n public void start(Stage stage) {\n //Setting the label\n Label label = new Label(\"Select Desired Color:\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n label.setFont(font);\n //Creating a Color picker\n ColorPicker picker = new ColorPicker();\n //Creating a hbox to hold the pagination\n HBox hbox = new HBox();\n hbox.setSpacing(20);\n hbox.setPadding(new Insets(25, 50, 50, 60));\n hbox.getChildren().addAll(label, picker);\n //Setting the stage\n Group root = new Group(hbox);\n Scene scene = new Scene(root, 595, 300, Color.BEIGE);\n stage.setTitle(\"Color Picker\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Implement Queue using array | Practice | GeeksforGeeks
|
Implement a Queue using an Array. Queries in the Queue are of the following type:
(i) 1 x (a query of this type means pushing 'x' into the queue)
(ii) 2 (a query of this type means to pop element from queue and print the poped element)
Example 1:
Input:
Q = 5
Queries = 1 2 1 3 2 1 4 2
Output: 2 3
Explanation:
In the first test case for query
1 2 the queue will be {2}
1 3 the queue will be {2 3}
2 poped element will be 2 the
queue will be {3}
1 4 the queue will be {3 4}
2 poped element will be 3
Example 2:
Input:
Q = 4
Queries = 1 3 2 2 1 4
Output: 3 -1
Explanation:
In the second testcase for query
1 3 the queue will be {3}
2 poped element will be 3 the
queue will be empty
2 there is no element in the
queue and hence -1
1 4 the queue will be {4}.
Your Task :
You are required to complete the two methods push() which take one argument an integer 'x' to be pushed into the queue and pop() which returns a integer poped out from othe queue. If the queue is empty, it should return -1 on a pop operation.
Expected Time Complexity: O(1) for both push() and pop().
Expected Auxiliary Space: O(1) for both push() and pop().
Constraints:
1 ≤ Q ≤ 105
1 ≤ x ≤ 105
0
amanahirwar1515 days ago
C++ EASY SOLUTION
//Function to push an element x in a queue.void MyQueue :: push(int x){ arr[rear++]=x; }
//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(rear==front){ return -1; } int d = arr[front]; front++; return d;}
+2
harshscode2 weeks ago
arr[rear]=x; rear=rear+1;}
//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(rear==front) return -1; int x=arr[front]; front=front+1; return x;
+1
vbn20012 weeks ago
Java Solution:
class MyQueue {
int front, rear;
int arr[] = new int[100005];
MyQueue()
{
front=0;
rear=0;
}
//Function to push an element x in a queue.
void push(int x)
{
arr[rear] = x;
rear++;
}
//Function to pop an element from queue and return that element.
int pop()
{
if(rear==front) return -1;
int temp = arr[front];
front++;
return temp;
}
}
0
zerefkhan2 weeks ago
C++ solution
Total Time Taken : 0.79/2.36
//Function to push an element x in a queue.
void MyQueue :: push(int x)
{
arr[rear++] = x;
}
//Function to pop an element from queue and return that element.
int MyQueue :: pop()
{
if(front == rear) return -1;
return arr[front++];
}
-1
atif836141 month ago
java solution:-
void push(){
arr[rear]=x;
rear++;
}
int pop(){
if(rear ==front){
return -1;
}
int temp=arr[front];
front++;
return arr[temp];
}
0
swastikp17111 month ago
Simple Java Code
class MyQueue {
int front, rear;
int arr[] = new int[100005];
MyQueue()
{
front=0;
rear=-1;
}
//Function to push an element x in a queue.
void push(int x)
{
arr[++rear]=x;
}
//Function to pop an element from queue and return that element.
int pop()
{ // when Queue is Empty
if(front>rear) return -1;
// When Queue is not Empty
int ans=arr[front++];
return ans;
}
}
0
hasnainraza1998hr1 month ago
C++, 0.8
//Function to push an element x in a queue.void MyQueue :: push(int x){ arr[rear++] = x;}
//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(front==rear) return -1; int temp; if(rear==1){ temp = arr[front]; front = rear = 0; } else{ temp = arr[front++]; if(front>rear) front = rear = 0; } return temp;}
0
harshitgoel0031 month ago
class MyQueue {
int front, rear; int arr[] = new int[100005];
MyQueue(){ front = -1; rear = -1;}//Function to push an element x in a queue.void push(int x){ // Your code here if((front == -1) && (rear == -1)) { arr[(front + 1)] = x; front += 1; rear += 1; } else { arr[(rear + 1)] = x; rear += 1; }}
//Function to pop an element from queue and return that element.int pop(){ // Your code here if((front == -1) && (rear == -1)) return -1; int result = arr[front]; front += 1; if(front > rear) { front = -1; rear = -1; }
return result; } }
0
detroix072 months ago
void MyQueue :: push(int x){ if(rear==100005) { cout << "queue is full" << endl; } else { arr[rear]=x; rear++; }}
//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(rear==front) { return -1; } else { int Element = arr[front]; front++; if(rear==front) { front=0; rear=0; } return Element; }}
0
akshitbansal7192 months ago
Javascript solution:-
class MyQueue {
constructor(){
this.front = 0;
this.rear = 0;
this.arr = new Array(100005);
}
push(x) {
// Your code here
this.arr[this.rear++] = x
}
pop() {
// Your code here
if (this.front >= this.rear) return -1
return this.arr[this.front++]
}
}
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": 481,
"s": 238,
"text": "Implement a Queue using an Array. Queries in the Queue are of the following type:\n(i) 1 x (a query of this type means pushing 'x' into the queue)\n(ii) 2 (a query of this type means to pop element from queue and print the poped element)"
},
{
"code": null,
"e": 492,
"s": 481,
"text": "Example 1:"
},
{
"code": null,
"e": 757,
"s": 492,
"text": "Input:\nQ = 5\nQueries = 1 2 1 3 2 1 4 2\nOutput: 2 3\nExplanation:\nIn the first test case for query \n1 2 the queue will be {2}\n1 3 the queue will be {2 3}\n2 poped element will be 2 the \n queue will be {3}\n1 4 the queue will be {3 4}\n2 poped element will be 3 \n"
},
{
"code": null,
"e": 768,
"s": 757,
"text": "Example 2:"
},
{
"code": null,
"e": 1030,
"s": 768,
"text": "Input:\nQ = 4\nQueries = 1 3 2 2 1 4 \nOutput: 3 -1\nExplanation:\nIn the second testcase for query \n1 3 the queue will be {3}\n2 poped element will be 3 the\n queue will be empty\n2 there is no element in the\n queue and hence -1\n1 4 the queue will be {4}. "
},
{
"code": null,
"e": 1286,
"s": 1030,
"text": "Your Task :\nYou are required to complete the two methods push() which take one argument an integer 'x' to be pushed into the queue and pop() which returns a integer poped out from othe queue. If the queue is empty, it should return -1 on a pop operation. "
},
{
"code": null,
"e": 1402,
"s": 1286,
"text": "Expected Time Complexity: O(1) for both push() and pop().\nExpected Auxiliary Space: O(1) for both push() and pop()."
},
{
"code": null,
"e": 1439,
"s": 1402,
"text": "Constraints:\n1 ≤ Q ≤ 105\n1 ≤ x ≤ 105"
},
{
"code": null,
"e": 1441,
"s": 1439,
"text": "0"
},
{
"code": null,
"e": 1466,
"s": 1441,
"text": "amanahirwar1515 days ago"
},
{
"code": null,
"e": 1484,
"s": 1466,
"text": "C++ EASY SOLUTION"
},
{
"code": null,
"e": 1577,
"s": 1484,
"text": "//Function to push an element x in a queue.void MyQueue :: push(int x){ arr[rear++]=x; }"
},
{
"code": null,
"e": 1755,
"s": 1577,
"text": "//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(rear==front){ return -1; } int d = arr[front]; front++; return d;}"
},
{
"code": null,
"e": 1758,
"s": 1755,
"text": "+2"
},
{
"code": null,
"e": 1780,
"s": 1758,
"text": "harshscode2 weeks ago"
},
{
"code": null,
"e": 1820,
"s": 1780,
"text": " arr[rear]=x; rear=rear+1;}"
},
{
"code": null,
"e": 2000,
"s": 1820,
"text": "//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(rear==front) return -1; int x=arr[front]; front=front+1; return x;"
},
{
"code": null,
"e": 2003,
"s": 2000,
"text": "+1"
},
{
"code": null,
"e": 2022,
"s": 2003,
"text": "vbn20012 weeks ago"
},
{
"code": null,
"e": 2038,
"s": 2022,
"text": "Java Solution: "
},
{
"code": null,
"e": 2426,
"s": 2038,
"text": "\nclass MyQueue {\n\n int front, rear;\n\tint arr[] = new int[100005];\n\n MyQueue()\n\t{\n\t\tfront=0;\n\t\trear=0;\n\t}\n\t\n\t//Function to push an element x in a queue.\n\tvoid push(int x)\n\t{\n\t arr[rear] = x;\n\t rear++;\n\t} \n\n //Function to pop an element from queue and return that element.\n\tint pop()\n\t{\n\t\tif(rear==front) return -1;\n\t\t\n\t\tint temp = arr[front];\n\t\tfront++;\n\t\treturn temp;\n\t} \n}\n"
},
{
"code": null,
"e": 2428,
"s": 2426,
"text": "0"
},
{
"code": null,
"e": 2449,
"s": 2428,
"text": "zerefkhan2 weeks ago"
},
{
"code": null,
"e": 2462,
"s": 2449,
"text": "C++ solution"
},
{
"code": null,
"e": 2491,
"s": 2462,
"text": "Total Time Taken : 0.79/2.36"
},
{
"code": null,
"e": 2739,
"s": 2493,
"text": "//Function to push an element x in a queue.\nvoid MyQueue :: push(int x)\n{\n arr[rear++] = x;\n}\n\n//Function to pop an element from queue and return that element.\nint MyQueue :: pop()\n{\n if(front == rear) return -1;\n return arr[front++];\n}"
},
{
"code": null,
"e": 2742,
"s": 2739,
"text": "-1"
},
{
"code": null,
"e": 2763,
"s": 2742,
"text": "atif836141 month ago"
},
{
"code": null,
"e": 2779,
"s": 2763,
"text": "java solution:-"
},
{
"code": null,
"e": 2793,
"s": 2779,
"text": "void push(){ "
},
{
"code": null,
"e": 2806,
"s": 2793,
"text": "arr[rear]=x;"
},
{
"code": null,
"e": 2814,
"s": 2806,
"text": "rear++;"
},
{
"code": null,
"e": 2816,
"s": 2814,
"text": "}"
},
{
"code": null,
"e": 2830,
"s": 2818,
"text": "int pop(){"
},
{
"code": null,
"e": 2848,
"s": 2830,
"text": "if(rear ==front){"
},
{
"code": null,
"e": 2859,
"s": 2848,
"text": "return -1;"
},
{
"code": null,
"e": 2861,
"s": 2859,
"text": "}"
},
{
"code": null,
"e": 2882,
"s": 2861,
"text": "int temp=arr[front];"
},
{
"code": null,
"e": 2891,
"s": 2882,
"text": "front++;"
},
{
"code": null,
"e": 2909,
"s": 2891,
"text": "return arr[temp];"
},
{
"code": null,
"e": 2911,
"s": 2909,
"text": "}"
},
{
"code": null,
"e": 2913,
"s": 2911,
"text": "0"
},
{
"code": null,
"e": 2937,
"s": 2913,
"text": "swastikp17111 month ago"
},
{
"code": null,
"e": 2954,
"s": 2937,
"text": "Simple Java Code"
},
{
"code": null,
"e": 3376,
"s": 2954,
"text": "class MyQueue {\n\n int front, rear;\n\tint arr[] = new int[100005];\n\n MyQueue()\n\t{\n\t\tfront=0;\n\t\trear=-1;\n\t}\n\t\n\t//Function to push an element x in a queue.\n\tvoid push(int x)\n\t{\n\t arr[++rear]=x; \n\t} \n\n //Function to pop an element from queue and return that element.\n\tint pop()\n\t{ // when Queue is Empty\n\t\tif(front>rear) return -1;\n\t\t\n\t\t// When Queue is not Empty\n\t\tint ans=arr[front++];\n\t\treturn ans;\n\t} \n}"
},
{
"code": null,
"e": 3378,
"s": 3376,
"text": "0"
},
{
"code": null,
"e": 3407,
"s": 3378,
"text": "hasnainraza1998hr1 month ago"
},
{
"code": null,
"e": 3416,
"s": 3407,
"text": "C++, 0.8"
},
{
"code": null,
"e": 3512,
"s": 3416,
"text": "//Function to push an element x in a queue.void MyQueue :: push(int x){ arr[rear++] = x;}"
},
{
"code": null,
"e": 3869,
"s": 3512,
"text": "//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(front==rear) return -1; int temp; if(rear==1){ temp = arr[front]; front = rear = 0; } else{ temp = arr[front++]; if(front>rear) front = rear = 0; } return temp;}"
},
{
"code": null,
"e": 3871,
"s": 3869,
"text": "0"
},
{
"code": null,
"e": 3897,
"s": 3871,
"text": "harshitgoel0031 month ago"
},
{
"code": null,
"e": 3913,
"s": 3897,
"text": "class MyQueue {"
},
{
"code": null,
"e": 3964,
"s": 3913,
"text": " int front, rear; int arr[] = new int[100005];"
},
{
"code": null,
"e": 4255,
"s": 3964,
"text": " MyQueue(){ front = -1; rear = -1;}//Function to push an element x in a queue.void push(int x){ // Your code here if((front == -1) && (rear == -1)) { arr[(front + 1)] = x; front += 1; rear += 1; } else { arr[(rear + 1)] = x; rear += 1; }}"
},
{
"code": null,
"e": 4507,
"s": 4255,
"text": " //Function to pop an element from queue and return that element.int pop(){ // Your code here if((front == -1) && (rear == -1)) return -1; int result = arr[front]; front += 1; if(front > rear) { front = -1; rear = -1; }"
},
{
"code": null,
"e": 4533,
"s": 4507,
"text": " return result; } }"
},
{
"code": null,
"e": 4539,
"s": 4537,
"text": "0"
},
{
"code": null,
"e": 4561,
"s": 4539,
"text": "detroix072 months ago"
},
{
"code": null,
"e": 4692,
"s": 4561,
"text": "void MyQueue :: push(int x){ if(rear==100005) { cout << \"queue is full\" << endl; } else { arr[rear]=x; rear++; }}"
},
{
"code": null,
"e": 4963,
"s": 4692,
"text": "//Function to pop an element from queue and return that element.int MyQueue :: pop(){ if(rear==front) { return -1; } else { int Element = arr[front]; front++; if(rear==front) { front=0; rear=0; } return Element; }} "
},
{
"code": null,
"e": 4965,
"s": 4963,
"text": "0"
},
{
"code": null,
"e": 4993,
"s": 4965,
"text": "akshitbansal7192 months ago"
},
{
"code": null,
"e": 5015,
"s": 4993,
"text": "Javascript solution:-"
},
{
"code": null,
"e": 5307,
"s": 5017,
"text": "class MyQueue {\n \n constructor(){\n\t\tthis.front = 0;\n\t\tthis.rear = 0;\n\t\tthis.arr = new Array(100005);\n\t}\n\n\tpush(x) {\n\t // Your code here\n\t this.arr[this.rear++] = x\n\t} \n\n\tpop() {\n\t\t// Your code here\n\t\tif (this.front >= this.rear) return -1\n\t\treturn this.arr[this.front++]\n\t} \n}\n"
},
{
"code": null,
"e": 5453,
"s": 5307,
"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": 5489,
"s": 5453,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5499,
"s": 5489,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5509,
"s": 5499,
"text": "\nContest\n"
},
{
"code": null,
"e": 5572,
"s": 5509,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5720,
"s": 5572,
"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": 5928,
"s": 5720,
"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": 6034,
"s": 5928,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Unix / Linux - Shell Manpage Help
|
All the Unix commands come with a number of optional and mandatory options. It is very common to forget the complete syntax of these commands.
Because no one can possibly remember every Unix command and all its options, we have online help available to mitigate this right from when Unix was at its development stage.
Unix's version of Help files are called man pages. If there is a command name and you are not sure how to use it, then Man Pages help you out with every step.
Here is the simple command that helps you get the detail of any Unix command while working with the system −
$man command
Suppose there is a command that requires you to get help; assume that you want to know about pwd then you simply need to use the following command −
$man pwd
The above command helps you with the complete information about the pwd command. Try it yourself at your command prompt to get more detail.
You can get complete detail on man command itself using the following command −
$man man
Man pages are generally divided into sections, which generally vary by the man page author's preference. Following table lists some common sections −
NAME
Name of the command
SYNOPSIS
General usage parameters of the command
DESCRIPTION
Describes what the command does
OPTIONS
Describes all the arguments or options to the command
SEE ALSO
Lists other commands that are directly related to the command in the man page or closely resemble its functionality
BUGS
Explains any known issues or bugs that exist with the command or its output
EXAMPLES
Common usage examples that give the reader an idea of how the command can be used
AUTHORS
The author of the man page/command
To sum it up, man pages are a vital resource and the first avenue of research when you need information about commands or files in a Unix system.
The following link gives you a list of the most important and very frequently used Unix Shell commands.
If you do not know how to use any command, then use man page to get complete detail about the command.
Here is the list of Unix Shell - Useful Commands
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2890,
"s": 2747,
"text": "All the Unix commands come with a number of optional and mandatory options. It is very common to forget the complete syntax of these commands."
},
{
"code": null,
"e": 3065,
"s": 2890,
"text": "Because no one can possibly remember every Unix command and all its options, we have online help available to mitigate this right from when Unix was at its development stage."
},
{
"code": null,
"e": 3224,
"s": 3065,
"text": "Unix's version of Help files are called man pages. If there is a command name and you are not sure how to use it, then Man Pages help you out with every step."
},
{
"code": null,
"e": 3333,
"s": 3224,
"text": "Here is the simple command that helps you get the detail of any Unix command while working with the system −"
},
{
"code": null,
"e": 3347,
"s": 3333,
"text": "$man command\n"
},
{
"code": null,
"e": 3496,
"s": 3347,
"text": "Suppose there is a command that requires you to get help; assume that you want to know about pwd then you simply need to use the following command −"
},
{
"code": null,
"e": 3506,
"s": 3496,
"text": "$man pwd\n"
},
{
"code": null,
"e": 3646,
"s": 3506,
"text": "The above command helps you with the complete information about the pwd command. Try it yourself at your command prompt to get more detail."
},
{
"code": null,
"e": 3726,
"s": 3646,
"text": "You can get complete detail on man command itself using the following command −"
},
{
"code": null,
"e": 3736,
"s": 3726,
"text": "$man man\n"
},
{
"code": null,
"e": 3886,
"s": 3736,
"text": "Man pages are generally divided into sections, which generally vary by the man page author's preference. Following table lists some common sections −"
},
{
"code": null,
"e": 3891,
"s": 3886,
"text": "NAME"
},
{
"code": null,
"e": 3911,
"s": 3891,
"text": "Name of the command"
},
{
"code": null,
"e": 3920,
"s": 3911,
"text": "SYNOPSIS"
},
{
"code": null,
"e": 3960,
"s": 3920,
"text": "General usage parameters of the command"
},
{
"code": null,
"e": 3972,
"s": 3960,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 4004,
"s": 3972,
"text": "Describes what the command does"
},
{
"code": null,
"e": 4012,
"s": 4004,
"text": "OPTIONS"
},
{
"code": null,
"e": 4066,
"s": 4012,
"text": "Describes all the arguments or options to the command"
},
{
"code": null,
"e": 4075,
"s": 4066,
"text": "SEE ALSO"
},
{
"code": null,
"e": 4191,
"s": 4075,
"text": "Lists other commands that are directly related to the command in the man page or closely resemble its functionality"
},
{
"code": null,
"e": 4196,
"s": 4191,
"text": "BUGS"
},
{
"code": null,
"e": 4272,
"s": 4196,
"text": "Explains any known issues or bugs that exist with the command or its output"
},
{
"code": null,
"e": 4281,
"s": 4272,
"text": "EXAMPLES"
},
{
"code": null,
"e": 4363,
"s": 4281,
"text": "Common usage examples that give the reader an idea of how the command can be used"
},
{
"code": null,
"e": 4371,
"s": 4363,
"text": "AUTHORS"
},
{
"code": null,
"e": 4406,
"s": 4371,
"text": "The author of the man page/command"
},
{
"code": null,
"e": 4552,
"s": 4406,
"text": "To sum it up, man pages are a vital resource and the first avenue of research when you need information about commands or files in a Unix system."
},
{
"code": null,
"e": 4656,
"s": 4552,
"text": "The following link gives you a list of the most important and very frequently used Unix Shell commands."
},
{
"code": null,
"e": 4759,
"s": 4656,
"text": "If you do not know how to use any command, then use man page to get complete detail about the command."
},
{
"code": null,
"e": 4808,
"s": 4759,
"text": "Here is the list of Unix Shell - Useful Commands"
},
{
"code": null,
"e": 4843,
"s": 4808,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 4871,
"s": 4843,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4905,
"s": 4871,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4922,
"s": 4905,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4955,
"s": 4922,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4966,
"s": 4955,
"text": " Pradeep D"
},
{
"code": null,
"e": 5001,
"s": 4966,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5017,
"s": 5001,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5050,
"s": 5017,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5062,
"s": 5050,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 5094,
"s": 5062,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5102,
"s": 5094,
"text": " Uplatz"
},
{
"code": null,
"e": 5109,
"s": 5102,
"text": " Print"
},
{
"code": null,
"e": 5120,
"s": 5109,
"text": " Add Notes"
}
] |
Do You Know Python Has A Built-In Database? | by Christopher Tao | Towards Data Science
|
If you are a software developer, I believe you must know or even have used an extremely light-weighted database — SQLite. It has almost all the features you need as a relational database, but everything is saved in a single file. On the official site, here are some scenarios that you could use SQLite.
Embedded devices and IoT
Data Analysis
Data Transferring
File archive and/or data container
Internal or temporary databases
Stand-in for an enterprise database during demos or testing
Education, training and testing
Experimental SQL language extensions
There are more reasons that you may want to use SQLite, please check out the documentation.
www.sqlite.org
Most importantly, SQLite is built-in into a Python library. In other words, you don’t need to install any server-side/client-side software, and you don’t need to keep something running as a service, as long as you imported the library in Python and start coding, then you have a relational database management system!
When we say “built-in”, it means that you don’t even need to run pip install to acquire the library. Simply import it by:
import sqlite3 as sl
Don’t be bothered with the drivers, connection strings and so on. You can create an SQLite database and have a connection object as simple as:
con = sl.connect('my-test.db')
After we run this line of code, we have created the database and connected it to it already. This is because the database we asked Python to connect to is not existing so that it automatically created an empty one. Otherwise, we can use the same code to connect to an existing database.
Then, let’s create a table.
with con: con.execute(""" CREATE TABLE USER ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER ); """)
In this USER table, we added three columns. As you can see, SQLite is indeed lightweight, but it supports all the basic features a regular RDBMS should have, such as the data type, nullable, primary key and auto-increment.
After running this code, we should have created a table already, although it outputs nothing.
Let’s insert some records into the USER table we just created, which can also prove that we indeed created it.
Suppose we want to insert multiple entries in one go. SQLite in Python can achieve this easily.
sql = 'INSERT INTO USER (id, name, age) values(?, ?, ?)'data = [ (1, 'Alice', 21), (2, 'Bob', 22), (3, 'Chris', 23)]
We need to define the SQL statement with question marks ? as a placeholder. Then, let’s create some sample data to be inserted. With the connection object, we can then insert these sample rows.
with con: con.executemany(sql, data)
It didn’t complain after we’ve run the code, so it was successful.
Now, it’s time to verify everything we have done tangibly. Let’s query the table to get the sample rows back.
with con: data = con.execute("SELECT * FROM USER WHERE age <= 22") for row in data: print(row)
You can see how simple it is.
Also, even though SQLite is light-weighted, but as a widely-used database, most of the SQL clients software support to consume it.
The one I use the most is DBeaver, let’s see how it looks like.
Because I’m using Google Colab, so I’m going to download the my-test.db file to my local machine. In your case, if you run Python on your local machine, you can use your SQL client to connect directly to the databases file.
In DBeaver, create a new connection and select SQLite as DB type.
Then, browse the DB file.
Now, you can run any SQL query on the database. It is nothing different from other regular relational databases.
Do you think that’s all? No. In fact, as a built-in feature of Python, SQLite can seamlessly integrate with Pandas Data Frame.
Let’s define a data frame.
df_skill = pd.DataFrame({ 'user_id': [1,1,2,2,3,3,3], 'skill': ['Network Security', 'Algorithm Development', 'Network Security', 'Java', 'Python', 'Data Science', 'Machine Learning']})
Then, we can simply call to_sql() method of the data frame to save it into the database.
df_skill.to_sql('SKILL', con)
That’s it! We even don’t need to create the table in advance, the column data types and length will be inferred. Of course, you can still define it beforehand if you want to.
Then, let’s say we want to join the table USER and SKILL, and read the result into a Pandas data frame. It’s also seamless.
df = pd.read_sql(''' SELECT s.user_id, u.name, u.age, s.skill FROM USER u LEFT JOIN SKILL s ON u.id = s.user_id''', con)
Super cool! Let’s write the results to a new table called USER_SKILL.
df.to_sql('USER_SKILL', con)
Then, we can also use our SQL client to retrieve the table.
Indeed, there are many surprises hidden in Python. They do not mean to be hidden, but just because there are too many out-of-box features existing in Python for one to discover all of them.
In this article, I have introduced how to use the Python built-in library sqlite3 to create and manipulate tables in an SQLite DB. Of course, it also supports updating and deleting but I think you would try it yourself after this.
Most importantly, we can easily read a table from an SQLite DB into a Pandas data frame, or vice versa. This allows us to even more easily to interact with our light-weight relational database.
You may notice that SQLite doesn’t have authentication, that’s its designed behaviour as everything needs to be lightweight. Go discover more surprising features in Python, enjoy it!
All the code in this article can be found in my Google Colab Notebook.
colab.research.google.com
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
|
[
{
"code": null,
"e": 475,
"s": 172,
"text": "If you are a software developer, I believe you must know or even have used an extremely light-weighted database — SQLite. It has almost all the features you need as a relational database, but everything is saved in a single file. On the official site, here are some scenarios that you could use SQLite."
},
{
"code": null,
"e": 500,
"s": 475,
"text": "Embedded devices and IoT"
},
{
"code": null,
"e": 514,
"s": 500,
"text": "Data Analysis"
},
{
"code": null,
"e": 532,
"s": 514,
"text": "Data Transferring"
},
{
"code": null,
"e": 567,
"s": 532,
"text": "File archive and/or data container"
},
{
"code": null,
"e": 599,
"s": 567,
"text": "Internal or temporary databases"
},
{
"code": null,
"e": 659,
"s": 599,
"text": "Stand-in for an enterprise database during demos or testing"
},
{
"code": null,
"e": 691,
"s": 659,
"text": "Education, training and testing"
},
{
"code": null,
"e": 728,
"s": 691,
"text": "Experimental SQL language extensions"
},
{
"code": null,
"e": 820,
"s": 728,
"text": "There are more reasons that you may want to use SQLite, please check out the documentation."
},
{
"code": null,
"e": 835,
"s": 820,
"text": "www.sqlite.org"
},
{
"code": null,
"e": 1153,
"s": 835,
"text": "Most importantly, SQLite is built-in into a Python library. In other words, you don’t need to install any server-side/client-side software, and you don’t need to keep something running as a service, as long as you imported the library in Python and start coding, then you have a relational database management system!"
},
{
"code": null,
"e": 1275,
"s": 1153,
"text": "When we say “built-in”, it means that you don’t even need to run pip install to acquire the library. Simply import it by:"
},
{
"code": null,
"e": 1296,
"s": 1275,
"text": "import sqlite3 as sl"
},
{
"code": null,
"e": 1439,
"s": 1296,
"text": "Don’t be bothered with the drivers, connection strings and so on. You can create an SQLite database and have a connection object as simple as:"
},
{
"code": null,
"e": 1470,
"s": 1439,
"text": "con = sl.connect('my-test.db')"
},
{
"code": null,
"e": 1757,
"s": 1470,
"text": "After we run this line of code, we have created the database and connected it to it already. This is because the database we asked Python to connect to is not existing so that it automatically created an empty one. Otherwise, we can use the same code to connect to an existing database."
},
{
"code": null,
"e": 1785,
"s": 1757,
"text": "Then, let’s create a table."
},
{
"code": null,
"e": 1962,
"s": 1785,
"text": "with con: con.execute(\"\"\" CREATE TABLE USER ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER ); \"\"\")"
},
{
"code": null,
"e": 2185,
"s": 1962,
"text": "In this USER table, we added three columns. As you can see, SQLite is indeed lightweight, but it supports all the basic features a regular RDBMS should have, such as the data type, nullable, primary key and auto-increment."
},
{
"code": null,
"e": 2279,
"s": 2185,
"text": "After running this code, we should have created a table already, although it outputs nothing."
},
{
"code": null,
"e": 2390,
"s": 2279,
"text": "Let’s insert some records into the USER table we just created, which can also prove that we indeed created it."
},
{
"code": null,
"e": 2486,
"s": 2390,
"text": "Suppose we want to insert multiple entries in one go. SQLite in Python can achieve this easily."
},
{
"code": null,
"e": 2612,
"s": 2486,
"text": "sql = 'INSERT INTO USER (id, name, age) values(?, ?, ?)'data = [ (1, 'Alice', 21), (2, 'Bob', 22), (3, 'Chris', 23)]"
},
{
"code": null,
"e": 2806,
"s": 2612,
"text": "We need to define the SQL statement with question marks ? as a placeholder. Then, let’s create some sample data to be inserted. With the connection object, we can then insert these sample rows."
},
{
"code": null,
"e": 2846,
"s": 2806,
"text": "with con: con.executemany(sql, data)"
},
{
"code": null,
"e": 2913,
"s": 2846,
"text": "It didn’t complain after we’ve run the code, so it was successful."
},
{
"code": null,
"e": 3023,
"s": 2913,
"text": "Now, it’s time to verify everything we have done tangibly. Let’s query the table to get the sample rows back."
},
{
"code": null,
"e": 3131,
"s": 3023,
"text": "with con: data = con.execute(\"SELECT * FROM USER WHERE age <= 22\") for row in data: print(row)"
},
{
"code": null,
"e": 3161,
"s": 3131,
"text": "You can see how simple it is."
},
{
"code": null,
"e": 3292,
"s": 3161,
"text": "Also, even though SQLite is light-weighted, but as a widely-used database, most of the SQL clients software support to consume it."
},
{
"code": null,
"e": 3356,
"s": 3292,
"text": "The one I use the most is DBeaver, let’s see how it looks like."
},
{
"code": null,
"e": 3580,
"s": 3356,
"text": "Because I’m using Google Colab, so I’m going to download the my-test.db file to my local machine. In your case, if you run Python on your local machine, you can use your SQL client to connect directly to the databases file."
},
{
"code": null,
"e": 3646,
"s": 3580,
"text": "In DBeaver, create a new connection and select SQLite as DB type."
},
{
"code": null,
"e": 3672,
"s": 3646,
"text": "Then, browse the DB file."
},
{
"code": null,
"e": 3785,
"s": 3672,
"text": "Now, you can run any SQL query on the database. It is nothing different from other regular relational databases."
},
{
"code": null,
"e": 3912,
"s": 3785,
"text": "Do you think that’s all? No. In fact, as a built-in feature of Python, SQLite can seamlessly integrate with Pandas Data Frame."
},
{
"code": null,
"e": 3939,
"s": 3912,
"text": "Let’s define a data frame."
},
{
"code": null,
"e": 4130,
"s": 3939,
"text": "df_skill = pd.DataFrame({ 'user_id': [1,1,2,2,3,3,3], 'skill': ['Network Security', 'Algorithm Development', 'Network Security', 'Java', 'Python', 'Data Science', 'Machine Learning']})"
},
{
"code": null,
"e": 4219,
"s": 4130,
"text": "Then, we can simply call to_sql() method of the data frame to save it into the database."
},
{
"code": null,
"e": 4249,
"s": 4219,
"text": "df_skill.to_sql('SKILL', con)"
},
{
"code": null,
"e": 4424,
"s": 4249,
"text": "That’s it! We even don’t need to create the table in advance, the column data types and length will be inferred. Of course, you can still define it beforehand if you want to."
},
{
"code": null,
"e": 4548,
"s": 4424,
"text": "Then, let’s say we want to join the table USER and SKILL, and read the result into a Pandas data frame. It’s also seamless."
},
{
"code": null,
"e": 4676,
"s": 4548,
"text": "df = pd.read_sql(''' SELECT s.user_id, u.name, u.age, s.skill FROM USER u LEFT JOIN SKILL s ON u.id = s.user_id''', con)"
},
{
"code": null,
"e": 4746,
"s": 4676,
"text": "Super cool! Let’s write the results to a new table called USER_SKILL."
},
{
"code": null,
"e": 4775,
"s": 4746,
"text": "df.to_sql('USER_SKILL', con)"
},
{
"code": null,
"e": 4835,
"s": 4775,
"text": "Then, we can also use our SQL client to retrieve the table."
},
{
"code": null,
"e": 5025,
"s": 4835,
"text": "Indeed, there are many surprises hidden in Python. They do not mean to be hidden, but just because there are too many out-of-box features existing in Python for one to discover all of them."
},
{
"code": null,
"e": 5256,
"s": 5025,
"text": "In this article, I have introduced how to use the Python built-in library sqlite3 to create and manipulate tables in an SQLite DB. Of course, it also supports updating and deleting but I think you would try it yourself after this."
},
{
"code": null,
"e": 5450,
"s": 5256,
"text": "Most importantly, we can easily read a table from an SQLite DB into a Pandas data frame, or vice versa. This allows us to even more easily to interact with our light-weight relational database."
},
{
"code": null,
"e": 5633,
"s": 5450,
"text": "You may notice that SQLite doesn’t have authentication, that’s its designed behaviour as everything needs to be lightweight. Go discover more surprising features in Python, enjoy it!"
},
{
"code": null,
"e": 5704,
"s": 5633,
"text": "All the code in this article can be found in my Google Colab Notebook."
},
{
"code": null,
"e": 5730,
"s": 5704,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 5741,
"s": 5730,
"text": "medium.com"
}
] |
Mockito - Exception Handling
|
Mockito provides the capability to a mock to throw exceptions, so exception handling can be tested. Take a look at the following code snippet.
//add the behavior to throw exception
doThrow(new Runtime Exception("divide operation not implemented"))
.when(calcService).add(10.0,20.0);
Here we've added an exception clause to a mock object. MathApplication makes use of calcService using its add method and the mock throws a RuntimeException whenever calcService.add() method is invoked.
Step 1 − Create an interface called CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}
Step 2 − Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
return calcService.add(input1, input2);
}
public double subtract(double input1, double input2){
return calcService.subtract(input1, input2);
}
public double multiply(double input1, double input2){
return calcService.multiply(input1, input2);
}
public double divide(double input1, double input2){
return calcService.divide(input1, input2);
}
}
Step 3 − Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito.
File: MathApplicationTester.java
import static org.mockito.Mockito.doThrow;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoRunner.class)
public class MathApplicationTester {
// @TestSubject annotation is used to identify class
which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test(expected = RuntimeException.class)
public void testAdd(){
//add the behavior to throw exception
doThrow(new RuntimeException("Add operation not implemented"))
.when(calcService).add(10.0,20.0);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
}
}
Step 4 − Execute test cases
Create a java class file named TestRunner in C:\> Mockito_WORKSPACE to execute Test case(s).
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5 − Verify the Result
Compile the classes using javac compiler as follows −
C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.
java MathApplicationTester.java TestRunner.java
Now run the Test Runner to see the result −
C:\Mockito_WORKSPACE>java TestRunner
Verify the output.
testAdd(MathApplicationTester): Add operation not implemented
false
31 Lectures
43 mins
Abhinav Manchanda
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2123,
"s": 1980,
"text": "Mockito provides the capability to a mock to throw exceptions, so exception handling can be tested. Take a look at the following code snippet."
},
{
"code": null,
"e": 2267,
"s": 2123,
"text": "//add the behavior to throw exception\ndoThrow(new Runtime Exception(\"divide operation not implemented\"))\n .when(calcService).add(10.0,20.0);\n"
},
{
"code": null,
"e": 2469,
"s": 2267,
"text": "Here we've added an exception clause to a mock object. MathApplication makes use of calcService using its add method and the mock throws a RuntimeException whenever calcService.add() method is invoked."
},
{
"code": null,
"e": 2557,
"s": 2469,
"text": "Step 1 − Create an interface called CalculatorService to provide mathematical functions"
},
{
"code": null,
"e": 2586,
"s": 2557,
"text": "File: CalculatorService.java"
},
{
"code": null,
"e": 2846,
"s": 2586,
"text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}"
},
{
"code": null,
"e": 2904,
"s": 2846,
"text": "Step 2 − Create a JAVA class to represent MathApplication"
},
{
"code": null,
"e": 2931,
"s": 2904,
"text": "File: MathApplication.java"
},
{
"code": null,
"e": 3574,
"s": 2931,
"text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n \n public double add(double input1, double input2){\n return calcService.add(input1, input2);\t\t\n }\n \n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n \n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n \n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}"
},
{
"code": null,
"e": 3614,
"s": 3574,
"text": "Step 3 − Test the MathApplication class"
},
{
"code": null,
"e": 3733,
"s": 3614,
"text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito."
},
{
"code": null,
"e": 3766,
"s": 3733,
"text": "File: MathApplicationTester.java"
},
{
"code": null,
"e": 4774,
"s": 3766,
"text": "import static org.mockito.Mockito.doThrow;\n\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(MockitoRunner.class)\npublic class MathApplicationTester {\n\t\n // @TestSubject annotation is used to identify class \n which is going to use the mock object\n @TestSubject\n MathApplication mathApplication = new MathApplication();\n\n //@Mock annotation is used to create the mock object to be injected\n @Mock\n CalculatorService calcService;\n\n @Test(expected = RuntimeException.class)\n public void testAdd(){\n //add the behavior to throw exception\n doThrow(new RuntimeException(\"Add operation not implemented\"))\n .when(calcService).add(10.0,20.0);\n\n //test the add functionality\n Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); \n }\n}"
},
{
"code": null,
"e": 4802,
"s": 4774,
"text": "Step 4 − Execute test cases"
},
{
"code": null,
"e": 4895,
"s": 4802,
"text": "Create a java class file named TestRunner in C:\\> Mockito_WORKSPACE to execute Test case(s)."
},
{
"code": null,
"e": 4917,
"s": 4895,
"text": "File: TestRunner.java"
},
{
"code": null,
"e": 5358,
"s": 4917,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n \n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n \n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 5385,
"s": 5358,
"text": "Step 5 − Verify the Result"
},
{
"code": null,
"e": 5439,
"s": 5385,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 5558,
"s": 5439,
"text": "C:\\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.\n java MathApplicationTester.java TestRunner.java\n"
},
{
"code": null,
"e": 5602,
"s": 5558,
"text": "Now run the Test Runner to see the result −"
},
{
"code": null,
"e": 5640,
"s": 5602,
"text": "C:\\Mockito_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 5659,
"s": 5640,
"text": "Verify the output."
},
{
"code": null,
"e": 5728,
"s": 5659,
"text": "testAdd(MathApplicationTester): Add operation not implemented\nfalse\n"
},
{
"code": null,
"e": 5760,
"s": 5728,
"text": "\n 31 Lectures \n 43 mins\n"
},
{
"code": null,
"e": 5779,
"s": 5760,
"text": " Abhinav Manchanda"
},
{
"code": null,
"e": 5786,
"s": 5779,
"text": " Print"
},
{
"code": null,
"e": 5797,
"s": 5786,
"text": " Add Notes"
}
] |
Program to add two numbers represented as strings in Python
|
Suppose we have two strings S, and T, these two are representing an integer, we have to add them and find the result in the same string representation.
So, if the input is like "256478921657", "5871257468", then the output will be "262350179125", as 256478921657 + 5871257468 = 262350179125
To solve this, we will follow these steps −
convert S and T from string to integer
ret = S + T
return ret as string
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, a, b):
return str(int(a) + int(b))
ob = Solution() print(ob.solve("256478921657", "5871257468"))
"256478921657", "5871257468"
262350179125
|
[
{
"code": null,
"e": 1214,
"s": 1062,
"text": "Suppose we have two strings S, and T, these two are representing an integer, we have to add them and find the result in the same string representation."
},
{
"code": null,
"e": 1353,
"s": 1214,
"text": "So, if the input is like \"256478921657\", \"5871257468\", then the output will be \"262350179125\", as 256478921657 + 5871257468 = 262350179125"
},
{
"code": null,
"e": 1397,
"s": 1353,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1436,
"s": 1397,
"text": "convert S and T from string to integer"
},
{
"code": null,
"e": 1448,
"s": 1436,
"text": "ret = S + T"
},
{
"code": null,
"e": 1469,
"s": 1448,
"text": "return ret as string"
},
{
"code": null,
"e": 1539,
"s": 1469,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1550,
"s": 1539,
"text": " Live Demo"
},
{
"code": null,
"e": 1688,
"s": 1550,
"text": "class Solution:\n def solve(self, a, b):\n return str(int(a) + int(b))\nob = Solution() print(ob.solve(\"256478921657\", \"5871257468\"))"
},
{
"code": null,
"e": 1717,
"s": 1688,
"text": "\"256478921657\", \"5871257468\""
},
{
"code": null,
"e": 1730,
"s": 1717,
"text": "262350179125"
}
] |
How to Create Simple Visualizations with Google Charts and Pandas Dataframes | by Alan Jones | Towards Data Science
|
Google Charts have been around for more years than I care to remember, so I think we can safely assume that it is a mature and stable technology.
It can also be used to create attractive charts and graphs.
Here, we can see a simple line chart which is interactive to the extent that when you hover over a point on the graph it will show you the detail of that data point.
We are going to look at how to create charts like this using some elementary boilerplate code in HTML and Javascript, Pandas dataframes, and a simple Flask web application. We’ll develop the complete code, below. (At the end of this article I’ll include a link to an app where you can see the code in action and download the code and sample data.)
Here’s an outline of what follows:
writing a basic Flask app (optional)
displaying a chart using boilerplate HTML and Javascript
creating a Pandas dataframe and converting it to a form compatible with Google Charts
Putting the Flask code and the web page together as an app
This is a very brief introduction to creating and running a Flask app. If you already know how to do this then you can safely skip this section.
Flask is a web application micro-framework which means it is a very lightweight library for developing web apps. Creating your first Flask app is easy but first you will need to install it with pip or conda, for example:
pip3 install flask
Next, open a new directory and create a file app.py with the following code:
from flask import Flaskapp = Flask(__name__)@app.route('/')def root(): return 'Hello'
The code is pretty straightforward. The first line imports the Flask library; the second creates a Flask object (that will be run); and the rest of it defines a route. A route is a web page, or endpoint, and the @app.route decorator defines the url, in this case it is the root url (i.e. /). Below this is a function definition that tells the Flask server what to do when this particular endpoint is requested — in this case simply return the string “Hello”.
Now open a terminal window, navigate to the correct directory, and type:
python3 -m flask run
(Note: I’m using Python3 in a standard Linux environment, here, if you are using a different environment where Python3 is the default — portable Python or Conda, for example — then your command may be python not python3.)
This will start the Flask server and the result should be this:
Flask is now running your app and it is available at the url, http://127.0.0.1:5000, so type that into the address bar in a browser and you should see something like this:
We are going to be using templates later to connect the Flask app to a web page but, for now, that’s all we need to know about Flask.
Now we’ll take a look at a template HTML page that can be reused for many different applications. The basic file layout looks like this:
<!DOCTYPE html><html> <head> <script> // Script 1 — where the data gets loaded </script> <! — Script 2 — Load the AJAX API → <script src=”https://www.gstatic.com/charts/loader.js"> </script> <script> // Script 3 — Where we create and display a chart </script> </head> <body> <! — the div where a chart will be displayed → <div style=”width:600px; height:300px” id=”chart1"></div> </body></html>
This is a simple HTML file with a single <div> in the body and 3 scripts in the head.
The <div> is where the chart will be displayed and is given an id — I’ve also given it a height and width. The id is compulsory, the sizing is not — you can mess around with the height and width or leave them out completely as you wish.
The main logic comes in the three scripts. The first one, Script 1, will be where we load the data. For this first example I’ll create the data locally but later we’ll load it from a Pandas dataframe. The second script, Script 2, loads a Google Charts API which will be used by Script 3. And Script 3. itself, does the main work of creating and displaying the chart.
We’ll see how these work in a second but it is worth pointing out that if you want to create your own app, you will only need to change Script 1 and the HTML. So very little Javascript programming is required.
Script 2 is already defined and we don’t need to modify it.
Script 3 is rather longer but, again, once we have defined it we don’t need to change it. Here it is:
<script> // Load the Visualization API and the corechart package google.charts.load(‘current’, {‘packages’:[‘corechart’]}); // Set a callback for when the API is loaded google.charts.setOnLoadCallback(drawChart); // This is the callback function which actually draws the chart function drawChart(){ google.visualization.drawChart({ "containerId": containerId, "dataTable": data, "chartType": chartType, "options": options }); }</script>
What’s happening here is that we are loading the visualization API from Google and then setting a callback function that will be run when the API has finished loading. The call back function is drawChart and does exactly what it says.
drawChart simply calls another function, by the same name, from the Google API and passes a number of parameters that we will define later in Script 1. Let’s go through those parameters.
containerId is the id of the <div> where the chart will be displayed.
data is the actual data to be plotted.
chartType is the type of plot that we want, for example, LineChart, PieChart, ColumnChart.
options can include a number of different options for the chart, for example a title.
We will define these options in Script 1.
In order to get a working web page, first we’ll define the data locally — we’ll import it from a python app later.
You can define the data for Google Charts in a few different ways but the simplest, for our purposes, is a simple table. Here’s a table of the number and make of cars parked in my street:
But we need to format it as a list of rows in a Javascript two-dimensional array. This is pretty much the same as a Python list of lists. It looks like:
[ ["Car","Number"], ["Audi", 3], ["BMW", 2], ["Mercedes", 1], ["Opel", 3], ["Volkswagen", 4]]
The first item in the list is a list of column names and the rest are the rows of data.
Here is a Script 1, that incorporates that data and the options that we saw earlier..
<script> data = [ ["Car","Number"], ["Audi", 3], ["BMW", 2], ["Mercedes", 1], ["Opel", 3], ["Volkswagen", 4] ]; chartType = "ColumnChart"; containerId = "chart1"; options = {"title":"Cars parked in my road"};</script>
The first thing we see is a variable data that contains the car table. Next is the type of chart that we are going to plot and then the id of the <div> that the chart will be drawn in. Finally, we set the options for the chart — here this is just the title but there could be other options depending on the type of chart we want to plot. You will see how the options are used later.
If you put these scripts together with the HTML template above, you will have a working web page. You can open it in your browser and see the resulting graph.
Now here is a neat trick: change the line
chartType = “ColumnChart”;
to
chartType = “PieChart”;
save it and reload the web page and...
That was easy!
OK, but this is just a simple stand-alone demonstration, in reality we want to get our data from elsewhere. And that is where we are going next.
We can see that the format of the data provided in the example was a list of lists. The first element of the list was a list containing the column titles and the remainder contained data that form the rows of a table.
While this is not very different in concept to a Pandas dataframe, we do need to do a little work to convert one to the other.
Let’s first of all write some Python code to load in our data and create a dataframe that represents the data that we want to plot.
If you download the program file you will find in the root directory a file called london2018.csv which we are going to load into a Pandas dataframe like this:
url = ‘london2018.csv’weather = pd.read_csv(url)
The dataframe looks like this:
It’s a record of weather statistics in London for the year 2018 (derived from the UK Met Office data). Tmax and Tmin are the maximum and minimum temperatures for each month in 2018, Rain is the total rainfall in millimetres, and Sun is the total number of hours of sunshine.
We are going to produce a temperature chart we only need Tmax and Tmin and the Month columns, so we create a new dataframe of the data that we need like this:
title = “Monthly Max and Min Temperature”temps = weather[[‘Month’,’Tmax’,’Tmin’]]temps[‘Month’] = temps[‘Month’].astype(str)
Notice that I’ve also converted the Month column to a string because it doesn’t make much sense for it to be treated as a number and I’ve also created a title for the chart.
So now we have the data we want; we just need to convert it into the shape that Google charts will deal with. We do this by extracting the values from the chart and convert them to a list. This will give us the values as a list of lists, exactly what we need for the chart. One problem: the column names are not included. That’s easily solved, we extract the column names and then append the resulting list to the top of the values list.
d = temps.values.tolist()c = temps.columns.tolist()d.insert(0,c)
Now we bundle the data and the title into a JSON string that we can pass to the web page.
tempdata = json.dumps({'title':title,'data':d})
We pass the data to the web page using a template mechanism that is built into Flask. Like this:
return render_template('weather.html', tempdata=tempdata)
The render_template function finds the template weather.html and creates a web page by inserting the data passed to it into the template.
So now we need to modify our html file to make it into a template. That means changing Script 1 into some that will load the JSON data into Javascript variables by putting named placeholders where the data being passed in will go. (A palace holder is a pair of double curly braces with a name inside.)
In our case there is only one data item called tempdata. So we replace the code in Script 1 with this:
<script> tdata = JSON.parse({{tempdata|tojson|safe}}); tempdata = tdata.data; temptitle = tdata.title; chartType = "LineChart"; containerId = "chart1"; options = {"title":temptitle};</script>
The name is enclosed in double curly braces, {{name}}, and here we are also saying that the data should be converted to json and that it contains ‘safe’ HTML, that is to say, we don’t want any of the special characters converted into escape sequences.
Having got the data into the template we assign it to the variable tdata and from that set variables for the data and the title.
So we end up with two the two files that you can see in Listings 1 and 2.
Now this bit is important: first, we call the Flask app app.py, second, the Flask app expects the HTML file to be called weather.html (as we see in the listing), so make sure you give it that name. Lastly, Flask expects it’s templates to be a directory called templates which is in the same directory as the Flask app.
And when you run the flask app, you’ll get the following page.
There is a great deal more to Google Charts than this but I hope this has been a useful introduction to generating them with a Python app. Thanks for reading.
Download the zip file here and see the basic app here.
When you have downloaded the files, unzip them into an empty folder and run the Flask app with python -m flask run (as above).
I may take this code further and/or write more articles on this topic. If you would like to be kept up-to-date with new articles, please consider subscribing to my occasional free newsletter here.
|
[
{
"code": null,
"e": 318,
"s": 172,
"text": "Google Charts have been around for more years than I care to remember, so I think we can safely assume that it is a mature and stable technology."
},
{
"code": null,
"e": 378,
"s": 318,
"text": "It can also be used to create attractive charts and graphs."
},
{
"code": null,
"e": 544,
"s": 378,
"text": "Here, we can see a simple line chart which is interactive to the extent that when you hover over a point on the graph it will show you the detail of that data point."
},
{
"code": null,
"e": 892,
"s": 544,
"text": "We are going to look at how to create charts like this using some elementary boilerplate code in HTML and Javascript, Pandas dataframes, and a simple Flask web application. We’ll develop the complete code, below. (At the end of this article I’ll include a link to an app where you can see the code in action and download the code and sample data.)"
},
{
"code": null,
"e": 927,
"s": 892,
"text": "Here’s an outline of what follows:"
},
{
"code": null,
"e": 964,
"s": 927,
"text": "writing a basic Flask app (optional)"
},
{
"code": null,
"e": 1021,
"s": 964,
"text": "displaying a chart using boilerplate HTML and Javascript"
},
{
"code": null,
"e": 1107,
"s": 1021,
"text": "creating a Pandas dataframe and converting it to a form compatible with Google Charts"
},
{
"code": null,
"e": 1166,
"s": 1107,
"text": "Putting the Flask code and the web page together as an app"
},
{
"code": null,
"e": 1311,
"s": 1166,
"text": "This is a very brief introduction to creating and running a Flask app. If you already know how to do this then you can safely skip this section."
},
{
"code": null,
"e": 1532,
"s": 1311,
"text": "Flask is a web application micro-framework which means it is a very lightweight library for developing web apps. Creating your first Flask app is easy but first you will need to install it with pip or conda, for example:"
},
{
"code": null,
"e": 1551,
"s": 1532,
"text": "pip3 install flask"
},
{
"code": null,
"e": 1628,
"s": 1551,
"text": "Next, open a new directory and create a file app.py with the following code:"
},
{
"code": null,
"e": 1716,
"s": 1628,
"text": "from flask import Flaskapp = Flask(__name__)@app.route('/')def root(): return 'Hello'"
},
{
"code": null,
"e": 2175,
"s": 1716,
"text": "The code is pretty straightforward. The first line imports the Flask library; the second creates a Flask object (that will be run); and the rest of it defines a route. A route is a web page, or endpoint, and the @app.route decorator defines the url, in this case it is the root url (i.e. /). Below this is a function definition that tells the Flask server what to do when this particular endpoint is requested — in this case simply return the string “Hello”."
},
{
"code": null,
"e": 2248,
"s": 2175,
"text": "Now open a terminal window, navigate to the correct directory, and type:"
},
{
"code": null,
"e": 2269,
"s": 2248,
"text": "python3 -m flask run"
},
{
"code": null,
"e": 2491,
"s": 2269,
"text": "(Note: I’m using Python3 in a standard Linux environment, here, if you are using a different environment where Python3 is the default — portable Python or Conda, for example — then your command may be python not python3.)"
},
{
"code": null,
"e": 2555,
"s": 2491,
"text": "This will start the Flask server and the result should be this:"
},
{
"code": null,
"e": 2727,
"s": 2555,
"text": "Flask is now running your app and it is available at the url, http://127.0.0.1:5000, so type that into the address bar in a browser and you should see something like this:"
},
{
"code": null,
"e": 2861,
"s": 2727,
"text": "We are going to be using templates later to connect the Flask app to a web page but, for now, that’s all we need to know about Flask."
},
{
"code": null,
"e": 2998,
"s": 2861,
"text": "Now we’ll take a look at a template HTML page that can be reused for many different applications. The basic file layout looks like this:"
},
{
"code": null,
"e": 3437,
"s": 2998,
"text": "<!DOCTYPE html><html> <head> <script> // Script 1 — where the data gets loaded </script> <! — Script 2 — Load the AJAX API → <script src=”https://www.gstatic.com/charts/loader.js\"> </script> <script> // Script 3 — Where we create and display a chart </script> </head> <body> <! — the div where a chart will be displayed → <div style=”width:600px; height:300px” id=”chart1\"></div> </body></html>"
},
{
"code": null,
"e": 3523,
"s": 3437,
"text": "This is a simple HTML file with a single <div> in the body and 3 scripts in the head."
},
{
"code": null,
"e": 3760,
"s": 3523,
"text": "The <div> is where the chart will be displayed and is given an id — I’ve also given it a height and width. The id is compulsory, the sizing is not — you can mess around with the height and width or leave them out completely as you wish."
},
{
"code": null,
"e": 4127,
"s": 3760,
"text": "The main logic comes in the three scripts. The first one, Script 1, will be where we load the data. For this first example I’ll create the data locally but later we’ll load it from a Pandas dataframe. The second script, Script 2, loads a Google Charts API which will be used by Script 3. And Script 3. itself, does the main work of creating and displaying the chart."
},
{
"code": null,
"e": 4337,
"s": 4127,
"text": "We’ll see how these work in a second but it is worth pointing out that if you want to create your own app, you will only need to change Script 1 and the HTML. So very little Javascript programming is required."
},
{
"code": null,
"e": 4397,
"s": 4337,
"text": "Script 2 is already defined and we don’t need to modify it."
},
{
"code": null,
"e": 4499,
"s": 4397,
"text": "Script 3 is rather longer but, again, once we have defined it we don’t need to change it. Here it is:"
},
{
"code": null,
"e": 4971,
"s": 4499,
"text": "<script> // Load the Visualization API and the corechart package google.charts.load(‘current’, {‘packages’:[‘corechart’]}); // Set a callback for when the API is loaded google.charts.setOnLoadCallback(drawChart); // This is the callback function which actually draws the chart function drawChart(){ google.visualization.drawChart({ \"containerId\": containerId, \"dataTable\": data, \"chartType\": chartType, \"options\": options }); }</script>"
},
{
"code": null,
"e": 5206,
"s": 4971,
"text": "What’s happening here is that we are loading the visualization API from Google and then setting a callback function that will be run when the API has finished loading. The call back function is drawChart and does exactly what it says."
},
{
"code": null,
"e": 5393,
"s": 5206,
"text": "drawChart simply calls another function, by the same name, from the Google API and passes a number of parameters that we will define later in Script 1. Let’s go through those parameters."
},
{
"code": null,
"e": 5463,
"s": 5393,
"text": "containerId is the id of the <div> where the chart will be displayed."
},
{
"code": null,
"e": 5502,
"s": 5463,
"text": "data is the actual data to be plotted."
},
{
"code": null,
"e": 5593,
"s": 5502,
"text": "chartType is the type of plot that we want, for example, LineChart, PieChart, ColumnChart."
},
{
"code": null,
"e": 5679,
"s": 5593,
"text": "options can include a number of different options for the chart, for example a title."
},
{
"code": null,
"e": 5721,
"s": 5679,
"text": "We will define these options in Script 1."
},
{
"code": null,
"e": 5836,
"s": 5721,
"text": "In order to get a working web page, first we’ll define the data locally — we’ll import it from a python app later."
},
{
"code": null,
"e": 6024,
"s": 5836,
"text": "You can define the data for Google Charts in a few different ways but the simplest, for our purposes, is a simple table. Here’s a table of the number and make of cars parked in my street:"
},
{
"code": null,
"e": 6177,
"s": 6024,
"text": "But we need to format it as a list of rows in a Javascript two-dimensional array. This is pretty much the same as a Python list of lists. It looks like:"
},
{
"code": null,
"e": 6277,
"s": 6177,
"text": "[ [\"Car\",\"Number\"], [\"Audi\", 3], [\"BMW\", 2], [\"Mercedes\", 1], [\"Opel\", 3], [\"Volkswagen\", 4]]"
},
{
"code": null,
"e": 6365,
"s": 6277,
"text": "The first item in the list is a list of column names and the rest are the rows of data."
},
{
"code": null,
"e": 6451,
"s": 6365,
"text": "Here is a Script 1, that incorporates that data and the options that we saw earlier.."
},
{
"code": null,
"e": 6692,
"s": 6451,
"text": "<script> data = [ [\"Car\",\"Number\"], [\"Audi\", 3], [\"BMW\", 2], [\"Mercedes\", 1], [\"Opel\", 3], [\"Volkswagen\", 4] ]; chartType = \"ColumnChart\"; containerId = \"chart1\"; options = {\"title\":\"Cars parked in my road\"};</script>"
},
{
"code": null,
"e": 7075,
"s": 6692,
"text": "The first thing we see is a variable data that contains the car table. Next is the type of chart that we are going to plot and then the id of the <div> that the chart will be drawn in. Finally, we set the options for the chart — here this is just the title but there could be other options depending on the type of chart we want to plot. You will see how the options are used later."
},
{
"code": null,
"e": 7234,
"s": 7075,
"text": "If you put these scripts together with the HTML template above, you will have a working web page. You can open it in your browser and see the resulting graph."
},
{
"code": null,
"e": 7276,
"s": 7234,
"text": "Now here is a neat trick: change the line"
},
{
"code": null,
"e": 7303,
"s": 7276,
"text": "chartType = “ColumnChart”;"
},
{
"code": null,
"e": 7306,
"s": 7303,
"text": "to"
},
{
"code": null,
"e": 7330,
"s": 7306,
"text": "chartType = “PieChart”;"
},
{
"code": null,
"e": 7369,
"s": 7330,
"text": "save it and reload the web page and..."
},
{
"code": null,
"e": 7384,
"s": 7369,
"text": "That was easy!"
},
{
"code": null,
"e": 7529,
"s": 7384,
"text": "OK, but this is just a simple stand-alone demonstration, in reality we want to get our data from elsewhere. And that is where we are going next."
},
{
"code": null,
"e": 7747,
"s": 7529,
"text": "We can see that the format of the data provided in the example was a list of lists. The first element of the list was a list containing the column titles and the remainder contained data that form the rows of a table."
},
{
"code": null,
"e": 7874,
"s": 7747,
"text": "While this is not very different in concept to a Pandas dataframe, we do need to do a little work to convert one to the other."
},
{
"code": null,
"e": 8006,
"s": 7874,
"text": "Let’s first of all write some Python code to load in our data and create a dataframe that represents the data that we want to plot."
},
{
"code": null,
"e": 8166,
"s": 8006,
"text": "If you download the program file you will find in the root directory a file called london2018.csv which we are going to load into a Pandas dataframe like this:"
},
{
"code": null,
"e": 8215,
"s": 8166,
"text": "url = ‘london2018.csv’weather = pd.read_csv(url)"
},
{
"code": null,
"e": 8246,
"s": 8215,
"text": "The dataframe looks like this:"
},
{
"code": null,
"e": 8521,
"s": 8246,
"text": "It’s a record of weather statistics in London for the year 2018 (derived from the UK Met Office data). Tmax and Tmin are the maximum and minimum temperatures for each month in 2018, Rain is the total rainfall in millimetres, and Sun is the total number of hours of sunshine."
},
{
"code": null,
"e": 8680,
"s": 8521,
"text": "We are going to produce a temperature chart we only need Tmax and Tmin and the Month columns, so we create a new dataframe of the data that we need like this:"
},
{
"code": null,
"e": 8805,
"s": 8680,
"text": "title = “Monthly Max and Min Temperature”temps = weather[[‘Month’,’Tmax’,’Tmin’]]temps[‘Month’] = temps[‘Month’].astype(str)"
},
{
"code": null,
"e": 8979,
"s": 8805,
"text": "Notice that I’ve also converted the Month column to a string because it doesn’t make much sense for it to be treated as a number and I’ve also created a title for the chart."
},
{
"code": null,
"e": 9417,
"s": 8979,
"text": "So now we have the data we want; we just need to convert it into the shape that Google charts will deal with. We do this by extracting the values from the chart and convert them to a list. This will give us the values as a list of lists, exactly what we need for the chart. One problem: the column names are not included. That’s easily solved, we extract the column names and then append the resulting list to the top of the values list."
},
{
"code": null,
"e": 9482,
"s": 9417,
"text": "d = temps.values.tolist()c = temps.columns.tolist()d.insert(0,c)"
},
{
"code": null,
"e": 9572,
"s": 9482,
"text": "Now we bundle the data and the title into a JSON string that we can pass to the web page."
},
{
"code": null,
"e": 9620,
"s": 9572,
"text": "tempdata = json.dumps({'title':title,'data':d})"
},
{
"code": null,
"e": 9717,
"s": 9620,
"text": "We pass the data to the web page using a template mechanism that is built into Flask. Like this:"
},
{
"code": null,
"e": 9775,
"s": 9717,
"text": "return render_template('weather.html', tempdata=tempdata)"
},
{
"code": null,
"e": 9913,
"s": 9775,
"text": "The render_template function finds the template weather.html and creates a web page by inserting the data passed to it into the template."
},
{
"code": null,
"e": 10215,
"s": 9913,
"text": "So now we need to modify our html file to make it into a template. That means changing Script 1 into some that will load the JSON data into Javascript variables by putting named placeholders where the data being passed in will go. (A palace holder is a pair of double curly braces with a name inside.)"
},
{
"code": null,
"e": 10318,
"s": 10215,
"text": "In our case there is only one data item called tempdata. So we replace the code in Script 1 with this:"
},
{
"code": null,
"e": 10516,
"s": 10318,
"text": "<script> tdata = JSON.parse({{tempdata|tojson|safe}}); tempdata = tdata.data; temptitle = tdata.title; chartType = \"LineChart\"; containerId = \"chart1\"; options = {\"title\":temptitle};</script>"
},
{
"code": null,
"e": 10768,
"s": 10516,
"text": "The name is enclosed in double curly braces, {{name}}, and here we are also saying that the data should be converted to json and that it contains ‘safe’ HTML, that is to say, we don’t want any of the special characters converted into escape sequences."
},
{
"code": null,
"e": 10897,
"s": 10768,
"text": "Having got the data into the template we assign it to the variable tdata and from that set variables for the data and the title."
},
{
"code": null,
"e": 10971,
"s": 10897,
"text": "So we end up with two the two files that you can see in Listings 1 and 2."
},
{
"code": null,
"e": 11290,
"s": 10971,
"text": "Now this bit is important: first, we call the Flask app app.py, second, the Flask app expects the HTML file to be called weather.html (as we see in the listing), so make sure you give it that name. Lastly, Flask expects it’s templates to be a directory called templates which is in the same directory as the Flask app."
},
{
"code": null,
"e": 11353,
"s": 11290,
"text": "And when you run the flask app, you’ll get the following page."
},
{
"code": null,
"e": 11512,
"s": 11353,
"text": "There is a great deal more to Google Charts than this but I hope this has been a useful introduction to generating them with a Python app. Thanks for reading."
},
{
"code": null,
"e": 11567,
"s": 11512,
"text": "Download the zip file here and see the basic app here."
},
{
"code": null,
"e": 11694,
"s": 11567,
"text": "When you have downloaded the files, unzip them into an empty folder and run the Flask app with python -m flask run (as above)."
}
] |
Deploying a Simple Machine Learning Model into a WebApp using TensorFlow.js | by Carlos Aguayo | Towards Data Science
|
Go ahead and try it in your browser or phone:
https://carlos-aguayo.github.io/tfjs.html
The beauty in TensorFlow.js is that you can train a Machine Learning Model in Python using Keras or Tensorflow and deploy it on a browser using TensorFlow.js. No need for an external service to run your queries.
This fun and simple app lets you draw a single-digit number, and it recognizes it using simple machine learning tools.
Here’s the complete code if you want to jump straight at it:
Google Colab Notebook to generate the Machine Learning Model
HTML file
Let’s get started; these are the ingredients and steps needed to build this demo.
Ingredients and steps:
Training Data
Training Environment
Pre-processing Data
Machine Learning
Convert a Keras model to Tensorflow.js
HTML5 Canvas
Hooking everything up
Any Machine Learning model needs quality data. We are going to use the MNIST dataset, which is a dataset of handwritten digits.
In this dataset, you have 60,000 images, all of them are of size 28 x 28 pixels in grayscale, with pixel values from 0 to 255.
See the snippet below for loading and viewing the MNIST dataset.
%tensorflow_version 2.x
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print ("X_train.shape: {}".format(X_train.shape))
print ("y_train.shape: {}".format(y_train.shape))
print ("X_test.shape: {}".format(X_test.shape))
print ("y_test.shape: {}".format(y_test.shape))
X_train.shape: (60000, 28, 28)
y_train.shape: (60000,)
X_test.shape: (10000, 28, 28)
y_test.shape: (10000,)
plt.subplot(161)
plt.imshow(X_train[3], cmap=plt.get_cmap('gray'))
plt.subplot(162)
plt.imshow(X_train[5], cmap=plt.get_cmap('gray'))
plt.subplot(163)
plt.imshow(X_train[7], cmap=plt.get_cmap('gray'))
plt.subplot(164)
plt.imshow(X_train[2], cmap=plt.get_cmap('gray'))
plt.subplot(165)
plt.imshow(X_train[0], cmap=plt.get_cmap('gray'))
plt.subplot(166)
plt.imshow(X_train[13], cmap=plt.get_cmap('gray'))
plt.show()
Google Colab allows you to write and execute Python in your browser.
Colab is a very convenient Jupyter Notebook Python Platform pre-loaded with most of the Python Machine Learning libraries that you need, making it a no-hassle approach to get you quickly up and running with an ML project.
Plus, it gives you free access to GPU/CPU.
There’s a small preprocessing that needs to happen in the data from MNIST:
Normalize inputs: The data comes with values from 0 to 255, we should normalize them to a scale from 0 to 1.One-Hot Encode the outputs.
Normalize inputs: The data comes with values from 0 to 255, we should normalize them to a scale from 0 to 1.
One-Hot Encode the outputs.
# Normalize Inputs from 0–255 to 0–1x_train = x_train / 255x_test = x_test / 255# One-Hot Encode outputsy_train = np_utils.to_categorical(y_train)y_test = np_utils.to_categorical(y_test)num_classes = 10
We are finally ready to do some Machine Learning. We can start with a very simple model. We will use a simple Neural Network with just one Hidden layer. This simple model is enough to get a 98% accuracy.
x_train_simple = x_train.reshape(60000, 28 * 28).astype(‘float32’)x_test_simple = x_test.reshape(10000, 28 * 28).astype(‘float32’)model = Sequential()model.add(Dense(28 * 28, input_dim=28 * 28, activation=’relu’))model.add(Dense(num_classes, activation=’softmax’))model.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])model.fit(x_train_simple, y_train, validation_data=(x_test_simple, y_test), epochs=30, batch_size=200, verbose=2)
If you want to be fancy, you can try a Deep Learning Model. With it, you can improve the accuracy to 99%.
x_train_deep_model = x_train.reshape((60000, 28, 28, 1)).astype(‘float32’)x_test_deep_model = x_test.reshape((10000, 28, 28, 1)).astype(‘float32’)deep_model = Sequential()deep_model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation=’relu’))deep_model.add(MaxPooling2D())deep_model.add(Conv2D(15, (3, 3), activation=’relu’))deep_model.add(MaxPooling2D())deep_model.add(Dropout(0.2))deep_model.add(Flatten())deep_model.add(Dense(128, activation=’relu’))deep_model.add(Dense(50, activation=’relu’))deep_model.add(Dense(num_classes, activation=’softmax’))deep_model.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])deep_model.fit(x_train_deep_model, y_train, validation_data=(x_test_deep_model, y_test), epochs=30, batch_size=200, verbose=2)
Now that we have a trained model, we need to convert it so that we can use it with TensorFlow.js.
First, we need to save the model into an HDF5 model.
model.save(“model.h5”)
Afterward, you can access the files saved by clicking on the folder icon in the left nav.
There are a few ways to convert the model. A simple one within a Notebook is like this:
!pip install tensorflowjs!tensorflowjs_converter --input_format keras ‘/content/model.h5’ ‘/content/model’
/content/model.h5 is the input and the output is saved into /content/model folder.
TensorFlow.js needs to be pointed at the JSON file (model.json) and expects a sibling file called “group1-shard1of1.bin”. You need these two files. Download both files.
Let’s have a simple HTML page that uses the HTML5 Canvas component that lets us draw on it. Let’s call this file “tfjs.html”.
The core drawing code comes from this website:
Using the HTML5 Canvas component, we can hook mouse events to draw into the Canvas.
canvas.addEventListener('mousedown', function(e) { context.moveTo(mouse.x, mouse.y); context.beginPath(); canvas.addEventListener('mousemove', onPaint, false);}, false);var onPaint = function() { context.lineTo(mouse.x, mouse.y); context.stroke();};
Then we add touch events so that it works on mobile.
Add the touch action to disable scrolling. The code for that is inspired by this site.
Once we can draw, let’s fetch the image upon mouse up. We will scale it down to 28 by 28 pixels so that it matches the trained model.
canvas.addEventListener('mouseup', function() { $('#number').html('<img id="spinner" src="spinner.gif"/>'); canvas.removeEventListener('mousemove', onPaint, false); var img = new Image(); img.onload = function() { context.drawImage(img, 0, 0, 28, 28); data = context.getImageData(0, 0, 28, 28).data; var input = []; for(var i = 0; i < data.length; i += 4) { input.push(data[i + 2] / 255); } predict(input); }; img.src = canvas.toDataURL('image/png');}, false);
We then get the data, keep it into an “input” array and pass it to a predict function that we will define later.
canvas.addEventListener('mouseup', function() { $('#number').html('<img id="spinner" src="spinner.gif"/>'); canvas.removeEventListener('mousemove', onPaint, false); var img = new Image(); img.onload = function() { context.drawImage(img, 0, 0, 28, 28); data = context.getImageData(0, 0, 28, 28).data; var input = []; for(var i = 0; i < data.length; i += 4) { input.push(data[i + 2] / 255); } predict(input); }; img.src = canvas.toDataURL('image/png');}, false);
data is a 1D array with values RGBA values. Our model only takes 0 to 1 values (or 0 from 255 thinking in grayscale). Given that we are drawing Blue into the canvas, we can slice the array in chunks of four and take every second element.
RGBARGBARG...0123456789...
Finally, let’s load TensorFlow.js and run predictions.
<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.5.2/dist/tf.min.js"></script>
You should have downloaded the files model.json and group1-shard1of1.bin and save them into a folder called model in the same folder where you have your HTML file.
Once loaded, we can load the trained model by simply doing:
tf.loadLayersModel(‘model/model.json’).then(function(model) { window.model = model;});
And upon mouseup, once we have the data, we can just feed it into the model:
window.model.predict([tf.tensor(input).reshape([1, 28, 28, 1])]).array().then(function(scores){ scores = scores[0]; predicted = scores.indexOf(Math.max(...scores)); $('#number').html(predicted);});
It’s straightforward to test things locally, and you can easily set up an HTTP server for testing with Python:
python3 -m http.server 8080
If then you want to test things using your phone, you can take advantage of this nifty tool called ngrok.
$ ngrok http 8080
That opens a tunnel to a URL that you can access from through phone.
Once you are happy with the result, you can deploy your HTML into a web hosting site. A simple place is Github. If you have never created a static website with Github, you need to create a repository named “{username}.github.io”. For example, my repository is:
https://github.com/carlos-aguayo/carlos-aguayo.github.io
And then you can access it via:
https://carlos-aguayo.github.io/tfjs.html
Notice how easily we can train a model in Google Colab, export the trained model, and query it within JavaScript without ever leaving the browser!
I’m Director of Software Development and Machine Learning Engineer at Appian. I’ve worked at Appian for the last 15 years, and I keep having a blast. Send me a message if you would like to know how we craft software, please our customers and have fun!
|
[
{
"code": null,
"e": 218,
"s": 172,
"text": "Go ahead and try it in your browser or phone:"
},
{
"code": null,
"e": 260,
"s": 218,
"text": "https://carlos-aguayo.github.io/tfjs.html"
},
{
"code": null,
"e": 472,
"s": 260,
"text": "The beauty in TensorFlow.js is that you can train a Machine Learning Model in Python using Keras or Tensorflow and deploy it on a browser using TensorFlow.js. No need for an external service to run your queries."
},
{
"code": null,
"e": 591,
"s": 472,
"text": "This fun and simple app lets you draw a single-digit number, and it recognizes it using simple machine learning tools."
},
{
"code": null,
"e": 652,
"s": 591,
"text": "Here’s the complete code if you want to jump straight at it:"
},
{
"code": null,
"e": 713,
"s": 652,
"text": "Google Colab Notebook to generate the Machine Learning Model"
},
{
"code": null,
"e": 723,
"s": 713,
"text": "HTML file"
},
{
"code": null,
"e": 805,
"s": 723,
"text": "Let’s get started; these are the ingredients and steps needed to build this demo."
},
{
"code": null,
"e": 828,
"s": 805,
"text": "Ingredients and steps:"
},
{
"code": null,
"e": 842,
"s": 828,
"text": "Training Data"
},
{
"code": null,
"e": 863,
"s": 842,
"text": "Training Environment"
},
{
"code": null,
"e": 883,
"s": 863,
"text": "Pre-processing Data"
},
{
"code": null,
"e": 900,
"s": 883,
"text": "Machine Learning"
},
{
"code": null,
"e": 939,
"s": 900,
"text": "Convert a Keras model to Tensorflow.js"
},
{
"code": null,
"e": 952,
"s": 939,
"text": "HTML5 Canvas"
},
{
"code": null,
"e": 974,
"s": 952,
"text": "Hooking everything up"
},
{
"code": null,
"e": 1102,
"s": 974,
"text": "Any Machine Learning model needs quality data. We are going to use the MNIST dataset, which is a dataset of handwritten digits."
},
{
"code": null,
"e": 1229,
"s": 1102,
"text": "In this dataset, you have 60,000 images, all of them are of size 28 x 28 pixels in grayscale, with pixel values from 0 to 255."
},
{
"code": null,
"e": 1294,
"s": 1229,
"text": "See the snippet below for loading and viewing the MNIST dataset."
},
{
"code": null,
"e": 1395,
"s": 1294,
"text": "%tensorflow_version 2.x\nfrom tensorflow.keras.datasets import mnist\nimport matplotlib.pyplot as plt\n"
},
{
"code": null,
"e": 1649,
"s": 1395,
"text": "(X_train, y_train), (X_test, y_test) = mnist.load_data()\nprint (\"X_train.shape: {}\".format(X_train.shape))\nprint (\"y_train.shape: {}\".format(y_train.shape))\nprint (\"X_test.shape: {}\".format(X_test.shape))\nprint (\"y_test.shape: {}\".format(y_test.shape))\n"
},
{
"code": null,
"e": 1758,
"s": 1649,
"text": "X_train.shape: (60000, 28, 28)\ny_train.shape: (60000,)\nX_test.shape: (10000, 28, 28)\ny_test.shape: (10000,)\n"
},
{
"code": null,
"e": 2174,
"s": 1758,
"text": "plt.subplot(161)\nplt.imshow(X_train[3], cmap=plt.get_cmap('gray'))\nplt.subplot(162)\nplt.imshow(X_train[5], cmap=plt.get_cmap('gray'))\nplt.subplot(163)\nplt.imshow(X_train[7], cmap=plt.get_cmap('gray'))\nplt.subplot(164)\nplt.imshow(X_train[2], cmap=plt.get_cmap('gray'))\nplt.subplot(165)\nplt.imshow(X_train[0], cmap=plt.get_cmap('gray'))\nplt.subplot(166)\nplt.imshow(X_train[13], cmap=plt.get_cmap('gray'))\n\nplt.show()\n"
},
{
"code": null,
"e": 2243,
"s": 2174,
"text": "Google Colab allows you to write and execute Python in your browser."
},
{
"code": null,
"e": 2465,
"s": 2243,
"text": "Colab is a very convenient Jupyter Notebook Python Platform pre-loaded with most of the Python Machine Learning libraries that you need, making it a no-hassle approach to get you quickly up and running with an ML project."
},
{
"code": null,
"e": 2508,
"s": 2465,
"text": "Plus, it gives you free access to GPU/CPU."
},
{
"code": null,
"e": 2583,
"s": 2508,
"text": "There’s a small preprocessing that needs to happen in the data from MNIST:"
},
{
"code": null,
"e": 2719,
"s": 2583,
"text": "Normalize inputs: The data comes with values from 0 to 255, we should normalize them to a scale from 0 to 1.One-Hot Encode the outputs."
},
{
"code": null,
"e": 2828,
"s": 2719,
"text": "Normalize inputs: The data comes with values from 0 to 255, we should normalize them to a scale from 0 to 1."
},
{
"code": null,
"e": 2856,
"s": 2828,
"text": "One-Hot Encode the outputs."
},
{
"code": null,
"e": 3059,
"s": 2856,
"text": "# Normalize Inputs from 0–255 to 0–1x_train = x_train / 255x_test = x_test / 255# One-Hot Encode outputsy_train = np_utils.to_categorical(y_train)y_test = np_utils.to_categorical(y_test)num_classes = 10"
},
{
"code": null,
"e": 3263,
"s": 3059,
"text": "We are finally ready to do some Machine Learning. We can start with a very simple model. We will use a simple Neural Network with just one Hidden layer. This simple model is enough to get a 98% accuracy."
},
{
"code": null,
"e": 3727,
"s": 3263,
"text": "x_train_simple = x_train.reshape(60000, 28 * 28).astype(‘float32’)x_test_simple = x_test.reshape(10000, 28 * 28).astype(‘float32’)model = Sequential()model.add(Dense(28 * 28, input_dim=28 * 28, activation=’relu’))model.add(Dense(num_classes, activation=’softmax’))model.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])model.fit(x_train_simple, y_train, validation_data=(x_test_simple, y_test), epochs=30, batch_size=200, verbose=2)"
},
{
"code": null,
"e": 3833,
"s": 3727,
"text": "If you want to be fancy, you can try a Deep Learning Model. With it, you can improve the accuracy to 99%."
},
{
"code": null,
"e": 4611,
"s": 3833,
"text": "x_train_deep_model = x_train.reshape((60000, 28, 28, 1)).astype(‘float32’)x_test_deep_model = x_test.reshape((10000, 28, 28, 1)).astype(‘float32’)deep_model = Sequential()deep_model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation=’relu’))deep_model.add(MaxPooling2D())deep_model.add(Conv2D(15, (3, 3), activation=’relu’))deep_model.add(MaxPooling2D())deep_model.add(Dropout(0.2))deep_model.add(Flatten())deep_model.add(Dense(128, activation=’relu’))deep_model.add(Dense(50, activation=’relu’))deep_model.add(Dense(num_classes, activation=’softmax’))deep_model.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])deep_model.fit(x_train_deep_model, y_train, validation_data=(x_test_deep_model, y_test), epochs=30, batch_size=200, verbose=2)"
},
{
"code": null,
"e": 4709,
"s": 4611,
"text": "Now that we have a trained model, we need to convert it so that we can use it with TensorFlow.js."
},
{
"code": null,
"e": 4762,
"s": 4709,
"text": "First, we need to save the model into an HDF5 model."
},
{
"code": null,
"e": 4785,
"s": 4762,
"text": "model.save(“model.h5”)"
},
{
"code": null,
"e": 4875,
"s": 4785,
"text": "Afterward, you can access the files saved by clicking on the folder icon in the left nav."
},
{
"code": null,
"e": 4963,
"s": 4875,
"text": "There are a few ways to convert the model. A simple one within a Notebook is like this:"
},
{
"code": null,
"e": 5070,
"s": 4963,
"text": "!pip install tensorflowjs!tensorflowjs_converter --input_format keras ‘/content/model.h5’ ‘/content/model’"
},
{
"code": null,
"e": 5153,
"s": 5070,
"text": "/content/model.h5 is the input and the output is saved into /content/model folder."
},
{
"code": null,
"e": 5322,
"s": 5153,
"text": "TensorFlow.js needs to be pointed at the JSON file (model.json) and expects a sibling file called “group1-shard1of1.bin”. You need these two files. Download both files."
},
{
"code": null,
"e": 5448,
"s": 5322,
"text": "Let’s have a simple HTML page that uses the HTML5 Canvas component that lets us draw on it. Let’s call this file “tfjs.html”."
},
{
"code": null,
"e": 5495,
"s": 5448,
"text": "The core drawing code comes from this website:"
},
{
"code": null,
"e": 5579,
"s": 5495,
"text": "Using the HTML5 Canvas component, we can hook mouse events to draw into the Canvas."
},
{
"code": null,
"e": 5834,
"s": 5579,
"text": "canvas.addEventListener('mousedown', function(e) { context.moveTo(mouse.x, mouse.y); context.beginPath(); canvas.addEventListener('mousemove', onPaint, false);}, false);var onPaint = function() { context.lineTo(mouse.x, mouse.y); context.stroke();};"
},
{
"code": null,
"e": 5887,
"s": 5834,
"text": "Then we add touch events so that it works on mobile."
},
{
"code": null,
"e": 5974,
"s": 5887,
"text": "Add the touch action to disable scrolling. The code for that is inspired by this site."
},
{
"code": null,
"e": 6108,
"s": 5974,
"text": "Once we can draw, let’s fetch the image upon mouse up. We will scale it down to 28 by 28 pixels so that it matches the trained model."
},
{
"code": null,
"e": 6598,
"s": 6108,
"text": "canvas.addEventListener('mouseup', function() { $('#number').html('<img id=\"spinner\" src=\"spinner.gif\"/>'); canvas.removeEventListener('mousemove', onPaint, false); var img = new Image(); img.onload = function() { context.drawImage(img, 0, 0, 28, 28); data = context.getImageData(0, 0, 28, 28).data; var input = []; for(var i = 0; i < data.length; i += 4) { input.push(data[i + 2] / 255); } predict(input); }; img.src = canvas.toDataURL('image/png');}, false);"
},
{
"code": null,
"e": 6711,
"s": 6598,
"text": "We then get the data, keep it into an “input” array and pass it to a predict function that we will define later."
},
{
"code": null,
"e": 7201,
"s": 6711,
"text": "canvas.addEventListener('mouseup', function() { $('#number').html('<img id=\"spinner\" src=\"spinner.gif\"/>'); canvas.removeEventListener('mousemove', onPaint, false); var img = new Image(); img.onload = function() { context.drawImage(img, 0, 0, 28, 28); data = context.getImageData(0, 0, 28, 28).data; var input = []; for(var i = 0; i < data.length; i += 4) { input.push(data[i + 2] / 255); } predict(input); }; img.src = canvas.toDataURL('image/png');}, false);"
},
{
"code": null,
"e": 7439,
"s": 7201,
"text": "data is a 1D array with values RGBA values. Our model only takes 0 to 1 values (or 0 from 255 thinking in grayscale). Given that we are drawing Blue into the canvas, we can slice the array in chunks of four and take every second element."
},
{
"code": null,
"e": 7466,
"s": 7439,
"text": "RGBARGBARG...0123456789..."
},
{
"code": null,
"e": 7521,
"s": 7466,
"text": "Finally, let’s load TensorFlow.js and run predictions."
},
{
"code": null,
"e": 7612,
"s": 7521,
"text": "<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.5.2/dist/tf.min.js\"></script>"
},
{
"code": null,
"e": 7776,
"s": 7612,
"text": "You should have downloaded the files model.json and group1-shard1of1.bin and save them into a folder called model in the same folder where you have your HTML file."
},
{
"code": null,
"e": 7836,
"s": 7776,
"text": "Once loaded, we can load the trained model by simply doing:"
},
{
"code": null,
"e": 7923,
"s": 7836,
"text": "tf.loadLayersModel(‘model/model.json’).then(function(model) { window.model = model;});"
},
{
"code": null,
"e": 8000,
"s": 7923,
"text": "And upon mouseup, once we have the data, we can just feed it into the model:"
},
{
"code": null,
"e": 8201,
"s": 8000,
"text": "window.model.predict([tf.tensor(input).reshape([1, 28, 28, 1])]).array().then(function(scores){ scores = scores[0]; predicted = scores.indexOf(Math.max(...scores)); $('#number').html(predicted);});"
},
{
"code": null,
"e": 8312,
"s": 8201,
"text": "It’s straightforward to test things locally, and you can easily set up an HTTP server for testing with Python:"
},
{
"code": null,
"e": 8340,
"s": 8312,
"text": "python3 -m http.server 8080"
},
{
"code": null,
"e": 8446,
"s": 8340,
"text": "If then you want to test things using your phone, you can take advantage of this nifty tool called ngrok."
},
{
"code": null,
"e": 8464,
"s": 8446,
"text": "$ ngrok http 8080"
},
{
"code": null,
"e": 8533,
"s": 8464,
"text": "That opens a tunnel to a URL that you can access from through phone."
},
{
"code": null,
"e": 8794,
"s": 8533,
"text": "Once you are happy with the result, you can deploy your HTML into a web hosting site. A simple place is Github. If you have never created a static website with Github, you need to create a repository named “{username}.github.io”. For example, my repository is:"
},
{
"code": null,
"e": 8851,
"s": 8794,
"text": "https://github.com/carlos-aguayo/carlos-aguayo.github.io"
},
{
"code": null,
"e": 8883,
"s": 8851,
"text": "And then you can access it via:"
},
{
"code": null,
"e": 8925,
"s": 8883,
"text": "https://carlos-aguayo.github.io/tfjs.html"
},
{
"code": null,
"e": 9072,
"s": 8925,
"text": "Notice how easily we can train a model in Google Colab, export the trained model, and query it within JavaScript without ever leaving the browser!"
}
] |
MariaDB - Alter Command
|
The ALTER command provides a way to change an existing table's structure, meaning modifications like removing or adding columns, modifying indices, changing data types, or changing names. ALTER also waits to apply changes when a metadata lock is active.
ALTER paired with DROP removes an existing column. However, it fails if the column is the only remaining column.
Review the example given below −
mysql> ALTER TABLE products_tbl DROP version_num;
Use an ALTER...ADD statement to add columns −
mysql> ALTER TABLE products_tbl ADD discontinued CHAR(1);
Use the keywords FIRST and AFTER to specify placement of the column −
ALTER TABLE products_tbl ADD discontinued CHAR(1) FIRST;
ALTER TABLE products_tbl ADD discontinued CHAR(1) AFTER quantity;
Note the FIRST and AFTER keywords only apply to ALTER...ADD statements. Furthermore, you must drop a table and then add it in order to reposition it.
Change a column definition or name by using the MODIFY or CHANGE clause in an ALTER statement. The clauses have similar effects, but utilize substantially different syntax.
Review a CHANGE example given below −
mysql> ALTER TABLE products_tbl CHANGE discontinued status CHAR(4);
In a statement using CHANGE, specify the original column and then the new column that will replace it. Review a MODIFY example below −
mysql> ALTER TABLE products_tbl MODIFY discontinued CHAR(4);
The ALTER command also allows for changing default values. Review an example −
mysql> ALTER TABLE products_tbl ALTER discontinued SET DEFAULT N;
You can also use it to remove default constraints by pairing it with a DROP clause −
mysql> ALTER TABLE products_tbl ALTER discontinued DROP DEFAULT;
Change table type with the TYPE clause −
mysql> ALTER TABLE products_tbl TYPE = INNODB;
Rename a table with the RENAME keyword −
mysql> ALTER TABLE products_tbl RENAME TO products2016_tbl;
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2616,
"s": 2362,
"text": "The ALTER command provides a way to change an existing table's structure, meaning modifications like removing or adding columns, modifying indices, changing data types, or changing names. ALTER also waits to apply changes when a metadata lock is active."
},
{
"code": null,
"e": 2729,
"s": 2616,
"text": "ALTER paired with DROP removes an existing column. However, it fails if the column is the only remaining column."
},
{
"code": null,
"e": 2762,
"s": 2729,
"text": "Review the example given below −"
},
{
"code": null,
"e": 2813,
"s": 2762,
"text": "mysql> ALTER TABLE products_tbl DROP version_num;\n"
},
{
"code": null,
"e": 2859,
"s": 2813,
"text": "Use an ALTER...ADD statement to add columns −"
},
{
"code": null,
"e": 2918,
"s": 2859,
"text": "mysql> ALTER TABLE products_tbl ADD discontinued CHAR(1);\n"
},
{
"code": null,
"e": 2988,
"s": 2918,
"text": "Use the keywords FIRST and AFTER to specify placement of the column −"
},
{
"code": null,
"e": 3112,
"s": 2988,
"text": "ALTER TABLE products_tbl ADD discontinued CHAR(1) FIRST;\nALTER TABLE products_tbl ADD discontinued CHAR(1) AFTER quantity;\n"
},
{
"code": null,
"e": 3262,
"s": 3112,
"text": "Note the FIRST and AFTER keywords only apply to ALTER...ADD statements. Furthermore, you must drop a table and then add it in order to reposition it."
},
{
"code": null,
"e": 3435,
"s": 3262,
"text": "Change a column definition or name by using the MODIFY or CHANGE clause in an ALTER statement. The clauses have similar effects, but utilize substantially different syntax."
},
{
"code": null,
"e": 3473,
"s": 3435,
"text": "Review a CHANGE example given below −"
},
{
"code": null,
"e": 3542,
"s": 3473,
"text": "mysql> ALTER TABLE products_tbl CHANGE discontinued status CHAR(4);\n"
},
{
"code": null,
"e": 3677,
"s": 3542,
"text": "In a statement using CHANGE, specify the original column and then the new column that will replace it. Review a MODIFY example below −"
},
{
"code": null,
"e": 3739,
"s": 3677,
"text": "mysql> ALTER TABLE products_tbl MODIFY discontinued CHAR(4);\n"
},
{
"code": null,
"e": 3818,
"s": 3739,
"text": "The ALTER command also allows for changing default values. Review an example −"
},
{
"code": null,
"e": 3885,
"s": 3818,
"text": "mysql> ALTER TABLE products_tbl ALTER discontinued SET DEFAULT N;\n"
},
{
"code": null,
"e": 3970,
"s": 3885,
"text": "You can also use it to remove default constraints by pairing it with a DROP clause −"
},
{
"code": null,
"e": 4036,
"s": 3970,
"text": "mysql> ALTER TABLE products_tbl ALTER discontinued DROP DEFAULT;\n"
},
{
"code": null,
"e": 4077,
"s": 4036,
"text": "Change table type with the TYPE clause −"
},
{
"code": null,
"e": 4125,
"s": 4077,
"text": "mysql> ALTER TABLE products_tbl TYPE = INNODB;\n"
},
{
"code": null,
"e": 4166,
"s": 4125,
"text": "Rename a table with the RENAME keyword −"
},
{
"code": null,
"e": 4227,
"s": 4166,
"text": "mysql> ALTER TABLE products_tbl RENAME TO products2016_tbl;\n"
},
{
"code": null,
"e": 4234,
"s": 4227,
"text": " Print"
},
{
"code": null,
"e": 4245,
"s": 4234,
"text": " Add Notes"
}
] |
SQL Server Index Analysis and Optimization | by Evgeniy Gribkov | Towards Data Science
|
Quite often there is a need to optimize indexes and statistics for quicker search for the necessary data and better construction of a query execution plan by an optimizer.
The following areas of work can be understood as index optimization:
creation of missing indexes
removal of overlapping indexes
removal of unused indexes
change of existing indexes in order to fit operating conditions changed over time (structures of key columns, structures of included columns, and properties of an index itself)
removal of those indexes for which servicing costs are significantly greater than their benefit for optimization under the operating conditions that have changed over time
indexes reorganization and rebuilding.
The level of index fragmentation in a database can be analyzed with the help of the following query:
The following columns are returned:
db — database nameschema — schema object (table, view)tb — table/view where the index is locatedidx — index IDdatabase_id — database IDindex_name — index nameindex_type_desc — index type descriptionobject_id — object ID (table, view) where the index is locatedfrag_num — the number of fragments at the final level of the allocation unitfrag — average percentage of available disk space used by all pagesfrag_page — average number of pages in one fragment at the final level of the allocation unit IN_ROW_DATApage — total number of index pages or data
db — database name
schema — schema object (table, view)
tb — table/view where the index is located
idx — index ID
database_id — database ID
index_name — index name
index_type_desc — index type description
object_id — object ID (table, view) where the index is located
frag_num — the number of fragments at the final level of the allocation unit
frag — average percentage of available disk space used by all pages
frag_page — average number of pages in one fragment at the final level of the allocation unit IN_ROW_DATA
page — total number of index pages or data
This shows the level of fragmentation of the indexes which size is no less than 1 extent (8 pages) and which fragmentation is more than 10%. It works only for tables with a clustered index, and only root indexes are taken into account. This query uses two system views:
sys.dm_db_index_physical_stats — returns information about the size and fragmentation of data and indexes of the specified table or view in SQL Server.sys.indexes — contains a row for each index or heap of a table object, such as a table, a view, or a table-valued function.
sys.dm_db_index_physical_stats — returns information about the size and fragmentation of data and indexes of the specified table or view in SQL Server.
sys.indexes — contains a row for each index or heap of a table object, such as a table, a view, or a table-valued function.
Next, let’s consider when index optimization is recommended and how to perform it.
In the previous query, two indicators are particularly important:
frag — the level of index fragmentation in percentpage — index size in total number of its pages
frag — the level of index fragmentation in percent
page — index size in total number of its pages
There are different approaches to the interpretation of the level of index fragmentation and index optimization methods. One of them will be considered in this article.
The index needs to be optimized if:
its size exceeds 8 pages and its level of fragmentation is more than 30%.
its size exceeds 64 pages and its level of fragmentation is more than 25%.
its size exceeds 1 000 pages and its level of fragmentation is more than 20%.
its size exceeds 10 000 pages and its level of fragmentation is more than 15%.
its size exceeds 100 000 pages and its level of fragmentation is more than 10%.
Two approaches can be used for index optimization:
1. Index reorganization
Index reorganization requires a minimum amount of system resources. During reorganization, the leaf level of clustered and nonclustered indexes in tables and views is defragmented by means of physical reorganization of the leaf level pages. As a result, they become arranged in accordance with the logical order of the leaf nodes (from left to right). In addition, the reorganization compresses the index pages. Their compression is performed in accordance with the current value of the fill factor.You can perform index reorganization with the help of the following command:
ALTER INDEX < index_name> ON <schema>.<table> REORGANIZE;
2. Index rebuilding
Rebuilding removes an old index and creates a new one. This eliminates fragmentation, restores disk space by means of compressing pages to the specified or existing fill factor, reorders index rows in consecutive pages, and updates the new index statistics.You can perform index rebuilding with the help of the following command:
ALTER INDEX < index_name> ON <schema>.<table> REBUILD;
If your edition of the MS SQL Server supports that, the index rebuilding can be done online:
ALTER INDEX <index_name> ON <schema>.<table> REBUILD WITH(ONLINE=ON);
More information about ALTER INDEX command can be found here.
There are many index optimization tools both free and fee-based. For example, Sergey Syrovatchenko is developing a fairly powerful and free tool for optimizing indexes.The advantages of this tool are as follows:
optimized algorithm for obtaining fragmented indexes
ability to serve multiple databases at once in one process
automatic action selection for indexes based on selected settings
support for global search and advanced filtering for better analytics
a lot of settings and useful information about indexes
automatic generation of index maintenance scripts
support for heap and column index maintenance
ability to enable index compression and statistics update instead of rebuilding
support for all editions of SQL Server 2008 and later, as well as the Azure SQL Database.
The detailed discussion about the tool can be found here.
Let’s consider one of the methods to determine obsolete statistics:
In the method given, obsolete statistics is determined by the following indicators:
If the data has been changed significantly.If statistics has not been updated for a long time.If the object size is less than the specified maximum or this maximum is not specified.If the number of rows in the section is less than the specified maximum or this maximum is not specified.
If the data has been changed significantly.
If statistics has not been updated for a long time.
If the object size is less than the specified maximum or this maximum is not specified.
If the number of rows in the section is less than the specified maximum or this maximum is not specified.
The following system views are used in the query:
sys.dm_db_partition_stats — returns the page and row count information for all sections of the current database.sys.objects — database objects.sys.stats — statistics for tables, indexes and indexed views.sys.indexes — indexes.sys.dm_db_stats_properties — returns the statistical properties of the specified database object (table or indexed view) from the current SQL Server database.sys.stats_columns — contains one row for each column that is part of the sys.stats statistics.sys.columns — columns of all objects with columns.sys.types — types of data.
sys.dm_db_partition_stats — returns the page and row count information for all sections of the current database.
sys.objects — database objects.
sys.stats — statistics for tables, indexes and indexed views.
sys.indexes — indexes.
sys.dm_db_stats_properties — returns the statistical properties of the specified database object (table or indexed view) from the current SQL Server database.
sys.stats_columns — contains one row for each column that is part of the sys.stats statistics.
sys.columns — columns of all objects with columns.
sys.types — types of data.
Statistics can be optimized further using the following commands:
IF (EXISTS(SELECT TOP(1) 1 FROM sys.stats AS s WHERE s.[object_id]=<object_id> AND s.[stats_id]=<stats_id>))UPDATE STATISTICS <SchemaName>.<ObjectName> (<StatName>) WITH FULLSCAN;
More information on UPDATE STATISTICS command can be found here.
An Example of Analysis and Optimization of Indices in dbForge Studio for SQL Server
In dbForge Studio for SQL Server, it is possible to analyze and optimize the level of index fragmentation. The product dbForge Index Manager also has this functionality.
In this example, we will consider the SRV database, which is designed to serve MS SQL Server DBMS.
This SRV database is distributed freely for any purpose. After opening the studio, click the “Manage Index Fragmentation ...” button on the “Administration” tab:
In the window that opens, select the server and click “Options” to configure the settings:
In the options window that appears, set the desired parameters:
The results of the settings can be saved as a bat-file by clicking the lower-left button “Save Command Line ...”. And you can reset to default settings by clicking the lower-right button “Restore defaults”.
Next, click “OK”.
Now select the database you need:
After that, the analysis will start. You can also update the analysis by clicking the “Reanalyze” button.
When the analysis is finished, select the desired indexes for optimization:
Please note that the analysis result can be downloaded as a CSV file by clicking the button “Export to CSV ...”.
Further on, optimization can be carried out in several ways:
generating a script in a new studio window (in “Script Changes” menu select “To New SQL Window”).generating a script to clipboard (in “Script Changes” menu select “To Clipboard”).running the optimization directly (click the “Fix” button).
generating a script in a new studio window (in “Script Changes” menu select “To New SQL Window”).
generating a script to clipboard (in “Script Changes” menu select “To Clipboard”).
running the optimization directly (click the “Fix” button).
Let’s choose the third method — click the “Fix” button .
After the optimization process is completed, you need to click the “Reanalyze” button again:
The analysis of indexes fragmentation level and the extent of statistics obsolescence with subsequent optimization was conducted. It is also clear from the example above that the dbForge Index Manager tool allows you to analyze quickly the level of index fragmentation, as well as generate a database index optimization script.
|
[
{
"code": null,
"e": 344,
"s": 172,
"text": "Quite often there is a need to optimize indexes and statistics for quicker search for the necessary data and better construction of a query execution plan by an optimizer."
},
{
"code": null,
"e": 413,
"s": 344,
"text": "The following areas of work can be understood as index optimization:"
},
{
"code": null,
"e": 441,
"s": 413,
"text": "creation of missing indexes"
},
{
"code": null,
"e": 472,
"s": 441,
"text": "removal of overlapping indexes"
},
{
"code": null,
"e": 498,
"s": 472,
"text": "removal of unused indexes"
},
{
"code": null,
"e": 675,
"s": 498,
"text": "change of existing indexes in order to fit operating conditions changed over time (structures of key columns, structures of included columns, and properties of an index itself)"
},
{
"code": null,
"e": 847,
"s": 675,
"text": "removal of those indexes for which servicing costs are significantly greater than their benefit for optimization under the operating conditions that have changed over time"
},
{
"code": null,
"e": 886,
"s": 847,
"text": "indexes reorganization and rebuilding."
},
{
"code": null,
"e": 987,
"s": 886,
"text": "The level of index fragmentation in a database can be analyzed with the help of the following query:"
},
{
"code": null,
"e": 1023,
"s": 987,
"text": "The following columns are returned:"
},
{
"code": null,
"e": 1574,
"s": 1023,
"text": "db — database nameschema — schema object (table, view)tb — table/view where the index is locatedidx — index IDdatabase_id — database IDindex_name — index nameindex_type_desc — index type descriptionobject_id — object ID (table, view) where the index is locatedfrag_num — the number of fragments at the final level of the allocation unitfrag — average percentage of available disk space used by all pagesfrag_page — average number of pages in one fragment at the final level of the allocation unit IN_ROW_DATApage — total number of index pages or data"
},
{
"code": null,
"e": 1593,
"s": 1574,
"text": "db — database name"
},
{
"code": null,
"e": 1630,
"s": 1593,
"text": "schema — schema object (table, view)"
},
{
"code": null,
"e": 1673,
"s": 1630,
"text": "tb — table/view where the index is located"
},
{
"code": null,
"e": 1688,
"s": 1673,
"text": "idx — index ID"
},
{
"code": null,
"e": 1714,
"s": 1688,
"text": "database_id — database ID"
},
{
"code": null,
"e": 1738,
"s": 1714,
"text": "index_name — index name"
},
{
"code": null,
"e": 1779,
"s": 1738,
"text": "index_type_desc — index type description"
},
{
"code": null,
"e": 1842,
"s": 1779,
"text": "object_id — object ID (table, view) where the index is located"
},
{
"code": null,
"e": 1919,
"s": 1842,
"text": "frag_num — the number of fragments at the final level of the allocation unit"
},
{
"code": null,
"e": 1987,
"s": 1919,
"text": "frag — average percentage of available disk space used by all pages"
},
{
"code": null,
"e": 2093,
"s": 1987,
"text": "frag_page — average number of pages in one fragment at the final level of the allocation unit IN_ROW_DATA"
},
{
"code": null,
"e": 2136,
"s": 2093,
"text": "page — total number of index pages or data"
},
{
"code": null,
"e": 2406,
"s": 2136,
"text": "This shows the level of fragmentation of the indexes which size is no less than 1 extent (8 pages) and which fragmentation is more than 10%. It works only for tables with a clustered index, and only root indexes are taken into account. This query uses two system views:"
},
{
"code": null,
"e": 2681,
"s": 2406,
"text": "sys.dm_db_index_physical_stats — returns information about the size and fragmentation of data and indexes of the specified table or view in SQL Server.sys.indexes — contains a row for each index or heap of a table object, such as a table, a view, or a table-valued function."
},
{
"code": null,
"e": 2833,
"s": 2681,
"text": "sys.dm_db_index_physical_stats — returns information about the size and fragmentation of data and indexes of the specified table or view in SQL Server."
},
{
"code": null,
"e": 2957,
"s": 2833,
"text": "sys.indexes — contains a row for each index or heap of a table object, such as a table, a view, or a table-valued function."
},
{
"code": null,
"e": 3040,
"s": 2957,
"text": "Next, let’s consider when index optimization is recommended and how to perform it."
},
{
"code": null,
"e": 3106,
"s": 3040,
"text": "In the previous query, two indicators are particularly important:"
},
{
"code": null,
"e": 3203,
"s": 3106,
"text": "frag — the level of index fragmentation in percentpage — index size in total number of its pages"
},
{
"code": null,
"e": 3254,
"s": 3203,
"text": "frag — the level of index fragmentation in percent"
},
{
"code": null,
"e": 3301,
"s": 3254,
"text": "page — index size in total number of its pages"
},
{
"code": null,
"e": 3470,
"s": 3301,
"text": "There are different approaches to the interpretation of the level of index fragmentation and index optimization methods. One of them will be considered in this article."
},
{
"code": null,
"e": 3506,
"s": 3470,
"text": "The index needs to be optimized if:"
},
{
"code": null,
"e": 3580,
"s": 3506,
"text": "its size exceeds 8 pages and its level of fragmentation is more than 30%."
},
{
"code": null,
"e": 3655,
"s": 3580,
"text": "its size exceeds 64 pages and its level of fragmentation is more than 25%."
},
{
"code": null,
"e": 3733,
"s": 3655,
"text": "its size exceeds 1 000 pages and its level of fragmentation is more than 20%."
},
{
"code": null,
"e": 3812,
"s": 3733,
"text": "its size exceeds 10 000 pages and its level of fragmentation is more than 15%."
},
{
"code": null,
"e": 3892,
"s": 3812,
"text": "its size exceeds 100 000 pages and its level of fragmentation is more than 10%."
},
{
"code": null,
"e": 3943,
"s": 3892,
"text": "Two approaches can be used for index optimization:"
},
{
"code": null,
"e": 3967,
"s": 3943,
"text": "1. Index reorganization"
},
{
"code": null,
"e": 4543,
"s": 3967,
"text": "Index reorganization requires a minimum amount of system resources. During reorganization, the leaf level of clustered and nonclustered indexes in tables and views is defragmented by means of physical reorganization of the leaf level pages. As a result, they become arranged in accordance with the logical order of the leaf nodes (from left to right). In addition, the reorganization compresses the index pages. Their compression is performed in accordance with the current value of the fill factor.You can perform index reorganization with the help of the following command:"
},
{
"code": null,
"e": 4601,
"s": 4543,
"text": "ALTER INDEX < index_name> ON <schema>.<table> REORGANIZE;"
},
{
"code": null,
"e": 4621,
"s": 4601,
"text": "2. Index rebuilding"
},
{
"code": null,
"e": 4951,
"s": 4621,
"text": "Rebuilding removes an old index and creates a new one. This eliminates fragmentation, restores disk space by means of compressing pages to the specified or existing fill factor, reorders index rows in consecutive pages, and updates the new index statistics.You can perform index rebuilding with the help of the following command:"
},
{
"code": null,
"e": 5006,
"s": 4951,
"text": "ALTER INDEX < index_name> ON <schema>.<table> REBUILD;"
},
{
"code": null,
"e": 5099,
"s": 5006,
"text": "If your edition of the MS SQL Server supports that, the index rebuilding can be done online:"
},
{
"code": null,
"e": 5169,
"s": 5099,
"text": "ALTER INDEX <index_name> ON <schema>.<table> REBUILD WITH(ONLINE=ON);"
},
{
"code": null,
"e": 5231,
"s": 5169,
"text": "More information about ALTER INDEX command can be found here."
},
{
"code": null,
"e": 5443,
"s": 5231,
"text": "There are many index optimization tools both free and fee-based. For example, Sergey Syrovatchenko is developing a fairly powerful and free tool for optimizing indexes.The advantages of this tool are as follows:"
},
{
"code": null,
"e": 5496,
"s": 5443,
"text": "optimized algorithm for obtaining fragmented indexes"
},
{
"code": null,
"e": 5555,
"s": 5496,
"text": "ability to serve multiple databases at once in one process"
},
{
"code": null,
"e": 5621,
"s": 5555,
"text": "automatic action selection for indexes based on selected settings"
},
{
"code": null,
"e": 5691,
"s": 5621,
"text": "support for global search and advanced filtering for better analytics"
},
{
"code": null,
"e": 5746,
"s": 5691,
"text": "a lot of settings and useful information about indexes"
},
{
"code": null,
"e": 5796,
"s": 5746,
"text": "automatic generation of index maintenance scripts"
},
{
"code": null,
"e": 5842,
"s": 5796,
"text": "support for heap and column index maintenance"
},
{
"code": null,
"e": 5922,
"s": 5842,
"text": "ability to enable index compression and statistics update instead of rebuilding"
},
{
"code": null,
"e": 6012,
"s": 5922,
"text": "support for all editions of SQL Server 2008 and later, as well as the Azure SQL Database."
},
{
"code": null,
"e": 6070,
"s": 6012,
"text": "The detailed discussion about the tool can be found here."
},
{
"code": null,
"e": 6138,
"s": 6070,
"text": "Let’s consider one of the methods to determine obsolete statistics:"
},
{
"code": null,
"e": 6222,
"s": 6138,
"text": "In the method given, obsolete statistics is determined by the following indicators:"
},
{
"code": null,
"e": 6509,
"s": 6222,
"text": "If the data has been changed significantly.If statistics has not been updated for a long time.If the object size is less than the specified maximum or this maximum is not specified.If the number of rows in the section is less than the specified maximum or this maximum is not specified."
},
{
"code": null,
"e": 6553,
"s": 6509,
"text": "If the data has been changed significantly."
},
{
"code": null,
"e": 6605,
"s": 6553,
"text": "If statistics has not been updated for a long time."
},
{
"code": null,
"e": 6693,
"s": 6605,
"text": "If the object size is less than the specified maximum or this maximum is not specified."
},
{
"code": null,
"e": 6799,
"s": 6693,
"text": "If the number of rows in the section is less than the specified maximum or this maximum is not specified."
},
{
"code": null,
"e": 6849,
"s": 6799,
"text": "The following system views are used in the query:"
},
{
"code": null,
"e": 7404,
"s": 6849,
"text": "sys.dm_db_partition_stats — returns the page and row count information for all sections of the current database.sys.objects — database objects.sys.stats — statistics for tables, indexes and indexed views.sys.indexes — indexes.sys.dm_db_stats_properties — returns the statistical properties of the specified database object (table or indexed view) from the current SQL Server database.sys.stats_columns — contains one row for each column that is part of the sys.stats statistics.sys.columns — columns of all objects with columns.sys.types — types of data."
},
{
"code": null,
"e": 7517,
"s": 7404,
"text": "sys.dm_db_partition_stats — returns the page and row count information for all sections of the current database."
},
{
"code": null,
"e": 7549,
"s": 7517,
"text": "sys.objects — database objects."
},
{
"code": null,
"e": 7611,
"s": 7549,
"text": "sys.stats — statistics for tables, indexes and indexed views."
},
{
"code": null,
"e": 7634,
"s": 7611,
"text": "sys.indexes — indexes."
},
{
"code": null,
"e": 7793,
"s": 7634,
"text": "sys.dm_db_stats_properties — returns the statistical properties of the specified database object (table or indexed view) from the current SQL Server database."
},
{
"code": null,
"e": 7888,
"s": 7793,
"text": "sys.stats_columns — contains one row for each column that is part of the sys.stats statistics."
},
{
"code": null,
"e": 7939,
"s": 7888,
"text": "sys.columns — columns of all objects with columns."
},
{
"code": null,
"e": 7966,
"s": 7939,
"text": "sys.types — types of data."
},
{
"code": null,
"e": 8032,
"s": 7966,
"text": "Statistics can be optimized further using the following commands:"
},
{
"code": null,
"e": 8212,
"s": 8032,
"text": "IF (EXISTS(SELECT TOP(1) 1 FROM sys.stats AS s WHERE s.[object_id]=<object_id> AND s.[stats_id]=<stats_id>))UPDATE STATISTICS <SchemaName>.<ObjectName> (<StatName>) WITH FULLSCAN;"
},
{
"code": null,
"e": 8277,
"s": 8212,
"text": "More information on UPDATE STATISTICS command can be found here."
},
{
"code": null,
"e": 8361,
"s": 8277,
"text": "An Example of Analysis and Optimization of Indices in dbForge Studio for SQL Server"
},
{
"code": null,
"e": 8531,
"s": 8361,
"text": "In dbForge Studio for SQL Server, it is possible to analyze and optimize the level of index fragmentation. The product dbForge Index Manager also has this functionality."
},
{
"code": null,
"e": 8630,
"s": 8531,
"text": "In this example, we will consider the SRV database, which is designed to serve MS SQL Server DBMS."
},
{
"code": null,
"e": 8792,
"s": 8630,
"text": "This SRV database is distributed freely for any purpose. After opening the studio, click the “Manage Index Fragmentation ...” button on the “Administration” tab:"
},
{
"code": null,
"e": 8883,
"s": 8792,
"text": "In the window that opens, select the server and click “Options” to configure the settings:"
},
{
"code": null,
"e": 8947,
"s": 8883,
"text": "In the options window that appears, set the desired parameters:"
},
{
"code": null,
"e": 9154,
"s": 8947,
"text": "The results of the settings can be saved as a bat-file by clicking the lower-left button “Save Command Line ...”. And you can reset to default settings by clicking the lower-right button “Restore defaults”."
},
{
"code": null,
"e": 9172,
"s": 9154,
"text": "Next, click “OK”."
},
{
"code": null,
"e": 9206,
"s": 9172,
"text": "Now select the database you need:"
},
{
"code": null,
"e": 9312,
"s": 9206,
"text": "After that, the analysis will start. You can also update the analysis by clicking the “Reanalyze” button."
},
{
"code": null,
"e": 9388,
"s": 9312,
"text": "When the analysis is finished, select the desired indexes for optimization:"
},
{
"code": null,
"e": 9501,
"s": 9388,
"text": "Please note that the analysis result can be downloaded as a CSV file by clicking the button “Export to CSV ...”."
},
{
"code": null,
"e": 9562,
"s": 9501,
"text": "Further on, optimization can be carried out in several ways:"
},
{
"code": null,
"e": 9801,
"s": 9562,
"text": "generating a script in a new studio window (in “Script Changes” menu select “To New SQL Window”).generating a script to clipboard (in “Script Changes” menu select “To Clipboard”).running the optimization directly (click the “Fix” button)."
},
{
"code": null,
"e": 9899,
"s": 9801,
"text": "generating a script in a new studio window (in “Script Changes” menu select “To New SQL Window”)."
},
{
"code": null,
"e": 9982,
"s": 9899,
"text": "generating a script to clipboard (in “Script Changes” menu select “To Clipboard”)."
},
{
"code": null,
"e": 10042,
"s": 9982,
"text": "running the optimization directly (click the “Fix” button)."
},
{
"code": null,
"e": 10099,
"s": 10042,
"text": "Let’s choose the third method — click the “Fix” button ."
},
{
"code": null,
"e": 10192,
"s": 10099,
"text": "After the optimization process is completed, you need to click the “Reanalyze” button again:"
}
] |
Difference Between RGB, CMYK, HSV, and YIQ Color Models - GeeksforGeeks
|
19 Nov, 2021
The colour spaces in image processing aim to facilitate the specifications of colours in some standard way. Different types of colour spaces are used in multiple fields like in hardware, in multiple applications of creating animation, etc. The colour model aims to facilitate the specifications of colours in some standard way.
Different types of colour models are used in multiple fields like in hardware, in multiple applications of creating animation, etc.
Let’s see each colour model and its application.
RGB
CMYK
HSV
YIQ
RGB: The RGB colour model is the most common colour model used in Digital image processing and openCV. The colour image consists of 3 channels. One channel each for one colour. Red, Green and Blue are the main colour components of this model. All other colours are produced by the proportional ratio of these three colours only. 0 represents the black and as the value increases the colour intensity increases.
Properties:
This is an additive colour model. The colours are added to the black.
3 main channels: Red, Green and Blue.
Used in DIP, openCV and online logos.
Colour combination:
Green(255) + Red(255) = Yellow
Green(255) + Blue(255) = Cyab
Red(255) + Blue(255) = Magenta
Red(255) + Greeb(255) + Blue(255) = White
CMYK: CMYK colour model is widely used in printers. It stands for Cyan, Magenta, Yellow and Black (key). It is a subtractive colour model. 0 represents the primary colour and 1 represents the lightest colour. In this model, point (1, 1, 1) represents black, and (0,0,0) represents white. It is a subtractive model thus the value is subtracted from 1 to vary from least intense to a most intense colour value.
1-RGB = CMY
Cyan is negative of Red.
Magenta is negative of Green.
Yellow is negative of Blue.
HSV: The image consists of three channels. Hue, Saturation and Value are three channels. This colour model does not use primary colours directly. It uses colour in the way humans perceive them. HSV colour when is represented by a cone.
Hue is a colour component. Since the cone represents the HSV model, the hue represents different colours in different angle ranges.
Red colour falls between 0 and 60 degrees in the HSV cone.
Yellow colour falls between 61 and 120 degrees in the HSV cone.
Green colour falls between 121 and 180 degrees in the HSV cone.
Cyan colour falls between 181 and 240 degrees in the HSV cone.
Blue colour falls between 241 and 300 degrees in the HSV cone.
Magenta colour falls between 301 and 360 degrees in the HSV cone.
Saturation as the name suggest describes the percentage of the colour. Sometimes this value lies in the 0 to 1 range. 0 being the grey and 1 being the primary colour. Saturation describes the grey colour.
The value represents the intensity of the colour chosen. Its value lies in percentage from 0 to 100. 0 is black and 1 is the brightest and reveals the colour.
HSV model is used in histogram equalization and converting grayscale images to RGB colour images.
YIQ: YIQ is the most widely colour model used in Television broadcasting. Y stands for luminance part and IQ stands for chrominance part. In the black and white television, only the luminance part (Y) was broadcast. The y value is similar to the grayscale part. The colour information is represented by the IQ part.
There exist a formula to convert RGB into YIQ and vice-versa.
YIQ model is used in the conversion of grayscale images to RGB colour images.
computer-graphics
Image-Processing
Computer Subject
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
What is Transmission Control Protocol (TCP)?
Software Engineering - Software Requirement Tasks
6 Best Books to Learn Computer Networking
Token, Patterns, and Lexems
Difference Between User Mode and Kernel Mode
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Differences between TCP and UDP
Difference between Process and Thread
|
[
{
"code": null,
"e": 24277,
"s": 24249,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 24606,
"s": 24277,
"text": "The colour spaces in image processing aim to facilitate the specifications of colours in some standard way. Different types of colour spaces are used in multiple fields like in hardware, in multiple applications of creating animation, etc. The colour model aims to facilitate the specifications of colours in some standard way. "
},
{
"code": null,
"e": 24740,
"s": 24606,
"text": "Different types of colour models are used in multiple fields like in hardware, in multiple applications of creating animation, etc. "
},
{
"code": null,
"e": 24789,
"s": 24740,
"text": "Let’s see each colour model and its application."
},
{
"code": null,
"e": 24793,
"s": 24789,
"text": "RGB"
},
{
"code": null,
"e": 24798,
"s": 24793,
"text": "CMYK"
},
{
"code": null,
"e": 24803,
"s": 24798,
"text": "HSV "
},
{
"code": null,
"e": 24808,
"s": 24803,
"text": "YIQ "
},
{
"code": null,
"e": 25219,
"s": 24808,
"text": "RGB: The RGB colour model is the most common colour model used in Digital image processing and openCV. The colour image consists of 3 channels. One channel each for one colour. Red, Green and Blue are the main colour components of this model. All other colours are produced by the proportional ratio of these three colours only. 0 represents the black and as the value increases the colour intensity increases."
},
{
"code": null,
"e": 25231,
"s": 25219,
"text": "Properties:"
},
{
"code": null,
"e": 25301,
"s": 25231,
"text": "This is an additive colour model. The colours are added to the black."
},
{
"code": null,
"e": 25339,
"s": 25301,
"text": "3 main channels: Red, Green and Blue."
},
{
"code": null,
"e": 25377,
"s": 25339,
"text": "Used in DIP, openCV and online logos."
},
{
"code": null,
"e": 25533,
"s": 25377,
"text": "Colour combination: \nGreen(255) + Red(255) = Yellow \nGreen(255) + Blue(255) = Cyab\nRed(255) + Blue(255) = Magenta\nRed(255) + Greeb(255) + Blue(255) = White"
},
{
"code": null,
"e": 25942,
"s": 25533,
"text": "CMYK: CMYK colour model is widely used in printers. It stands for Cyan, Magenta, Yellow and Black (key). It is a subtractive colour model. 0 represents the primary colour and 1 represents the lightest colour. In this model, point (1, 1, 1) represents black, and (0,0,0) represents white. It is a subtractive model thus the value is subtracted from 1 to vary from least intense to a most intense colour value."
},
{
"code": null,
"e": 26037,
"s": 25942,
"text": "1-RGB = CMY\nCyan is negative of Red.\nMagenta is negative of Green.\nYellow is negative of Blue."
},
{
"code": null,
"e": 26274,
"s": 26037,
"text": "HSV: The image consists of three channels. Hue, Saturation and Value are three channels. This colour model does not use primary colours directly. It uses colour in the way humans perceive them. HSV colour when is represented by a cone. "
},
{
"code": null,
"e": 26407,
"s": 26274,
"text": "Hue is a colour component. Since the cone represents the HSV model, the hue represents different colours in different angle ranges. "
},
{
"code": null,
"e": 26786,
"s": 26407,
"text": "Red colour falls between 0 and 60 degrees in the HSV cone.\nYellow colour falls between 61 and 120 degrees in the HSV cone.\nGreen colour falls between 121 and 180 degrees in the HSV cone.\nCyan colour falls between 181 and 240 degrees in the HSV cone.\nBlue colour falls between 241 and 300 degrees in the HSV cone.\nMagenta colour falls between 301 and 360 degrees in the HSV cone."
},
{
"code": null,
"e": 26991,
"s": 26786,
"text": "Saturation as the name suggest describes the percentage of the colour. Sometimes this value lies in the 0 to 1 range. 0 being the grey and 1 being the primary colour. Saturation describes the grey colour."
},
{
"code": null,
"e": 27151,
"s": 26991,
"text": "The value represents the intensity of the colour chosen. Its value lies in percentage from 0 to 100. 0 is black and 1 is the brightest and reveals the colour. "
},
{
"code": null,
"e": 27249,
"s": 27151,
"text": "HSV model is used in histogram equalization and converting grayscale images to RGB colour images."
},
{
"code": null,
"e": 27565,
"s": 27249,
"text": "YIQ: YIQ is the most widely colour model used in Television broadcasting. Y stands for luminance part and IQ stands for chrominance part. In the black and white television, only the luminance part (Y) was broadcast. The y value is similar to the grayscale part. The colour information is represented by the IQ part."
},
{
"code": null,
"e": 27627,
"s": 27565,
"text": "There exist a formula to convert RGB into YIQ and vice-versa."
},
{
"code": null,
"e": 27705,
"s": 27627,
"text": "YIQ model is used in the conversion of grayscale images to RGB colour images."
},
{
"code": null,
"e": 27723,
"s": 27705,
"text": "computer-graphics"
},
{
"code": null,
"e": 27740,
"s": 27723,
"text": "Image-Processing"
},
{
"code": null,
"e": 27757,
"s": 27740,
"text": "Computer Subject"
},
{
"code": null,
"e": 27776,
"s": 27757,
"text": "Difference Between"
},
{
"code": null,
"e": 27874,
"s": 27776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27883,
"s": 27874,
"text": "Comments"
},
{
"code": null,
"e": 27896,
"s": 27883,
"text": "Old Comments"
},
{
"code": null,
"e": 27941,
"s": 27896,
"text": "What is Transmission Control Protocol (TCP)?"
},
{
"code": null,
"e": 27991,
"s": 27941,
"text": "Software Engineering - Software Requirement Tasks"
},
{
"code": null,
"e": 28033,
"s": 27991,
"text": "6 Best Books to Learn Computer Networking"
},
{
"code": null,
"e": 28061,
"s": 28033,
"text": "Token, Patterns, and Lexems"
},
{
"code": null,
"e": 28106,
"s": 28061,
"text": "Difference Between User Mode and Kernel Mode"
},
{
"code": null,
"e": 28137,
"s": 28106,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 28177,
"s": 28137,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 28238,
"s": 28177,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28270,
"s": 28238,
"text": "Differences between TCP and UDP"
}
] |
How to perform post hoc test for Kruskal-Wallis in R?
|
The Kruskal-Wallis test is the non-parametric analogue of one-way analysis of variance. The non-parametric tests are used in situations when the assumptions of parametric tests are not met. If we find significant difference in Kruskal-Wallis then post hoc tests are done to find where the difference exists. For this purpose, we can perform dunn test. The function of dunn test can be accessed through FSA package.
Loading FSA package:
> library(FSA)
Consider the below data frame:
Live Demo
> x1<-sample(LETTERS[1:5],20,replace=TRUE)
> y1<-rnorm(20,1,0.35)
> df1<-data.frame(x1,y1)
> df1
x1 y1
1 E 1.1191117
2 D 1.1276032
3 D 1.5610692
4 E 1.1585054
5 E 1.0239322
6 C 0.8000165
7 C 1.2009313
8 B 1.1928228
9 A 0.7421504
10 B 0.7212436
11 C 1.4088902
12 B 1.3171291
13 D 0.9434812
14 A 0.7986718
15 C 1.0394762
16 A 0.9239324
17 E 1.1447561
18 D 1.0192032
19 B 0.8772467
20 A 0.5723085
Performing dunnTest:
> dunnTest(y1~x1,data=df1)
Dunn (1964) Kruskal-Wallis multiple comparison
p-values adjusted with the Holm method.
Comparison Z P.unadj P.adj
1 A - B -1.61355862 0.10662320 0.7463624
2 A - C -2.21117293 0.02702386 0.2702386
3 B - C -0.59761430 0.55009732 1.0000000
4 A - D -2.09165007 0.03646983 0.2917586
5 B - D -0.47809144 0.63258512 1.0000000
6 C - D 0.11952286 0.90486113 1.0000000
7 A - E -2.15141150 0.03144373 0.2829936
8 B - E -0.53785287 0.59067863 1.0000000
9 C - E 0.05976143 0.95234564 1.0000000
10 D - E -0.05976143 0.95234564 0.9523456
Warning message:
x1 was coerced to a factor.
Live Demo
> x2<-sample(c("India","Russia","China","Croatia"),20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(x2,y2)
> df2
x2 y2
1 Russia 0
2 Russia 6
3 Croatia 8
4 Croatia 5
5 Russia 5
6 Croatia 9
7 India 9
8 Croatia 6
9 India 4
10 China 1
11 Croatia 7
12 China 3
13 India 3
14 India 4
15 Croatia 6
16 China 7
17 China 8
18 Croatia 10
19 India 8
20 China 7
> dunnTest(y2~x2,data=df2)
Dunn (1964) Kruskal-Wallis multiple comparison
p-values adjusted with the Holm method.
Comparison Z P.unadj P.adj
1 China - Croatia -1.18245422 0.23702552 1.0000000
2 China - India -0.08066504 0.93570834 0.9357083
3 Croatia - India 1.09532601 0.27337384 1.0000000
4 China - Russia 0.77619975 0.43763106 0.8752621
5 Croatia - Russia 1.82479827 0.06803148 0.4081889
6 India - Russia 0.84605772 0.39752054 1.0000000
Warning message:
x2 was coerced to a factor.
Live Demo
> x3<-sample(c("G1","G2","G3","G4","G5"),20,replace=TRUE)
> y3<-rexp(20,1.34)
> df3<-data.frame(x3,y3)
> df3
x3 y3
1 G2 1.89169184
2 G3 2.74074462
3 G3 0.17273122
4 G2 0.34856852
5 G2 0.80544065
6 G1 0.54582070
7 G2 0.24551988
8 G5 0.02546690
9 G3 2.86315652
10 G1 0.43704405
11 G1 1.89036598
12 G5 0.02423629
13 G5 0.03848270
14 G1 1.01897322
15 G1 0.44416202
16 G5 0.96637068
17 G2 0.74919567
18 G5 3.24106689
19 G1 1.22994992
20 G3 0.84658591
> dunnTest(y3~x3,data=df3)
Dunn (1964) Kruskal-Wallis multiple comparison
p-values adjusted with the Holm method.
Comparison Z P.unadj P.adj
1 G1 - G2 0.4745469 0.6351099 1.0000000
2 G1 - G3 -0.4582576 0.6467674 0.6467674
3 G2 - G3 -0.8693183 0.3846731 1.0000000
4 G1 - G5 1.0328375 0.3016800 1.0000000
5 G2 - G5 0.5345225 0.5929801 1.0000000
6 G3 - G5 1.3732709 0.1696681 1.0000000
Warning message:
x3 was coerced to a factor.
|
[
{
"code": null,
"e": 1477,
"s": 1062,
"text": "The Kruskal-Wallis test is the non-parametric analogue of one-way analysis of variance. The non-parametric tests are used in situations when the assumptions of parametric tests are not met. If we find significant difference in Kruskal-Wallis then post hoc tests are done to find where the difference exists. For this purpose, we can perform dunn test. The function of dunn test can be accessed through FSA package."
},
{
"code": null,
"e": 1498,
"s": 1477,
"text": "Loading FSA package:"
},
{
"code": null,
"e": 1513,
"s": 1498,
"text": "> library(FSA)"
},
{
"code": null,
"e": 1544,
"s": 1513,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1554,
"s": 1544,
"text": "Live Demo"
},
{
"code": null,
"e": 1651,
"s": 1554,
"text": "> x1<-sample(LETTERS[1:5],20,replace=TRUE)\n> y1<-rnorm(20,1,0.35)\n> df1<-data.frame(x1,y1)\n> df1"
},
{
"code": null,
"e": 1953,
"s": 1651,
"text": " x1 y1\n1 E 1.1191117\n2 D 1.1276032\n3 D 1.5610692\n4 E 1.1585054\n5 E 1.0239322\n6 C 0.8000165\n7 C 1.2009313\n8 B 1.1928228\n9 A 0.7421504\n10 B 0.7212436\n11 C 1.4088902\n12 B 1.3171291\n13 D 0.9434812\n14 A 0.7986718\n15 C 1.0394762\n16 A 0.9239324\n17 E 1.1447561\n18 D 1.0192032\n19 B 0.8772467\n20 A 0.5723085"
},
{
"code": null,
"e": 1974,
"s": 1953,
"text": "Performing dunnTest:"
},
{
"code": null,
"e": 2088,
"s": 1974,
"text": "> dunnTest(y1~x1,data=df1)\nDunn (1964) Kruskal-Wallis multiple comparison\np-values adjusted with the Holm method."
},
{
"code": null,
"e": 2580,
"s": 2088,
"text": "Comparison Z P.unadj P.adj\n1 A - B -1.61355862 0.10662320 0.7463624\n2 A - C -2.21117293 0.02702386 0.2702386\n3 B - C -0.59761430 0.55009732 1.0000000\n4 A - D -2.09165007 0.03646983 0.2917586\n5 B - D -0.47809144 0.63258512 1.0000000\n6 C - D 0.11952286 0.90486113 1.0000000\n7 A - E -2.15141150 0.03144373 0.2829936\n8 B - E -0.53785287 0.59067863 1.0000000\n9 C - E 0.05976143 0.95234564 1.0000000\n10 D - E -0.05976143 0.95234564 0.9523456\nWarning message:\nx1 was coerced to a factor."
},
{
"code": null,
"e": 2590,
"s": 2580,
"text": "Live Demo"
},
{
"code": null,
"e": 2707,
"s": 2590,
"text": "> x2<-sample(c(\"India\",\"Russia\",\"China\",\"Croatia\"),20,replace=TRUE)\n> y2<-rpois(20,5)\n> df2<-data.frame(x2,y2)\n> df2"
},
{
"code": null,
"e": 2948,
"s": 2707,
"text": " x2 y2\n1 Russia 0\n2 Russia 6\n3 Croatia 8\n4 Croatia 5\n5 Russia 5\n6 Croatia 9\n7 India 9\n8 Croatia 6\n9 India 4\n10 China 1\n11 Croatia 7\n12 China 3\n13 India 3\n14 India 4\n15 Croatia 6\n16 China 7\n17 China 8\n18 Croatia 10\n19 India 8\n20 China 7"
},
{
"code": null,
"e": 3062,
"s": 2948,
"text": "> dunnTest(y2~x2,data=df2)\nDunn (1964) Kruskal-Wallis multiple comparison\np-values adjusted with the Holm method."
},
{
"code": null,
"e": 3433,
"s": 3062,
"text": "Comparison Z P.unadj P.adj\n1 China - Croatia -1.18245422 0.23702552 1.0000000\n2 China - India -0.08066504 0.93570834 0.9357083\n3 Croatia - India 1.09532601 0.27337384 1.0000000\n4 China - Russia 0.77619975 0.43763106 0.8752621\n5 Croatia - Russia 1.82479827 0.06803148 0.4081889\n6 India - Russia 0.84605772 0.39752054 1.0000000\nWarning message:\nx2 was coerced to a factor."
},
{
"code": null,
"e": 3443,
"s": 3433,
"text": "Live Demo"
},
{
"code": null,
"e": 3552,
"s": 3443,
"text": "> x3<-sample(c(\"G1\",\"G2\",\"G3\",\"G4\",\"G5\"),20,replace=TRUE)\n> y3<-rexp(20,1.34)\n> df3<-data.frame(x3,y3)\n> df3"
},
{
"code": null,
"e": 3904,
"s": 3552,
"text": " x3 y3\n1 G2 1.89169184\n2 G3 2.74074462\n3 G3 0.17273122\n4 G2 0.34856852\n5 G2 0.80544065\n6 G1 0.54582070\n7 G2 0.24551988\n8 G5 0.02546690\n9 G3 2.86315652\n10 G1 0.43704405\n11 G1 1.89036598\n12 G5 0.02423629\n13 G5 0.03848270\n14 G1 1.01897322\n15 G1 0.44416202\n16 G5 0.96637068\n17 G2 0.74919567\n18 G5 3.24106689\n19 G1 1.22994992\n20 G3 0.84658591"
},
{
"code": null,
"e": 4018,
"s": 3904,
"text": "> dunnTest(y3~x3,data=df3)\nDunn (1964) Kruskal-Wallis multiple comparison\np-values adjusted with the Holm method."
},
{
"code": null,
"e": 4332,
"s": 4018,
"text": "Comparison Z P.unadj P.adj\n1 G1 - G2 0.4745469 0.6351099 1.0000000\n2 G1 - G3 -0.4582576 0.6467674 0.6467674\n3 G2 - G3 -0.8693183 0.3846731 1.0000000\n4 G1 - G5 1.0328375 0.3016800 1.0000000\n5 G2 - G5 0.5345225 0.5929801 1.0000000\n6 G3 - G5 1.3732709 0.1696681 1.0000000\nWarning message:\nx3 was coerced to a factor."
}
] |
Unary operator in C++
|
Unary operator is operators that act upon a single operand to produce a new value. The unary operators are as follows:
These operators have right-to-left associativity. Unary expressions generally involve syntax that precedes a postfix or primary expression.
Let's look at an example of the -(minus) and casting() unary operators.
#include<iostream>
using namespace std;
int main() {
int x;
float y = 1.23;
x = (int) y;
x = -x;
cout << x;
return 0;
}
This gives the output −
-1
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Unary operator is operators that act upon a single operand to produce a new value. The unary operators are as follows:"
},
{
"code": null,
"e": 1321,
"s": 1181,
"text": "These operators have right-to-left associativity. Unary expressions generally involve syntax that precedes a postfix or primary expression."
},
{
"code": null,
"e": 1393,
"s": 1321,
"text": "Let's look at an example of the -(minus) and casting() unary operators."
},
{
"code": null,
"e": 1532,
"s": 1393,
"text": "#include<iostream>\nusing namespace std;\n\nint main() {\n int x;\n float y = 1.23;\n x = (int) y;\n x = -x;\n cout << x;\n return 0;\n}"
},
{
"code": null,
"e": 1556,
"s": 1532,
"text": "This gives the output −"
},
{
"code": null,
"e": 1559,
"s": 1556,
"text": "-1"
}
] |
Build, Train and Deploy A Real-World Flower Classifier of 102 Flower Types | by Juv Chan | Towards Data Science
|
I love flowers. The lotus flower above is one of my most favorite flower photos taken during my visit to the Summer Palace Beijing in 2008. Since I am a developer and enjoy learning and working on artificial intelligence and cloud projects, I decide to write this blog post to share my project on building a real-world flower classifier with TensorFlow, Amazon SageMaker and Docker.
This post shows step-by-step guide on:
Using ready-to-use Flower dataset from TensorFlow Datasets.
Using Transfer Learning for feature extraction from a pre-trained model from TensorFlow Hub.
Using tf.data API to build input pipelines for the dataset split into training, validation and test datasets.
Using tf.keras API to build, train and evaluate the model.
Using Callback to define early stopping threshold for model training.
Preparing training script to train and export the model in SavedModel format for deploy with TensorFlow and Amazon SageMaker Python SDK.
Preparing inference code and configuration to run the TensorFlow Serving ModelServer for serving the model.
Building custom Docker Containers for training and serving the TensorFlow model with Amazon SageMaker Python SDK and SageMaker TensorFlow Training Toolkit in Local mode.
The project is available to the public at:
github.com
Below is the list of system, hardware, software and Python packages that are used to develop and test the project.
Ubuntu 18.04.5 LTS
Docker 19.03.12
Python 3.8.5
Conda 4.8.4
NVIDIA GeForce RTX 2070
NVIDIA Container Runtime Library 1.20
NVIDIA CUDA Toolkit 10.1
sagemaker 2.5.3
sagemaker-tensorflow-training 20.1.2
tensorflow-gpu 2.3.0
tensorflow-datasets 3.2.1
tensorflow-hub 0.9.0
tensorflow-model-server 2.3.0
jupyterlab 2.2.6
Pillow 7.2.0
matplotlib 3.3.1
TensorFlow Datasets (TFDS) is a collection of public datasets ready to use with TensorFlow, JAX and other machine learning frameworks. All TFDS datasets are exposed as tf.data.Datasets, which are easy to use for high-performance input pipelines.
There are a total of 195 ready-to-use datasets available in the TFDS to date. There are 2 flower datasets in TFDS: oxford_flowers102, tf_flowers
The oxford_flowers102 dataset is used because it has both larger dataset size and larger number of flower categories.
ds_name = 'oxford_flowers102'splits = ['test', 'validation', 'train']ds, info = tfds.load(ds_name, split = splits, with_info=True)(train_examples, validation_examples, test_examples) = dsprint(f"Number of flower types {info.features['label'].num_classes}")print(f"Number of training examples: {tf.data.experimental.cardinality(train_examples)}")print(f"Number of validation examples: {tf.data.experimental.cardinality(validation_examples)}")print(f"Number of test examples: {tf.data.experimental.cardinality(test_examples)}\n")print('Flower types full list:')print(info.features['label'].names)tfds.show_examples(train_examples, info, rows=2, cols=8)
Amazon SageMaker allows users to use training script or inference code in the same way that would be used outside SageMaker to run custom training or inference algorithm. One of the differences is that the training script used with Amazon SageMaker could make use of the SageMaker Containers Environment Variables, e.g. SM_MODEL_DIR, SM_NUM_GPUS, SM_NUM_CPUS in the SageMaker container.
Amazon SageMaker always uses Docker containers when running scripts, training algorithms or deploying models. Amazon SageMaker provides containers for its built-in algorithms and pre-built Docker images for some of the most common machine learning frameworks. You can also create your own container images to manage more advanced use cases not addressed by the containers provided by Amazon SageMaker.
The custom training script is as shown below:
TensorFlow Hub is a library of reusable pre-trained machine learning models for transfer learning in different problem domains. For this flower classification problem, we evaluate the pre-trained image feature vectors based on different image model architectures and datasets from TF-Hub as below for transfer learning on the oxford_flowers102 dataset.
ResNet50 Feature Vector
MobileNet V2 (ImageNet) Feature Vector
Inception V3 (ImageNet) Feature Vector
Inception V3 (iNaturalist) Feature Vector
In the final training script, the Inception V3 (iNaturalist) feature vector pre-trained model is used for transfer learning for this problem because it performs the best compared to the others above (~95% test accuracy over 5 epochs without fine-tune). This model uses the Inception V3 architecture and trained on the iNaturalist (iNat) 2017 dataset of over 5,000 different species of plants and animals from https://www.inaturalist.org/. In contrast, the ImageNet 2012 dataset has only 1,000 classes which has very few flower types.
TensorFlow Serving is a flexible, high-performance machine learning models serving system, designed for production environment. It is part of TensorFlow Extended (TFX), an end-to-end platform for deploying production Machine Learning (ML) pipelines. The TensorFlow Serving ModelServer binary is available in two variants: tensorflow-model-server and tensorflow-model-server-universal. The TensorFlow Serving ModelServer supports both gRPC APIs and RESTful APIs.
In the inference code, the tensorflow-model-server is used to serve the model via RESTful APIs from where it is exported in the SageMaker container. It is a fully optimized server that uses some platform specific compiler optimizations and should be the preferred option for users. The inference code is as shown below:
Amazon SageMaker utilizes Docker containers to run all training jobs and inference endpoints. Amazon SageMaker provides pre-built Docker containers that support machine learning frameworks such as SageMaker Scikit-learn Container, SageMaker XGBoost Container, SageMaker SparkML Serving Container, Deep Learning Containers (TensorFlow, PyTorch, MXNet and Chainer) as well as SageMaker RL (Reinforcement Learning) Container for training and inference. These pre-built SageMaker containers should be sufficient for general purpose machine learning training and inference scenarios.
There are some scenarios where the pre-built SageMaker containers are unable to support, e.g.
Using unsupported machine learning framework versions
Using third-party packages, libraries, run-times or dependencies which are not available in the pre-built SageMaker container
Using custom machine learning algorithms
Amazon SageMaker supports user-provided custom Docker images and containers for the advanced scenarios above. Users can use any programming language, framework or packages to build their own Docker image and container that are tailored for their machine learning scenario with Amazon SageMaker.
In this flower classification scenario, custom Docker image and containers are used for the training and inference because the pre-built SageMaker TensorFlow containers do not have the packages required for the training, i.e. tensorflow_hub and tensorflow_datasets. Below is the Dockerfile used to build the custom Docker image.
The Docker command below is used to build the custom Docker image used for both training and hosting with SageMaker for this project.
docker build ./container/ -t sagemaker-custom-tensorflow-container-gpu:1.0
After the Docker image is built successfully, use the Docker commands below to verify the new image is listed as expected.
docker images
The SageMaker Python SDK supports local mode, which allows users to create estimators, train models and deploy them to their local environments. This is very useful and cost-effective for anyone who wants to prototype, build, develop and test his or her machine learning projects in a Jupyter Notebook with the SageMaker Python SDK on the local instance before running in the cloud.
The Amazon SageMaker local mode supports local CPU instance (single and multiple-instance) and local GPU instance (single instance). It also allows users to switch seamlessly between local and cloud instances (i.e. Amazon EC2 instance) by changing the instance_type argument for the SageMaker Estimator object (Note: This argument is previously known as train_instance_type in SageMaker Python SDK 1.x). Everything else works the same.
In this scenario, the local GPU instance is used by default if available, else fall back to local CPU instance. Note that the output_path is set to the local current directory (file://.) which will output the trained model artifacts to the local current directory instead of uploading onto Amazon S3. The image_uri is set to the local custom Docker image which is built locally so that SageMaker will not fetch from the pre-built Docker images based on framework and version. You can refer to the latest SageMaker TensorFlow Estimator and SageMaker Estimator Base API documentations for the full details.
In addition, hyperparameters can be passed to the training script by setting the hyperparameters of the SageMaker Estimator object. The hyperparameters that can be set depending on the hyperparameters used in the training script. In this case, they are ‘epochs’, ‘batch_size’ and ‘learning_rate’.
After the SageMaker training job is completed, the Docker container that run that job will be exited. When the training is completed successfully, the trained model can be deployed to a local SageMaker endpoint by calling the deploy method of the SageMaker Estimator object and setting the instance_type to local instance type (i.e. local_gpu or local).
A new Docker container will be started to run the custom inference code (i.e the serve program), which runs the TensorFlow Serving ModelServer to serve the model for real-time inference. The ModelServer will serve in RESTful APIs mode and expect both the request and response data in JSON format. When the local SageMaker endpoint is deployed successfully, users can make prediction requests to the endpoint and get prediction responses in real-time.
tf_local_predictor = tf_local_estimator.deploy(initial_instance_count=1, instance_type=instance_type)
To evaluate this flower classification model performance using the accuracy metric, different flower images from external sources which are independent of the oxford_flowers102 dataset are used. The main sources of these test images are from websites which provide high quality free images such as unsplash.com and pixabay.com as well as self-taken photos.
The final flower classification model is evaluated against a set of real-world flower images of different types from external sources to test how well it generalizes against unseen data. As a result, the model is able to classify all the unseen flower images correctly. The model size is approximately 80 MB, which could be considered as reasonably compact and efficient for edge deployment in production. In summary, the model seemed to be able to perform well on a given small set of unseen data and reasonably compact for production edge or web deployment.
Due to time and resources constraints, the solution here may not be providing the best practices or optimal designs and implementations. Here are some of the ideas which could be useful for anyone who is interested to contribute to improve the current solution.
Apply Data Augmentation, i.e. random (but realistic) transformations such as rotation, flip, crop, brightness and contrast etc. on the training dataset to increase its size and diversity.
Use Keras preprocessing layers. Keras provides preprocessing layers such as Image preprocessing layers and Image Data Augmentation preprocessing layers which can be combined and exported as part of a Keras SavedModel. As a result, the model can accept raw images as input.
Convert the TensorFlow model (SavedModel format) to a TensorFlow Lite model (.tflite) for edge deployment and optimization on mobile and IoT devices.
Optimize the TensorFlow Serving signature (SignatureDefs in SavedModel) to minimize the prediction output data structure and payload size. The current model prediction output returns the predicted class and score for all 102 flower types.
Use TensorFlow Profiler tools to track, analyze and optimize the performance of TensorFlow model.
Use Intel Distribution of OpenVINO toolkit for the model’s optimization and high-performance inference on Intel hardware such as CPU, iGPU, VPU or FPGA.
Optimize the Docker image size.
Add unit test for the TensorFlow training script.
Add unit test for the Dockerfile.
After the machine learning workflow has been tested working as expected in the local environment, the next step is to fully migrate this workflow to AWS Cloud with Amazon SageMaker Notebook Instance. In the next guide, I will demonstrate how to adapt this Jupyter notebook to run on SageMaker Notebook Instance as well as how to push the custom Docker image to the Amazon Elastic Container Registry (ECR) so that the whole workflow is fully hosted and managed in AWS.
It is always a best practice to clean up obsolete resources or sessions at the end to reclaim compute, memory and storage resources as well as to save cost if clean up on cloud or distributed environment. For this scenario, the local SageMaker inference endpoint as well as SageMaker containers are deleted as shown below.
tf_local_predictor.delete_endpoint()
docker container ls -a
docker rm $(docker ps -a -q)docker container ls -a
|
[
{
"code": null,
"e": 555,
"s": 172,
"text": "I love flowers. The lotus flower above is one of my most favorite flower photos taken during my visit to the Summer Palace Beijing in 2008. Since I am a developer and enjoy learning and working on artificial intelligence and cloud projects, I decide to write this blog post to share my project on building a real-world flower classifier with TensorFlow, Amazon SageMaker and Docker."
},
{
"code": null,
"e": 594,
"s": 555,
"text": "This post shows step-by-step guide on:"
},
{
"code": null,
"e": 654,
"s": 594,
"text": "Using ready-to-use Flower dataset from TensorFlow Datasets."
},
{
"code": null,
"e": 747,
"s": 654,
"text": "Using Transfer Learning for feature extraction from a pre-trained model from TensorFlow Hub."
},
{
"code": null,
"e": 857,
"s": 747,
"text": "Using tf.data API to build input pipelines for the dataset split into training, validation and test datasets."
},
{
"code": null,
"e": 916,
"s": 857,
"text": "Using tf.keras API to build, train and evaluate the model."
},
{
"code": null,
"e": 986,
"s": 916,
"text": "Using Callback to define early stopping threshold for model training."
},
{
"code": null,
"e": 1123,
"s": 986,
"text": "Preparing training script to train and export the model in SavedModel format for deploy with TensorFlow and Amazon SageMaker Python SDK."
},
{
"code": null,
"e": 1231,
"s": 1123,
"text": "Preparing inference code and configuration to run the TensorFlow Serving ModelServer for serving the model."
},
{
"code": null,
"e": 1401,
"s": 1231,
"text": "Building custom Docker Containers for training and serving the TensorFlow model with Amazon SageMaker Python SDK and SageMaker TensorFlow Training Toolkit in Local mode."
},
{
"code": null,
"e": 1444,
"s": 1401,
"text": "The project is available to the public at:"
},
{
"code": null,
"e": 1455,
"s": 1444,
"text": "github.com"
},
{
"code": null,
"e": 1570,
"s": 1455,
"text": "Below is the list of system, hardware, software and Python packages that are used to develop and test the project."
},
{
"code": null,
"e": 1589,
"s": 1570,
"text": "Ubuntu 18.04.5 LTS"
},
{
"code": null,
"e": 1605,
"s": 1589,
"text": "Docker 19.03.12"
},
{
"code": null,
"e": 1618,
"s": 1605,
"text": "Python 3.8.5"
},
{
"code": null,
"e": 1630,
"s": 1618,
"text": "Conda 4.8.4"
},
{
"code": null,
"e": 1654,
"s": 1630,
"text": "NVIDIA GeForce RTX 2070"
},
{
"code": null,
"e": 1692,
"s": 1654,
"text": "NVIDIA Container Runtime Library 1.20"
},
{
"code": null,
"e": 1717,
"s": 1692,
"text": "NVIDIA CUDA Toolkit 10.1"
},
{
"code": null,
"e": 1733,
"s": 1717,
"text": "sagemaker 2.5.3"
},
{
"code": null,
"e": 1770,
"s": 1733,
"text": "sagemaker-tensorflow-training 20.1.2"
},
{
"code": null,
"e": 1791,
"s": 1770,
"text": "tensorflow-gpu 2.3.0"
},
{
"code": null,
"e": 1817,
"s": 1791,
"text": "tensorflow-datasets 3.2.1"
},
{
"code": null,
"e": 1838,
"s": 1817,
"text": "tensorflow-hub 0.9.0"
},
{
"code": null,
"e": 1868,
"s": 1838,
"text": "tensorflow-model-server 2.3.0"
},
{
"code": null,
"e": 1885,
"s": 1868,
"text": "jupyterlab 2.2.6"
},
{
"code": null,
"e": 1898,
"s": 1885,
"text": "Pillow 7.2.0"
},
{
"code": null,
"e": 1915,
"s": 1898,
"text": "matplotlib 3.3.1"
},
{
"code": null,
"e": 2161,
"s": 1915,
"text": "TensorFlow Datasets (TFDS) is a collection of public datasets ready to use with TensorFlow, JAX and other machine learning frameworks. All TFDS datasets are exposed as tf.data.Datasets, which are easy to use for high-performance input pipelines."
},
{
"code": null,
"e": 2306,
"s": 2161,
"text": "There are a total of 195 ready-to-use datasets available in the TFDS to date. There are 2 flower datasets in TFDS: oxford_flowers102, tf_flowers"
},
{
"code": null,
"e": 2424,
"s": 2306,
"text": "The oxford_flowers102 dataset is used because it has both larger dataset size and larger number of flower categories."
},
{
"code": null,
"e": 3075,
"s": 2424,
"text": "ds_name = 'oxford_flowers102'splits = ['test', 'validation', 'train']ds, info = tfds.load(ds_name, split = splits, with_info=True)(train_examples, validation_examples, test_examples) = dsprint(f\"Number of flower types {info.features['label'].num_classes}\")print(f\"Number of training examples: {tf.data.experimental.cardinality(train_examples)}\")print(f\"Number of validation examples: {tf.data.experimental.cardinality(validation_examples)}\")print(f\"Number of test examples: {tf.data.experimental.cardinality(test_examples)}\\n\")print('Flower types full list:')print(info.features['label'].names)tfds.show_examples(train_examples, info, rows=2, cols=8)"
},
{
"code": null,
"e": 3462,
"s": 3075,
"text": "Amazon SageMaker allows users to use training script or inference code in the same way that would be used outside SageMaker to run custom training or inference algorithm. One of the differences is that the training script used with Amazon SageMaker could make use of the SageMaker Containers Environment Variables, e.g. SM_MODEL_DIR, SM_NUM_GPUS, SM_NUM_CPUS in the SageMaker container."
},
{
"code": null,
"e": 3864,
"s": 3462,
"text": "Amazon SageMaker always uses Docker containers when running scripts, training algorithms or deploying models. Amazon SageMaker provides containers for its built-in algorithms and pre-built Docker images for some of the most common machine learning frameworks. You can also create your own container images to manage more advanced use cases not addressed by the containers provided by Amazon SageMaker."
},
{
"code": null,
"e": 3910,
"s": 3864,
"text": "The custom training script is as shown below:"
},
{
"code": null,
"e": 4263,
"s": 3910,
"text": "TensorFlow Hub is a library of reusable pre-trained machine learning models for transfer learning in different problem domains. For this flower classification problem, we evaluate the pre-trained image feature vectors based on different image model architectures and datasets from TF-Hub as below for transfer learning on the oxford_flowers102 dataset."
},
{
"code": null,
"e": 4287,
"s": 4263,
"text": "ResNet50 Feature Vector"
},
{
"code": null,
"e": 4326,
"s": 4287,
"text": "MobileNet V2 (ImageNet) Feature Vector"
},
{
"code": null,
"e": 4365,
"s": 4326,
"text": "Inception V3 (ImageNet) Feature Vector"
},
{
"code": null,
"e": 4407,
"s": 4365,
"text": "Inception V3 (iNaturalist) Feature Vector"
},
{
"code": null,
"e": 4941,
"s": 4407,
"text": "In the final training script, the Inception V3 (iNaturalist) feature vector pre-trained model is used for transfer learning for this problem because it performs the best compared to the others above (~95% test accuracy over 5 epochs without fine-tune). This model uses the Inception V3 architecture and trained on the iNaturalist (iNat) 2017 dataset of over 5,000 different species of plants and animals from https://www.inaturalist.org/. In contrast, the ImageNet 2012 dataset has only 1,000 classes which has very few flower types."
},
{
"code": null,
"e": 5403,
"s": 4941,
"text": "TensorFlow Serving is a flexible, high-performance machine learning models serving system, designed for production environment. It is part of TensorFlow Extended (TFX), an end-to-end platform for deploying production Machine Learning (ML) pipelines. The TensorFlow Serving ModelServer binary is available in two variants: tensorflow-model-server and tensorflow-model-server-universal. The TensorFlow Serving ModelServer supports both gRPC APIs and RESTful APIs."
},
{
"code": null,
"e": 5723,
"s": 5403,
"text": "In the inference code, the tensorflow-model-server is used to serve the model via RESTful APIs from where it is exported in the SageMaker container. It is a fully optimized server that uses some platform specific compiler optimizations and should be the preferred option for users. The inference code is as shown below:"
},
{
"code": null,
"e": 6302,
"s": 5723,
"text": "Amazon SageMaker utilizes Docker containers to run all training jobs and inference endpoints. Amazon SageMaker provides pre-built Docker containers that support machine learning frameworks such as SageMaker Scikit-learn Container, SageMaker XGBoost Container, SageMaker SparkML Serving Container, Deep Learning Containers (TensorFlow, PyTorch, MXNet and Chainer) as well as SageMaker RL (Reinforcement Learning) Container for training and inference. These pre-built SageMaker containers should be sufficient for general purpose machine learning training and inference scenarios."
},
{
"code": null,
"e": 6396,
"s": 6302,
"text": "There are some scenarios where the pre-built SageMaker containers are unable to support, e.g."
},
{
"code": null,
"e": 6450,
"s": 6396,
"text": "Using unsupported machine learning framework versions"
},
{
"code": null,
"e": 6576,
"s": 6450,
"text": "Using third-party packages, libraries, run-times or dependencies which are not available in the pre-built SageMaker container"
},
{
"code": null,
"e": 6617,
"s": 6576,
"text": "Using custom machine learning algorithms"
},
{
"code": null,
"e": 6912,
"s": 6617,
"text": "Amazon SageMaker supports user-provided custom Docker images and containers for the advanced scenarios above. Users can use any programming language, framework or packages to build their own Docker image and container that are tailored for their machine learning scenario with Amazon SageMaker."
},
{
"code": null,
"e": 7241,
"s": 6912,
"text": "In this flower classification scenario, custom Docker image and containers are used for the training and inference because the pre-built SageMaker TensorFlow containers do not have the packages required for the training, i.e. tensorflow_hub and tensorflow_datasets. Below is the Dockerfile used to build the custom Docker image."
},
{
"code": null,
"e": 7375,
"s": 7241,
"text": "The Docker command below is used to build the custom Docker image used for both training and hosting with SageMaker for this project."
},
{
"code": null,
"e": 7450,
"s": 7375,
"text": "docker build ./container/ -t sagemaker-custom-tensorflow-container-gpu:1.0"
},
{
"code": null,
"e": 7573,
"s": 7450,
"text": "After the Docker image is built successfully, use the Docker commands below to verify the new image is listed as expected."
},
{
"code": null,
"e": 7587,
"s": 7573,
"text": "docker images"
},
{
"code": null,
"e": 7970,
"s": 7587,
"text": "The SageMaker Python SDK supports local mode, which allows users to create estimators, train models and deploy them to their local environments. This is very useful and cost-effective for anyone who wants to prototype, build, develop and test his or her machine learning projects in a Jupyter Notebook with the SageMaker Python SDK on the local instance before running in the cloud."
},
{
"code": null,
"e": 8406,
"s": 7970,
"text": "The Amazon SageMaker local mode supports local CPU instance (single and multiple-instance) and local GPU instance (single instance). It also allows users to switch seamlessly between local and cloud instances (i.e. Amazon EC2 instance) by changing the instance_type argument for the SageMaker Estimator object (Note: This argument is previously known as train_instance_type in SageMaker Python SDK 1.x). Everything else works the same."
},
{
"code": null,
"e": 9011,
"s": 8406,
"text": "In this scenario, the local GPU instance is used by default if available, else fall back to local CPU instance. Note that the output_path is set to the local current directory (file://.) which will output the trained model artifacts to the local current directory instead of uploading onto Amazon S3. The image_uri is set to the local custom Docker image which is built locally so that SageMaker will not fetch from the pre-built Docker images based on framework and version. You can refer to the latest SageMaker TensorFlow Estimator and SageMaker Estimator Base API documentations for the full details."
},
{
"code": null,
"e": 9308,
"s": 9011,
"text": "In addition, hyperparameters can be passed to the training script by setting the hyperparameters of the SageMaker Estimator object. The hyperparameters that can be set depending on the hyperparameters used in the training script. In this case, they are ‘epochs’, ‘batch_size’ and ‘learning_rate’."
},
{
"code": null,
"e": 9662,
"s": 9308,
"text": "After the SageMaker training job is completed, the Docker container that run that job will be exited. When the training is completed successfully, the trained model can be deployed to a local SageMaker endpoint by calling the deploy method of the SageMaker Estimator object and setting the instance_type to local instance type (i.e. local_gpu or local)."
},
{
"code": null,
"e": 10113,
"s": 9662,
"text": "A new Docker container will be started to run the custom inference code (i.e the serve program), which runs the TensorFlow Serving ModelServer to serve the model for real-time inference. The ModelServer will serve in RESTful APIs mode and expect both the request and response data in JSON format. When the local SageMaker endpoint is deployed successfully, users can make prediction requests to the endpoint and get prediction responses in real-time."
},
{
"code": null,
"e": 10298,
"s": 10113,
"text": "tf_local_predictor = tf_local_estimator.deploy(initial_instance_count=1, instance_type=instance_type)"
},
{
"code": null,
"e": 10655,
"s": 10298,
"text": "To evaluate this flower classification model performance using the accuracy metric, different flower images from external sources which are independent of the oxford_flowers102 dataset are used. The main sources of these test images are from websites which provide high quality free images such as unsplash.com and pixabay.com as well as self-taken photos."
},
{
"code": null,
"e": 11215,
"s": 10655,
"text": "The final flower classification model is evaluated against a set of real-world flower images of different types from external sources to test how well it generalizes against unseen data. As a result, the model is able to classify all the unseen flower images correctly. The model size is approximately 80 MB, which could be considered as reasonably compact and efficient for edge deployment in production. In summary, the model seemed to be able to perform well on a given small set of unseen data and reasonably compact for production edge or web deployment."
},
{
"code": null,
"e": 11477,
"s": 11215,
"text": "Due to time and resources constraints, the solution here may not be providing the best practices or optimal designs and implementations. Here are some of the ideas which could be useful for anyone who is interested to contribute to improve the current solution."
},
{
"code": null,
"e": 11665,
"s": 11477,
"text": "Apply Data Augmentation, i.e. random (but realistic) transformations such as rotation, flip, crop, brightness and contrast etc. on the training dataset to increase its size and diversity."
},
{
"code": null,
"e": 11938,
"s": 11665,
"text": "Use Keras preprocessing layers. Keras provides preprocessing layers such as Image preprocessing layers and Image Data Augmentation preprocessing layers which can be combined and exported as part of a Keras SavedModel. As a result, the model can accept raw images as input."
},
{
"code": null,
"e": 12088,
"s": 11938,
"text": "Convert the TensorFlow model (SavedModel format) to a TensorFlow Lite model (.tflite) for edge deployment and optimization on mobile and IoT devices."
},
{
"code": null,
"e": 12327,
"s": 12088,
"text": "Optimize the TensorFlow Serving signature (SignatureDefs in SavedModel) to minimize the prediction output data structure and payload size. The current model prediction output returns the predicted class and score for all 102 flower types."
},
{
"code": null,
"e": 12425,
"s": 12327,
"text": "Use TensorFlow Profiler tools to track, analyze and optimize the performance of TensorFlow model."
},
{
"code": null,
"e": 12578,
"s": 12425,
"text": "Use Intel Distribution of OpenVINO toolkit for the model’s optimization and high-performance inference on Intel hardware such as CPU, iGPU, VPU or FPGA."
},
{
"code": null,
"e": 12610,
"s": 12578,
"text": "Optimize the Docker image size."
},
{
"code": null,
"e": 12660,
"s": 12610,
"text": "Add unit test for the TensorFlow training script."
},
{
"code": null,
"e": 12694,
"s": 12660,
"text": "Add unit test for the Dockerfile."
},
{
"code": null,
"e": 13162,
"s": 12694,
"text": "After the machine learning workflow has been tested working as expected in the local environment, the next step is to fully migrate this workflow to AWS Cloud with Amazon SageMaker Notebook Instance. In the next guide, I will demonstrate how to adapt this Jupyter notebook to run on SageMaker Notebook Instance as well as how to push the custom Docker image to the Amazon Elastic Container Registry (ECR) so that the whole workflow is fully hosted and managed in AWS."
},
{
"code": null,
"e": 13485,
"s": 13162,
"text": "It is always a best practice to clean up obsolete resources or sessions at the end to reclaim compute, memory and storage resources as well as to save cost if clean up on cloud or distributed environment. For this scenario, the local SageMaker inference endpoint as well as SageMaker containers are deleted as shown below."
},
{
"code": null,
"e": 13522,
"s": 13485,
"text": "tf_local_predictor.delete_endpoint()"
},
{
"code": null,
"e": 13545,
"s": 13522,
"text": "docker container ls -a"
}
] |
How to call a JavaScript function from an onmouseover event?
|
The onmouseover event triggers when you bring your mouse over any element.
You can try to run the following example to learn how to call a JavaScript function from onmouseover event
Live Demo
<html>
<head>
<script>
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "The onmouseover event triggers when you bring your mouse over any element."
},
{
"code": null,
"e": 1244,
"s": 1137,
"text": "You can try to run the following example to learn how to call a JavaScript function from onmouseover event"
},
{
"code": null,
"e": 1254,
"s": 1244,
"text": "Live Demo"
},
{
"code": null,
"e": 1731,
"s": 1254,
"text": "<html>\n <head>\n <script>\n <!--\n function over() {\n document.write (\"Mouse Over\");\n }\n function out() {\n document.write (\"Mouse Out\");\n }\n //-->\n </script>\n </head>\n <body>\n <p>Bring your mouse inside the division to see the result:</p>\n <div onmouseover=\"over()\" onmouseout=\"out()\">\n <h2> This is inside the division </h2>\n </div>\n </body>\n</html>"
}
] |
Random vs Secure Random numbers in Java
|
Java provides two classes for having random numbers generation - SecureRandom.java and Random.java.The random numbers can be used generally for encryption key or session key or simply password on web server.SecureRandom is under java.security package while Random.java comes under java.util package.The basic and important difference between both is SecureRandom generate more non predictable random numbers as it implements Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) as compare to Random class which uses Linear Congruential Generator (LCG).
A important point to mention here is SecureRandom is subclass of Random class and inherits its all method such as nextBoolean(),nextDouble(),nextFloat(),nextGaussian(),nextInt() and nextLong().
Other differences between Random and SecureRandom includes −
Random class uses system time for its generation algorithm as input while SecureRandom class uses random data from operating system such as timing of I/O events.
Random class uses system time for its generation algorithm as input while SecureRandom class uses random data from operating system such as timing of I/O events.
Due to complex algorithm used in case of SecureRandom which make it more unpredictable,it takes more memory consumption in create secure random numbers than random numbers.
Due to complex algorithm used in case of SecureRandom which make it more unpredictable,it takes more memory consumption in create secure random numbers than random numbers.
Random class has only 48 bits where as SecureRandom can have upto 128 bits which makes the probability of repeating in SecureRandom are smaller.Due to this also the number of attempts to break Random number prediction comes to 2^48 while that of SecureRandom number is 2^128 which again makes it more secure.
Random class has only 48 bits where as SecureRandom can have upto 128 bits which makes the probability of repeating in SecureRandom are smaller.Due to this also the number of attempts to break Random number prediction comes to 2^48 while that of SecureRandom number is 2^128 which again makes it more secure.
Live Demo
import java.util.Random;
public class RandomClass {
public static void main(String args[]) {
Random objRandom = new Random();
int randomInt1 = objRandom.nextInt(1000);//1000 is range i.e number to be generated would be between 0 and 1000.
int randonInt2 = objRandom.nextInt(1000);
System.out.println("Random Integers: " + randomInt1);
System.out.println("Random Integers: " + randonInt2);
}
}
Random Integers: 459
Random Integers: 348
Live Demo
import java.security.SecureRandom;
public class SecureRandomClass {
public static void main(String args[]) {
SecureRandom objSecureRandom = new SecureRandom();
int randomInt1 = objSecureRandom.nextInt(1000);
int randonInt2 = objSecureRandom.nextInt(1000);
System.out.println("Random Integers: " + randomInt1);
System.out.println("Random Integers: " + randonInt2);
}
}
Random Integers: 983
Random Integers: 579
|
[
{
"code": null,
"e": 1627,
"s": 1062,
"text": "Java provides two classes for having random numbers generation - SecureRandom.java and Random.java.The random numbers can be used generally for encryption key or session key or simply password on web server.SecureRandom is under java.security package while Random.java comes under java.util package.The basic and important difference between both is SecureRandom generate more non predictable random numbers as it implements Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) as compare to Random class which uses Linear Congruential Generator (LCG)."
},
{
"code": null,
"e": 1821,
"s": 1627,
"text": "A important point to mention here is SecureRandom is subclass of Random class and inherits its all method such as nextBoolean(),nextDouble(),nextFloat(),nextGaussian(),nextInt() and nextLong()."
},
{
"code": null,
"e": 1882,
"s": 1821,
"text": "Other differences between Random and SecureRandom includes −"
},
{
"code": null,
"e": 2044,
"s": 1882,
"text": "Random class uses system time for its generation algorithm as input while SecureRandom class uses random data from operating system such as timing of I/O events."
},
{
"code": null,
"e": 2206,
"s": 2044,
"text": "Random class uses system time for its generation algorithm as input while SecureRandom class uses random data from operating system such as timing of I/O events."
},
{
"code": null,
"e": 2379,
"s": 2206,
"text": "Due to complex algorithm used in case of SecureRandom which make it more unpredictable,it takes more memory consumption in create secure random numbers than random numbers."
},
{
"code": null,
"e": 2552,
"s": 2379,
"text": "Due to complex algorithm used in case of SecureRandom which make it more unpredictable,it takes more memory consumption in create secure random numbers than random numbers."
},
{
"code": null,
"e": 2861,
"s": 2552,
"text": "Random class has only 48 bits where as SecureRandom can have upto 128 bits which makes the probability of repeating in SecureRandom are smaller.Due to this also the number of attempts to break Random number prediction comes to 2^48 while that of SecureRandom number is 2^128 which again makes it more secure."
},
{
"code": null,
"e": 3170,
"s": 2861,
"text": "Random class has only 48 bits where as SecureRandom can have upto 128 bits which makes the probability of repeating in SecureRandom are smaller.Due to this also the number of attempts to break Random number prediction comes to 2^48 while that of SecureRandom number is 2^128 which again makes it more secure."
},
{
"code": null,
"e": 3181,
"s": 3170,
"text": " Live Demo"
},
{
"code": null,
"e": 3619,
"s": 3181,
"text": "import java.util.Random;\npublic class RandomClass {\n public static void main(String args[]) {\n Random objRandom = new Random();\n int randomInt1 = objRandom.nextInt(1000);//1000 is range i.e number to be generated would be between 0 and 1000.\n int randonInt2 = objRandom.nextInt(1000);\n System.out.println(\"Random Integers: \" + randomInt1);\n System.out.println(\"Random Integers: \" + randonInt2);\n }\n}"
},
{
"code": null,
"e": 3661,
"s": 3619,
"text": "Random Integers: 459\nRandom Integers: 348"
},
{
"code": null,
"e": 3672,
"s": 3661,
"text": " Live Demo"
},
{
"code": null,
"e": 4076,
"s": 3672,
"text": "import java.security.SecureRandom;\npublic class SecureRandomClass {\n public static void main(String args[]) {\n SecureRandom objSecureRandom = new SecureRandom();\n int randomInt1 = objSecureRandom.nextInt(1000);\n int randonInt2 = objSecureRandom.nextInt(1000);\n System.out.println(\"Random Integers: \" + randomInt1);\n System.out.println(\"Random Integers: \" + randonInt2);\n }\n}"
},
{
"code": null,
"e": 4118,
"s": 4076,
"text": "Random Integers: 983\nRandom Integers: 579"
}
] |
Difference between HashMap and HashSet in Java.
|
HashMap and HashSet both are one of the most important classes of Java Collection framework.
Following are the important differences between HashMap and HashSet.
JavaTester.java
Live Demo
import java.util.HashSet;
public class JavaTester {
public static void main(String[] args){
HashSet<String> hs = new HashSet<String>();
hs.add("John");
hs.add("Smith");
hs.add("Peter");
System.out.println("Before adding duplicate values \n\n" + hs);
hs.add("John");
hs.add("Smith");
System.out.println("\nAfter adding duplicate values \n\n" + hs);
hs.add(null);
hs.add(null);
System.out.println("\nAfter adding null values \n\n" + hs);
}
}
Before adding duplicate values
[John, Smith, Peter]
After adding duplicate values
[John, Smith, Peter]
After adding null values
[null, John, Smith, Peter]
JavaTester.java
Live Demo
import java.util.HashMap;
public class JavaTester {
public static void main(String[] args){
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(12, "John");
hm.put(2, "Smith");
hm.put(7, "Peter");
System.out.println("\nHashMap object output :\n\n" + hm);
hm.put(12, "Smith");
System.out.println("\nAfter inserting duplicate key :\n\n" + hm);
}
}
HashMap object output :
{2=Smith, 7=Peter, 12=John}
After inserting duplicate key :
{2=Smith, 7=Peter, 12=John}
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "HashMap and HashSet both are one of the most important classes of Java Collection framework."
},
{
"code": null,
"e": 1224,
"s": 1155,
"text": "Following are the important differences between HashMap and HashSet."
},
{
"code": null,
"e": 1240,
"s": 1224,
"text": "JavaTester.java"
},
{
"code": null,
"e": 1251,
"s": 1240,
"text": " Live Demo"
},
{
"code": null,
"e": 1763,
"s": 1251,
"text": "import java.util.HashSet;\npublic class JavaTester {\n public static void main(String[] args){\n HashSet<String> hs = new HashSet<String>();\n hs.add(\"John\");\n hs.add(\"Smith\");\n hs.add(\"Peter\");\n System.out.println(\"Before adding duplicate values \\n\\n\" + hs);\n hs.add(\"John\");\n hs.add(\"Smith\");\n System.out.println(\"\\nAfter adding duplicate values \\n\\n\" + hs);\n hs.add(null);\n hs.add(null);\n System.out.println(\"\\nAfter adding null values \\n\\n\" + hs);\n }\n}"
},
{
"code": null,
"e": 1918,
"s": 1763,
"text": "Before adding duplicate values\n[John, Smith, Peter]\nAfter adding duplicate values\n[John, Smith, Peter]\nAfter adding null values\n[null, John, Smith, Peter]"
},
{
"code": null,
"e": 1934,
"s": 1918,
"text": "JavaTester.java"
},
{
"code": null,
"e": 1945,
"s": 1934,
"text": " Live Demo"
},
{
"code": null,
"e": 2356,
"s": 1945,
"text": "import java.util.HashMap;\npublic class JavaTester {\n public static void main(String[] args){\n HashMap<Integer, String> hm = new HashMap<Integer, String>();\n hm.put(12, \"John\");\n hm.put(2, \"Smith\");\n hm.put(7, \"Peter\");\n System.out.println(\"\\nHashMap object output :\\n\\n\" + hm);\n hm.put(12, \"Smith\");\n System.out.println(\"\\nAfter inserting duplicate key :\\n\\n\" + hm);\n }\n}"
},
{
"code": null,
"e": 2468,
"s": 2356,
"text": "HashMap object output :\n{2=Smith, 7=Peter, 12=John}\nAfter inserting duplicate key :\n{2=Smith, 7=Peter, 12=John}"
}
] |
How to Build a Poisson Hidden Markov Model Using Python and Statsmodels | by Sachin Date | Towards Data Science
|
A Poisson Hidden Markov Model is a mixture of two regression models: A Poisson regression model which is visible and a Markov model which is ‘hidden’. In a Poisson HMM, the mean value predicted by the Poisson model depends on not only the regression variables of the Poisson model, but also on the current state or regime that the hidden Markov process is in.
In an earlier article, we looked at the architecture of the Poisson Hidden Markov Model and we inspected its theoretical underpinnings. If you are new to Markov Models or the Poisson HMM, I will encourage you to review it here:
towardsdatascience.com
In this article, we will walk through a step by step tutorial in Python and statsmodels for building and training a Poisson HMM on the real world data set of labor strikes in US manufacturing that is used extensively in the literature on statistical modeling.
To illustrate the model fitting procedure, we will use the following open source data set:
The data set is a monthly time series showing the relationship between U.S. manufacturing activity measured as a departure from the trend line, and the number of contract strikes in U.S. manufacturing industries beginning each month from 1968 through 1976.
This data set is available in R and it can be fetched using the Python statsmodels Datasets package.
The tutorial in this article uses Python, not R.
Our goal is to investigate the effect of manufacturing output (the output variable) on the incidence of manufacturing strikes (the strikes variable). In other words, does the variance in manufacturing output ‘explain’ the variance in the number of monthly strikes?
Let’s import all the required packages, load the strikes data set into a Pandas DaraFrame, and inspect a plot of strikes against time:
import mathimport numpy as npimport statsmodels.api as smfrom statsmodels.base.model import GenericLikelihoodModelfrom scipy.stats import poissonfrom patsy import dmatricesimport statsmodels.graphics.tsaplots as tsafrom matplotlib import pyplot as pltfrom statsmodels.tools.numdiff import approx_hess1, approx_hess2, approx_hess3#Download the data set and load it into a Pandas Dataframestrikes_dataset = sm.datasets.get_rdataset(dataname='StrikeNb', package='Ecdat')#Plot the number of strikes starting each monthplt.xlabel('Month index')plt.ylabel('Number of strikes beginning each month')strikes_data['strikes'].plot()plt.show()
We see the following plot:
The up-down whipsaw pattern of strikes suggests that the time series may be auto-correlated. Let’s verify this by looking at the auto-correlation plot of the strikes column:
tsa.plot_acf(strikes_data['strikes'], alpha=0.05)plt.show()
We see the following plot:
The perfect correlation at lag 0 is to be ignored as a value is always perfectly correlated with itself. There is a strong correlation at lag-1. The correlations at lags 2 and 3 are likely to be a domino effect of the correlation at lag 1. This can be confirmed by plotting the partial auto-correlation plot of strikes.
tsa.plot_pacf(strikes_data['strikes'], alpha=0.05)plt.show()
The partial auto-correlation plot reveals the following:
The partial auto-correlation is 1.0 at LAG-0. This is expected, and to be ignored.
The PACF plot shows a strong partial auto-correlation at LAG-1, which suggests an AR(1) process.
The correlation at LAG-2 is just outside the 5% significance bounds. So, it may or may not be significant.
On the whole, the ACF and PACF plots indicate a definite, and strong auto-regressive influence at LAG-1. Hence, in addition to the output variable, we should include the lagged version of strikes at LAG-1 as a regression variable.
Our strategy will be based upon regressing strikes on both output and on the time-lagged copy of strikes at lag-1.
Since strikes contains whole numbered data, we will use a Poisson regression model to study the relationship between output and strikes.
We will additional hypothesize that the manufacturing strikes data cycles between periods of low and high variability which can be modeled using a 2-state discrete Markov process.
Why did we choose only 2 regimes for the Markov model? Why not 3 or 4 regimes? The answer is simply that it is best to start with a Markov model with the least possible states so as to avoid over-fitting.
In summary, we will use a 2-state Poisson Hidden Markov Model to study the relationship of manufacturing output on strikes.
Therefore, we have:
y = strikes
X = [output, strikes_LAG_1] + Hidden Markov model related variables which we will soon describe.
We’ll first spec-out the Poisson portion of the model, and then see how to ‘mix-in’ the Markov model.
The Poisson model’s mean (without considering the effect of the Markov model) can be expressed as follows:
Since we are assuming that strikes is Poisson distributed, it’s Probability Mass Function is as follows:
Our Poisson model has a problem. Let’s take a look at the specification of the mean again:
If the coefficient β_2 of the (strikes)_(t-1) term turns out to be greater than 0, we will face what is colorfully called the ‘model explosion’ effect, caused by a positive feedback loop from (strikes)_(t-1) to (strikes)_t. The solution is to replace (strikes)_(t-1) with its natural logarithm ln (strikes)_(t-1). But (strikes)_(t-1) is undefined when (strikes)_(t-1) is zero. We will fix that problem by doing two things:
We introduce an indicator variable d_t which is set to 1 when (strikes)_(t-1), otherwise it is set to 0, and,We set (strikes)_(t-1) to 1.0 whenever (strikes)_(t-1) is zero.
We introduce an indicator variable d_t which is set to 1 when (strikes)_(t-1), otherwise it is set to 0, and,
We set (strikes)_(t-1) to 1.0 whenever (strikes)_(t-1) is zero.
The net effect of the above two interventions is to force the optimizer to train the coefficient of d_t whenever (strikes)_(t-1) was zero in the original data set. This approach has been discussed in detail by Cameron and Trivedi in their book Regression Analysis of Count Data (See Section 7.5: Auto-regressive models).
Considering the above changes, a more robust specification of the Poisson process’s mean is as follows:
Now, let’s inject the impact of the 2-state Markov model. This causes all the regression coefficients β_cap=[β_cap_0, β_cap_1, β_cap_2, β_cap_3], and therefore the fitted mean μ_cap_t to become Markov state specific as shown below. Notice the additional subscript j that indicates the Markov state in effect at time t:
The corresponding Markov-specific Poisson probability of observing a particular count of strikes at time t given that the Markov state variable s_t is in state j at time t is as follows:
Where, the Markov state transition matrix P is:
And the Markov state probability vector containing the state-wise probability distribution at time t is as follows:
With the above discussion in context, let’s restate the exogenous and endogenous variables of our Poisson Hidden Markov Model for the strikes data set:
y = strikes
X = [output, ln (strikes_LAG_1), d_t] and P
Training the Poisson PMM involves optimizing the Markov-state dependent matrix of regression coefficients (Note that in the Python code, we’ll work with the transpose of this matrix):
And also optimizing the state transition probabilities (the P matrix):
Optimization will be done via Maximum Likelihood Estimation where the optimizer will find the values of β and P which will maximize the likelihood of observing y. We will use the BFGS optimizer supplied by statsmodels to perform the optimization.
There is a little wrinkle that we need to smooth out. All throughout the optimization process, the Markov state transition probabilities p_ij need to obey the following constraints which say that all transition probabilities lie in the [0,1] interval and the probabilities across any row of P always sum to 1:
During optimization, we tackle these constraints by defining a matrix Q of size (k x k) that acts as a proxy for P as follows:
Instead of optimizing P, we will optimize Q by allowing q_ij to range freely from -∞ to +∞. In each optimization iteration, we obtain p_ij by standardizing the q values to the interval [0.0, 1.0], as follows:
With that, let’s circle back to our strikes data set.
We saw that in the strikes time series, there is a strong correlation at lag-1, add the lag-1 copy of strikes as a regression variable.
strikes_data['strikes_lag1'] = strikes_data['strikes'].shift(1)#Drop rows with empty cells created by the shift operationstrikes_data = strikes_data.dropna()
Create the indicator function for calculating the value of the indicator variable d1 as follows: if strikes == 0, d1 = 1, else d1 = 0.
def indicator_func(x): if x == 0: return 1 else: return 0
Add the column for d1 into the Dataframe:
strikes_data['d1'] = strikes_data['strikes_lag1'].apply(indicator_func)
Adjust the lagged strikes variable so that it is set to 1, when its value is 0.
strikes_data['strikes_adj_lag1'] = np.maximum(1, strikes_data['strikes_lag1'])
Add the natural log of strikes_lag1 as a regression variable.
strikes_data['ln_strikes_adj_lag1'] = np.log(strikes_data['strikes_adj_lag1'])
Form the regression expression in Patsy syntax. There is no need to explicitly specify the regression intercept β_0. Patsy will automatically include a placeholder for it in X.
expr = 'strikes ~ output + ln_strikes_adj_lag1 + d1'
Use Patsy to carve out the y and X matrices.
y_train, X_train = dmatrices(expr, strikes_data, return_type='dataframe')
Let’s look at how our X and y matrices have turned out:
print(y_train)
print(X_train)
Before we get any further, we need to build the PoissonHMM class. For that we will use the statsmodels provided class GenericLikelihoodModel.
The PoissonHMM class that we will create, will extend the GenericLikelihoodModel class so that we can train the model using a custom log-likelihood function. Let’s start by defining the constructor of the PoissonHMM class.
class PoissonHMM(GenericLikelihoodModel): def __init__(self, endog, exog, k_regimes=2, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds): super(PoissonHMM, self).__init__(endog=endog, exog=exog, loglike=loglike, score=score, hessian=hessian, missing=missing, extra_params_names=extra_params_names, kwds=kwds)
Now, let’s fill in the constructor i.e. the __init__ method of PoissonHMM with the following lines of code:
First, we’ll cast the dependent variable into a numpy array which statsmodels likes to work with. We’ll also copy over the number of regimes.
self.y = np.array(self.endog)self.k_regimes = k_regimes
Next, set the k x m size matrix of regime specific regression coefficients β. m=self.exog.shape[1] being the number of regression coefficients including the intercept:
self.beta_matrix = np.ones([self.k_regimes, self.exog.shape[1]])
Set the k x k matrix of proxy transition probabilities matrix Q. Initialize it to 1.0/k.
self.q_matrix = np.ones([self.k_regimes,self.k_regimes])*(1.0/self.k_regimes)print('self.q_matrix='+str(self.q_matrix))
Set the regime wise matrix of Poisson means. These would be updated during the optimization loop.
self.mu_matrix = []
Set the k x k matrix of the real Markov transition probabilities which will be calculated from the q-matrix using the standardization technique described earlier. Initialized to 1.0/k.
self.gamma_matrix = np.ones([self.k_regimes, self.k_regimes])*(1.0/self.k_regimes)print('self.gamma_matrix='+str(self.gamma_matrix))
Set the Markov state probabilities (the π vector). But to avoid confusion with the regression model’s mean value which is also referred to as π, we will follow the convention used in Cameron and Trivedi and use the notation δ.
self.delta_matrix = np.ones([self.exog.shape[0],self.k_regimes])*(1.0/self.k_regimes)print('self.delta_matrix='+str(self.delta_matrix))
Initialize the vector of initial values for the parameters β and Q that the optimizer will optimize.
self.start_params = np.repeat(np.ones(self.exog.shape[1]), repeats=self.k_regimes)self.start_params = np.append(self.start_params, self.q_matrix.flatten())print('self.start_params='+str(self.start_params))
Initialize a very tiny number that is machine specific. It is used by our custom Loglikelihood function which we will soon write.
self.EPS = np.MachAr().eps
Finally, initialize the optimizer’s iteration counter.
self.iter_num=0
The completed constructor of the PoissonHMM class looks like this:
Next, we will override the nloglikeobs(self, params) method of GenericLikelihoodModel. This method is called by the optimizer once in each iteration to get the current value of the loglikelihood function corresponding to the current values of all the params that are passed into it.
def nloglikeobs(self, params):
Let’s fill in this method with the following functions which we will define soon:
Reconstitute the Q and β matrices from the current values of all the params.
self.reconstitute_parameter_matrices(params)
Build the regime wise matrix of Poisson means.
self.compute_regime_specific_poisson_means()
Build the matrix of Markov transition probabilities by standardizing all the Q values to the 0 to 1 range.
self.compute_markov_transition_probabilities()
Build the (len(y) x k) matrix delta of Markov state probabilities distribution.
self.compute_markov_state_probabilities()
Compute the log-likelihood value for each observation. This function returns an array of size len(y) of loglikelihood values.
ll = self.compute_loglikelihood()
Increment the iteration count.
self.iter_num=self.iter_num+1
Print out the iteration summary.
print('ITER='+str(self.iter_num) + ' ll='+str(((-ll).sum(0)))
Finally, return the negated loglikelihood array.
return -ll
Here’s the entire nloglikeobs(self, params) method:
And following are the implementations of the helper methods called from the nloglikeobs(self, params) method:
Reconstitute the Q and β matrices from the current values of all the params:
Build the regime wise matrix of Poisson means:
Build the matrix of Markov transition probabilities P by standardizing all the Q values to the 0 to 1 range:
Build the (len(y) x k) size δ matrix of Markov state probabilities distribution.
Finally, compute all the log-likelihood values for the Poisson Markov model:
Let’s also override a method from the super class that tries its best to compute an invertible Hessian so that the standard errors and confidence intervals of all the trained parameters can be computed successfully.
def hessian(self, params): for approx_hess_func in [approx_hess3, approx_hess2, approx_hess1]: H = approx_hess_func(x=params, f=self.loglike, epsilon=self.EPS) if np.linalg.cond(H) < 1 / self.EPS: print('Found invertible hessian using' + str(approx_hess_func)) return H print('DID NOT find invertible hessian') H[H == 0.0] = self.EPS return H
Bringing it all together, here is the complete class definition of the PoissonHMM class:
Now that we have our custom PoissonHMM class in place, let’s get on with the task of training it on our (y_train, X_train) dataset of manufacturing strikes that we had carved out using Patsy.
Let’s recall how the constructor of PoissonHMM looks like:
def __init__(self, endog, exog, k_regimes=2, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds):
We’ll experiment with a 2-state HMM with the consequent assumption that the data cycles through 2 distinct but hidden regimes, each one of which influences the mean of the Poisson process. So we set k_regimes to 2:
k_regimes = 2
Notice that PoissonHMM takes an extra_param_names parameter. This is a list of parameters that we want the optimizer to optimize in addition to the column names of the X_train matrix. Let’s initialize and build this list of extra param names.
extra_params_names = []
There will len(X_train.columns) number of regression coefficients per regime to be sent into the model for optimization. So, in total, len(X_train.columns) * k_regimes β coefficients in all to be optimized. Out of which, the coefficients corresponding to one regime (say regime 1) are already baked into X_train in the form of the regression parameters. statsmodels will glean out their names from the X_train matrix. And it will automatically supply the names of this set of params to the model. So, we need to tell statsmodels the names of the remaining set of params via the extra_param_names parameter (hence the name extra_param_names), corresponding to the remaining regimes. Therefore, we insert the balance set of params for the 2nd regime into extra_param_names as follows:
for regime_num in range(1, k_regimes): for param_name in X_train.columns: extra_params_names.append(param_name+'_R'+str(regime_num))
The model will also optimize the k x k matrix of proxy transition probabilities: the Q matrix. So send those too into the extra_params list:
for i in range(k_regimes): for j in range(k_regimes): extra_params_names.append('q'+str(i)+str(j))
Note: In the Python code, we have chosen to work with 0 based indices for the Markov states. i.e. what we were referring to as state 1 is state 0 in the code.
Our list of extra_param_names is now ready.
Create an instance of the PoissonHMM model class.
poisson_hmm = PoissonHMM(endog=y_train, exog=X_train, k_regimes=k_regimes, extra_params_names=extra_params_names)
Train the model. Notice that we are asking statsmodels to use the BFGS optimizer.
poisson_hmm_results = poisson_hmm.fit(method=’bfgs’, maxiter=1000)
Print out the fitted Markov transition probabilities:
print(poisson_hmm.gamma_matrix)
We see the following output:
[[0.96884629 0.03115371] [0.0043594 0.9956406 ]]
Thus, our Markov state transition matrix P is as follows:
Which corresponds to the following state transition diagram:
The state transition diagram shows that once the system gets into state 1 or 2, it really likes to be in that state and shows very little inclination to switch to the other state.
Finally, print out the model training summary:
print(poisson_hmm_results.summary())
We see the following output. I have called out the model’s parameters corresponding to the two Markov states 1 and 2, and the Q-matrix values (which happen to 0 indexed as noted earlier).
Here are a few things we observe in the output:
The model fits to a different intercept in each one of the two Markov regimes. The intercept (β_0) is 2.2891 and 0.7355 in regimes 1 and 2 respectively.The effect of output (β_1) is -2.6620 in regime 1 indicating an inverse relationship between the growth of manufacturing output and number of strikes, and it is 7.6534 in regime 2 indicating as manufacturing output increases, so dothe incidence of strikes.
The model fits to a different intercept in each one of the two Markov regimes. The intercept (β_0) is 2.2891 and 0.7355 in regimes 1 and 2 respectively.
The effect of output (β_1) is -2.6620 in regime 1 indicating an inverse relationship between the growth of manufacturing output and number of strikes, and it is 7.6534 in regime 2 indicating as manufacturing output increases, so dothe incidence of strikes.
As we can see from the model training summary, the fit isn’t exactly fantastic as evidenced by the model’s inability to find valid standard errors for β_01 and q_11. And the params β_31, β_22, β_32 and q_01 are found to be not statistically significant as evidenced by their p-values.
Nevertheless, it is a good start.
To achieve a better fit, we may want to experiment with a 3 or 4 state Markov process and also experiment with another one of the large variety of optimizers supplied by statsmodels, such as ‘nm’ (Newton-Raphson), ‘powell’ and ‘basinhopping’.
Incidentally, since we are using the out-of-the-box method from statsmodels for printing the training summary, the df_model value of 3 printed in the training summary is misleading and should be ignored.
Lastly, it would be instructive to compare the goodness-of-fit of this model with that of the Poisson Auto-regressive model described here, and the Poisson INAR(1) model described here. All three models were fitted on the same manufacturing strikes data set:
We can see that even after accounting for the much larger number of fitted parameters used by the Poisson HMM, the Poisson HMM model produces a much higher likelihood of observing the strikes data set values, than the other two kinds of time series models.
Here are some ways to build upon our work on the Poisson HMM:
We could try to improve the fit of the PoissonHMM model class using a different optimizer and/or by introducing one more Markov state.We may want to calculate the pseudo-R-squared of the PoissonHMM class. The pseudo-R-squared provides an excellent way of comparing the goodness-of-fit of nonlinear models such as Poisson-HMM that are fitted on heteroskedastic datasets.Recollect that the Poisson model we have used assumes that the variance of strikes with any Markov regime is the same as mean value of strikes in that regime — a property kown as equidispersion. We can indirectly test this assumption by replacing the Poisson model with a Generalized Poisson or a Negative Binomial regression model. These models do not make the equidispersion assumption about the data. If a GP-HMM or an NB-HMM generates a better goodness-of-fit than the straight up Poisson-HMM, it makes a case for using those models.
We could try to improve the fit of the PoissonHMM model class using a different optimizer and/or by introducing one more Markov state.
We may want to calculate the pseudo-R-squared of the PoissonHMM class. The pseudo-R-squared provides an excellent way of comparing the goodness-of-fit of nonlinear models such as Poisson-HMM that are fitted on heteroskedastic datasets.
Recollect that the Poisson model we have used assumes that the variance of strikes with any Markov regime is the same as mean value of strikes in that regime — a property kown as equidispersion. We can indirectly test this assumption by replacing the Poisson model with a Generalized Poisson or a Negative Binomial regression model. These models do not make the equidispersion assumption about the data. If a GP-HMM or an NB-HMM generates a better goodness-of-fit than the straight up Poisson-HMM, it makes a case for using those models.
Happy modeling!
Here is the complete source code:
Cameron A. Colin, Trivedi Pravin K., Regression Analysis of Count Data, Econometric Society Monograph No30, Cambridge University Press, 1998. ISBN: 0521635675
Kennan J., The duration of contract strikes in U.S. manufacturing, Journal of Econometrics, Volume 28, Issue 1, 1985, Pages 5–28, ISSN 0304–4076, https://doi.org/10.1016/0304-4076(85)90064-8. PDF download link
Cameron C. A., Trivedi P. K., Regression-based tests for overdispersion in the Poisson model, Journal of Econometrics, Volume 46, Issue 3, 1990, Pages 347–364, ISSN 0304–4076, https://doi.org/10.1016/0304-4076(90)90014-K.
The Manufacturing strikes data set used in article is one of several data sets available for public use and experimentation in statistical software, most notably, over here as an R package. The data set has been made accessible for use in Python by Vincent Arel-Bundock via vincentarelbundock.github.io/rdatasets under a GPL v3 license.
All images in this article are copyright Sachin Date under CC-BY-NC-SA, unless a different source and copyright are mentioned underneath the image.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Thanks for reading! If you liked this article, please follow me to receive tips, how-tos and programming advice on regression and time series analysis.
Some rights reserved
|
[
{
"code": null,
"e": 531,
"s": 171,
"text": "A Poisson Hidden Markov Model is a mixture of two regression models: A Poisson regression model which is visible and a Markov model which is ‘hidden’. In a Poisson HMM, the mean value predicted by the Poisson model depends on not only the regression variables of the Poisson model, but also on the current state or regime that the hidden Markov process is in."
},
{
"code": null,
"e": 759,
"s": 531,
"text": "In an earlier article, we looked at the architecture of the Poisson Hidden Markov Model and we inspected its theoretical underpinnings. If you are new to Markov Models or the Poisson HMM, I will encourage you to review it here:"
},
{
"code": null,
"e": 782,
"s": 759,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1042,
"s": 782,
"text": "In this article, we will walk through a step by step tutorial in Python and statsmodels for building and training a Poisson HMM on the real world data set of labor strikes in US manufacturing that is used extensively in the literature on statistical modeling."
},
{
"code": null,
"e": 1133,
"s": 1042,
"text": "To illustrate the model fitting procedure, we will use the following open source data set:"
},
{
"code": null,
"e": 1390,
"s": 1133,
"text": "The data set is a monthly time series showing the relationship between U.S. manufacturing activity measured as a departure from the trend line, and the number of contract strikes in U.S. manufacturing industries beginning each month from 1968 through 1976."
},
{
"code": null,
"e": 1491,
"s": 1390,
"text": "This data set is available in R and it can be fetched using the Python statsmodels Datasets package."
},
{
"code": null,
"e": 1540,
"s": 1491,
"text": "The tutorial in this article uses Python, not R."
},
{
"code": null,
"e": 1805,
"s": 1540,
"text": "Our goal is to investigate the effect of manufacturing output (the output variable) on the incidence of manufacturing strikes (the strikes variable). In other words, does the variance in manufacturing output ‘explain’ the variance in the number of monthly strikes?"
},
{
"code": null,
"e": 1940,
"s": 1805,
"text": "Let’s import all the required packages, load the strikes data set into a Pandas DaraFrame, and inspect a plot of strikes against time:"
},
{
"code": null,
"e": 2572,
"s": 1940,
"text": "import mathimport numpy as npimport statsmodels.api as smfrom statsmodels.base.model import GenericLikelihoodModelfrom scipy.stats import poissonfrom patsy import dmatricesimport statsmodels.graphics.tsaplots as tsafrom matplotlib import pyplot as pltfrom statsmodels.tools.numdiff import approx_hess1, approx_hess2, approx_hess3#Download the data set and load it into a Pandas Dataframestrikes_dataset = sm.datasets.get_rdataset(dataname='StrikeNb', package='Ecdat')#Plot the number of strikes starting each monthplt.xlabel('Month index')plt.ylabel('Number of strikes beginning each month')strikes_data['strikes'].plot()plt.show()"
},
{
"code": null,
"e": 2599,
"s": 2572,
"text": "We see the following plot:"
},
{
"code": null,
"e": 2773,
"s": 2599,
"text": "The up-down whipsaw pattern of strikes suggests that the time series may be auto-correlated. Let’s verify this by looking at the auto-correlation plot of the strikes column:"
},
{
"code": null,
"e": 2833,
"s": 2773,
"text": "tsa.plot_acf(strikes_data['strikes'], alpha=0.05)plt.show()"
},
{
"code": null,
"e": 2860,
"s": 2833,
"text": "We see the following plot:"
},
{
"code": null,
"e": 3180,
"s": 2860,
"text": "The perfect correlation at lag 0 is to be ignored as a value is always perfectly correlated with itself. There is a strong correlation at lag-1. The correlations at lags 2 and 3 are likely to be a domino effect of the correlation at lag 1. This can be confirmed by plotting the partial auto-correlation plot of strikes."
},
{
"code": null,
"e": 3241,
"s": 3180,
"text": "tsa.plot_pacf(strikes_data['strikes'], alpha=0.05)plt.show()"
},
{
"code": null,
"e": 3298,
"s": 3241,
"text": "The partial auto-correlation plot reveals the following:"
},
{
"code": null,
"e": 3381,
"s": 3298,
"text": "The partial auto-correlation is 1.0 at LAG-0. This is expected, and to be ignored."
},
{
"code": null,
"e": 3478,
"s": 3381,
"text": "The PACF plot shows a strong partial auto-correlation at LAG-1, which suggests an AR(1) process."
},
{
"code": null,
"e": 3585,
"s": 3478,
"text": "The correlation at LAG-2 is just outside the 5% significance bounds. So, it may or may not be significant."
},
{
"code": null,
"e": 3816,
"s": 3585,
"text": "On the whole, the ACF and PACF plots indicate a definite, and strong auto-regressive influence at LAG-1. Hence, in addition to the output variable, we should include the lagged version of strikes at LAG-1 as a regression variable."
},
{
"code": null,
"e": 3931,
"s": 3816,
"text": "Our strategy will be based upon regressing strikes on both output and on the time-lagged copy of strikes at lag-1."
},
{
"code": null,
"e": 4068,
"s": 3931,
"text": "Since strikes contains whole numbered data, we will use a Poisson regression model to study the relationship between output and strikes."
},
{
"code": null,
"e": 4248,
"s": 4068,
"text": "We will additional hypothesize that the manufacturing strikes data cycles between periods of low and high variability which can be modeled using a 2-state discrete Markov process."
},
{
"code": null,
"e": 4453,
"s": 4248,
"text": "Why did we choose only 2 regimes for the Markov model? Why not 3 or 4 regimes? The answer is simply that it is best to start with a Markov model with the least possible states so as to avoid over-fitting."
},
{
"code": null,
"e": 4577,
"s": 4453,
"text": "In summary, we will use a 2-state Poisson Hidden Markov Model to study the relationship of manufacturing output on strikes."
},
{
"code": null,
"e": 4597,
"s": 4577,
"text": "Therefore, we have:"
},
{
"code": null,
"e": 4609,
"s": 4597,
"text": "y = strikes"
},
{
"code": null,
"e": 4706,
"s": 4609,
"text": "X = [output, strikes_LAG_1] + Hidden Markov model related variables which we will soon describe."
},
{
"code": null,
"e": 4808,
"s": 4706,
"text": "We’ll first spec-out the Poisson portion of the model, and then see how to ‘mix-in’ the Markov model."
},
{
"code": null,
"e": 4915,
"s": 4808,
"text": "The Poisson model’s mean (without considering the effect of the Markov model) can be expressed as follows:"
},
{
"code": null,
"e": 5020,
"s": 4915,
"text": "Since we are assuming that strikes is Poisson distributed, it’s Probability Mass Function is as follows:"
},
{
"code": null,
"e": 5111,
"s": 5020,
"text": "Our Poisson model has a problem. Let’s take a look at the specification of the mean again:"
},
{
"code": null,
"e": 5534,
"s": 5111,
"text": "If the coefficient β_2 of the (strikes)_(t-1) term turns out to be greater than 0, we will face what is colorfully called the ‘model explosion’ effect, caused by a positive feedback loop from (strikes)_(t-1) to (strikes)_t. The solution is to replace (strikes)_(t-1) with its natural logarithm ln (strikes)_(t-1). But (strikes)_(t-1) is undefined when (strikes)_(t-1) is zero. We will fix that problem by doing two things:"
},
{
"code": null,
"e": 5707,
"s": 5534,
"text": "We introduce an indicator variable d_t which is set to 1 when (strikes)_(t-1), otherwise it is set to 0, and,We set (strikes)_(t-1) to 1.0 whenever (strikes)_(t-1) is zero."
},
{
"code": null,
"e": 5817,
"s": 5707,
"text": "We introduce an indicator variable d_t which is set to 1 when (strikes)_(t-1), otherwise it is set to 0, and,"
},
{
"code": null,
"e": 5881,
"s": 5817,
"text": "We set (strikes)_(t-1) to 1.0 whenever (strikes)_(t-1) is zero."
},
{
"code": null,
"e": 6202,
"s": 5881,
"text": "The net effect of the above two interventions is to force the optimizer to train the coefficient of d_t whenever (strikes)_(t-1) was zero in the original data set. This approach has been discussed in detail by Cameron and Trivedi in their book Regression Analysis of Count Data (See Section 7.5: Auto-regressive models)."
},
{
"code": null,
"e": 6306,
"s": 6202,
"text": "Considering the above changes, a more robust specification of the Poisson process’s mean is as follows:"
},
{
"code": null,
"e": 6625,
"s": 6306,
"text": "Now, let’s inject the impact of the 2-state Markov model. This causes all the regression coefficients β_cap=[β_cap_0, β_cap_1, β_cap_2, β_cap_3], and therefore the fitted mean μ_cap_t to become Markov state specific as shown below. Notice the additional subscript j that indicates the Markov state in effect at time t:"
},
{
"code": null,
"e": 6812,
"s": 6625,
"text": "The corresponding Markov-specific Poisson probability of observing a particular count of strikes at time t given that the Markov state variable s_t is in state j at time t is as follows:"
},
{
"code": null,
"e": 6860,
"s": 6812,
"text": "Where, the Markov state transition matrix P is:"
},
{
"code": null,
"e": 6976,
"s": 6860,
"text": "And the Markov state probability vector containing the state-wise probability distribution at time t is as follows:"
},
{
"code": null,
"e": 7128,
"s": 6976,
"text": "With the above discussion in context, let’s restate the exogenous and endogenous variables of our Poisson Hidden Markov Model for the strikes data set:"
},
{
"code": null,
"e": 7140,
"s": 7128,
"text": "y = strikes"
},
{
"code": null,
"e": 7184,
"s": 7140,
"text": "X = [output, ln (strikes_LAG_1), d_t] and P"
},
{
"code": null,
"e": 7368,
"s": 7184,
"text": "Training the Poisson PMM involves optimizing the Markov-state dependent matrix of regression coefficients (Note that in the Python code, we’ll work with the transpose of this matrix):"
},
{
"code": null,
"e": 7439,
"s": 7368,
"text": "And also optimizing the state transition probabilities (the P matrix):"
},
{
"code": null,
"e": 7686,
"s": 7439,
"text": "Optimization will be done via Maximum Likelihood Estimation where the optimizer will find the values of β and P which will maximize the likelihood of observing y. We will use the BFGS optimizer supplied by statsmodels to perform the optimization."
},
{
"code": null,
"e": 7996,
"s": 7686,
"text": "There is a little wrinkle that we need to smooth out. All throughout the optimization process, the Markov state transition probabilities p_ij need to obey the following constraints which say that all transition probabilities lie in the [0,1] interval and the probabilities across any row of P always sum to 1:"
},
{
"code": null,
"e": 8123,
"s": 7996,
"text": "During optimization, we tackle these constraints by defining a matrix Q of size (k x k) that acts as a proxy for P as follows:"
},
{
"code": null,
"e": 8332,
"s": 8123,
"text": "Instead of optimizing P, we will optimize Q by allowing q_ij to range freely from -∞ to +∞. In each optimization iteration, we obtain p_ij by standardizing the q values to the interval [0.0, 1.0], as follows:"
},
{
"code": null,
"e": 8386,
"s": 8332,
"text": "With that, let’s circle back to our strikes data set."
},
{
"code": null,
"e": 8522,
"s": 8386,
"text": "We saw that in the strikes time series, there is a strong correlation at lag-1, add the lag-1 copy of strikes as a regression variable."
},
{
"code": null,
"e": 8680,
"s": 8522,
"text": "strikes_data['strikes_lag1'] = strikes_data['strikes'].shift(1)#Drop rows with empty cells created by the shift operationstrikes_data = strikes_data.dropna()"
},
{
"code": null,
"e": 8815,
"s": 8680,
"text": "Create the indicator function for calculating the value of the indicator variable d1 as follows: if strikes == 0, d1 = 1, else d1 = 0."
},
{
"code": null,
"e": 8893,
"s": 8815,
"text": "def indicator_func(x): if x == 0: return 1 else: return 0"
},
{
"code": null,
"e": 8935,
"s": 8893,
"text": "Add the column for d1 into the Dataframe:"
},
{
"code": null,
"e": 9007,
"s": 8935,
"text": "strikes_data['d1'] = strikes_data['strikes_lag1'].apply(indicator_func)"
},
{
"code": null,
"e": 9087,
"s": 9007,
"text": "Adjust the lagged strikes variable so that it is set to 1, when its value is 0."
},
{
"code": null,
"e": 9166,
"s": 9087,
"text": "strikes_data['strikes_adj_lag1'] = np.maximum(1, strikes_data['strikes_lag1'])"
},
{
"code": null,
"e": 9228,
"s": 9166,
"text": "Add the natural log of strikes_lag1 as a regression variable."
},
{
"code": null,
"e": 9307,
"s": 9228,
"text": "strikes_data['ln_strikes_adj_lag1'] = np.log(strikes_data['strikes_adj_lag1'])"
},
{
"code": null,
"e": 9484,
"s": 9307,
"text": "Form the regression expression in Patsy syntax. There is no need to explicitly specify the regression intercept β_0. Patsy will automatically include a placeholder for it in X."
},
{
"code": null,
"e": 9537,
"s": 9484,
"text": "expr = 'strikes ~ output + ln_strikes_adj_lag1 + d1'"
},
{
"code": null,
"e": 9582,
"s": 9537,
"text": "Use Patsy to carve out the y and X matrices."
},
{
"code": null,
"e": 9656,
"s": 9582,
"text": "y_train, X_train = dmatrices(expr, strikes_data, return_type='dataframe')"
},
{
"code": null,
"e": 9712,
"s": 9656,
"text": "Let’s look at how our X and y matrices have turned out:"
},
{
"code": null,
"e": 9727,
"s": 9712,
"text": "print(y_train)"
},
{
"code": null,
"e": 9742,
"s": 9727,
"text": "print(X_train)"
},
{
"code": null,
"e": 9884,
"s": 9742,
"text": "Before we get any further, we need to build the PoissonHMM class. For that we will use the statsmodels provided class GenericLikelihoodModel."
},
{
"code": null,
"e": 10107,
"s": 9884,
"text": "The PoissonHMM class that we will create, will extend the GenericLikelihoodModel class so that we can train the model using a custom log-likelihood function. Let’s start by defining the constructor of the PoissonHMM class."
},
{
"code": null,
"e": 10534,
"s": 10107,
"text": "class PoissonHMM(GenericLikelihoodModel): def __init__(self, endog, exog, k_regimes=2, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds): super(PoissonHMM, self).__init__(endog=endog, exog=exog, loglike=loglike, score=score, hessian=hessian, missing=missing, extra_params_names=extra_params_names, kwds=kwds)"
},
{
"code": null,
"e": 10642,
"s": 10534,
"text": "Now, let’s fill in the constructor i.e. the __init__ method of PoissonHMM with the following lines of code:"
},
{
"code": null,
"e": 10784,
"s": 10642,
"text": "First, we’ll cast the dependent variable into a numpy array which statsmodels likes to work with. We’ll also copy over the number of regimes."
},
{
"code": null,
"e": 10840,
"s": 10784,
"text": "self.y = np.array(self.endog)self.k_regimes = k_regimes"
},
{
"code": null,
"e": 11008,
"s": 10840,
"text": "Next, set the k x m size matrix of regime specific regression coefficients β. m=self.exog.shape[1] being the number of regression coefficients including the intercept:"
},
{
"code": null,
"e": 11073,
"s": 11008,
"text": "self.beta_matrix = np.ones([self.k_regimes, self.exog.shape[1]])"
},
{
"code": null,
"e": 11162,
"s": 11073,
"text": "Set the k x k matrix of proxy transition probabilities matrix Q. Initialize it to 1.0/k."
},
{
"code": null,
"e": 11282,
"s": 11162,
"text": "self.q_matrix = np.ones([self.k_regimes,self.k_regimes])*(1.0/self.k_regimes)print('self.q_matrix='+str(self.q_matrix))"
},
{
"code": null,
"e": 11380,
"s": 11282,
"text": "Set the regime wise matrix of Poisson means. These would be updated during the optimization loop."
},
{
"code": null,
"e": 11400,
"s": 11380,
"text": "self.mu_matrix = []"
},
{
"code": null,
"e": 11585,
"s": 11400,
"text": "Set the k x k matrix of the real Markov transition probabilities which will be calculated from the q-matrix using the standardization technique described earlier. Initialized to 1.0/k."
},
{
"code": null,
"e": 11718,
"s": 11585,
"text": "self.gamma_matrix = np.ones([self.k_regimes, self.k_regimes])*(1.0/self.k_regimes)print('self.gamma_matrix='+str(self.gamma_matrix))"
},
{
"code": null,
"e": 11945,
"s": 11718,
"text": "Set the Markov state probabilities (the π vector). But to avoid confusion with the regression model’s mean value which is also referred to as π, we will follow the convention used in Cameron and Trivedi and use the notation δ."
},
{
"code": null,
"e": 12081,
"s": 11945,
"text": "self.delta_matrix = np.ones([self.exog.shape[0],self.k_regimes])*(1.0/self.k_regimes)print('self.delta_matrix='+str(self.delta_matrix))"
},
{
"code": null,
"e": 12182,
"s": 12081,
"text": "Initialize the vector of initial values for the parameters β and Q that the optimizer will optimize."
},
{
"code": null,
"e": 12388,
"s": 12182,
"text": "self.start_params = np.repeat(np.ones(self.exog.shape[1]), repeats=self.k_regimes)self.start_params = np.append(self.start_params, self.q_matrix.flatten())print('self.start_params='+str(self.start_params))"
},
{
"code": null,
"e": 12518,
"s": 12388,
"text": "Initialize a very tiny number that is machine specific. It is used by our custom Loglikelihood function which we will soon write."
},
{
"code": null,
"e": 12545,
"s": 12518,
"text": "self.EPS = np.MachAr().eps"
},
{
"code": null,
"e": 12600,
"s": 12545,
"text": "Finally, initialize the optimizer’s iteration counter."
},
{
"code": null,
"e": 12616,
"s": 12600,
"text": "self.iter_num=0"
},
{
"code": null,
"e": 12683,
"s": 12616,
"text": "The completed constructor of the PoissonHMM class looks like this:"
},
{
"code": null,
"e": 12966,
"s": 12683,
"text": "Next, we will override the nloglikeobs(self, params) method of GenericLikelihoodModel. This method is called by the optimizer once in each iteration to get the current value of the loglikelihood function corresponding to the current values of all the params that are passed into it."
},
{
"code": null,
"e": 12997,
"s": 12966,
"text": "def nloglikeobs(self, params):"
},
{
"code": null,
"e": 13079,
"s": 12997,
"text": "Let’s fill in this method with the following functions which we will define soon:"
},
{
"code": null,
"e": 13156,
"s": 13079,
"text": "Reconstitute the Q and β matrices from the current values of all the params."
},
{
"code": null,
"e": 13201,
"s": 13156,
"text": "self.reconstitute_parameter_matrices(params)"
},
{
"code": null,
"e": 13248,
"s": 13201,
"text": "Build the regime wise matrix of Poisson means."
},
{
"code": null,
"e": 13293,
"s": 13248,
"text": "self.compute_regime_specific_poisson_means()"
},
{
"code": null,
"e": 13400,
"s": 13293,
"text": "Build the matrix of Markov transition probabilities by standardizing all the Q values to the 0 to 1 range."
},
{
"code": null,
"e": 13447,
"s": 13400,
"text": "self.compute_markov_transition_probabilities()"
},
{
"code": null,
"e": 13527,
"s": 13447,
"text": "Build the (len(y) x k) matrix delta of Markov state probabilities distribution."
},
{
"code": null,
"e": 13569,
"s": 13527,
"text": "self.compute_markov_state_probabilities()"
},
{
"code": null,
"e": 13695,
"s": 13569,
"text": "Compute the log-likelihood value for each observation. This function returns an array of size len(y) of loglikelihood values."
},
{
"code": null,
"e": 13729,
"s": 13695,
"text": "ll = self.compute_loglikelihood()"
},
{
"code": null,
"e": 13760,
"s": 13729,
"text": "Increment the iteration count."
},
{
"code": null,
"e": 13790,
"s": 13760,
"text": "self.iter_num=self.iter_num+1"
},
{
"code": null,
"e": 13823,
"s": 13790,
"text": "Print out the iteration summary."
},
{
"code": null,
"e": 13885,
"s": 13823,
"text": "print('ITER='+str(self.iter_num) + ' ll='+str(((-ll).sum(0)))"
},
{
"code": null,
"e": 13934,
"s": 13885,
"text": "Finally, return the negated loglikelihood array."
},
{
"code": null,
"e": 13945,
"s": 13934,
"text": "return -ll"
},
{
"code": null,
"e": 13997,
"s": 13945,
"text": "Here’s the entire nloglikeobs(self, params) method:"
},
{
"code": null,
"e": 14107,
"s": 13997,
"text": "And following are the implementations of the helper methods called from the nloglikeobs(self, params) method:"
},
{
"code": null,
"e": 14184,
"s": 14107,
"text": "Reconstitute the Q and β matrices from the current values of all the params:"
},
{
"code": null,
"e": 14231,
"s": 14184,
"text": "Build the regime wise matrix of Poisson means:"
},
{
"code": null,
"e": 14340,
"s": 14231,
"text": "Build the matrix of Markov transition probabilities P by standardizing all the Q values to the 0 to 1 range:"
},
{
"code": null,
"e": 14421,
"s": 14340,
"text": "Build the (len(y) x k) size δ matrix of Markov state probabilities distribution."
},
{
"code": null,
"e": 14498,
"s": 14421,
"text": "Finally, compute all the log-likelihood values for the Poisson Markov model:"
},
{
"code": null,
"e": 14714,
"s": 14498,
"text": "Let’s also override a method from the super class that tries its best to compute an invertible Hessian so that the standard errors and confidence intervals of all the trained parameters can be computed successfully."
},
{
"code": null,
"e": 15161,
"s": 14714,
"text": "def hessian(self, params): for approx_hess_func in [approx_hess3, approx_hess2, approx_hess1]: H = approx_hess_func(x=params, f=self.loglike, epsilon=self.EPS) if np.linalg.cond(H) < 1 / self.EPS: print('Found invertible hessian using' + str(approx_hess_func)) return H print('DID NOT find invertible hessian') H[H == 0.0] = self.EPS return H"
},
{
"code": null,
"e": 15250,
"s": 15161,
"text": "Bringing it all together, here is the complete class definition of the PoissonHMM class:"
},
{
"code": null,
"e": 15442,
"s": 15250,
"text": "Now that we have our custom PoissonHMM class in place, let’s get on with the task of training it on our (y_train, X_train) dataset of manufacturing strikes that we had carved out using Patsy."
},
{
"code": null,
"e": 15501,
"s": 15442,
"text": "Let’s recall how the constructor of PoissonHMM looks like:"
},
{
"code": null,
"e": 15660,
"s": 15501,
"text": "def __init__(self, endog, exog, k_regimes=2, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds):"
},
{
"code": null,
"e": 15875,
"s": 15660,
"text": "We’ll experiment with a 2-state HMM with the consequent assumption that the data cycles through 2 distinct but hidden regimes, each one of which influences the mean of the Poisson process. So we set k_regimes to 2:"
},
{
"code": null,
"e": 15889,
"s": 15875,
"text": "k_regimes = 2"
},
{
"code": null,
"e": 16132,
"s": 15889,
"text": "Notice that PoissonHMM takes an extra_param_names parameter. This is a list of parameters that we want the optimizer to optimize in addition to the column names of the X_train matrix. Let’s initialize and build this list of extra param names."
},
{
"code": null,
"e": 16156,
"s": 16132,
"text": "extra_params_names = []"
},
{
"code": null,
"e": 16939,
"s": 16156,
"text": "There will len(X_train.columns) number of regression coefficients per regime to be sent into the model for optimization. So, in total, len(X_train.columns) * k_regimes β coefficients in all to be optimized. Out of which, the coefficients corresponding to one regime (say regime 1) are already baked into X_train in the form of the regression parameters. statsmodels will glean out their names from the X_train matrix. And it will automatically supply the names of this set of params to the model. So, we need to tell statsmodels the names of the remaining set of params via the extra_param_names parameter (hence the name extra_param_names), corresponding to the remaining regimes. Therefore, we insert the balance set of params for the 2nd regime into extra_param_names as follows:"
},
{
"code": null,
"e": 17082,
"s": 16939,
"text": "for regime_num in range(1, k_regimes): for param_name in X_train.columns: extra_params_names.append(param_name+'_R'+str(regime_num))"
},
{
"code": null,
"e": 17223,
"s": 17082,
"text": "The model will also optimize the k x k matrix of proxy transition probabilities: the Q matrix. So send those too into the extra_params list:"
},
{
"code": null,
"e": 17332,
"s": 17223,
"text": "for i in range(k_regimes): for j in range(k_regimes): extra_params_names.append('q'+str(i)+str(j))"
},
{
"code": null,
"e": 17491,
"s": 17332,
"text": "Note: In the Python code, we have chosen to work with 0 based indices for the Markov states. i.e. what we were referring to as state 1 is state 0 in the code."
},
{
"code": null,
"e": 17535,
"s": 17491,
"text": "Our list of extra_param_names is now ready."
},
{
"code": null,
"e": 17585,
"s": 17535,
"text": "Create an instance of the PoissonHMM model class."
},
{
"code": null,
"e": 17746,
"s": 17585,
"text": "poisson_hmm = PoissonHMM(endog=y_train, exog=X_train, k_regimes=k_regimes, extra_params_names=extra_params_names)"
},
{
"code": null,
"e": 17828,
"s": 17746,
"text": "Train the model. Notice that we are asking statsmodels to use the BFGS optimizer."
},
{
"code": null,
"e": 17895,
"s": 17828,
"text": "poisson_hmm_results = poisson_hmm.fit(method=’bfgs’, maxiter=1000)"
},
{
"code": null,
"e": 17949,
"s": 17895,
"text": "Print out the fitted Markov transition probabilities:"
},
{
"code": null,
"e": 17981,
"s": 17949,
"text": "print(poisson_hmm.gamma_matrix)"
},
{
"code": null,
"e": 18010,
"s": 17981,
"text": "We see the following output:"
},
{
"code": null,
"e": 18060,
"s": 18010,
"text": "[[0.96884629 0.03115371] [0.0043594 0.9956406 ]]"
},
{
"code": null,
"e": 18118,
"s": 18060,
"text": "Thus, our Markov state transition matrix P is as follows:"
},
{
"code": null,
"e": 18179,
"s": 18118,
"text": "Which corresponds to the following state transition diagram:"
},
{
"code": null,
"e": 18359,
"s": 18179,
"text": "The state transition diagram shows that once the system gets into state 1 or 2, it really likes to be in that state and shows very little inclination to switch to the other state."
},
{
"code": null,
"e": 18406,
"s": 18359,
"text": "Finally, print out the model training summary:"
},
{
"code": null,
"e": 18443,
"s": 18406,
"text": "print(poisson_hmm_results.summary())"
},
{
"code": null,
"e": 18631,
"s": 18443,
"text": "We see the following output. I have called out the model’s parameters corresponding to the two Markov states 1 and 2, and the Q-matrix values (which happen to 0 indexed as noted earlier)."
},
{
"code": null,
"e": 18679,
"s": 18631,
"text": "Here are a few things we observe in the output:"
},
{
"code": null,
"e": 19088,
"s": 18679,
"text": "The model fits to a different intercept in each one of the two Markov regimes. The intercept (β_0) is 2.2891 and 0.7355 in regimes 1 and 2 respectively.The effect of output (β_1) is -2.6620 in regime 1 indicating an inverse relationship between the growth of manufacturing output and number of strikes, and it is 7.6534 in regime 2 indicating as manufacturing output increases, so dothe incidence of strikes."
},
{
"code": null,
"e": 19241,
"s": 19088,
"text": "The model fits to a different intercept in each one of the two Markov regimes. The intercept (β_0) is 2.2891 and 0.7355 in regimes 1 and 2 respectively."
},
{
"code": null,
"e": 19498,
"s": 19241,
"text": "The effect of output (β_1) is -2.6620 in regime 1 indicating an inverse relationship between the growth of manufacturing output and number of strikes, and it is 7.6534 in regime 2 indicating as manufacturing output increases, so dothe incidence of strikes."
},
{
"code": null,
"e": 19783,
"s": 19498,
"text": "As we can see from the model training summary, the fit isn’t exactly fantastic as evidenced by the model’s inability to find valid standard errors for β_01 and q_11. And the params β_31, β_22, β_32 and q_01 are found to be not statistically significant as evidenced by their p-values."
},
{
"code": null,
"e": 19817,
"s": 19783,
"text": "Nevertheless, it is a good start."
},
{
"code": null,
"e": 20060,
"s": 19817,
"text": "To achieve a better fit, we may want to experiment with a 3 or 4 state Markov process and also experiment with another one of the large variety of optimizers supplied by statsmodels, such as ‘nm’ (Newton-Raphson), ‘powell’ and ‘basinhopping’."
},
{
"code": null,
"e": 20264,
"s": 20060,
"text": "Incidentally, since we are using the out-of-the-box method from statsmodels for printing the training summary, the df_model value of 3 printed in the training summary is misleading and should be ignored."
},
{
"code": null,
"e": 20523,
"s": 20264,
"text": "Lastly, it would be instructive to compare the goodness-of-fit of this model with that of the Poisson Auto-regressive model described here, and the Poisson INAR(1) model described here. All three models were fitted on the same manufacturing strikes data set:"
},
{
"code": null,
"e": 20780,
"s": 20523,
"text": "We can see that even after accounting for the much larger number of fitted parameters used by the Poisson HMM, the Poisson HMM model produces a much higher likelihood of observing the strikes data set values, than the other two kinds of time series models."
},
{
"code": null,
"e": 20842,
"s": 20780,
"text": "Here are some ways to build upon our work on the Poisson HMM:"
},
{
"code": null,
"e": 21749,
"s": 20842,
"text": "We could try to improve the fit of the PoissonHMM model class using a different optimizer and/or by introducing one more Markov state.We may want to calculate the pseudo-R-squared of the PoissonHMM class. The pseudo-R-squared provides an excellent way of comparing the goodness-of-fit of nonlinear models such as Poisson-HMM that are fitted on heteroskedastic datasets.Recollect that the Poisson model we have used assumes that the variance of strikes with any Markov regime is the same as mean value of strikes in that regime — a property kown as equidispersion. We can indirectly test this assumption by replacing the Poisson model with a Generalized Poisson or a Negative Binomial regression model. These models do not make the equidispersion assumption about the data. If a GP-HMM or an NB-HMM generates a better goodness-of-fit than the straight up Poisson-HMM, it makes a case for using those models."
},
{
"code": null,
"e": 21884,
"s": 21749,
"text": "We could try to improve the fit of the PoissonHMM model class using a different optimizer and/or by introducing one more Markov state."
},
{
"code": null,
"e": 22120,
"s": 21884,
"text": "We may want to calculate the pseudo-R-squared of the PoissonHMM class. The pseudo-R-squared provides an excellent way of comparing the goodness-of-fit of nonlinear models such as Poisson-HMM that are fitted on heteroskedastic datasets."
},
{
"code": null,
"e": 22658,
"s": 22120,
"text": "Recollect that the Poisson model we have used assumes that the variance of strikes with any Markov regime is the same as mean value of strikes in that regime — a property kown as equidispersion. We can indirectly test this assumption by replacing the Poisson model with a Generalized Poisson or a Negative Binomial regression model. These models do not make the equidispersion assumption about the data. If a GP-HMM or an NB-HMM generates a better goodness-of-fit than the straight up Poisson-HMM, it makes a case for using those models."
},
{
"code": null,
"e": 22674,
"s": 22658,
"text": "Happy modeling!"
},
{
"code": null,
"e": 22708,
"s": 22674,
"text": "Here is the complete source code:"
},
{
"code": null,
"e": 22867,
"s": 22708,
"text": "Cameron A. Colin, Trivedi Pravin K., Regression Analysis of Count Data, Econometric Society Monograph No30, Cambridge University Press, 1998. ISBN: 0521635675"
},
{
"code": null,
"e": 23077,
"s": 22867,
"text": "Kennan J., The duration of contract strikes in U.S. manufacturing, Journal of Econometrics, Volume 28, Issue 1, 1985, Pages 5–28, ISSN 0304–4076, https://doi.org/10.1016/0304-4076(85)90064-8. PDF download link"
},
{
"code": null,
"e": 23299,
"s": 23077,
"text": "Cameron C. A., Trivedi P. K., Regression-based tests for overdispersion in the Poisson model, Journal of Econometrics, Volume 46, Issue 3, 1990, Pages 347–364, ISSN 0304–4076, https://doi.org/10.1016/0304-4076(90)90014-K."
},
{
"code": null,
"e": 23636,
"s": 23299,
"text": "The Manufacturing strikes data set used in article is one of several data sets available for public use and experimentation in statistical software, most notably, over here as an R package. The data set has been made accessible for use in Python by Vincent Arel-Bundock via vincentarelbundock.github.io/rdatasets under a GPL v3 license."
},
{
"code": null,
"e": 23784,
"s": 23636,
"text": "All images in this article are copyright Sachin Date under CC-BY-NC-SA, unless a different source and copyright are mentioned underneath the image."
},
{
"code": null,
"e": 23807,
"s": 23784,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 23830,
"s": 23807,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 23853,
"s": 23830,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 24005,
"s": 23853,
"text": "Thanks for reading! If you liked this article, please follow me to receive tips, how-tos and programming advice on regression and time series analysis."
}
] |
How to set list in descending order in HTML5 ?
|
31 Mar, 2021
HTML Lists are used to create informative lists. Any list will have one or more list items. We have three types of lists in HTML.
ul: An unordered list is referred to as an ul. Simple bullets would be used to list the items.
ol: A number that is arranged in a certain order. This will list the items using various numbering schemes.
dl: A definition list. This puts the things in the same order as they will be in a dictionary.
To set reversed ordering of list items in an ordered list, we can use the reversed attribute of the <ol> element in HTML. It was introduced in HTML5 and shows the numbering in descending order.
Syntax:
<ol reversed>
<li>ListName</li>
</ol>
Example 1:
HTML
<!DOCTYPE html><html> <body> <h2>Rank in Descending order</h2> <ol reversed> <li>Kapil</li> <li>sachin</li> <li>Will</li> <li>nikhil</li> <li>Aakash</li> <li>Steve</li> <li>Rahul</li> <li>Kane</li> <li>Rohan</li> <li>John</li> </ol></body> </html>
Output:
Example 2: Using the start attribute, you can specify at what number you want the list to begin.
HTML
<!DOCTYPE html><html> <body> <h2>Rank in Descending order</h2> <ol reversed start = 23> <li>Kapil</li> <li>sachin</li> <li>Will</li> <li>nikhil</li> <li>Aakash</li> <li>Steve</li> <li>Rahul</li> <li>Kane</li> <li>Rohan</li> <li>John</li> </ol></body> </html>
Output:
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "HTML Lists are used to create informative lists. Any list will have one or more list items. We have three types of lists in HTML."
},
{
"code": null,
"e": 253,
"s": 158,
"text": "ul: An unordered list is referred to as an ul. Simple bullets would be used to list the items."
},
{
"code": null,
"e": 361,
"s": 253,
"text": "ol: A number that is arranged in a certain order. This will list the items using various numbering schemes."
},
{
"code": null,
"e": 456,
"s": 361,
"text": "dl: A definition list. This puts the things in the same order as they will be in a dictionary."
},
{
"code": null,
"e": 650,
"s": 456,
"text": "To set reversed ordering of list items in an ordered list, we can use the reversed attribute of the <ol> element in HTML. It was introduced in HTML5 and shows the numbering in descending order."
},
{
"code": null,
"e": 658,
"s": 650,
"text": "Syntax:"
},
{
"code": null,
"e": 699,
"s": 658,
"text": "<ol reversed>\n <li>ListName</li>\n </ol>"
},
{
"code": null,
"e": 710,
"s": 699,
"text": "Example 1:"
},
{
"code": null,
"e": 715,
"s": 710,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Rank in Descending order</h2> <ol reversed> <li>Kapil</li> <li>sachin</li> <li>Will</li> <li>nikhil</li> <li>Aakash</li> <li>Steve</li> <li>Rahul</li> <li>Kane</li> <li>Rohan</li> <li>John</li> </ol></body> </html>",
"e": 1000,
"s": 715,
"text": null
},
{
"code": null,
"e": 1008,
"s": 1000,
"text": "Output:"
},
{
"code": null,
"e": 1105,
"s": 1008,
"text": "Example 2: Using the start attribute, you can specify at what number you want the list to begin."
},
{
"code": null,
"e": 1110,
"s": 1105,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Rank in Descending order</h2> <ol reversed start = 23> <li>Kapil</li> <li>sachin</li> <li>Will</li> <li>nikhil</li> <li>Aakash</li> <li>Steve</li> <li>Rahul</li> <li>Kane</li> <li>Rohan</li> <li>John</li> </ol></body> </html>",
"e": 1406,
"s": 1110,
"text": null
},
{
"code": null,
"e": 1414,
"s": 1406,
"text": "Output:"
},
{
"code": null,
"e": 1430,
"s": 1414,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1445,
"s": 1430,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1455,
"s": 1445,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1462,
"s": 1455,
"text": "Picked"
},
{
"code": null,
"e": 1467,
"s": 1462,
"text": "HTML"
},
{
"code": null,
"e": 1484,
"s": 1467,
"text": "Web Technologies"
},
{
"code": null,
"e": 1489,
"s": 1484,
"text": "HTML"
}
] |
How to Detect Shapes in Images in Python using OpenCV?
|
13 Jan, 2021
Prerequisites: OpenCV
OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function to draw edges on images. A contour is an outline or a boundary of shape.
Import module
Import image
Convert it to grayscale image
Apply thresholding on image and then find out contours.
Run a loop in the range of contours and iterate through it.
In this loop draw a outline of shapes (Using drawContours() ) and find out center point of shape.
Classify the detected shape on the basis of a number of contour points it has and put the detected shape name at the center point of shape.
cv2.findContours(): Basically this method find outs all the boundary points of shape in image.
Syntax: cv2.findContours(src, contour_retrieval, contours_approximation)
Parameters:
src: input image n-dimensional (but for in our example we are going to use 2 dimensional image which is mostly preferred.)
contour_retrieval:cv.RETR_EXTERNAL:retrieves only the extreme outer contourscv.RETR_LIST:retrieves all of the contours without establishing any hierarchical relationships.cv.RETR_TREE:retrieves all of the contours and reconstructs a full hierarchy of nested contours.
cv.RETR_EXTERNAL:retrieves only the extreme outer contours
cv.RETR_LIST:retrieves all of the contours without establishing any hierarchical relationships.
cv.RETR_TREE:retrieves all of the contours and reconstructs a full hierarchy of nested contours.
contours_approximation:cv.CHAIN_APPROX_NONE: It will store all the boundary points.cv.CHAIN_APPROX_SIMPLE: It will store number of end points(eg.In case of rectangle it will store 4)
cv.CHAIN_APPROX_NONE: It will store all the boundary points.
cv.CHAIN_APPROX_SIMPLE: It will store number of end points(eg.In case of rectangle it will store 4)
Return value: list of contour points
cv2.drawContours() : This method draws a contour. It can also draw a shape if you provide boundary points.
Syntax: cv.DrawContours(src, contour, contourIndex, colour, thickness)
Parameters:
src: n dimensional image
contour: contour points it can be list.
contourIndex:-1:draw all the contours
-1:draw all the contours
To draw individual contour we can pass here index valuecolor:color valuesthickness: size of outline
color:color values
thickness: size of outline
Input:
Program:
Python3
import cv2import numpy as npfrom matplotlib import pyplot as plt # reading imageimg = cv2.imread('shapes.png') # converting image into grayscale imagegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # setting threshold of gray image_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # using a findContours() functioncontours, _ = cv2.findContours( threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) i = 0 # list for storing names of shapesfor contour in contours: # here we are ignoring first counter because # findcontour function detects whole image as shape if i == 0: i = 1 continue # cv2.approxPloyDP() function to approximate the shape approx = cv2.approxPolyDP( contour, 0.01 * cv2.arcLength(contour, True), True) # using drawContours() function cv2.drawContours(img, [contour], 0, (0, 0, 255), 5) # finding center point of shape M = cv2.moments(contour) if M['m00'] != 0.0: x = int(M['m10']/M['m00']) y = int(M['m01']/M['m00']) # putting shape name at center of each shape if len(approx) == 3: cv2.putText(img, 'Triangle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) elif len(approx) == 4: cv2.putText(img, 'Quadrilateral', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) elif len(approx) == 5: cv2.putText(img, 'Pentagon', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) elif len(approx) == 6: cv2.putText(img, 'Hexagon', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) else: cv2.putText(img, 'circle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) # displaying the image after drawing contourscv2.imshow('shapes', img) cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "Prerequisites: OpenCV"
},
{
"code": null,
"e": 451,
"s": 50,
"text": "OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function to draw edges on images. A contour is an outline or a boundary of shape."
},
{
"code": null,
"e": 465,
"s": 451,
"text": "Import module"
},
{
"code": null,
"e": 478,
"s": 465,
"text": "Import image"
},
{
"code": null,
"e": 508,
"s": 478,
"text": "Convert it to grayscale image"
},
{
"code": null,
"e": 564,
"s": 508,
"text": "Apply thresholding on image and then find out contours."
},
{
"code": null,
"e": 624,
"s": 564,
"text": "Run a loop in the range of contours and iterate through it."
},
{
"code": null,
"e": 722,
"s": 624,
"text": "In this loop draw a outline of shapes (Using drawContours() ) and find out center point of shape."
},
{
"code": null,
"e": 862,
"s": 722,
"text": "Classify the detected shape on the basis of a number of contour points it has and put the detected shape name at the center point of shape."
},
{
"code": null,
"e": 957,
"s": 862,
"text": "cv2.findContours(): Basically this method find outs all the boundary points of shape in image."
},
{
"code": null,
"e": 1030,
"s": 957,
"text": "Syntax: cv2.findContours(src, contour_retrieval, contours_approximation)"
},
{
"code": null,
"e": 1042,
"s": 1030,
"text": "Parameters:"
},
{
"code": null,
"e": 1165,
"s": 1042,
"text": "src: input image n-dimensional (but for in our example we are going to use 2 dimensional image which is mostly preferred.)"
},
{
"code": null,
"e": 1433,
"s": 1165,
"text": "contour_retrieval:cv.RETR_EXTERNAL:retrieves only the extreme outer contourscv.RETR_LIST:retrieves all of the contours without establishing any hierarchical relationships.cv.RETR_TREE:retrieves all of the contours and reconstructs a full hierarchy of nested contours."
},
{
"code": null,
"e": 1492,
"s": 1433,
"text": "cv.RETR_EXTERNAL:retrieves only the extreme outer contours"
},
{
"code": null,
"e": 1588,
"s": 1492,
"text": "cv.RETR_LIST:retrieves all of the contours without establishing any hierarchical relationships."
},
{
"code": null,
"e": 1685,
"s": 1588,
"text": "cv.RETR_TREE:retrieves all of the contours and reconstructs a full hierarchy of nested contours."
},
{
"code": null,
"e": 1868,
"s": 1685,
"text": "contours_approximation:cv.CHAIN_APPROX_NONE: It will store all the boundary points.cv.CHAIN_APPROX_SIMPLE: It will store number of end points(eg.In case of rectangle it will store 4)"
},
{
"code": null,
"e": 1929,
"s": 1868,
"text": "cv.CHAIN_APPROX_NONE: It will store all the boundary points."
},
{
"code": null,
"e": 2029,
"s": 1929,
"text": "cv.CHAIN_APPROX_SIMPLE: It will store number of end points(eg.In case of rectangle it will store 4)"
},
{
"code": null,
"e": 2066,
"s": 2029,
"text": "Return value: list of contour points"
},
{
"code": null,
"e": 2173,
"s": 2066,
"text": "cv2.drawContours() : This method draws a contour. It can also draw a shape if you provide boundary points."
},
{
"code": null,
"e": 2244,
"s": 2173,
"text": "Syntax: cv.DrawContours(src, contour, contourIndex, colour, thickness)"
},
{
"code": null,
"e": 2256,
"s": 2244,
"text": "Parameters:"
},
{
"code": null,
"e": 2281,
"s": 2256,
"text": "src: n dimensional image"
},
{
"code": null,
"e": 2321,
"s": 2281,
"text": "contour: contour points it can be list."
},
{
"code": null,
"e": 2359,
"s": 2321,
"text": "contourIndex:-1:draw all the contours"
},
{
"code": null,
"e": 2384,
"s": 2359,
"text": "-1:draw all the contours"
},
{
"code": null,
"e": 2484,
"s": 2384,
"text": "To draw individual contour we can pass here index valuecolor:color valuesthickness: size of outline"
},
{
"code": null,
"e": 2503,
"s": 2484,
"text": "color:color values"
},
{
"code": null,
"e": 2530,
"s": 2503,
"text": "thickness: size of outline"
},
{
"code": null,
"e": 2537,
"s": 2530,
"text": "Input:"
},
{
"code": null,
"e": 2546,
"s": 2537,
"text": "Program:"
},
{
"code": null,
"e": 2554,
"s": 2546,
"text": "Python3"
},
{
"code": "import cv2import numpy as npfrom matplotlib import pyplot as plt # reading imageimg = cv2.imread('shapes.png') # converting image into grayscale imagegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # setting threshold of gray image_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # using a findContours() functioncontours, _ = cv2.findContours( threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) i = 0 # list for storing names of shapesfor contour in contours: # here we are ignoring first counter because # findcontour function detects whole image as shape if i == 0: i = 1 continue # cv2.approxPloyDP() function to approximate the shape approx = cv2.approxPolyDP( contour, 0.01 * cv2.arcLength(contour, True), True) # using drawContours() function cv2.drawContours(img, [contour], 0, (0, 0, 255), 5) # finding center point of shape M = cv2.moments(contour) if M['m00'] != 0.0: x = int(M['m10']/M['m00']) y = int(M['m01']/M['m00']) # putting shape name at center of each shape if len(approx) == 3: cv2.putText(img, 'Triangle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) elif len(approx) == 4: cv2.putText(img, 'Quadrilateral', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) elif len(approx) == 5: cv2.putText(img, 'Pentagon', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) elif len(approx) == 6: cv2.putText(img, 'Hexagon', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) else: cv2.putText(img, 'circle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) # displaying the image after drawing contourscv2.imshow('shapes', img) cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 4438,
"s": 2554,
"text": null
},
{
"code": null,
"e": 4446,
"s": 4438,
"text": "Output:"
},
{
"code": null,
"e": 4453,
"s": 4446,
"text": "Picked"
},
{
"code": null,
"e": 4467,
"s": 4453,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 4474,
"s": 4467,
"text": "Python"
},
{
"code": null,
"e": 4572,
"s": 4474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4604,
"s": 4572,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4631,
"s": 4604,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4652,
"s": 4631,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4675,
"s": 4652,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4706,
"s": 4675,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4762,
"s": 4706,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4804,
"s": 4762,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4846,
"s": 4804,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4885,
"s": 4846,
"text": "Python | datetime.timedelta() function"
}
] |
numpy.roll() in Python
|
09 Mar, 2022
The numpy.roll() function rolls array elements along the specified axis. Basically what happens is that elements of the input array are being shifted. If an element is being rolled first to the last position, it is rolled back to the first position.
Syntax :
numpy.roll(array, shift, axis = None)
Parameters :
array : [array_like][array_like]Input array, whose elements we want to roll
shift : [int or int_tuple]No. of times we need to shift array elements.
If a tuple, then axis must be a tuple of the same size, and each of the given
axes is shifted
by the corresponding number.
If an int while axis is a tuple of ints, then the same value is used for all given axes.
axis : [array_like]Plane, along which we wish to roll array or shift it's elements.
Return :
Output rolled array, with the same shape as a.
Python
# Python Program illustrating# numpy.roll() method import numpy as geek array = geek.arange(12).reshape(3, 4)print("Original array : \n", array) # Rolling array; Shifting one placeprint("\nRolling with 1 shift : \n", geek.roll(array, 1)) # Rolling array; Shifting five placesprint("\nRolling with 5 shift : \n", geek.roll(array, 5)) # Rolling array; Shifting five places with 0th axisprint("\nRolling with 2 shift with 0 axis : \n", geek.roll(array, 2, axis = 0))
Output :
Original array :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Rolling with 1 shift :
[[11 0 1 2]
[ 3 4 5 6]
[ 7 8 9 10]]
Rolling with 5 shift :
[[ 7 8 9 10]
[11 0 1 2]
[ 3 4 5 6]]
Rolling with 2 shift with 0 axis :
[[ 4 5 6 7]
[ 8 9 10 11]
[ 0 1 2 3]]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.roll.htmlNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . 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.
shauryagoyal04
vinayedula
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "The numpy.roll() function rolls array elements along the specified axis. Basically what happens is that elements of the input array are being shifted. If an element is being rolled first to the last position, it is rolled back to the first position. "
},
{
"code": null,
"e": 290,
"s": 280,
"text": "Syntax : "
},
{
"code": null,
"e": 328,
"s": 290,
"text": "numpy.roll(array, shift, axis = None)"
},
{
"code": null,
"e": 342,
"s": 328,
"text": "Parameters : "
},
{
"code": null,
"e": 822,
"s": 342,
"text": "array : [array_like][array_like]Input array, whose elements we want to roll\nshift : [int or int_tuple]No. of times we need to shift array elements.\n If a tuple, then axis must be a tuple of the same size, and each of the given \n axes is shifted\n by the corresponding number. \n If an int while axis is a tuple of ints, then the same value is used for all given axes.\naxis : [array_like]Plane, along which we wish to roll array or shift it's elements."
},
{
"code": null,
"e": 832,
"s": 822,
"text": "Return : "
},
{
"code": null,
"e": 879,
"s": 832,
"text": "Output rolled array, with the same shape as a."
},
{
"code": null,
"e": 888,
"s": 881,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.roll() method import numpy as geek array = geek.arange(12).reshape(3, 4)print(\"Original array : \\n\", array) # Rolling array; Shifting one placeprint(\"\\nRolling with 1 shift : \\n\", geek.roll(array, 1)) # Rolling array; Shifting five placesprint(\"\\nRolling with 5 shift : \\n\", geek.roll(array, 5)) # Rolling array; Shifting five places with 0th axisprint(\"\\nRolling with 2 shift with 0 axis : \\n\", geek.roll(array, 2, axis = 0))",
"e": 1355,
"s": 888,
"text": null
},
{
"code": null,
"e": 1366,
"s": 1355,
"text": "Output : "
},
{
"code": null,
"e": 1659,
"s": 1366,
"text": "Original array : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nRolling with 1 shift : \n [[11 0 1 2]\n [ 3 4 5 6]\n [ 7 8 9 10]]\n\nRolling with 5 shift : \n [[ 7 8 9 10]\n [11 0 1 2]\n [ 3 4 5 6]]\n\nRolling with 2 shift with 0 axis : \n [[ 4 5 6 7]\n [ 8 9 10 11]\n [ 0 1 2 3]]"
},
{
"code": null,
"e": 2274,
"s": 1659,
"text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.roll.htmlNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . 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": 2289,
"s": 2274,
"text": "shauryagoyal04"
},
{
"code": null,
"e": 2300,
"s": 2289,
"text": "vinayedula"
},
{
"code": null,
"e": 2331,
"s": 2300,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 2344,
"s": 2331,
"text": "Python-numpy"
},
{
"code": null,
"e": 2351,
"s": 2344,
"text": "Python"
},
{
"code": null,
"e": 2449,
"s": 2351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2467,
"s": 2449,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2489,
"s": 2467,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2531,
"s": 2489,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2566,
"s": 2531,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2598,
"s": 2566,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2624,
"s": 2598,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2653,
"s": 2624,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2674,
"s": 2653,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2701,
"s": 2674,
"text": "Python Classes and Objects"
}
] |
Traits vs. Interfaces in PHP
|
05 Aug, 2019
The main difference between the Traits and Interfaces in PHP is that the Traits define the actual implementation of each method within each class, so many classes implement the same interface but having different behavior, while traits are just chunks of code injected in a class in PHP.
Traits
Traits are not interfaces at all. Traits can define both static members and static methods. It helps developers to reuse methods freely in several independent classes in different class hierarchies. Traits reduces the complexity, and avoids problems associated with multiple inheritance and Mixins. Note that PHP does not allow multiple inheritance. So Traits is used to fulfill this gap by allowing us to reuse same functionality in multiple classes.
Syntax:
<?php// A sample trait in PHPtrait namethis { function ReturnType() { } function ReturnDescription() { }}?>
Traits can not implement interfaces. A trait allow both classes to use it for common interface requirement. It supports the use of abstract methods. It enables horizontal composition of behavior to traditional inheritance. Traits are a mechanism for code reuse in single inheritance languages such as PHP. Write the same code again, to avoid this use the traits. The traits are used when multiple classes share the same functionality.
Example:
<?php// PHP program to demonstrate working// of trait.trait HelloGeeks { public function geeks() { echo 'Hello World!'; }} class Geeksforgeeks { use HelloGeeks; public function geeks() { echo 'Hello Geeks!'; }} $obj = new Geeksforgeeks();$obj->geeks();?>
Output:
Hello Geeks!
Interface
It specifies the lists of all such methods that a class must implement. Use the keyword Interface to implement interface same as a class. It can extend an interface using the extends operator. All the methods in Interface are abstract methods and can have their own constants. There is a concrete class concept which is a class that implements an interface which must implement all methods having the same names and signatures.All the methods in the interface must have a public access level.
Syntax:
<?php// A sample interface in PHPinterface MyInterface{ // function...}
No two interface can be implemented by a particular class having same method name and signatures because it give error. Also helps in multiple inheritance because a class can implement more than one interface whereas it can extend only one class. Implementations can be changed without affecting the caller of the interface.
Example:
<?php // PHP program to demonstrate working// of interface.interface MyInterface{ public function examplemethod1(); public function examplemethod2(); } class MyClass implements MyInterface{ public function examplemethod1(){ echo "ExampleMethod1 Called" . "\n"; } public function examplemethod2(){ echo "ExampleMethod2 Called". "\n"; } } $ob = new MyClass; $ob->examplemethod1(); $ob->examplemethod2(); ?>
Output:
ExampleMethod1 Called
ExampleMethod2 Called
PHP-OOP
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Aug, 2019"
},
{
"code": null,
"e": 341,
"s": 53,
"text": "The main difference between the Traits and Interfaces in PHP is that the Traits define the actual implementation of each method within each class, so many classes implement the same interface but having different behavior, while traits are just chunks of code injected in a class in PHP."
},
{
"code": null,
"e": 348,
"s": 341,
"text": "Traits"
},
{
"code": null,
"e": 800,
"s": 348,
"text": "Traits are not interfaces at all. Traits can define both static members and static methods. It helps developers to reuse methods freely in several independent classes in different class hierarchies. Traits reduces the complexity, and avoids problems associated with multiple inheritance and Mixins. Note that PHP does not allow multiple inheritance. So Traits is used to fulfill this gap by allowing us to reuse same functionality in multiple classes."
},
{
"code": null,
"e": 808,
"s": 800,
"text": "Syntax:"
},
{
"code": "<?php// A sample trait in PHPtrait namethis { function ReturnType() { } function ReturnDescription() { }}?>",
"e": 924,
"s": 808,
"text": null
},
{
"code": null,
"e": 1359,
"s": 924,
"text": "Traits can not implement interfaces. A trait allow both classes to use it for common interface requirement. It supports the use of abstract methods. It enables horizontal composition of behavior to traditional inheritance. Traits are a mechanism for code reuse in single inheritance languages such as PHP. Write the same code again, to avoid this use the traits. The traits are used when multiple classes share the same functionality."
},
{
"code": null,
"e": 1368,
"s": 1359,
"text": "Example:"
},
{
"code": "<?php// PHP program to demonstrate working// of trait.trait HelloGeeks { public function geeks() { echo 'Hello World!'; }} class Geeksforgeeks { use HelloGeeks; public function geeks() { echo 'Hello Geeks!'; }} $obj = new Geeksforgeeks();$obj->geeks();?>",
"e": 1654,
"s": 1368,
"text": null
},
{
"code": null,
"e": 1662,
"s": 1654,
"text": "Output:"
},
{
"code": null,
"e": 1675,
"s": 1662,
"text": "Hello Geeks!"
},
{
"code": null,
"e": 1685,
"s": 1675,
"text": "Interface"
},
{
"code": null,
"e": 2178,
"s": 1685,
"text": "It specifies the lists of all such methods that a class must implement. Use the keyword Interface to implement interface same as a class. It can extend an interface using the extends operator. All the methods in Interface are abstract methods and can have their own constants. There is a concrete class concept which is a class that implements an interface which must implement all methods having the same names and signatures.All the methods in the interface must have a public access level."
},
{
"code": null,
"e": 2186,
"s": 2178,
"text": "Syntax:"
},
{
"code": "<?php// A sample interface in PHPinterface MyInterface{ // function...}",
"e": 2258,
"s": 2186,
"text": null
},
{
"code": null,
"e": 2583,
"s": 2258,
"text": "No two interface can be implemented by a particular class having same method name and signatures because it give error. Also helps in multiple inheritance because a class can implement more than one interface whereas it can extend only one class. Implementations can be changed without affecting the caller of the interface."
},
{
"code": null,
"e": 2592,
"s": 2583,
"text": "Example:"
},
{
"code": "<?php // PHP program to demonstrate working// of interface.interface MyInterface{ public function examplemethod1(); public function examplemethod2(); } class MyClass implements MyInterface{ public function examplemethod1(){ echo \"ExampleMethod1 Called\" . \"\\n\"; } public function examplemethod2(){ echo \"ExampleMethod2 Called\". \"\\n\"; } } $ob = new MyClass; $ob->examplemethod1(); $ob->examplemethod2(); ?> ",
"e": 3052,
"s": 2592,
"text": null
},
{
"code": null,
"e": 3060,
"s": 3052,
"text": "Output:"
},
{
"code": null,
"e": 3105,
"s": 3060,
"text": "ExampleMethod1 Called\nExampleMethod2 Called\n"
},
{
"code": null,
"e": 3113,
"s": 3105,
"text": "PHP-OOP"
},
{
"code": null,
"e": 3120,
"s": 3113,
"text": "Picked"
},
{
"code": null,
"e": 3124,
"s": 3120,
"text": "PHP"
},
{
"code": null,
"e": 3141,
"s": 3124,
"text": "Web Technologies"
},
{
"code": null,
"e": 3145,
"s": 3141,
"text": "PHP"
}
] |
Working with forms using Express.js in Node.js
|
01 Apr, 2021
In this article, we will be working with forms using ExpressJS in NodeJS.
Using server side programming in Node.js, we can create forms where we can put certain parameters which upon filling gets stored in the database.
Setting up environment:
You can refer to this website for downloading Node.js. Along with that, we also have to keep in mind that we are working with something that involves storing of data. For that we need something that can store the information that is submitted from the user end.
We will be using MongoDB for storing up of our data submitted from the form. We should have MongoDB preinstalled in our device before proceeding further.
You can refer to this website for downloading MongoDB.
After downloading MongoDB, we have to follow some steps before going to the above implementation :
Run "mongod" command at first.
Press 'ctrl+c' and write 'echo "mongod --nojournal" > mongod'
Write 'chmod a+x mongod'
Now, set up the npm package :
npm init -y
Installing Dependencies:
Use to the following command in the terminal to install the packages at once:
npm install express body-parser mongoose ejs --save
Folder Structure:
Now let us move to the code section.
App.js
//importing dependenciesconst express = require("express")const app=express();var mongoose=require("mongoose");var bodyParser=require("body-parser"); // Calling form.js from modelsvar Form=require("./models/form"); // Connecting to databasemongoose.connect("mongodb://localhost/form",{ useNewUrlParser: true, useUnifiedTopology: true}); //middlewaresapp.set('view engine','ejs');app.use(bodyParser.urlencoded({extended:true})); //rendering form.ejsapp.get("/",function(req,res){ res.render("form");}); // form submissionapp.get('/result',(req,res)=>{ res.render('result');}); //creating formapp.post("/",function(req,res){ var username=req.body.username; var email=req.body.email; var f={username: username,email:email}; Form.create(f,function(err,newlyCreatedForm){ if(err) { console.log(err); }else{ res.redirect("/result"); } });}); // Starting the server at port 3000app.listen(3000, function() { console.log('Server running on port 3000'); });
Form.js
//Requiring mongoose packagevar mongoose=require("mongoose"); // Schemavar formSchema=new mongoose.Schema({ username : String, email : String}); module.exports=mongoose.model("Form",formSchema);
header.ejs
<!DOCTYPE html><!-- Opening HTML Tags--><html> <!-- Opening head Tags--><head> <!-- Opening head Tags--> <title>Form</title></head><!-- Opening body Tag --><body>
form.ejs
<!--Opening the ejs tags for including header file--><%- include("./partials/header") %><!-- Creating a form where action will be on "/" and the method will be "POST" --><form action="/" method="POST"> <!-- Creating the parameter Username as type= "text"--> <label>Username: </label> <input type="text" placeholder="Name" name="username"><br><br> <!-- Creating the parameter Email as type= "text"--> <label>Email: </label> <input type="email" placeholder="Email" name="email"><br><br> <!-- Creating the submit button --> <button>Submit</button></form><!--Opening the ejs tags for including footer file--><%- include("./partials/footer") %>
Output:
Upon filling the form:
Clicking on the submit button, we get redirected to the /result route.
Mongo Shell:
We can see that the information submitted by the form is stored in the database. This is how forms work in node js.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 128,
"s": 54,
"text": "In this article, we will be working with forms using ExpressJS in NodeJS."
},
{
"code": null,
"e": 274,
"s": 128,
"text": "Using server side programming in Node.js, we can create forms where we can put certain parameters which upon filling gets stored in the database."
},
{
"code": null,
"e": 298,
"s": 274,
"text": "Setting up environment:"
},
{
"code": null,
"e": 560,
"s": 298,
"text": "You can refer to this website for downloading Node.js. Along with that, we also have to keep in mind that we are working with something that involves storing of data. For that we need something that can store the information that is submitted from the user end."
},
{
"code": null,
"e": 715,
"s": 560,
"text": "We will be using MongoDB for storing up of our data submitted from the form. We should have MongoDB preinstalled in our device before proceeding further. "
},
{
"code": null,
"e": 770,
"s": 715,
"text": "You can refer to this website for downloading MongoDB."
},
{
"code": null,
"e": 869,
"s": 770,
"text": "After downloading MongoDB, we have to follow some steps before going to the above implementation :"
},
{
"code": null,
"e": 987,
"s": 869,
"text": "Run \"mongod\" command at first.\nPress 'ctrl+c' and write 'echo \"mongod --nojournal\" > mongod'\nWrite 'chmod a+x mongod'"
},
{
"code": null,
"e": 1018,
"s": 987,
"text": "Now, set up the npm package : "
},
{
"code": null,
"e": 1030,
"s": 1018,
"text": "npm init -y"
},
{
"code": null,
"e": 1055,
"s": 1030,
"text": "Installing Dependencies:"
},
{
"code": null,
"e": 1133,
"s": 1055,
"text": "Use to the following command in the terminal to install the packages at once:"
},
{
"code": null,
"e": 1185,
"s": 1133,
"text": "npm install express body-parser mongoose ejs --save"
},
{
"code": null,
"e": 1203,
"s": 1185,
"text": "Folder Structure:"
},
{
"code": null,
"e": 1240,
"s": 1203,
"text": "Now let us move to the code section."
},
{
"code": null,
"e": 1247,
"s": 1240,
"text": "App.js"
},
{
"code": "//importing dependenciesconst express = require(\"express\")const app=express();var mongoose=require(\"mongoose\");var bodyParser=require(\"body-parser\"); // Calling form.js from modelsvar Form=require(\"./models/form\"); // Connecting to databasemongoose.connect(\"mongodb://localhost/form\",{ useNewUrlParser: true, useUnifiedTopology: true}); //middlewaresapp.set('view engine','ejs');app.use(bodyParser.urlencoded({extended:true})); //rendering form.ejsapp.get(\"/\",function(req,res){ res.render(\"form\");}); // form submissionapp.get('/result',(req,res)=>{ res.render('result');}); //creating formapp.post(\"/\",function(req,res){ var username=req.body.username; var email=req.body.email; var f={username: username,email:email}; Form.create(f,function(err,newlyCreatedForm){ if(err) { console.log(err); }else{ res.redirect(\"/result\"); } });}); // Starting the server at port 3000app.listen(3000, function() { console.log('Server running on port 3000'); });",
"e": 2284,
"s": 1247,
"text": null
},
{
"code": null,
"e": 2292,
"s": 2284,
"text": "Form.js"
},
{
"code": "//Requiring mongoose packagevar mongoose=require(\"mongoose\"); // Schemavar formSchema=new mongoose.Schema({ username : String, email : String}); module.exports=mongoose.model(\"Form\",formSchema);",
"e": 2498,
"s": 2292,
"text": null
},
{
"code": null,
"e": 2509,
"s": 2498,
"text": "header.ejs"
},
{
"code": "<!DOCTYPE html><!-- Opening HTML Tags--><html> <!-- Opening head Tags--><head> <!-- Opening head Tags--> <title>Form</title></head><!-- Opening body Tag --><body>",
"e": 2681,
"s": 2509,
"text": null
},
{
"code": null,
"e": 2690,
"s": 2681,
"text": "form.ejs"
},
{
"code": "<!--Opening the ejs tags for including header file--><%- include(\"./partials/header\") %><!-- Creating a form where action will be on \"/\" and the method will be \"POST\" --><form action=\"/\" method=\"POST\"> <!-- Creating the parameter Username as type= \"text\"--> <label>Username: </label> <input type=\"text\" placeholder=\"Name\" name=\"username\"><br><br> <!-- Creating the parameter Email as type= \"text\"--> <label>Email: </label> <input type=\"email\" placeholder=\"Email\" name=\"email\"><br><br> <!-- Creating the submit button --> <button>Submit</button></form><!--Opening the ejs tags for including footer file--><%- include(\"./partials/footer\") %>",
"e": 3358,
"s": 2690,
"text": null
},
{
"code": null,
"e": 3366,
"s": 3358,
"text": "Output:"
},
{
"code": null,
"e": 3389,
"s": 3366,
"text": "Upon filling the form:"
},
{
"code": null,
"e": 3460,
"s": 3389,
"text": "Clicking on the submit button, we get redirected to the /result route."
},
{
"code": null,
"e": 3473,
"s": 3460,
"text": "Mongo Shell:"
},
{
"code": null,
"e": 3589,
"s": 3473,
"text": "We can see that the information submitted by the form is stored in the database. This is how forms work in node js."
},
{
"code": null,
"e": 3600,
"s": 3589,
"text": "Express.js"
},
{
"code": null,
"e": 3617,
"s": 3600,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 3624,
"s": 3617,
"text": "Picked"
},
{
"code": null,
"e": 3632,
"s": 3624,
"text": "Node.js"
},
{
"code": null,
"e": 3649,
"s": 3632,
"text": "Web Technologies"
}
] |
Most commonly used tags in HTML
|
02 Jun, 2022
HTML contains lots of predefined tags. Some of them are described below:
Document structure tag:
HTML tag: It is the root of the HTML document which is used to specify that the document is HTML.
Syntax:
<html> Statements... </html>
Code:
html
<html> <head> <title>Title of your web page</title> </head> <body>HTML web page contents </body></html>
Output :
Head tag: The head tag is used to contain all the head elements in the HTML file. It contains the title, style, meta, ... etc tag.
Syntax:
<head> Statements... </head>
Code:
html
<head>Contains elements describing the document</head>
Output :
Body tag: It is used to define the body of an HTML document. It contains images, tables, lists, ... etc.
Syntax:
<body> Statements... </body>
Code:
html
<body>The content of your HTML page</body>
Output :
Title tag: It is used to define the title of an HTML document.
Syntax:
<title> Statements... </title>
Code:
html
<title>tab name</title>
Output :
Content container tag:
Heading tag: It is used to define the heading of an HTML document.
Syntax:
<h1> Statements... </h>
<h2> Statements... </h2>
<h3> Statements... </h3>
<h4> Statements... </h4>
<h5> Statements... </h5>
<h6> Statements... </h6>
Code:
html
<h1>Heading 1 </h1> <h2>Heading 2 </h2><h3>Heading 3 </h3><h4>Heading 4 </h4><h5>Heading 5 </h5><h6>Heading 6 </h6>
Output :
Paragraph tag: It is used to define paragraph content in an HTML document.
Syntax:
<p> Statements... </p>
Code:
html
<p>GeeksforGeeks: Computer science portal</p>
Output :
Emphasis tag: It is used to render as emphasized text.
Syntax:
<em> Statements... </em>
Code:
html
<em>GeeksforGeeks</em>
Output :
Bold tag: It is used to specify bold content in an HTML document.
Syntax:
<b> Statements... </b>
Code:
html
<b>Bold word</b>
Output :
Italic tag: It is used to write the content in italic format.
Syntax:
<i> Statements... </i>
Code:
html
<i>GeeksforGeeks</i>
Output :
Small (text) tag: It is used to set the small font size of the content.
Syntax:
<small> Statements... </small>
Code:
html
<small>Example</small>
Output :
Underline tag: It is used to set the content underline.
Syntax:
<u> Statements... </u>
Code:
html
<u>GeeksforGeeks</u>
Output :
Deleted text tag: It is used to represent deleted text. It crosses the text content.
Syntax:
<strike> Statements... </strike>
Code:
html
<strike>geeksforgeeks</strike>GeeksforGeeks
Output :
Anchor tag: It is used to link one page to another page.
Syntax:
<a href="..."> Statements... </a>
Code:
html
Visit <a href="https://www.geeksforgeeks.org/">GeeksforGeeks</a> for better experience.
Output :
List tag: It is used to list the content.
Syntax:
<li> Statements... </li>
Code:
html
<li>List item 1</li><li>List item 2</li>
Output :
Ordered List tag: It is used to list the content in a particular order.
Syntax:
<ol> Statements... </ol>
Code:
html
<ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li></ol>
Output :
Unordered List tag: It is used to list the content without order.
Syntax:
<ul> Statements... </ul>
Code:
html
<ul> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li></ul>
Output :
Comment tag: It is used to set the comment in an HTML document. It is not visible on the browser.
Syntax:
<!-- Statements... -->
Code:
html
<!--Comment section-->
Scrolling Text tag: It is used to scroll the text or image content.
Syntax:
<marquee> Statements... </marquee>
Code:
html
<marquee bgcolor="#cccccc" loop="-1"scrollamount="2" width="100%">Example Marquee</marquee>
Output :
Center tag: It is used to set the content into the center.
Syntax:
<center> Statements... </center>
Code:
html
<center>GeeksforGeeks</center>
Output :
Font tag: It is used to specify the font size, font color, and font family in an HTML document.
Syntax:
<font> Statements ... </font>
Code:
html
<font face="Times New Roman">Example</font>
Output :
Empty (Non-Container) Tags:
Line break tag: It is used to break the line.
Syntax:
<br>
Code:
html
GeeksforGeeks<br>A computer science portal
Output :
Image tag: It is used to add image elements in HTML documents.
Syntax:
<img>
Code:
html
<img src="gfg.PNG" alt="GeeksforGeeks Image">
Output :
Link tag: It is used to link the content from an external source.
Syntax:
<link>
Code:
html
<head><link rel="stylesheet" type="text/css" href="style.css"></head>
Horizontal rule tag: It is used to display the horizontal line in an HTML document.
Syntax:
<hr/>
Code:
html
<hr width="100%" size="5" />
Output :
Meta tag: It is used to specify the page description. For example last modifier, authors, ... etc.
Syntax:
<meta> Statements ... <meta>
Code:
html
<meta name="Description" content="Description of your site"><meta name="keywords" content="keywords describing your site">
Table tag: A table tag is used to create a table in an HTML document.
Syntax:
<table> Statements... </table>
Code:
html
<table border="4" cellpadding="2" cellspacing="2" width="50%"><tr> <td>Column 1</td><td>Column 2</td> </tr> </table>
Output :
Tr tag: It is used to define a row of an HTML table.
Syntax:
<tr> Statements... </tr>
Code:
html
<table> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr></table>
Output :
Th tag: It defines the header cell in a table. By default, it set the content with the bold and center property.
Syntax:
<th> Statements ... </th>
Code:
html
<table> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr></table>
Output :
Td tag: It defines the standard cell in an HTML document.
Syntax:
<td> Statements ... </td>
Code:
html
<table> <tr> <td>Cell A</td> <td>Cell B</td> </tr></table>
Output :
Input Tags:
Form tag: It is used to create an HTML form for the user.
Syntax:
<form> Statements ... </form>
Code:
html
<form action="mailto:you@yourdomain.com "> Name: <input name="Name" value="" size="80"><br> Email: <input name="Email" value="" size="80"><br> <br><center><input type="submit"></center></form>
Output :
Submit input tag: It is used to take the input from the user.
Syntax:
<input>
Code:
html
<form method=post action="/cgibin/example.cgi"><input type="text" style="color: #ffffff; font-family: Verdana; font-weight: bold; fontsize: 12px; background-color: #72a4d2;" size="10" maxlength="30"><input type="Submit" value="Submit"></form>
Output :
Dropdown option tag: It is used to select an option from a drop-down list.
Syntax:
<option> Statements ... </option>
Code:
html
<form method=post action="/cgibin/example.cgi"><center> Select an option:<select><option>option 1</option><option selected>option 2</option><option>option 3</option></form>
Output :
Radio button tag: It is used to select only one option from the given options.
Syntax:
<input>
Code:
html
<form method=post action="/cgibin/example.cgi">Select an option:<br><input type="radio" name="option"> Option 1<input type="radio" name="option" checked> Option 2<input type="radio" name="option"> Option 3
Output :
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
arorakashish0911
ysachin2314
siddharthredhu01
Kanchan_Ray
HTML-Misc
Picked
HTML
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "HTML contains lots of predefined tags. Some of them are described below: "
},
{
"code": null,
"e": 151,
"s": 126,
"text": "Document structure tag: "
},
{
"code": null,
"e": 249,
"s": 151,
"text": "HTML tag: It is the root of the HTML document which is used to specify that the document is HTML."
},
{
"code": null,
"e": 258,
"s": 249,
"text": "Syntax: "
},
{
"code": null,
"e": 287,
"s": 258,
"text": "<html> Statements... </html>"
},
{
"code": null,
"e": 294,
"s": 287,
"text": "Code: "
},
{
"code": null,
"e": 299,
"s": 294,
"text": "html"
},
{
"code": "<html> <head> <title>Title of your web page</title> </head> <body>HTML web page contents </body></html>",
"e": 419,
"s": 299,
"text": null
},
{
"code": null,
"e": 428,
"s": 419,
"text": "Output :"
},
{
"code": null,
"e": 561,
"s": 430,
"text": "Head tag: The head tag is used to contain all the head elements in the HTML file. It contains the title, style, meta, ... etc tag."
},
{
"code": null,
"e": 571,
"s": 561,
"text": "Syntax: "
},
{
"code": null,
"e": 600,
"s": 571,
"text": "<head> Statements... </head>"
},
{
"code": null,
"e": 608,
"s": 600,
"text": "Code: "
},
{
"code": null,
"e": 613,
"s": 608,
"text": "html"
},
{
"code": "<head>Contains elements describing the document</head>",
"e": 668,
"s": 613,
"text": null
},
{
"code": null,
"e": 677,
"s": 668,
"text": "Output :"
},
{
"code": null,
"e": 784,
"s": 679,
"text": "Body tag: It is used to define the body of an HTML document. It contains images, tables, lists, ... etc."
},
{
"code": null,
"e": 794,
"s": 784,
"text": "Syntax: "
},
{
"code": null,
"e": 823,
"s": 794,
"text": "<body> Statements... </body>"
},
{
"code": null,
"e": 830,
"s": 823,
"text": "Code: "
},
{
"code": null,
"e": 835,
"s": 830,
"text": "html"
},
{
"code": "<body>The content of your HTML page</body>",
"e": 878,
"s": 835,
"text": null
},
{
"code": null,
"e": 887,
"s": 878,
"text": "Output :"
},
{
"code": null,
"e": 952,
"s": 889,
"text": "Title tag: It is used to define the title of an HTML document."
},
{
"code": null,
"e": 961,
"s": 952,
"text": "Syntax: "
},
{
"code": null,
"e": 992,
"s": 961,
"text": "<title> Statements... </title>"
},
{
"code": null,
"e": 999,
"s": 992,
"text": "Code: "
},
{
"code": null,
"e": 1004,
"s": 999,
"text": "html"
},
{
"code": "<title>tab name</title>",
"e": 1028,
"s": 1004,
"text": null
},
{
"code": null,
"e": 1037,
"s": 1028,
"text": "Output :"
},
{
"code": null,
"e": 1065,
"s": 1041,
"text": "Content container tag: "
},
{
"code": null,
"e": 1133,
"s": 1065,
"text": "Heading tag: It is used to define the heading of an HTML document. "
},
{
"code": null,
"e": 1142,
"s": 1133,
"text": "Syntax: "
},
{
"code": null,
"e": 1291,
"s": 1142,
"text": "<h1> Statements... </h>\n<h2> Statements... </h2>\n<h3> Statements... </h3>\n<h4> Statements... </h4>\n<h5> Statements... </h5>\n<h6> Statements... </h6>"
},
{
"code": null,
"e": 1298,
"s": 1291,
"text": "Code: "
},
{
"code": null,
"e": 1303,
"s": 1298,
"text": "html"
},
{
"code": "<h1>Heading 1 </h1> <h2>Heading 2 </h2><h3>Heading 3 </h3><h4>Heading 4 </h4><h5>Heading 5 </h5><h6>Heading 6 </h6>",
"e": 1419,
"s": 1303,
"text": null
},
{
"code": null,
"e": 1429,
"s": 1419,
"text": "Output : "
},
{
"code": null,
"e": 1506,
"s": 1431,
"text": "Paragraph tag: It is used to define paragraph content in an HTML document."
},
{
"code": null,
"e": 1515,
"s": 1506,
"text": "Syntax: "
},
{
"code": null,
"e": 1538,
"s": 1515,
"text": "<p> Statements... </p>"
},
{
"code": null,
"e": 1545,
"s": 1538,
"text": "Code: "
},
{
"code": null,
"e": 1550,
"s": 1545,
"text": "html"
},
{
"code": "<p>GeeksforGeeks: Computer science portal</p>",
"e": 1596,
"s": 1550,
"text": null
},
{
"code": null,
"e": 1606,
"s": 1596,
"text": "Output : "
},
{
"code": null,
"e": 1663,
"s": 1608,
"text": "Emphasis tag: It is used to render as emphasized text."
},
{
"code": null,
"e": 1672,
"s": 1663,
"text": "Syntax: "
},
{
"code": null,
"e": 1697,
"s": 1672,
"text": "<em> Statements... </em>"
},
{
"code": null,
"e": 1704,
"s": 1697,
"text": "Code: "
},
{
"code": null,
"e": 1709,
"s": 1704,
"text": "html"
},
{
"code": "<em>GeeksforGeeks</em>",
"e": 1732,
"s": 1709,
"text": null
},
{
"code": null,
"e": 1741,
"s": 1732,
"text": "Output :"
},
{
"code": null,
"e": 1809,
"s": 1743,
"text": "Bold tag: It is used to specify bold content in an HTML document."
},
{
"code": null,
"e": 1818,
"s": 1809,
"text": "Syntax: "
},
{
"code": null,
"e": 1841,
"s": 1818,
"text": "<b> Statements... </b>"
},
{
"code": null,
"e": 1848,
"s": 1841,
"text": "Code: "
},
{
"code": null,
"e": 1853,
"s": 1848,
"text": "html"
},
{
"code": "<b>Bold word</b>",
"e": 1870,
"s": 1853,
"text": null
},
{
"code": null,
"e": 1879,
"s": 1870,
"text": "Output :"
},
{
"code": null,
"e": 1943,
"s": 1881,
"text": "Italic tag: It is used to write the content in italic format."
},
{
"code": null,
"e": 1952,
"s": 1943,
"text": "Syntax: "
},
{
"code": null,
"e": 1975,
"s": 1952,
"text": "<i> Statements... </i>"
},
{
"code": null,
"e": 1983,
"s": 1975,
"text": "Code: "
},
{
"code": null,
"e": 1988,
"s": 1983,
"text": "html"
},
{
"code": "<i>GeeksforGeeks</i>",
"e": 2009,
"s": 1988,
"text": null
},
{
"code": null,
"e": 2018,
"s": 2009,
"text": "Output :"
},
{
"code": null,
"e": 2092,
"s": 2020,
"text": "Small (text) tag: It is used to set the small font size of the content."
},
{
"code": null,
"e": 2101,
"s": 2092,
"text": "Syntax: "
},
{
"code": null,
"e": 2132,
"s": 2101,
"text": "<small> Statements... </small>"
},
{
"code": null,
"e": 2139,
"s": 2132,
"text": "Code: "
},
{
"code": null,
"e": 2144,
"s": 2139,
"text": "html"
},
{
"code": "<small>Example</small>",
"e": 2167,
"s": 2144,
"text": null
},
{
"code": null,
"e": 2176,
"s": 2167,
"text": "Output :"
},
{
"code": null,
"e": 2234,
"s": 2178,
"text": "Underline tag: It is used to set the content underline."
},
{
"code": null,
"e": 2243,
"s": 2234,
"text": "Syntax: "
},
{
"code": null,
"e": 2266,
"s": 2243,
"text": "<u> Statements... </u>"
},
{
"code": null,
"e": 2273,
"s": 2266,
"text": "Code: "
},
{
"code": null,
"e": 2278,
"s": 2273,
"text": "html"
},
{
"code": "<u>GeeksforGeeks</u>",
"e": 2299,
"s": 2278,
"text": null
},
{
"code": null,
"e": 2308,
"s": 2299,
"text": "Output :"
},
{
"code": null,
"e": 2395,
"s": 2310,
"text": "Deleted text tag: It is used to represent deleted text. It crosses the text content."
},
{
"code": null,
"e": 2404,
"s": 2395,
"text": "Syntax: "
},
{
"code": null,
"e": 2437,
"s": 2404,
"text": "<strike> Statements... </strike>"
},
{
"code": null,
"e": 2444,
"s": 2437,
"text": "Code: "
},
{
"code": null,
"e": 2449,
"s": 2444,
"text": "html"
},
{
"code": "<strike>geeksforgeeks</strike>GeeksforGeeks",
"e": 2493,
"s": 2449,
"text": null
},
{
"code": null,
"e": 2502,
"s": 2493,
"text": "Output :"
},
{
"code": null,
"e": 2561,
"s": 2504,
"text": "Anchor tag: It is used to link one page to another page."
},
{
"code": null,
"e": 2570,
"s": 2561,
"text": "Syntax: "
},
{
"code": null,
"e": 2604,
"s": 2570,
"text": "<a href=\"...\"> Statements... </a>"
},
{
"code": null,
"e": 2611,
"s": 2604,
"text": "Code: "
},
{
"code": null,
"e": 2616,
"s": 2611,
"text": "html"
},
{
"code": "Visit <a href=\"https://www.geeksforgeeks.org/\">GeeksforGeeks</a> for better experience.",
"e": 2704,
"s": 2616,
"text": null
},
{
"code": null,
"e": 2713,
"s": 2704,
"text": "Output :"
},
{
"code": null,
"e": 2757,
"s": 2715,
"text": "List tag: It is used to list the content."
},
{
"code": null,
"e": 2766,
"s": 2757,
"text": "Syntax: "
},
{
"code": null,
"e": 2791,
"s": 2766,
"text": "<li> Statements... </li>"
},
{
"code": null,
"e": 2798,
"s": 2791,
"text": "Code: "
},
{
"code": null,
"e": 2803,
"s": 2798,
"text": "html"
},
{
"code": "<li>List item 1</li><li>List item 2</li>",
"e": 2844,
"s": 2803,
"text": null
},
{
"code": null,
"e": 2853,
"s": 2844,
"text": "Output :"
},
{
"code": null,
"e": 2927,
"s": 2855,
"text": "Ordered List tag: It is used to list the content in a particular order."
},
{
"code": null,
"e": 2936,
"s": 2927,
"text": "Syntax: "
},
{
"code": null,
"e": 2961,
"s": 2936,
"text": "<ol> Statements... </ol>"
},
{
"code": null,
"e": 2968,
"s": 2961,
"text": "Code: "
},
{
"code": null,
"e": 2973,
"s": 2968,
"text": "html"
},
{
"code": "<ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li></ol>",
"e": 3083,
"s": 2973,
"text": null
},
{
"code": null,
"e": 3092,
"s": 3083,
"text": "Output :"
},
{
"code": null,
"e": 3160,
"s": 3094,
"text": "Unordered List tag: It is used to list the content without order."
},
{
"code": null,
"e": 3169,
"s": 3160,
"text": "Syntax: "
},
{
"code": null,
"e": 3194,
"s": 3169,
"text": "<ul> Statements... </ul>"
},
{
"code": null,
"e": 3201,
"s": 3194,
"text": "Code: "
},
{
"code": null,
"e": 3206,
"s": 3201,
"text": "html"
},
{
"code": "<ul> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li></ul>",
"e": 3316,
"s": 3206,
"text": null
},
{
"code": null,
"e": 3325,
"s": 3316,
"text": "Output :"
},
{
"code": null,
"e": 3425,
"s": 3327,
"text": "Comment tag: It is used to set the comment in an HTML document. It is not visible on the browser."
},
{
"code": null,
"e": 3434,
"s": 3425,
"text": "Syntax: "
},
{
"code": null,
"e": 3457,
"s": 3434,
"text": "<!-- Statements... -->"
},
{
"code": null,
"e": 3465,
"s": 3457,
"text": "Code: "
},
{
"code": null,
"e": 3470,
"s": 3465,
"text": "html"
},
{
"code": "<!--Comment section-->",
"e": 3493,
"s": 3470,
"text": null
},
{
"code": null,
"e": 3561,
"s": 3493,
"text": "Scrolling Text tag: It is used to scroll the text or image content."
},
{
"code": null,
"e": 3570,
"s": 3561,
"text": "Syntax: "
},
{
"code": null,
"e": 3605,
"s": 3570,
"text": "<marquee> Statements... </marquee>"
},
{
"code": null,
"e": 3612,
"s": 3605,
"text": "Code: "
},
{
"code": null,
"e": 3617,
"s": 3612,
"text": "html"
},
{
"code": "<marquee bgcolor=\"#cccccc\" loop=\"-1\"scrollamount=\"2\" width=\"100%\">Example Marquee</marquee>",
"e": 3709,
"s": 3617,
"text": null
},
{
"code": null,
"e": 3718,
"s": 3709,
"text": "Output :"
},
{
"code": null,
"e": 3779,
"s": 3720,
"text": "Center tag: It is used to set the content into the center."
},
{
"code": null,
"e": 3788,
"s": 3779,
"text": "Syntax: "
},
{
"code": null,
"e": 3821,
"s": 3788,
"text": "<center> Statements... </center>"
},
{
"code": null,
"e": 3828,
"s": 3821,
"text": "Code: "
},
{
"code": null,
"e": 3833,
"s": 3828,
"text": "html"
},
{
"code": "<center>GeeksforGeeks</center>",
"e": 3864,
"s": 3833,
"text": null
},
{
"code": null,
"e": 3873,
"s": 3864,
"text": "Output :"
},
{
"code": null,
"e": 3971,
"s": 3875,
"text": "Font tag: It is used to specify the font size, font color, and font family in an HTML document."
},
{
"code": null,
"e": 3980,
"s": 3971,
"text": "Syntax: "
},
{
"code": null,
"e": 4010,
"s": 3980,
"text": "<font> Statements ... </font>"
},
{
"code": null,
"e": 4017,
"s": 4010,
"text": "Code: "
},
{
"code": null,
"e": 4022,
"s": 4017,
"text": "html"
},
{
"code": "<font face=\"Times New Roman\">Example</font>",
"e": 4066,
"s": 4022,
"text": null
},
{
"code": null,
"e": 4075,
"s": 4066,
"text": "Output :"
},
{
"code": null,
"e": 4107,
"s": 4077,
"text": "Empty (Non-Container) Tags: "
},
{
"code": null,
"e": 4153,
"s": 4107,
"text": "Line break tag: It is used to break the line."
},
{
"code": null,
"e": 4162,
"s": 4153,
"text": "Syntax: "
},
{
"code": null,
"e": 4167,
"s": 4162,
"text": "<br>"
},
{
"code": null,
"e": 4174,
"s": 4167,
"text": "Code: "
},
{
"code": null,
"e": 4179,
"s": 4174,
"text": "html"
},
{
"code": "GeeksforGeeks<br>A computer science portal",
"e": 4222,
"s": 4179,
"text": null
},
{
"code": null,
"e": 4231,
"s": 4222,
"text": "Output :"
},
{
"code": null,
"e": 4297,
"s": 4233,
"text": "Image tag: It is used to add image elements in HTML documents. "
},
{
"code": null,
"e": 4306,
"s": 4297,
"text": "Syntax: "
},
{
"code": null,
"e": 4312,
"s": 4306,
"text": "<img>"
},
{
"code": null,
"e": 4319,
"s": 4312,
"text": "Code: "
},
{
"code": null,
"e": 4324,
"s": 4319,
"text": "html"
},
{
"code": "<img src=\"gfg.PNG\" alt=\"GeeksforGeeks Image\">",
"e": 4370,
"s": 4324,
"text": null
},
{
"code": null,
"e": 4379,
"s": 4370,
"text": "Output :"
},
{
"code": null,
"e": 4447,
"s": 4381,
"text": "Link tag: It is used to link the content from an external source."
},
{
"code": null,
"e": 4456,
"s": 4447,
"text": "Syntax: "
},
{
"code": null,
"e": 4463,
"s": 4456,
"text": "<link>"
},
{
"code": null,
"e": 4471,
"s": 4463,
"text": "Code: "
},
{
"code": null,
"e": 4476,
"s": 4471,
"text": "html"
},
{
"code": "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head>",
"e": 4546,
"s": 4476,
"text": null
},
{
"code": null,
"e": 4630,
"s": 4546,
"text": "Horizontal rule tag: It is used to display the horizontal line in an HTML document."
},
{
"code": null,
"e": 4639,
"s": 4630,
"text": "Syntax: "
},
{
"code": null,
"e": 4645,
"s": 4639,
"text": "<hr/>"
},
{
"code": null,
"e": 4653,
"s": 4645,
"text": "Code: "
},
{
"code": null,
"e": 4658,
"s": 4653,
"text": "html"
},
{
"code": "<hr width=\"100%\" size=\"5\" />",
"e": 4687,
"s": 4658,
"text": null
},
{
"code": null,
"e": 4696,
"s": 4687,
"text": "Output :"
},
{
"code": null,
"e": 4797,
"s": 4698,
"text": "Meta tag: It is used to specify the page description. For example last modifier, authors, ... etc."
},
{
"code": null,
"e": 4806,
"s": 4797,
"text": "Syntax: "
},
{
"code": null,
"e": 4835,
"s": 4806,
"text": "<meta> Statements ... <meta>"
},
{
"code": null,
"e": 4842,
"s": 4835,
"text": "Code: "
},
{
"code": null,
"e": 4847,
"s": 4842,
"text": "html"
},
{
"code": "<meta name=\"Description\" content=\"Description of your site\"><meta name=\"keywords\" content=\"keywords describing your site\">",
"e": 4976,
"s": 4847,
"text": null
},
{
"code": null,
"e": 5047,
"s": 4976,
"text": "Table tag: A table tag is used to create a table in an HTML document. "
},
{
"code": null,
"e": 5056,
"s": 5047,
"text": "Syntax: "
},
{
"code": null,
"e": 5087,
"s": 5056,
"text": "<table> Statements... </table>"
},
{
"code": null,
"e": 5094,
"s": 5087,
"text": "Code: "
},
{
"code": null,
"e": 5099,
"s": 5094,
"text": "html"
},
{
"code": "<table border=\"4\" cellpadding=\"2\" cellspacing=\"2\" width=\"50%\"><tr> <td>Column 1</td><td>Column 2</td> </tr> </table>",
"e": 5216,
"s": 5099,
"text": null
},
{
"code": null,
"e": 5225,
"s": 5216,
"text": "Output :"
},
{
"code": null,
"e": 5280,
"s": 5227,
"text": "Tr tag: It is used to define a row of an HTML table."
},
{
"code": null,
"e": 5289,
"s": 5280,
"text": "Syntax: "
},
{
"code": null,
"e": 5314,
"s": 5289,
"text": "<tr> Statements... </tr>"
},
{
"code": null,
"e": 5321,
"s": 5314,
"text": "Code: "
},
{
"code": null,
"e": 5326,
"s": 5321,
"text": "html"
},
{
"code": "<table> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr></table>",
"e": 5443,
"s": 5326,
"text": null
},
{
"code": null,
"e": 5452,
"s": 5443,
"text": "Output :"
},
{
"code": null,
"e": 5567,
"s": 5454,
"text": "Th tag: It defines the header cell in a table. By default, it set the content with the bold and center property."
},
{
"code": null,
"e": 5575,
"s": 5567,
"text": "Syntax:"
},
{
"code": null,
"e": 5601,
"s": 5575,
"text": "<th> Statements ... </th>"
},
{
"code": null,
"e": 5608,
"s": 5601,
"text": "Code: "
},
{
"code": null,
"e": 5613,
"s": 5608,
"text": "html"
},
{
"code": "<table> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr></table>",
"e": 5722,
"s": 5613,
"text": null
},
{
"code": null,
"e": 5731,
"s": 5722,
"text": "Output :"
},
{
"code": null,
"e": 5791,
"s": 5733,
"text": "Td tag: It defines the standard cell in an HTML document."
},
{
"code": null,
"e": 5800,
"s": 5791,
"text": "Syntax: "
},
{
"code": null,
"e": 5826,
"s": 5800,
"text": "<td> Statements ... </td>"
},
{
"code": null,
"e": 5833,
"s": 5826,
"text": "Code: "
},
{
"code": null,
"e": 5838,
"s": 5833,
"text": "html"
},
{
"code": "<table> <tr> <td>Cell A</td> <td>Cell B</td> </tr></table>",
"e": 5905,
"s": 5838,
"text": null
},
{
"code": null,
"e": 5914,
"s": 5905,
"text": "Output :"
},
{
"code": null,
"e": 5930,
"s": 5916,
"text": "Input Tags: "
},
{
"code": null,
"e": 5988,
"s": 5930,
"text": "Form tag: It is used to create an HTML form for the user."
},
{
"code": null,
"e": 5997,
"s": 5988,
"text": "Syntax: "
},
{
"code": null,
"e": 6027,
"s": 5997,
"text": "<form> Statements ... </form>"
},
{
"code": null,
"e": 6034,
"s": 6027,
"text": "Code: "
},
{
"code": null,
"e": 6039,
"s": 6034,
"text": "html"
},
{
"code": "<form action=\"mailto:you@yourdomain.com \"> Name: <input name=\"Name\" value=\"\" size=\"80\"><br> Email: <input name=\"Email\" value=\"\" size=\"80\"><br> <br><center><input type=\"submit\"></center></form>",
"e": 6235,
"s": 6039,
"text": null
},
{
"code": null,
"e": 6244,
"s": 6235,
"text": "Output :"
},
{
"code": null,
"e": 6308,
"s": 6246,
"text": "Submit input tag: It is used to take the input from the user."
},
{
"code": null,
"e": 6317,
"s": 6308,
"text": "Syntax: "
},
{
"code": null,
"e": 6325,
"s": 6317,
"text": "<input>"
},
{
"code": null,
"e": 6332,
"s": 6325,
"text": "Code: "
},
{
"code": null,
"e": 6337,
"s": 6332,
"text": "html"
},
{
"code": "<form method=post action=\"/cgibin/example.cgi\"><input type=\"text\" style=\"color: #ffffff; font-family: Verdana; font-weight: bold; fontsize: 12px; background-color: #72a4d2;\" size=\"10\" maxlength=\"30\"><input type=\"Submit\" value=\"Submit\"></form>",
"e": 6580,
"s": 6337,
"text": null
},
{
"code": null,
"e": 6589,
"s": 6580,
"text": "Output :"
},
{
"code": null,
"e": 6666,
"s": 6591,
"text": "Dropdown option tag: It is used to select an option from a drop-down list."
},
{
"code": null,
"e": 6675,
"s": 6666,
"text": "Syntax: "
},
{
"code": null,
"e": 6709,
"s": 6675,
"text": "<option> Statements ... </option>"
},
{
"code": null,
"e": 6716,
"s": 6709,
"text": "Code: "
},
{
"code": null,
"e": 6721,
"s": 6716,
"text": "html"
},
{
"code": "<form method=post action=\"/cgibin/example.cgi\"><center> Select an option:<select><option>option 1</option><option selected>option 2</option><option>option 3</option></form>",
"e": 6894,
"s": 6721,
"text": null
},
{
"code": null,
"e": 6903,
"s": 6894,
"text": "Output :"
},
{
"code": null,
"e": 6984,
"s": 6905,
"text": "Radio button tag: It is used to select only one option from the given options."
},
{
"code": null,
"e": 6993,
"s": 6984,
"text": "Syntax: "
},
{
"code": null,
"e": 7001,
"s": 6993,
"text": "<input>"
},
{
"code": null,
"e": 7008,
"s": 7001,
"text": "Code: "
},
{
"code": null,
"e": 7013,
"s": 7008,
"text": "html"
},
{
"code": "<form method=post action=\"/cgibin/example.cgi\">Select an option:<br><input type=\"radio\" name=\"option\"> Option 1<input type=\"radio\" name=\"option\" checked> Option 2<input type=\"radio\" name=\"option\"> Option 3",
"e": 7219,
"s": 7013,
"text": null
},
{
"code": null,
"e": 7228,
"s": 7219,
"text": "Output :"
},
{
"code": null,
"e": 7252,
"s": 7232,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 7266,
"s": 7252,
"text": "Google Chrome"
},
{
"code": null,
"e": 7284,
"s": 7266,
"text": "Internet Explorer"
},
{
"code": null,
"e": 7292,
"s": 7284,
"text": "Firefox"
},
{
"code": null,
"e": 7298,
"s": 7292,
"text": "Opera"
},
{
"code": null,
"e": 7305,
"s": 7298,
"text": "Safari"
},
{
"code": null,
"e": 7504,
"s": 7305,
"text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 7521,
"s": 7504,
"text": "arorakashish0911"
},
{
"code": null,
"e": 7533,
"s": 7521,
"text": "ysachin2314"
},
{
"code": null,
"e": 7550,
"s": 7533,
"text": "siddharthredhu01"
},
{
"code": null,
"e": 7562,
"s": 7550,
"text": "Kanchan_Ray"
},
{
"code": null,
"e": 7572,
"s": 7562,
"text": "HTML-Misc"
},
{
"code": null,
"e": 7579,
"s": 7572,
"text": "Picked"
},
{
"code": null,
"e": 7584,
"s": 7579,
"text": "HTML"
},
{
"code": null,
"e": 7611,
"s": 7584,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 7616,
"s": 7611,
"text": "HTML"
}
] |
R – Vector
|
22 Apr, 2020
R programming is one of the most popular languages when it comes to data science, statistical computations or scientific research. R programming is widely used in machine learning and it is very efficient and user-friendly. It provides flexibility in doing big statistical operations with a few lines of code.
Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. One major key point is that in R the indexing of the vector will start from ‘1’ and not from ‘0’. We can create numeric vectors and character vectors as well.
Vectors are of different types which are used in R. Following are some of the types of vectors:
Numeric vectorsNumeric vectors are those which contain numeric values such as integer, float, etc.# R program to create numeric Vectors # creation of vectors using c() function.v1 <- c(4, 5, 6, 7) # display type of vectortypeof(v1) # by using 'L' we can specify that we want integer values.v2 <- c(1L, 4L, 2L, 5L) # display type of vectortypeof(v2)Output:[1] "double"
[1] "integer"
# R program to create numeric Vectors # creation of vectors using c() function.v1 <- c(4, 5, 6, 7) # display type of vectortypeof(v1) # by using 'L' we can specify that we want integer values.v2 <- c(1L, 4L, 2L, 5L) # display type of vectortypeof(v2)
Output:
[1] "double"
[1] "integer"
Character vectorsCharacter vectors contain alphanumeric values and special characters.# R program to create Character Vectors # by default numeric values # are converted into charactersv1 <- c('geeks', '2', 'hello', 57) # Displaying type of vectortypeof(v1)Output:[1] "character"
# R program to create Character Vectors # by default numeric values # are converted into charactersv1 <- c('geeks', '2', 'hello', 57) # Displaying type of vectortypeof(v1)
Output:
[1] "character"
Logical vectorsLogical vectors contain boolean values such as TRUE, FALSE and NA for Null values.# R program to create Logical Vectors # Creating logical vector# using c() functionv1 <- c(TRUE, FALSE, TRUE, NA) # Displaying type of vectortypeof(v1)Output:[1] "logical"
# R program to create Logical Vectors # Creating logical vector# using c() functionv1 <- c(TRUE, FALSE, TRUE, NA) # Displaying type of vectortypeof(v1)
Output:
[1] "logical"
There are different ways of creating vectors. Generally, we use ‘c’ to combine different elements together.
# R program to create Vectors # we can use the c function# to combine the values as a vector.# By default the type will be doubleX <- c(61, 4, 21, 67, 89, 2)cat('using c function', X, '\n') # seq() function for creating# a sequence of continuous values.# length.out defines the length of vector.Y <- seq(1, 10, length.out = 5) cat('using seq() function', Y, '\n') # use':' to create a vector # of continuous values.Z <- 2:7cat('using colon', Z)
Output:
using c function 61 4 21 67 89 2
using seq() function 1 3.25 5.5 7.75 10
using colon 2 3 4 5 6 7
Accessing elements in a vector is the process of performing operation on an individual element of a vector. There are many ways through which we can access the elements of the vector. The most common is using the ‘[]’, symbol.
Note: Vectors in R are 1 based indexing unlike the normal C, python, etc format.
# R program to access elements of a Vector # accessing elements with an index number.X <- c(2, 5, 18, 1, 12)cat('Using Subscript operator', X[2], '\n') # by passing a range of values# inside the vector index.Y <- c(4, 8, 2, 1, 17)cat('Using combine() function', Y[c(4, 1)], '\n') # using logical expressionsZ <- c(5, 2, 1, 4, 4, 3)cat('Using Logical indexing', Z[Z>4])
Output
Using Subscript operator 5
Using combine() function 1 4
Using Logical indexing 5
Modification of a Vector is the process of applying some operation on an individual element of a vector to change its value in the vector. There are different ways through which we can modify a vector:
# R program to modify elements of a Vector # Creating a vectorX <- c(2, 7, 9, 7, 8, 2) # modify a specific elementX[3] <- 1X[2] <-9cat('subscript operator', X, '\n') # Modify using different logics.X[X>5] <- 0cat('Logical indexing', X, '\n') # Modify by specifying # the position or elements.X <- X[c(3, 2, 1)]cat('combine() function', X)
Output
subscript operator 2 9 1 7 8 2
Logical indexing 2 0 1 0 0 2
combine() function 1 0 2
Deletion of a Vector is the process of deleting all of the elements of the vector. This can be done by assigning it to a NULL value.
# R program to delete a Vector # Creating a VectorM <- c(8, 10, 2, 5) # set NULL to the vectorM <- NULL cat('Output vector', M)
Output:
Output vector NULL
sort() function is used with the help of which we can sort the values in ascending or descending order.
# R program to sort elements of a Vector # Creation of VectorX <- c(8, 2, 7, 1, 11, 2) # Sort in ascending orderA <- sort(X)cat('ascending order', A, '\n') # sort in descending order # by setting decreasing as TRUEB <- sort(X, decreasing = TRUE)cat('descending order', B)
Output:
ascending order 1 2 2 7 8 11
descending order 11 8 7 2 2 1
Picked
R Data-types
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 362,
"s": 52,
"text": "R programming is one of the most popular languages when it comes to data science, statistical computations or scientific research. R programming is widely used in machine learning and it is very efficient and user-friendly. It provides flexibility in doing big statistical operations with a few lines of code."
},
{
"code": null,
"e": 637,
"s": 362,
"text": "Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. One major key point is that in R the indexing of the vector will start from ‘1’ and not from ‘0’. We can create numeric vectors and character vectors as well."
},
{
"code": null,
"e": 733,
"s": 637,
"text": "Vectors are of different types which are used in R. Following are some of the types of vectors:"
},
{
"code": null,
"e": 1120,
"s": 733,
"text": "Numeric vectorsNumeric vectors are those which contain numeric values such as integer, float, etc.# R program to create numeric Vectors # creation of vectors using c() function.v1 <- c(4, 5, 6, 7) # display type of vectortypeof(v1) # by using 'L' we can specify that we want integer values.v2 <- c(1L, 4L, 2L, 5L) # display type of vectortypeof(v2)Output:[1] \"double\"\n[1] \"integer\""
},
{
"code": "# R program to create numeric Vectors # creation of vectors using c() function.v1 <- c(4, 5, 6, 7) # display type of vectortypeof(v1) # by using 'L' we can specify that we want integer values.v2 <- c(1L, 4L, 2L, 5L) # display type of vectortypeof(v2)",
"e": 1376,
"s": 1120,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1376,
"text": "Output:"
},
{
"code": null,
"e": 1411,
"s": 1384,
"text": "[1] \"double\"\n[1] \"integer\""
},
{
"code": null,
"e": 1694,
"s": 1411,
"text": "Character vectorsCharacter vectors contain alphanumeric values and special characters.# R program to create Character Vectors # by default numeric values # are converted into charactersv1 <- c('geeks', '2', 'hello', 57) # Displaying type of vectortypeof(v1)Output:[1] \"character\""
},
{
"code": "# R program to create Character Vectors # by default numeric values # are converted into charactersv1 <- c('geeks', '2', 'hello', 57) # Displaying type of vectortypeof(v1)",
"e": 1869,
"s": 1694,
"text": null
},
{
"code": null,
"e": 1877,
"s": 1869,
"text": "Output:"
},
{
"code": null,
"e": 1893,
"s": 1877,
"text": "[1] \"character\""
},
{
"code": null,
"e": 2164,
"s": 1893,
"text": "Logical vectorsLogical vectors contain boolean values such as TRUE, FALSE and NA for Null values.# R program to create Logical Vectors # Creating logical vector# using c() functionv1 <- c(TRUE, FALSE, TRUE, NA) # Displaying type of vectortypeof(v1)Output:[1] \"logical\""
},
{
"code": "# R program to create Logical Vectors # Creating logical vector# using c() functionv1 <- c(TRUE, FALSE, TRUE, NA) # Displaying type of vectortypeof(v1)",
"e": 2318,
"s": 2164,
"text": null
},
{
"code": null,
"e": 2326,
"s": 2318,
"text": "Output:"
},
{
"code": null,
"e": 2340,
"s": 2326,
"text": "[1] \"logical\""
},
{
"code": null,
"e": 2448,
"s": 2340,
"text": "There are different ways of creating vectors. Generally, we use ‘c’ to combine different elements together."
},
{
"code": "# R program to create Vectors # we can use the c function# to combine the values as a vector.# By default the type will be doubleX <- c(61, 4, 21, 67, 89, 2)cat('using c function', X, '\\n') # seq() function for creating# a sequence of continuous values.# length.out defines the length of vector.Y <- seq(1, 10, length.out = 5) cat('using seq() function', Y, '\\n') # use':' to create a vector # of continuous values.Z <- 2:7cat('using colon', Z)",
"e": 2897,
"s": 2448,
"text": null
},
{
"code": null,
"e": 2905,
"s": 2897,
"text": "Output:"
},
{
"code": null,
"e": 3005,
"s": 2905,
"text": "using c function 61 4 21 67 89 2 \nusing seq() function 1 3.25 5.5 7.75 10 \nusing colon 2 3 4 5 6 7\n"
},
{
"code": null,
"e": 3232,
"s": 3005,
"text": "Accessing elements in a vector is the process of performing operation on an individual element of a vector. There are many ways through which we can access the elements of the vector. The most common is using the ‘[]’, symbol."
},
{
"code": null,
"e": 3313,
"s": 3232,
"text": "Note: Vectors in R are 1 based indexing unlike the normal C, python, etc format."
},
{
"code": "# R program to access elements of a Vector # accessing elements with an index number.X <- c(2, 5, 18, 1, 12)cat('Using Subscript operator', X[2], '\\n') # by passing a range of values# inside the vector index.Y <- c(4, 8, 2, 1, 17)cat('Using combine() function', Y[c(4, 1)], '\\n') # using logical expressionsZ <- c(5, 2, 1, 4, 4, 3)cat('Using Logical indexing', Z[Z>4])",
"e": 3685,
"s": 3313,
"text": null
},
{
"code": null,
"e": 3692,
"s": 3685,
"text": "Output"
},
{
"code": null,
"e": 3776,
"s": 3692,
"text": "Using Subscript operator 5 \nUsing combine() function 1 4 \nUsing Logical indexing 5\n"
},
{
"code": null,
"e": 3978,
"s": 3776,
"text": "Modification of a Vector is the process of applying some operation on an individual element of a vector to change its value in the vector. There are different ways through which we can modify a vector:"
},
{
"code": "# R program to modify elements of a Vector # Creating a vectorX <- c(2, 7, 9, 7, 8, 2) # modify a specific elementX[3] <- 1X[2] <-9cat('subscript operator', X, '\\n') # Modify using different logics.X[X>5] <- 0cat('Logical indexing', X, '\\n') # Modify by specifying # the position or elements.X <- X[c(3, 2, 1)]cat('combine() function', X)",
"e": 4321,
"s": 3978,
"text": null
},
{
"code": null,
"e": 4328,
"s": 4321,
"text": "Output"
},
{
"code": null,
"e": 4416,
"s": 4328,
"text": "subscript operator 2 9 1 7 8 2 \nLogical indexing 2 0 1 0 0 2 \ncombine() function 1 0 2\n"
},
{
"code": null,
"e": 4549,
"s": 4416,
"text": "Deletion of a Vector is the process of deleting all of the elements of the vector. This can be done by assigning it to a NULL value."
},
{
"code": "# R program to delete a Vector # Creating a VectorM <- c(8, 10, 2, 5) # set NULL to the vectorM <- NULL cat('Output vector', M)",
"e": 4679,
"s": 4549,
"text": null
},
{
"code": null,
"e": 4687,
"s": 4679,
"text": "Output:"
},
{
"code": null,
"e": 4707,
"s": 4687,
"text": "Output vector NULL\n"
},
{
"code": null,
"e": 4811,
"s": 4707,
"text": "sort() function is used with the help of which we can sort the values in ascending or descending order."
},
{
"code": "# R program to sort elements of a Vector # Creation of VectorX <- c(8, 2, 7, 1, 11, 2) # Sort in ascending orderA <- sort(X)cat('ascending order', A, '\\n') # sort in descending order # by setting decreasing as TRUEB <- sort(X, decreasing = TRUE)cat('descending order', B)",
"e": 5086,
"s": 4811,
"text": null
},
{
"code": null,
"e": 5094,
"s": 5086,
"text": "Output:"
},
{
"code": null,
"e": 5163,
"s": 5094,
"text": "ascending order 1 2 2 7 8 11\ndescending order 11 8 7 2 2 1\n"
},
{
"code": null,
"e": 5170,
"s": 5163,
"text": "Picked"
},
{
"code": null,
"e": 5183,
"s": 5170,
"text": "R Data-types"
},
{
"code": null,
"e": 5194,
"s": 5183,
"text": "R Language"
}
] |
Node.js crypto.createHash() Method
|
24 Jun, 2022
The crypto.createHash() method is used to create a Hash object that can be used to create hash digests by using the stated algorithm.
Syntax:
crypto.createHash( algorithm, options )
Parameters: This method accept two parameters as mentioned above and described below:
algorithm: It is dependent on the accessible algorithms which are favored by the version of OpenSSL on the platform. It returns string. The examples are sha256, sha512, etc.
options: It is optional parameter and is used to control stream behavior. It returns an object. Moreover, For XOF hash functions like ‘shake256’, the option outputLength can be used to determine the required output length in bytes.
Return Type: It returns Hash object.
Below examples illustrate the use of crypto.createHash() method in Node.js:
Example 1:
javascript
// Node.js program to demonstrate the // crypto.createHash() method // Includes crypto moduleconst crypto = require('crypto'); // Defining keyconst secret = 'Hi'; // Calling createHash methodconst hash = crypto.createHash('sha256', secret) // updating data .update('How are you?') // Encoding to be used .digest('hex'); // Displays outputconsole.log(hash);
Output:
df287dfc1406ed2b692e1c2c783bb5cec97eac53151ee1d9810397aa0afa0d89
Example 2:
javascript
// Node.js program to demonstrate the // crypto.createHash() method // Defining filenameconst filename = process.argv[1]; // Includes crypto and fs moduleconst crypto = require('crypto');const fs = require('fs'); // Creating Hashconst hash = crypto.createHash('sha256', 'Geeksforgeeks'); // Creating read streamconst input = fs.createReadStream(filename); input.on('readable', () => { // Calling read method to read data const data = input.read(); if (data) // Updating hash.update(data); else { // Encoding and displaying filename console.log(`${hash.digest('base64')} ${filename}`); }});console.log("Program done!");
Output:
Program done!
n95mt3468ZzAIwu/bbNU7dej6CoFkDRcNaJo7rGpLF4= index.js
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options
vinayedula
claudioplatzx5
Node.js-crypto-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 189,
"s": 54,
"text": "The crypto.createHash() method is used to create a Hash object that can be used to create hash digests by using the stated algorithm. "
},
{
"code": null,
"e": 197,
"s": 189,
"text": "Syntax:"
},
{
"code": null,
"e": 237,
"s": 197,
"text": "crypto.createHash( algorithm, options )"
},
{
"code": null,
"e": 323,
"s": 237,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 497,
"s": 323,
"text": "algorithm: It is dependent on the accessible algorithms which are favored by the version of OpenSSL on the platform. It returns string. The examples are sha256, sha512, etc."
},
{
"code": null,
"e": 729,
"s": 497,
"text": "options: It is optional parameter and is used to control stream behavior. It returns an object. Moreover, For XOF hash functions like ‘shake256’, the option outputLength can be used to determine the required output length in bytes."
},
{
"code": null,
"e": 767,
"s": 729,
"text": "Return Type: It returns Hash object. "
},
{
"code": null,
"e": 844,
"s": 767,
"text": "Below examples illustrate the use of crypto.createHash() method in Node.js: "
},
{
"code": null,
"e": 856,
"s": 844,
"text": "Example 1: "
},
{
"code": null,
"e": 867,
"s": 856,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the // crypto.createHash() method // Includes crypto moduleconst crypto = require('crypto'); // Defining keyconst secret = 'Hi'; // Calling createHash methodconst hash = crypto.createHash('sha256', secret) // updating data .update('How are you?') // Encoding to be used .digest('hex'); // Displays outputconsole.log(hash);",
"e": 1320,
"s": 867,
"text": null
},
{
"code": null,
"e": 1328,
"s": 1320,
"text": "Output:"
},
{
"code": null,
"e": 1393,
"s": 1328,
"text": "df287dfc1406ed2b692e1c2c783bb5cec97eac53151ee1d9810397aa0afa0d89"
},
{
"code": null,
"e": 1405,
"s": 1393,
"text": "Example 2: "
},
{
"code": null,
"e": 1416,
"s": 1405,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the // crypto.createHash() method // Defining filenameconst filename = process.argv[1]; // Includes crypto and fs moduleconst crypto = require('crypto');const fs = require('fs'); // Creating Hashconst hash = crypto.createHash('sha256', 'Geeksforgeeks'); // Creating read streamconst input = fs.createReadStream(filename); input.on('readable', () => { // Calling read method to read data const data = input.read(); if (data) // Updating hash.update(data); else { // Encoding and displaying filename console.log(`${hash.digest('base64')} ${filename}`); }});console.log(\"Program done!\");",
"e": 2064,
"s": 1416,
"text": null
},
{
"code": null,
"e": 2072,
"s": 2064,
"text": "Output:"
},
{
"code": null,
"e": 2140,
"s": 2072,
"text": "Program done!\nn95mt3468ZzAIwu/bbNU7dej6CoFkDRcNaJo7rGpLF4= index.js"
},
{
"code": null,
"e": 2229,
"s": 2140,
"text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options"
},
{
"code": null,
"e": 2240,
"s": 2229,
"text": "vinayedula"
},
{
"code": null,
"e": 2255,
"s": 2240,
"text": "claudioplatzx5"
},
{
"code": null,
"e": 2277,
"s": 2255,
"text": "Node.js-crypto-module"
},
{
"code": null,
"e": 2285,
"s": 2277,
"text": "Node.js"
},
{
"code": null,
"e": 2302,
"s": 2285,
"text": "Web Technologies"
},
{
"code": null,
"e": 2400,
"s": 2302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2448,
"s": 2400,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2481,
"s": 2448,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 2511,
"s": 2481,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 2531,
"s": 2511,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 2585,
"s": 2531,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 2647,
"s": 2585,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2689,
"s": 2647,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2750,
"s": 2689,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2800,
"s": 2750,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Get tuple element data types
|
18 Oct, 2019
Tuples can be a collection of various data types, and unlike simpler data types, conventional methods of getting the type of each element of tuple is not possible. For this we need to have different ways to achieve this task. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using map() + type()Using this function is most conventional and best way to perform this task. In this, we just allow map() to extend the logic of finding data types using type() to each element of tuple.
# Python3 code to demonstrate working of# Get tuple element data types# Using map() + type() # Initializing tupletest_tup = ('gfg', 1, ['is', 'best']) # printing original tupleprint("The original tuple is : " + str(test_tup)) # Get tuple element data types# Using map() + type()res = list(map(type, test_tup)) # printing resultprint("The data types of tuple in order are : " + str(res))
The original tuple is : ('gfg', 1, ['is', 'best'])
The data types of tuple in order are : [<class 'str'>, <class 'int'>, <class 'list'>]
Method #2 : Using collections.Sequence + isinstance() + type()We can perform this task using the combination of above functions. The additional advantage of using this method it that it also provides us with the length of each element if its type is complex data type.
# Python3 code to demonstrate working of# Get tuple element data types# Using collections.Sequence + isinstance() + type()import collections # Initializing tupletest_tup = ('gfg', 1, ['is', 'best']) # printing original tupleprint("The original tuple is : " + str(test_tup)) # Get tuple element data types# Using collections.Sequence + isinstance() + type()res = [(type(ele), len(ele) if isinstance(ele, collections.Sequence) else None) for ele in test_tup] # printing resultprint("The data types of tuple in order are : " + str(res))
The original tuple is : ('gfg', 1, ['is', 'best'])
The data types of tuple in order are : [(<class 'str'>, 3), (<class 'int'>, None), (<class 'list'>, 2)]
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "Tuples can be a collection of various data types, and unlike simpler data types, conventional methods of getting the type of each element of tuple is not possible. For this we need to have different ways to achieve this task. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 536,
"s": 318,
"text": "Method #1 : Using map() + type()Using this function is most conventional and best way to perform this task. In this, we just allow map() to extend the logic of finding data types using type() to each element of tuple."
},
{
"code": "# Python3 code to demonstrate working of# Get tuple element data types# Using map() + type() # Initializing tupletest_tup = ('gfg', 1, ['is', 'best']) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # Get tuple element data types# Using map() + type()res = list(map(type, test_tup)) # printing resultprint(\"The data types of tuple in order are : \" + str(res))",
"e": 927,
"s": 536,
"text": null
},
{
"code": null,
"e": 1065,
"s": 927,
"text": "The original tuple is : ('gfg', 1, ['is', 'best'])\nThe data types of tuple in order are : [<class 'str'>, <class 'int'>, <class 'list'>]\n"
},
{
"code": null,
"e": 1336,
"s": 1067,
"text": "Method #2 : Using collections.Sequence + isinstance() + type()We can perform this task using the combination of above functions. The additional advantage of using this method it that it also provides us with the length of each element if its type is complex data type."
},
{
"code": "# Python3 code to demonstrate working of# Get tuple element data types# Using collections.Sequence + isinstance() + type()import collections # Initializing tupletest_tup = ('gfg', 1, ['is', 'best']) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # Get tuple element data types# Using collections.Sequence + isinstance() + type()res = [(type(ele), len(ele) if isinstance(ele, collections.Sequence) else None) for ele in test_tup] # printing resultprint(\"The data types of tuple in order are : \" + str(res))",
"e": 1878,
"s": 1336,
"text": null
},
{
"code": null,
"e": 2034,
"s": 1878,
"text": "The original tuple is : ('gfg', 1, ['is', 'best'])\nThe data types of tuple in order are : [(<class 'str'>, 3), (<class 'int'>, None), (<class 'list'>, 2)]\n"
},
{
"code": null,
"e": 2056,
"s": 2034,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 2063,
"s": 2056,
"text": "Python"
},
{
"code": null,
"e": 2079,
"s": 2063,
"text": "Python Programs"
},
{
"code": null,
"e": 2177,
"s": 2079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2209,
"s": 2177,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2236,
"s": 2209,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2257,
"s": 2236,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2280,
"s": 2257,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2311,
"s": 2280,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2333,
"s": 2311,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2372,
"s": 2333,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2410,
"s": 2372,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2447,
"s": 2410,
"text": "Python Program for Fibonacci numbers"
}
] |
A Classification Problem with Python — Homesite Quote Conversion | by Shirley Chen | Towards Data Science
|
Homesite, a leading provider of homeowners insurance, does not currently have a dynamic conversion rate model that can give them confidence a quoted price will lead to a purchase. Using an anonymized database of information on customer and sales activity, including property and coverage information, they are challenging us to predict which customers will purchase a given quote. Accurately predicting conversion would help Homesite better understand the impact of proposed pricing changes and maintain an ideal portfolio of customer segments.
The dataset represents the activity of a large number of customers who are interested in buying policies from Homesite. Each QuoteNumber corresponds to a potential customer and the QuoteConversion_Flag indicates whether the customer purchased a policy. The provided features are anonymized and provide a rich representation of the prospective customer and policy. They include specific coverage information, sales information, personal information, property information, and geographic information. Our task is to predict QuoteConversion_Flag for each QuoteNumber in the test set.
Let’s read the data first and take a look at this data.
Training Dataset: a subset to train a model.
Test Dataset: a subset to test the trained model.
trainfile = r'RevisedHomesiteTrain.csv'train_data = pd.read_csv(trainfile)testfile = r'RevisedHomesiteTest.csv'test_data = pd.read_csv(testfile)print(train_data.shape)print(train_data.head())print(test_data.shape)print(test_data.head())
We copy train data excluding target and separate train data and test data. Then, we select just target column.
trainData_Copy = train_data.drop('QuoteNumber', axis=1).iloc[:, :-1].copy()testData_Copy = test_data.drop('QuoteNumber', axis=1).iloc[:, :-1].copy()X_train = trainData_CopyX_test = testData_Copyy_train = train_data["QuoteConversion_Flag"]y_train = train_data.iloc[:, -1]y_test = test_data.iloc[:, -1]
from sklearn.model_selection import train_test_splitX_train1, X_val, y_train1, y_val = train_test_split(X_train, y_train, test_size = 0.2)
A decision tree is a decision support tool that uses a tree-like graph or model of decisions and their possible consequences, including chance event outcomes, resource costs, and utility. It is one way to display an algorithm that only contains conditional control statements. A Decision Tree Classifier functions by breaking down a dataset into smaller and smaller subsets based on different criteria. Different sorting criteria will be used to divide the dataset, with the number of examples getting smaller with every division.
from sklearn.tree import DecisionTreeClassifierclf = DecisionTreeClassifier()clf.fit(X_train1, y_train1)clf_predict = clf.predict(X_val)
Kaggle score of Decision Tree Classifier: 0.94499
Random Forests are an ensemble learning method that fit multiple Decision Trees on subsets of the data and average the results.
from sklearn.ensemble import RandomForestClassifierrfc = RandomForestClassifier()rfc.fit(X_train, y_train)rfc_predict = rfc.predict(X_test)
Kaggle score of Random Forest Classifier: 0.91963
K-Nearest Neighbors operates by checking the distance from some test example to the known values of some training example. The group of data points/class that would give the smallest distance between the training points and the testing point is the class that is selected.
from sklearn.neighbors import KNeighborsClassifierknc = KNeighborsClassifier()knc.fit(X_train, y_train)knc_predict = knc.predict(X_test)
Kaggle score of K-Nearest Neighbor Classifier: 0.60289
Neural Networks are a machine learning algorithm that involves fitting many hidden layers used to represent neurons that are connected with synaptic activation functions. These essentially use a very simplified model of the brain to model and predict data.
from sklearn.neural_network import MLPClassifiermlp = MLPClassifier()mlp.fit(X_train, y_train)mlp_predict = mlp.predict(X_test)
Kaggle score of Neural Networks Classifier: 0.86759
Gradient boosting classifiers are a group of machine learning algorithms that combine many weak learning models together to create a strong predictive model. Decision trees are usually used when doing gradient boosting.
from sklearn.ensemble import GradientBoostingClassifierabc = GradientBoostingClassifier()abc.fit(X_train, y_train)abc_predict = abc.predict(X_test)
Kaggle score of Neural Networks Classifier: 0.95882
Based on the model I create, first we can realize that gradient boosting classifier get the highest Kaggle score. Also, gradient boosting models are becoming popular because of their effectiveness at classifying complex datasets, and have recently been used to win many Kaggle data science competitions.
To sum up, we use the different classification methods(Decision Tree, Random Forest, K-Nearest Neighbors, Neural Networks, and Gradient Boosting) from Scikit Learn to predict the probability that a customer would buy the quoted insurance plan and focus on the prediction accuracy. The purpose is to learn a model that can maximize the prediction accuracy, compare different algorithms, and select the best-performing one.
Source code that created this post can be found here.
Thank you so much for reading my article! Hi, I’m Shirley, currently studying for a Master Degree in MS-Business Analytics at ASU. If you have questions, please don’t hesitate to contact me!
Email me at kchen122@asu.edu and feel free to connect me on LinkedIn!
|
[
{
"code": null,
"e": 717,
"s": 172,
"text": "Homesite, a leading provider of homeowners insurance, does not currently have a dynamic conversion rate model that can give them confidence a quoted price will lead to a purchase. Using an anonymized database of information on customer and sales activity, including property and coverage information, they are challenging us to predict which customers will purchase a given quote. Accurately predicting conversion would help Homesite better understand the impact of proposed pricing changes and maintain an ideal portfolio of customer segments."
},
{
"code": null,
"e": 1298,
"s": 717,
"text": "The dataset represents the activity of a large number of customers who are interested in buying policies from Homesite. Each QuoteNumber corresponds to a potential customer and the QuoteConversion_Flag indicates whether the customer purchased a policy. The provided features are anonymized and provide a rich representation of the prospective customer and policy. They include specific coverage information, sales information, personal information, property information, and geographic information. Our task is to predict QuoteConversion_Flag for each QuoteNumber in the test set."
},
{
"code": null,
"e": 1354,
"s": 1298,
"text": "Let’s read the data first and take a look at this data."
},
{
"code": null,
"e": 1399,
"s": 1354,
"text": "Training Dataset: a subset to train a model."
},
{
"code": null,
"e": 1449,
"s": 1399,
"text": "Test Dataset: a subset to test the trained model."
},
{
"code": null,
"e": 1686,
"s": 1449,
"text": "trainfile = r'RevisedHomesiteTrain.csv'train_data = pd.read_csv(trainfile)testfile = r'RevisedHomesiteTest.csv'test_data = pd.read_csv(testfile)print(train_data.shape)print(train_data.head())print(test_data.shape)print(test_data.head())"
},
{
"code": null,
"e": 1797,
"s": 1686,
"text": "We copy train data excluding target and separate train data and test data. Then, we select just target column."
},
{
"code": null,
"e": 2098,
"s": 1797,
"text": "trainData_Copy = train_data.drop('QuoteNumber', axis=1).iloc[:, :-1].copy()testData_Copy = test_data.drop('QuoteNumber', axis=1).iloc[:, :-1].copy()X_train = trainData_CopyX_test = testData_Copyy_train = train_data[\"QuoteConversion_Flag\"]y_train = train_data.iloc[:, -1]y_test = test_data.iloc[:, -1]"
},
{
"code": null,
"e": 2237,
"s": 2098,
"text": "from sklearn.model_selection import train_test_splitX_train1, X_val, y_train1, y_val = train_test_split(X_train, y_train, test_size = 0.2)"
},
{
"code": null,
"e": 2768,
"s": 2237,
"text": "A decision tree is a decision support tool that uses a tree-like graph or model of decisions and their possible consequences, including chance event outcomes, resource costs, and utility. It is one way to display an algorithm that only contains conditional control statements. A Decision Tree Classifier functions by breaking down a dataset into smaller and smaller subsets based on different criteria. Different sorting criteria will be used to divide the dataset, with the number of examples getting smaller with every division."
},
{
"code": null,
"e": 2905,
"s": 2768,
"text": "from sklearn.tree import DecisionTreeClassifierclf = DecisionTreeClassifier()clf.fit(X_train1, y_train1)clf_predict = clf.predict(X_val)"
},
{
"code": null,
"e": 2955,
"s": 2905,
"text": "Kaggle score of Decision Tree Classifier: 0.94499"
},
{
"code": null,
"e": 3083,
"s": 2955,
"text": "Random Forests are an ensemble learning method that fit multiple Decision Trees on subsets of the data and average the results."
},
{
"code": null,
"e": 3223,
"s": 3083,
"text": "from sklearn.ensemble import RandomForestClassifierrfc = RandomForestClassifier()rfc.fit(X_train, y_train)rfc_predict = rfc.predict(X_test)"
},
{
"code": null,
"e": 3273,
"s": 3223,
"text": "Kaggle score of Random Forest Classifier: 0.91963"
},
{
"code": null,
"e": 3546,
"s": 3273,
"text": "K-Nearest Neighbors operates by checking the distance from some test example to the known values of some training example. The group of data points/class that would give the smallest distance between the training points and the testing point is the class that is selected."
},
{
"code": null,
"e": 3683,
"s": 3546,
"text": "from sklearn.neighbors import KNeighborsClassifierknc = KNeighborsClassifier()knc.fit(X_train, y_train)knc_predict = knc.predict(X_test)"
},
{
"code": null,
"e": 3738,
"s": 3683,
"text": "Kaggle score of K-Nearest Neighbor Classifier: 0.60289"
},
{
"code": null,
"e": 3995,
"s": 3738,
"text": "Neural Networks are a machine learning algorithm that involves fitting many hidden layers used to represent neurons that are connected with synaptic activation functions. These essentially use a very simplified model of the brain to model and predict data."
},
{
"code": null,
"e": 4123,
"s": 3995,
"text": "from sklearn.neural_network import MLPClassifiermlp = MLPClassifier()mlp.fit(X_train, y_train)mlp_predict = mlp.predict(X_test)"
},
{
"code": null,
"e": 4175,
"s": 4123,
"text": "Kaggle score of Neural Networks Classifier: 0.86759"
},
{
"code": null,
"e": 4395,
"s": 4175,
"text": "Gradient boosting classifiers are a group of machine learning algorithms that combine many weak learning models together to create a strong predictive model. Decision trees are usually used when doing gradient boosting."
},
{
"code": null,
"e": 4543,
"s": 4395,
"text": "from sklearn.ensemble import GradientBoostingClassifierabc = GradientBoostingClassifier()abc.fit(X_train, y_train)abc_predict = abc.predict(X_test)"
},
{
"code": null,
"e": 4595,
"s": 4543,
"text": "Kaggle score of Neural Networks Classifier: 0.95882"
},
{
"code": null,
"e": 4899,
"s": 4595,
"text": "Based on the model I create, first we can realize that gradient boosting classifier get the highest Kaggle score. Also, gradient boosting models are becoming popular because of their effectiveness at classifying complex datasets, and have recently been used to win many Kaggle data science competitions."
},
{
"code": null,
"e": 5321,
"s": 4899,
"text": "To sum up, we use the different classification methods(Decision Tree, Random Forest, K-Nearest Neighbors, Neural Networks, and Gradient Boosting) from Scikit Learn to predict the probability that a customer would buy the quoted insurance plan and focus on the prediction accuracy. The purpose is to learn a model that can maximize the prediction accuracy, compare different algorithms, and select the best-performing one."
},
{
"code": null,
"e": 5375,
"s": 5321,
"text": "Source code that created this post can be found here."
},
{
"code": null,
"e": 5566,
"s": 5375,
"text": "Thank you so much for reading my article! Hi, I’m Shirley, currently studying for a Master Degree in MS-Business Analytics at ASU. If you have questions, please don’t hesitate to contact me!"
}
] |
Interesting Patterns | Practice | GeeksforGeeks
|
Given an integer N. Your task is to identify the pattern from the Examples and print the pattern.
Example 1:
Input:
N = 4
Output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Example 2:
Input:
N = 3
Output:
33333
32223
32123
32223
33333
Your Task:
You don't need to read input or print anything. Your task is to complete the function interestingPattern() which takes an Integer N as input and returns a vector of strings where each line representins each line of the pattern. For example, if N = 3, you have to return a vector v = {"33333", "32223", "32123", "32223", "33333"}.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 <= N < 10
0
ashwinaditya214 weeks ago
Length = 2*n -1
for i,j=0 to i,j<Length (two for loops)
Find min of i, j, length-1-i, length-1-j
subtract min from N and print
class Solution {
static String[] interestingPattern(int N) {
// code here
int length = 2*N - 1;
String[] result = new String[length];
for(int i=0; i<length; i++) {
StringBuilder sb = new StringBuilder();
for(int j=0; j<length; j++) {
int a = (int)Math.min(i, j);
int b = (int)Math.min(length-1-i, length-1-j);
sb.append(N-(int)Math.min(a, b));
}
result[i] = sb.toString();
}
return result;
}
};
+3
choudharymanojloul8447 months ago
code not work for 60?
+2
choudharymanojloul8447 months ago
vector<string> interestingPattern(int N) { vector<string> v; for(int i=1;i<=2*N-1;++i) { string str=""; for(int j=1;j<=2*N-1;++j) { int k=max(abs(i-N),abs(j-N))+1; str+=to_string(k); } v.push_back(str); } return v; }
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": 324,
"s": 226,
"text": "Given an integer N. Your task is to identify the pattern from the Examples and print the pattern."
},
{
"code": null,
"e": 338,
"s": 326,
"text": "Example 1: "
},
{
"code": null,
"e": 421,
"s": 338,
"text": "Input:\nN = 4\nOutput:\n4444444 \n4333334 \n4322234 \n4321234 \n4322234 \n4333334 \n4444444"
},
{
"code": null,
"e": 433,
"s": 421,
"text": "Example 2: "
},
{
"code": null,
"e": 488,
"s": 433,
"text": "Input:\nN = 3\nOutput:\n33333 \n32223 \n32123 \n32223 \n33333"
},
{
"code": null,
"e": 831,
"s": 490,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function interestingPattern() which takes an Integer N as input and returns a vector of strings where each line representins each line of the pattern. For example, if N = 3, you have to return a vector v = {\"33333\", \"32223\", \"32123\", \"32223\", \"33333\"}."
},
{
"code": null,
"e": 895,
"s": 833,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 922,
"s": 897,
"text": "Constraints:\n1 <= N < 10"
},
{
"code": null,
"e": 924,
"s": 922,
"text": "0"
},
{
"code": null,
"e": 950,
"s": 924,
"text": "ashwinaditya214 weeks ago"
},
{
"code": null,
"e": 966,
"s": 950,
"text": "Length = 2*n -1"
},
{
"code": null,
"e": 1006,
"s": 966,
"text": "for i,j=0 to i,j<Length (two for loops)"
},
{
"code": null,
"e": 1047,
"s": 1006,
"text": "Find min of i, j, length-1-i, length-1-j"
},
{
"code": null,
"e": 1077,
"s": 1047,
"text": "subtract min from N and print"
},
{
"code": null,
"e": 1635,
"s": 1079,
"text": "class Solution {\n static String[] interestingPattern(int N) {\n // code here\n int length = 2*N - 1;\n String[] result = new String[length];\n \n for(int i=0; i<length; i++) {\n StringBuilder sb = new StringBuilder();\n for(int j=0; j<length; j++) {\n int a = (int)Math.min(i, j);\n int b = (int)Math.min(length-1-i, length-1-j);\n sb.append(N-(int)Math.min(a, b));\n }\n result[i] = sb.toString();\n }\n return result;\n }\n};"
},
{
"code": null,
"e": 1638,
"s": 1635,
"text": "+3"
},
{
"code": null,
"e": 1672,
"s": 1638,
"text": "choudharymanojloul8447 months ago"
},
{
"code": null,
"e": 1694,
"s": 1672,
"text": "code not work for 60?"
},
{
"code": null,
"e": 1699,
"s": 1696,
"text": "+2"
},
{
"code": null,
"e": 1733,
"s": 1699,
"text": "choudharymanojloul8447 months ago"
},
{
"code": null,
"e": 2019,
"s": 1733,
"text": "vector<string> interestingPattern(int N) { vector<string> v; for(int i=1;i<=2*N-1;++i) { string str=\"\"; for(int j=1;j<=2*N-1;++j) { int k=max(abs(i-N),abs(j-N))+1; str+=to_string(k); } v.push_back(str); } return v; }"
},
{
"code": null,
"e": 2167,
"s": 2021,
"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": 2203,
"s": 2167,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2213,
"s": 2203,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2223,
"s": 2213,
"text": "\nContest\n"
},
{
"code": null,
"e": 2286,
"s": 2223,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2434,
"s": 2286,
"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": 2642,
"s": 2434,
"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": 2748,
"s": 2642,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How long JWT token valid ? - GeeksforGeeks
|
01 Dec, 2021
JSON web token is an efficient, secured as well mostly used method of transferring or exchanging data on the internet. Generally, it is used for authentication and authorization in applications. The workflow of the authentication is we generate the token at the server and send back it to the client which is used for further requests on the server, Now the point of discussion is how long this jwt token will be valid? that means after which duration the server will not consider the token sent by the client. Let’s first understand how a JWT token gets created.
The sign() method of the jsonwebtoken library is used for creating a token that accepts certain information as parameter objects and returns the generated token.
Syntax:
jwt.sign(payload, secretOrPrivateKey, [options, callback])
Parameters:
payload: It is the information to be encrypted in the token
secretKey: It is the signature or can say a code that is used to identify the authenticity of the token.
options: In the option, we pass certain information about the token and that’s the place where we provide the duration of the token up to which it will be valid.
Return type: This method will return JWT token
Example: Creating a token with 10 minutes expiry.
Step 1: Create a node project
As we are working on a node library it is a mandatory step to create a node project, write npm init in the terminal. It will ask for a few configurations about your project which is super easy to provide.
npm init
Step 2: Install the “jsonwebtoken” Package
Before going to write the JWT code we must have to install the package,
npm install jsonwebtoken
This would be our project structure after installation where node_modules contain the modules and package.json stores the description of the project. Also, we have created an app.js file to write the entire code.
Project Structure:
Step 3: Creating JWT token with a definite expire time.
There are two methods of registering the expiry of the token both are shown below with an explanation.
Creating an expression of an expiry time.
Providing expiry time of JWT token in the options argument of the method.
Approach 1: There exists a key exp in which we can provide the number of seconds since the epoch and the token will be valid till those seconds.
Javascript
// Importing moduleconst jwt = require('jsonwebtoken');const token = jwt.sign({ // Expression for initialising expiry time exp: Math.floor(Date.now() / 1000) + (10 * 60), data: 'Token Data'}, 'secretKey');const date = new Date();console.log(`Token Generated at:- ${date.getHours()} :${date.getMinutes()} :${date.getSeconds()}`); // Printing the JWT tokenconsole.log(token);
Output:
Approach 2: In this method, we can pass the time to expiresIn key in the options, it requires the number of seconds till the token will remain valid or the string of duration as ‘1h’, ‘2h’, ’10m’, etc.
Javascript
// Importing moduleconst jwt = require('jsonwebtoken');const token = jwt.sign({ // Assigning data value data: 'Token Data'}, 'secretKey', { expiresIn: '10m'});const date = new Date();console.log(`Token Generated at:- ${date.getHours()} :${date.getMinutes()} :${date.getSeconds()}`);// Printing JWT tokenconsole.log(token);
Output:
Step 4: Verify the token in terms of expiry duration
We have successfully generated the token now it’s time to verify whether the code is working in its intended way or not.
Javascript
//Importing moduleconst jwt = require('jsonwebtoken');// JWT tokenconst token ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mzc4NjgxMzMsImRhdGWf" const date = new Date();// Verifing the JWT tokenjwt.verify(token, 'secretKey', function(err, decoded) { if (err) { console.log(`${date.getHours()}:${date.getMinutes()} :${date.getSeconds()}`); console.log(err); } else { console.log(`${date.getHours()}:${date.getMinutes()} :${date.getSeconds()}`); console.log("Token verifified successfully"); }});
Before 10 minutes:
Output 1: Here we are checking before 10 minutes of generating token, as expected the else block of code will work.
After 10 minutes:
Output 2: Here we are checking once the token is expired, the TokenExpirationError will be thrown in this case.
Conclusion: After seeing these two outputs and the method of creating tokens we can analyze that how the duration of the token is declared and how long it remains valid.
anikakapoor
JSON
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Difference between npm i and npm ci in Node.js
Express.js req.params Property
Mongoose Populate() Method
Roadmap to Become a Web Developer in 2022
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?
Top 10 Angular Libraries For Web Developers
|
[
{
"code": null,
"e": 24842,
"s": 24814,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 25406,
"s": 24842,
"text": "JSON web token is an efficient, secured as well mostly used method of transferring or exchanging data on the internet. Generally, it is used for authentication and authorization in applications. The workflow of the authentication is we generate the token at the server and send back it to the client which is used for further requests on the server, Now the point of discussion is how long this jwt token will be valid? that means after which duration the server will not consider the token sent by the client. Let’s first understand how a JWT token gets created."
},
{
"code": null,
"e": 25570,
"s": 25406,
"text": "The sign() method of the jsonwebtoken library is used for creating a token that accepts certain information as parameter objects and returns the generated token. "
},
{
"code": null,
"e": 25578,
"s": 25570,
"text": "Syntax:"
},
{
"code": null,
"e": 25637,
"s": 25578,
"text": "jwt.sign(payload, secretOrPrivateKey, [options, callback])"
},
{
"code": null,
"e": 25649,
"s": 25637,
"text": "Parameters:"
},
{
"code": null,
"e": 25709,
"s": 25649,
"text": "payload: It is the information to be encrypted in the token"
},
{
"code": null,
"e": 25814,
"s": 25709,
"text": "secretKey: It is the signature or can say a code that is used to identify the authenticity of the token."
},
{
"code": null,
"e": 25976,
"s": 25814,
"text": "options: In the option, we pass certain information about the token and that’s the place where we provide the duration of the token up to which it will be valid."
},
{
"code": null,
"e": 26023,
"s": 25976,
"text": "Return type: This method will return JWT token"
},
{
"code": null,
"e": 26073,
"s": 26023,
"text": "Example: Creating a token with 10 minutes expiry."
},
{
"code": null,
"e": 26103,
"s": 26073,
"text": "Step 1: Create a node project"
},
{
"code": null,
"e": 26308,
"s": 26103,
"text": "As we are working on a node library it is a mandatory step to create a node project, write npm init in the terminal. It will ask for a few configurations about your project which is super easy to provide."
},
{
"code": null,
"e": 26317,
"s": 26308,
"text": "npm init"
},
{
"code": null,
"e": 26360,
"s": 26317,
"text": "Step 2: Install the “jsonwebtoken” Package"
},
{
"code": null,
"e": 26433,
"s": 26360,
"text": "Before going to write the JWT code we must have to install the package, "
},
{
"code": null,
"e": 26458,
"s": 26433,
"text": "npm install jsonwebtoken"
},
{
"code": null,
"e": 26672,
"s": 26458,
"text": "This would be our project structure after installation where node_modules contain the modules and package.json stores the description of the project. Also, we have created an app.js file to write the entire code. "
},
{
"code": null,
"e": 26691,
"s": 26672,
"text": "Project Structure:"
},
{
"code": null,
"e": 26747,
"s": 26691,
"text": "Step 3: Creating JWT token with a definite expire time."
},
{
"code": null,
"e": 26851,
"s": 26747,
"text": "There are two methods of registering the expiry of the token both are shown below with an explanation. "
},
{
"code": null,
"e": 26893,
"s": 26851,
"text": "Creating an expression of an expiry time."
},
{
"code": null,
"e": 26967,
"s": 26893,
"text": "Providing expiry time of JWT token in the options argument of the method."
},
{
"code": null,
"e": 27112,
"s": 26967,
"text": "Approach 1: There exists a key exp in which we can provide the number of seconds since the epoch and the token will be valid till those seconds."
},
{
"code": null,
"e": 27123,
"s": 27112,
"text": "Javascript"
},
{
"code": "// Importing moduleconst jwt = require('jsonwebtoken');const token = jwt.sign({ // Expression for initialising expiry time exp: Math.floor(Date.now() / 1000) + (10 * 60), data: 'Token Data'}, 'secretKey');const date = new Date();console.log(`Token Generated at:- ${date.getHours()} :${date.getMinutes()} :${date.getSeconds()}`); // Printing the JWT tokenconsole.log(token);",
"e": 27567,
"s": 27123,
"text": null
},
{
"code": null,
"e": 27576,
"s": 27567,
"text": " Output:"
},
{
"code": null,
"e": 27779,
"s": 27576,
"text": "Approach 2: In this method, we can pass the time to expiresIn key in the options, it requires the number of seconds till the token will remain valid or the string of duration as ‘1h’, ‘2h’, ’10m’, etc."
},
{
"code": null,
"e": 27790,
"s": 27779,
"text": "Javascript"
},
{
"code": "// Importing moduleconst jwt = require('jsonwebtoken');const token = jwt.sign({ // Assigning data value data: 'Token Data'}, 'secretKey', { expiresIn: '10m'});const date = new Date();console.log(`Token Generated at:- ${date.getHours()} :${date.getMinutes()} :${date.getSeconds()}`);// Printing JWT tokenconsole.log(token);",
"e": 28183,
"s": 27790,
"text": null
},
{
"code": null,
"e": 28191,
"s": 28183,
"text": "Output:"
},
{
"code": null,
"e": 28244,
"s": 28191,
"text": "Step 4: Verify the token in terms of expiry duration"
},
{
"code": null,
"e": 28366,
"s": 28244,
"text": "We have successfully generated the token now it’s time to verify whether the code is working in its intended way or not. "
},
{
"code": null,
"e": 28377,
"s": 28366,
"text": "Javascript"
},
{
"code": "//Importing moduleconst jwt = require('jsonwebtoken');// JWT tokenconst token =\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mzc4NjgxMzMsImRhdGWf\" const date = new Date();// Verifing the JWT tokenjwt.verify(token, 'secretKey', function(err, decoded) { if (err) { console.log(`${date.getHours()}:${date.getMinutes()} :${date.getSeconds()}`); console.log(err); } else { console.log(`${date.getHours()}:${date.getMinutes()} :${date.getSeconds()}`); console.log(\"Token verifified successfully\"); }});",
"e": 28994,
"s": 28377,
"text": null
},
{
"code": null,
"e": 29013,
"s": 28994,
"text": "Before 10 minutes:"
},
{
"code": null,
"e": 29129,
"s": 29013,
"text": "Output 1: Here we are checking before 10 minutes of generating token, as expected the else block of code will work."
},
{
"code": null,
"e": 29147,
"s": 29129,
"text": "After 10 minutes:"
},
{
"code": null,
"e": 29260,
"s": 29147,
"text": "Output 2: Here we are checking once the token is expired, the TokenExpirationError will be thrown in this case. "
},
{
"code": null,
"e": 29430,
"s": 29260,
"text": "Conclusion: After seeing these two outputs and the method of creating tokens we can analyze that how the duration of the token is declared and how long it remains valid."
},
{
"code": null,
"e": 29442,
"s": 29430,
"text": "anikakapoor"
},
{
"code": null,
"e": 29447,
"s": 29442,
"text": "JSON"
},
{
"code": null,
"e": 29464,
"s": 29447,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 29471,
"s": 29464,
"text": "Picked"
},
{
"code": null,
"e": 29479,
"s": 29471,
"text": "Node.js"
},
{
"code": null,
"e": 29496,
"s": 29479,
"text": "Web Technologies"
},
{
"code": null,
"e": 29594,
"s": 29496,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29603,
"s": 29594,
"text": "Comments"
},
{
"code": null,
"e": 29616,
"s": 29603,
"text": "Old Comments"
},
{
"code": null,
"e": 29653,
"s": 29616,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 29685,
"s": 29653,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 29732,
"s": 29685,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 29763,
"s": 29732,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 29790,
"s": 29763,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29832,
"s": 29790,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29894,
"s": 29832,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29937,
"s": 29894,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29987,
"s": 29937,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Absolute and Relative Imports in Python
|
Many times when we create python code we find that we need to access code from another python file or package. This is when you need to import that other python file or package into your current code. So the straight forward way to achieve this is just written the below statement at the top of your current python program.
import package_name or module_name
or
from pacakge_name import module_name/object_name
When the above statement is parsed the interpreter does the following.
The interpreter will look for names in the cache of all modules that have already been imported previously. The name of this cache module in sys.modules.
The interpreter will look for names in the cache of all modules that have already been imported previously. The name of this cache module in sys.modules.
If not found in the above step then the interpreter will search for it in a list of built-in modules. These modules are part of python standard libraries.
If not found in the above step then the interpreter will search for it in a list of built-in modules. These modules are part of python standard libraries.
In case it is still not found in step-2 above, then the interpreter will search for the packages or module names in a list of directories defined in sys.path which has the current directory as the first directory to be searched.
In case it is still not found in step-2 above, then the interpreter will search for the packages or module names in a list of directories defined in sys.path which has the current directory as the first directory to be searched.
On finding them to be an imported module in any of the above steps, the name of the package or module is bound to the local scope of the current program.
On finding them to be an imported module in any of the above steps, the name of the package or module is bound to the local scope of the current program.
If the package or module is never found, then ModuleNotFoundError is raised.
If the package or module is never found, then ModuleNotFoundError is raised.
Some rules about importing.
Import statements should be mentioned at the top of the files using those statements. The order in which the import has to be mentioned is as below.
Python's standard library modules
Python's standard library modules
Import from third-party modules
Import from third-party modules
Import from local applications
Import from local applications
In this type of import, we specify the full path of the package/module/function to be imported.
A dot(.) is used in pace of slash(/) for the directory structure.
Consider the following directory structure for a package.
python_project_name/packageA/moduleA1.py
python_project_name/packageA/moduleA2.py
Also, Let's assume moduleA2 has a function names myfunc. When we want to import that function to our current python program, then using absolute path we mention the following import statement.
from packageA.moduleA2 import myfunc
The big advantage of absolute import is, it clearly indicates where the import is happening on the other hand sometimes it can get quite lengthy.
In relative import, we mention the path of the imported package as relative to the location of the current script which is using the imported module.
A dot indicates one directory up from the current location and two dots indicates two directories up and so on.
Consider the following directory structure for a package.
python_project_name/packageA/moduleA1.py
python_project_name/packageB/moduleB1.py
Let's assume moduleB1 in the above package structure needs to import moduleA1. Then the import statement is:
from ..packageA import moduleA1
The two dots indicate that from the location of moduleB1, we have to move to the directory python_project_name and then go to packageA to get moduleA1.
This kind of import are short and the top level project can be moved from one location to another without changing the path in the import statements easily. On the downside, if the import folders are shared then the code easily gets impacted when there is some modification in the path.
|
[
{
"code": null,
"e": 1386,
"s": 1062,
"text": "Many times when we create python code we find that we need to access code from another python file or package. This is when you need to import that other python file or package into your current code. So the straight forward way to achieve this is just written the below statement at the top of your current python program."
},
{
"code": null,
"e": 1473,
"s": 1386,
"text": "import package_name or module_name\nor\nfrom pacakge_name import module_name/object_name"
},
{
"code": null,
"e": 1544,
"s": 1473,
"text": "When the above statement is parsed the interpreter does the following."
},
{
"code": null,
"e": 1698,
"s": 1544,
"text": "The interpreter will look for names in the cache of all modules that have already been imported previously. The name of this cache module in sys.modules."
},
{
"code": null,
"e": 1852,
"s": 1698,
"text": "The interpreter will look for names in the cache of all modules that have already been imported previously. The name of this cache module in sys.modules."
},
{
"code": null,
"e": 2007,
"s": 1852,
"text": "If not found in the above step then the interpreter will search for it in a list of built-in modules. These modules are part of python standard libraries."
},
{
"code": null,
"e": 2162,
"s": 2007,
"text": "If not found in the above step then the interpreter will search for it in a list of built-in modules. These modules are part of python standard libraries."
},
{
"code": null,
"e": 2391,
"s": 2162,
"text": "In case it is still not found in step-2 above, then the interpreter will search for the packages or module names in a list of directories defined in sys.path which has the current directory as the first directory to be searched."
},
{
"code": null,
"e": 2620,
"s": 2391,
"text": "In case it is still not found in step-2 above, then the interpreter will search for the packages or module names in a list of directories defined in sys.path which has the current directory as the first directory to be searched."
},
{
"code": null,
"e": 2774,
"s": 2620,
"text": "On finding them to be an imported module in any of the above steps, the name of the package or module is bound to the local scope of the current program."
},
{
"code": null,
"e": 2928,
"s": 2774,
"text": "On finding them to be an imported module in any of the above steps, the name of the package or module is bound to the local scope of the current program."
},
{
"code": null,
"e": 3005,
"s": 2928,
"text": "If the package or module is never found, then ModuleNotFoundError is raised."
},
{
"code": null,
"e": 3082,
"s": 3005,
"text": "If the package or module is never found, then ModuleNotFoundError is raised."
},
{
"code": null,
"e": 3110,
"s": 3082,
"text": "Some rules about importing."
},
{
"code": null,
"e": 3259,
"s": 3110,
"text": "Import statements should be mentioned at the top of the files using those statements. The order in which the import has to be mentioned is as below."
},
{
"code": null,
"e": 3293,
"s": 3259,
"text": "Python's standard library modules"
},
{
"code": null,
"e": 3327,
"s": 3293,
"text": "Python's standard library modules"
},
{
"code": null,
"e": 3359,
"s": 3327,
"text": "Import from third-party modules"
},
{
"code": null,
"e": 3391,
"s": 3359,
"text": "Import from third-party modules"
},
{
"code": null,
"e": 3422,
"s": 3391,
"text": "Import from local applications"
},
{
"code": null,
"e": 3453,
"s": 3422,
"text": "Import from local applications"
},
{
"code": null,
"e": 3615,
"s": 3453,
"text": "In this type of import, we specify the full path of the package/module/function to be imported.\nA dot(.) is used in pace of slash(/) for the directory structure."
},
{
"code": null,
"e": 3673,
"s": 3615,
"text": "Consider the following directory structure for a package."
},
{
"code": null,
"e": 3755,
"s": 3673,
"text": "python_project_name/packageA/moduleA1.py\npython_project_name/packageA/moduleA2.py"
},
{
"code": null,
"e": 3948,
"s": 3755,
"text": "Also, Let's assume moduleA2 has a function names myfunc. When we want to import that function to our current python program, then using absolute path we mention the following import statement."
},
{
"code": null,
"e": 3985,
"s": 3948,
"text": "from packageA.moduleA2 import myfunc"
},
{
"code": null,
"e": 4131,
"s": 3985,
"text": "The big advantage of absolute import is, it clearly indicates where the import is happening on the other hand sometimes it can get quite lengthy."
},
{
"code": null,
"e": 4281,
"s": 4131,
"text": "In relative import, we mention the path of the imported package as relative to the location of the current script which is using the imported module."
},
{
"code": null,
"e": 4393,
"s": 4281,
"text": "A dot indicates one directory up from the current location and two dots indicates two directories up and so on."
},
{
"code": null,
"e": 4451,
"s": 4393,
"text": "Consider the following directory structure for a package."
},
{
"code": null,
"e": 4533,
"s": 4451,
"text": "python_project_name/packageA/moduleA1.py\npython_project_name/packageB/moduleB1.py"
},
{
"code": null,
"e": 4642,
"s": 4533,
"text": "Let's assume moduleB1 in the above package structure needs to import moduleA1. Then the import statement is:"
},
{
"code": null,
"e": 4674,
"s": 4642,
"text": "from ..packageA import moduleA1"
},
{
"code": null,
"e": 4826,
"s": 4674,
"text": "The two dots indicate that from the location of moduleB1, we have to move to the directory python_project_name and then go to packageA to get moduleA1."
},
{
"code": null,
"e": 5113,
"s": 4826,
"text": "This kind of import are short and the top level project can be moved from one location to another without changing the path in the import statements easily. On the downside, if the import folders are shared then the code easily gets impacted when there is some modification in the path."
}
] |
Struts 2 - Control Tags
|
The Struts 2 tags has a set of tags that makes it easy to control the flow of page execution.
Following is the list of important Struts 2 Control Tags −
These tags perform basic condition flow found in every language.
'If' tag is used by itself or with 'Else If' Tag and/or single/multiple 'Else' Tag as shown below −
<s:if test = "%{false}">
<div>Will Not Be Executed</div>
</s:if>
<s:elseif test = "%{true}">
<div>Will Be Executed</div>
</s:elseif>
<s:else>
<div>Will Not Be Executed</div>
</s:else>
Check Detailed Example
This iterator will iterate over a value. An iterable value can be either itherjava.util.Collection or java.util.Iterator file. While iterating over an iterator, you can use Sort tag to sort the result or SubSet tag to get a sub set of the list or array.
The following example retrieves the value of the getDays() method of the current object on the value stack and uses it to iterate over.
The <s:property/> tag prints out the current value of the iterator.
<s:iterator value = "days">
<p>day is: <s:property/></p>
</s:iterator>
Check Detailed Example
These merge tag takes two or more lists as parameters and merge them all together as shown below −
<s:merge var = "myMergedIterator">
<s:param value = "%{myList1}" />
<s:param value = "%{myList2}" />
<s:param value = "%{myList3}" />
</s:merge>
<s:iterator value = "%{#myMergedIterator}">
<s:property />
</s:iterator>
Check Detailed Example
These append tag take two or more lists as parameters and append them all together as shown below −
<s:append var = "myAppendIterator">
<s:param value = "%{myList1}" />
<s:param value = "%{myList2}" />
<s:param value = "%{myList3}" />
</s:append>
<s:iterator value = "%{#myAppendIterator}">
<s:property />
</s:iterator>
Check Detailed Example
These generator tag generates an iterator based on the val attribute supplied. The following generator tag generates an iterator and prints it out using the iterator tag.
<s:generator val = "%{'aaa,bbb,ccc,ddd,eee'}">
<s:iterator>
<s:property /><br/>
</s:iterator>
</s:generator>
Check Detailed Example
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2340,
"s": 2246,
"text": "The Struts 2 tags has a set of tags that makes it easy to control the flow of page execution."
},
{
"code": null,
"e": 2399,
"s": 2340,
"text": "Following is the list of important Struts 2 Control Tags −"
},
{
"code": null,
"e": 2464,
"s": 2399,
"text": "These tags perform basic condition flow found in every language."
},
{
"code": null,
"e": 2564,
"s": 2464,
"text": "'If' tag is used by itself or with 'Else If' Tag and/or single/multiple 'Else' Tag as shown below −"
},
{
"code": null,
"e": 2759,
"s": 2564,
"text": "<s:if test = \"%{false}\">\n <div>Will Not Be Executed</div>\n</s:if>\n\n<s:elseif test = \"%{true}\">\n <div>Will Be Executed</div>\n</s:elseif>\n\n<s:else>\n <div>Will Not Be Executed</div>\n</s:else>"
},
{
"code": null,
"e": 2782,
"s": 2759,
"text": "Check Detailed Example"
},
{
"code": null,
"e": 3036,
"s": 2782,
"text": "This iterator will iterate over a value. An iterable value can be either itherjava.util.Collection or java.util.Iterator file. While iterating over an iterator, you can use Sort tag to sort the result or SubSet tag to get a sub set of the list or array."
},
{
"code": null,
"e": 3172,
"s": 3036,
"text": "The following example retrieves the value of the getDays() method of the current object on the value stack and uses it to iterate over."
},
{
"code": null,
"e": 3240,
"s": 3172,
"text": "The <s:property/> tag prints out the current value of the iterator."
},
{
"code": null,
"e": 3314,
"s": 3240,
"text": "<s:iterator value = \"days\">\n <p>day is: <s:property/></p>\n</s:iterator>"
},
{
"code": null,
"e": 3337,
"s": 3314,
"text": "Check Detailed Example"
},
{
"code": null,
"e": 3436,
"s": 3337,
"text": "These merge tag takes two or more lists as parameters and merge them all together as shown below −"
},
{
"code": null,
"e": 3667,
"s": 3436,
"text": "<s:merge var = \"myMergedIterator\">\n <s:param value = \"%{myList1}\" />\n <s:param value = \"%{myList2}\" />\n <s:param value = \"%{myList3}\" />\n</s:merge>\n\n<s:iterator value = \"%{#myMergedIterator}\">\n <s:property />\n</s:iterator>"
},
{
"code": null,
"e": 3690,
"s": 3667,
"text": "Check Detailed Example"
},
{
"code": null,
"e": 3790,
"s": 3690,
"text": "These append tag take two or more lists as parameters and append them all together as shown below −"
},
{
"code": null,
"e": 4023,
"s": 3790,
"text": "<s:append var = \"myAppendIterator\">\n <s:param value = \"%{myList1}\" />\n <s:param value = \"%{myList2}\" />\n <s:param value = \"%{myList3}\" />\n</s:append>\n\n<s:iterator value = \"%{#myAppendIterator}\">\n <s:property />\n</s:iterator>"
},
{
"code": null,
"e": 4046,
"s": 4023,
"text": "Check Detailed Example"
},
{
"code": null,
"e": 4217,
"s": 4046,
"text": "These generator tag generates an iterator based on the val attribute supplied. The following generator tag generates an iterator and prints it out using the iterator tag."
},
{
"code": null,
"e": 4338,
"s": 4217,
"text": "<s:generator val = \"%{'aaa,bbb,ccc,ddd,eee'}\">\n <s:iterator>\n <s:property /><br/>\n </s:iterator>\n</s:generator>"
},
{
"code": null,
"e": 4361,
"s": 4338,
"text": "Check Detailed Example"
},
{
"code": null,
"e": 4368,
"s": 4361,
"text": " Print"
},
{
"code": null,
"e": 4379,
"s": 4368,
"text": " Add Notes"
}
] |
jQuery - Drawsvg.js
|
Drawsvg.js is a jQuery plugin to draw svg images
A Simple of drawsvg example as shown below −
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<link rel = "shortcut icon" type = "image/x-icon" href = "favicon.ico">
<link rel = "stylesheet"
href = "https://fonts.googleapis.com/css?family=Open+Sans:400,600">
<link rel = "stylesheet" href = "style.css">
</head>
<body>
<div class = "intro">
<div class = "container">
<div class = "overlay">
<div class = "inner">
<h1>jQuery DrawSVG Sample</h1>
<div class = "items-wrapper">
<div class ="item active">
<svg viewBox = "0 0 201 146" class = "svgClass"
style = "background-color:#ffffff00"
xmlns = "https://www.w3.org/2000/svg" width = "201"
height = "146">
<g stroke = "#FFF" stroke-width = "1" fill = "none">
<path d = "M200.5 128.586c0 9.302-7.678
16.914-17.06 16.914H17.56C8.18 145.5.5
137.888.5 128.586V29.414C.5 20.112 8.178
12.5 17.56 12.5h165.88c9.382 0 17.06
7.612 17.06 16.914v99.172z"/>
<path d = "M183.828 80.118c0 26.467-21.644
47.924-48.34 47.924-26.698
0-48.342-21.457-48.342-47.924s21.644-47.924
48.34-47.924c26.698 0 48.342 21.457 48.342
47.924z"/>
<path d = "M171.98 80.118c0 19.978-16.338
36.177-36.493 36.177-20.15
0-36.49-16.2-36.49-36.177 0-19.98
16.34-36.177 36.49-36.177 20.155 0
36.494 16.2 36.494 36.178z"/>
<path d = "M50.18 48.637c0 6.49-5.304
11.747-11.852 11.747-6.543
0-11.847-5.258-11.847-11.747 0-6.488
5.305-11.746 11.848-11.746 6.548 0 11.852
5.26 11. 852 11.747z"/>
<path d = "M17.928 39.877c3.41-7.835
11.258-13.305 20.416-13.305 9.16 0 17.006
5.47 20.416 13.305"/>
<path d = "M46 12V4H26v8"/>
<path d = "M94.833 12l11.5-11.5h59.5l11.5 11.5"/>
<path d = "M26.333 92.5h35.5"/>
<path d = "M26.333 105.5h43"/>
<path d = "M26.333 117.5h52"/>
</g>
</svg>
</div>
<div class = "item">
<svg viewBox = "0 0 207 105" style = "background-color:#ffffff00"
xmlns = "https://www.w3.org/2000/svg" width = "207"
height = "105">
<g stroke = "#FFF" stroke-width = "1" fill = "none">
<path d = "M127 63.496C127 85.306 144.455
103 165.998 103 187.538 103 205 85.306
205 63.496 205 41.682 187.537 24 165.998
24 144.455 24 127 41.682 127 63.496z"/>
<path d = "M195 63.497C195 47.206 182.015 34 166 34"/>
<path d = "M2 63.496C2 85.306 19.455 103
41.002 103 62.542 103 80 85.306 80 63.496
80 41.682 62.54 24 41.002 24 19.455 24 2
41.682 2 63.496z"/>
<path d = "M64.296 22.732C57.656 18.094
47.492 16 41.002 16c-6.49 0-12.675
1.33-18.3 3.732-5.622 2.404-10.686
5.88-14.938 10.178"/>
<path d = "M159.715 63.576c0 3.634 2.902
6.575 6.49 6.575 3.582 0 6.484-2.94
6.484-6.574 0-3.63-2.903-6.575-6.486-6.575-3.587
0-6.49 2.946-6.49 6.576z"/>
<path d = "M34.873 64.032c0 3.63 2.907
6.575 6.494 6.575 3.578 0 6.485-2.945
6.485-6.575 0-3.635-2.907-6.575-6.485-6.575-3.587
0-6.494 2.94-6.494 6.575z"/>
<path d = "M163.25 57.026L141.773 3"/>
<path d = "M98 63.5H48"/>
<path d = "M101.73 57.63L70.5 14.013"/>
<path d = "M70.49 14.5h76.646v-.206"/>
<path d = "M139.134 14.505L108.468 57.95"/>
<path d = "M70.894 15.05L42.834 57.05"/>
<path d = "M70.5 14V3"/>
<path d = "M141.427 3.23s19.83-7.71 19.83 6.344"/>
<path d = "M97.816 62.52c0 3.576 2.86 6.475
6.39 6.475s6.392-2.9
6.392-6.476c0-3.577-2.86-6.476-6.39
-6.476s-6.392 2.9-6.392 6.476z"/>
<path d = "M106.642 69.26l2.913 11.044"/>
<path d = "M105 83l10-5"/>
<path d = "M62.5 3.5h18"/>
</g>
</svg>
</div>
<div class = "item">
<svg viewBox = "0 0 201 116" style = "background-color:#ffffff00"
xmlns = "https://www.w3.org/2000/svg" width = "201"
height = "116">
<g stroke = "#FFF" stroke-width = "1" fill = "none">
<path d = "M19.5 101.5V6.45C19.5 3.176 23.12.5
26.402.5H175.53c3.282 0 5.97 2.677 5.97
5.95v95.05"/>
<path d = "M171.5 89.5h-140v-77h140v77z"/>
<path d = "M200.5 107.526c0 1.635-1.344
2.974-2.985 2.974H3.485c-1.64
0-2.985-1.34-2.985-2.974v-3.052c0-1.635
1.344-2.974 2.985-2.974h194.03c1.64 0 2.985
1.34 2.9852.974v3.052z"/>
<path d = "M1 110l10.5 5.5"/>
<path d = "M11.604 115.5H189.46"/>
<path d = "M189.5 115.5l9.5-5.5"/>
<path d = "M99.5 7.5h5"/>
<path d = "M138.5 12.5l28 28"/>
<path d = "M148.5 12.5l18 18"/>
<path d = "M159.5 12.5l7 6"/>
</g>
</svg>
</div>
<div class = "item">
<svg viewBox = "0 0 200 155" style = "background-color:#ffffff00"
xmlns = "https://www.w3.org/2000/svg" width = "200"
height = "155">
<g stroke = "#FFF" stroke-width = "1" fill = "none">
<path d="M161.996 151.39l-33.97-27.178-45.01
30.576-35.67-27.603L.36 154.245 38.662 20.04
80.893 4.034l39.066 17.41L161.995.213l37.792
22.932-37.792 128.246z"/>
<path d = "M47.346 127.185L80.892 4.035"/>
<path d = "M83.015 154.788l36.942-133.343"/>
<path d = "M128.025 124.212l33.97-124"/>
<path d = "M46.278 23.935L32.29 75.605"/>
<path d = "M95.802 45.718L81.19 97.225"/>
<path d = "M106.91 33.115l-22.26 81.39"/>
<path d = "M176.768 46.665c0 3.523-2.85
6.376-6.366 6.376-3.514 0-6.364-2.852
-6.364-6.375 0-3.512 2.85-6.37
6.364-6.37 3.516 0 6.366 2.858
6.366 6.37z"/>
<path d = "M180.9 52.392l-10.844
19.91-10.394-19.995s-1.143-3.215-1.
143-5.067c0-6.514 5.273-11.81 11.79-11.81
6.508 0 11.782 5.296 11.782 11.81
0 1.852-1.192 5.152-1.192 5.152z"/>
<path d = "M43.86 92.528c0 3.523-2.85
6.376-6.367 6.376-3.514 0-6.364-2.
853-6.364-6.376 0-3.512 2.85-6.37
6.363-6.37 3.517 0 6.366 2.858
6.366 6.37z"/>
<path d = "M47.99 98.255l-10.843 19.91L26.754
98.17s-1.143-3.215-1.
143-5.067c0-6.514 5.275-11.81
11.793-11.81 6.507 0 11.78 5.296
11.78 11.81 0 1.852-1.192
5.152-1.192 5.152z"/>
</g>
</svg>
</div>
</div>
</div>
</div>
</div>
</div>
<div id = "fb-root"></div>
<script async src = "//assets.codepen.io/assets/embed/ei.js">
</script>
<script src = "https://cdn.jsdelivr.net/jquery/1.11.3/jquery.min.js">
</script>
<script
src = "https://cdn.jsdelivr.net/jquery.easing/1.3/jquery.easing.1.3.min.js">
</script>
<script src = "jquery.drawsvg.min.js"></script>
<script>
$(function() {
var $doc = $(document),
$win = $(window);
var $intro = $('.intro'),
$items = $intro.find('.item'),
itemsLen = $items.length,
svgs = $intro.find('svg').drawsvg({
callback: animateIntro,
easing: 'easeOutQuart'
}),
currItem = 0;
function animateIntro() {
$items.removeClass('active').eq( currItem++ % itemsLen
).addClass('active').find('svg').drawsvg('animate');
}
animateIntro();
var $header = $('header'),
headerOffTop = $header.offset().top,
isFixed = false;
function menu() {
if ( $win.scrollTop() >= headerOffTop ) {
if ( !isFixed ) {
isFixed = true;
$header.addClass('affix');
}
} else if ( isFixed ) {
isFixed = false;
$header.removeClass('affix');
}
}
$win.on('scroll', menu);
menu();
$header.on('click', 'a[href^="#"]', function(e) {
e.preventDefault();
var hash = this.hash,
offset = $(hash).offset().top;
$('body, html').animate({
scrollTop: offset
}, 600, 'easeInOutQuart', function() {
document.location.hash = hash;
});
});
});
</script>
</body>
</html>
This should produce following result −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2371,
"s": 2322,
"text": "Drawsvg.js is a jQuery plugin to draw svg images"
},
{
"code": null,
"e": 2416,
"s": 2371,
"text": "A Simple of drawsvg example as shown below −"
},
{
"code": null,
"e": 14699,
"s": 2416,
"text": "<!DOCTYPE html>\n<html lang = \"en\">\n <head>\n <meta charset = \"UTF-8\">\n <link rel = \"shortcut icon\" type = \"image/x-icon\" href = \"favicon.ico\">\n <link rel = \"stylesheet\" \n href = \"https://fonts.googleapis.com/css?family=Open+Sans:400,600\">\n <link rel = \"stylesheet\" href = \"style.css\">\n </head>\n\t\n <body>\n <div class = \"intro\">\n <div class = \"container\">\n <div class = \"overlay\">\n <div class = \"inner\">\n <h1>jQuery DrawSVG Sample</h1>\n\n <div class = \"items-wrapper\">\n <div class =\"item active\">\n <svg viewBox = \"0 0 201 146\" class = \"svgClass\" \n style = \"background-color:#ffffff00\" \n xmlns = \"https://www.w3.org/2000/svg\" width = \"201\"\n height = \"146\">\n\t\t\t\t\t\t\t\t\t\n <g stroke = \"#FFF\" stroke-width = \"1\" fill = \"none\">\n <path d = \"M200.5 128.586c0 9.302-7.678\n 16.914-17.06 16.914H17.56C8.18 145.5.5 \n 137.888.5 128.586V29.414C.5 20.112 8.178 \n 12.5 17.56 12.5h165.88c9.382 0 17.06 \n 7.612 17.06 16.914v99.172z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M183.828 80.118c0 26.467-21.644 \n 47.924-48.34 47.924-26.698 \n 0-48.342-21.457-48.342-47.924s21.644-47.924 \n 48.34-47.924c26.698 0 48.342 21.457 48.342\n 47.924z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M171.98 80.118c0 19.978-16.338\n 36.177-36.493 36.177-20.15 \n 0-36.49-16.2-36.49-36.177 0-19.98 \n 16.34-36.177 36.49-36.177 20.155 0 \n 36.494 16.2 36.494 36.178z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M50.18 48.637c0 6.49-5.304 \n 11.747-11.852 11.747-6.543\n 0-11.847-5.258-11.847-11.747 0-6.488 \n 5.305-11.746 11.848-11.746 6.548 0 11.852 \n 5.26 11. 852 11.747z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M17.928 39.877c3.41-7.835 \n 11.258-13.305 20.416-13.305 9.16 0 17.006 \n 5.47 20.416 13.305\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M46 12V4H26v8\"/>\n <path d = \"M94.833 12l11.5-11.5h59.5l11.5 11.5\"/>\n <path d = \"M26.333 92.5h35.5\"/>\n <path d = \"M26.333 105.5h43\"/>\n <path d = \"M26.333 117.5h52\"/>\n </g>\n\t\t\t\t\t\t\t\t\t\n </svg>\n </div>\n\n <div class = \"item\">\n <svg viewBox = \"0 0 207 105\" style = \"background-color:#ffffff00\" \n xmlns = \"https://www.w3.org/2000/svg\" width = \"207\" \n height = \"105\">\n\t\t\t\t\t\t\t\t\n <g stroke = \"#FFF\" stroke-width = \"1\" fill = \"none\">\n <path d = \"M127 63.496C127 85.306 144.455 \n 103 165.998 103 187.538 103 205 85.306 \n 205 63.496 205 41.682 187.537 24 165.998\n 24 144.455 24 127 41.682 127 63.496z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M195 63.497C195 47.206 182.015 34 166 34\"/>\n\t\t\t\t\t\t\t\t\t\t\n <path d = \"M2 63.496C2 85.306 19.455 103 \n 41.002 103 62.542 103 80 85.306 80 63.496 \n 80 41.682 62.54 24 41.002 24 19.455 24 2\n 41.682 2 63.496z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M64.296 22.732C57.656 18.094 \n 47.492 16 41.002 16c-6.49 0-12.675 \n 1.33-18.3 3.732-5.622 2.404-10.686 \n 5.88-14.938 10.178\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M159.715 63.576c0 3.634 2.902 \n 6.575 6.49 6.575 3.582 0 6.484-2.94 \n 6.484-6.574 0-3.63-2.903-6.575-6.486-6.575-3.587\n 0-6.49 2.946-6.49 6.576z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M34.873 64.032c0 3.63 2.907 \n 6.575 6.494 6.575 3.578 0 6.485-2.945 \n 6.485-6.575 0-3.635-2.907-6.575-6.485-6.575-3.587 \n 0-6.494 2.94-6.494 6.575z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M163.25 57.026L141.773 3\"/>\n <path d = \"M98 63.5H48\"/>\n <path d = \"M101.73 57.63L70.5 14.013\"/>\n <path d = \"M70.49 14.5h76.646v-.206\"/>\n <path d = \"M139.134 14.505L108.468 57.95\"/>\n <path d = \"M70.894 15.05L42.834 57.05\"/>\n <path d = \"M70.5 14V3\"/>\n <path d = \"M141.427 3.23s19.83-7.71 19.83 6.344\"/>\n\t\t\t\t\t\t\t\t\t\t\n <path d = \"M97.816 62.52c0 3.576 2.86 6.475 \n 6.39 6.475s6.392-2.9 \n 6.392-6.476c0-3.577-2.86-6.476-6.39\n -6.476s-6.392 2.9-6.392 6.476z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M106.642 69.26l2.913 11.044\"/>\n <path d = \"M105 83l10-5\"/>\n <path d = \"M62.5 3.5h18\"/>\n </g>\n\t\t\t\t\t\t\t\t\t\n </svg>\n </div>\n\n <div class = \"item\">\n <svg viewBox = \"0 0 201 116\" style = \"background-color:#ffffff00\" \n xmlns = \"https://www.w3.org/2000/svg\" width = \"201\" \n height = \"116\">\n\t\t\t\t\t\t\t\t\t\n <g stroke = \"#FFF\" stroke-width = \"1\" fill = \"none\">\n <path d = \"M19.5 101.5V6.45C19.5 3.176 23.12.5 \n 26.402.5H175.53c3.282 0 5.97 2.677 5.97\n 5.95v95.05\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M171.5 89.5h-140v-77h140v77z\"/>\n\t\t\t\t\t\t\t\t\t\t\n <path d = \"M200.5 107.526c0 1.635-1.344 \n 2.974-2.985 2.974H3.485c-1.64 \n 0-2.985-1.34-2.985-2.974v-3.052c0-1.635\n 1.344-2.974 2.985-2.974h194.03c1.64 0 2.985 \n 1.34 2.9852.974v3.052z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M1 110l10.5 5.5\"/>\n <path d = \"M11.604 115.5H189.46\"/>\n <path d = \"M189.5 115.5l9.5-5.5\"/>\n <path d = \"M99.5 7.5h5\"/>\n <path d = \"M138.5 12.5l28 28\"/>\n <path d = \"M148.5 12.5l18 18\"/>\n <path d = \"M159.5 12.5l7 6\"/>\n </g>\n\t\t\t\t\t\t\t\t\t\n </svg>\n </div>\n\n <div class = \"item\">\n <svg viewBox = \"0 0 200 155\" style = \"background-color:#ffffff00\" \n xmlns = \"https://www.w3.org/2000/svg\" width = \"200\" \n height = \"155\">\n\t\t\t\t\t\t\t\t\t\n <g stroke = \"#FFF\" stroke-width = \"1\" fill = \"none\">\n <path d=\"M161.996 151.39l-33.97-27.178-45.01 \n 30.576-35.67-27.603L.36 154.245 38.662 20.04 \n 80.893 4.034l39.066 17.41L161.995.213l37.792 \n 22.932-37.792 128.246z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M47.346 127.185L80.892 4.035\"/>\n <path d = \"M83.015 154.788l36.942-133.343\"/>\n <path d = \"M128.025 124.212l33.97-124\"/>\n <path d = \"M46.278 23.935L32.29 75.605\"/>\n <path d = \"M95.802 45.718L81.19 97.225\"/>\n <path d = \"M106.91 33.115l-22.26 81.39\"/>\n\t\t\t\t\t\t\t\t\t\t\n <path d = \"M176.768 46.665c0 3.523-2.85\n 6.376-6.366 6.376-3.514 0-6.364-2.852\n -6.364-6.375 0-3.512 2.85-6.37\n 6.364-6.37 3.516 0 6.366 2.858 \n 6.366 6.37z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M180.9 52.392l-10.844 \n 19.91-10.394-19.995s-1.143-3.215-1.\n 143-5.067c0-6.514 5.273-11.81 11.79-11.81 \n 6.508 0 11.782 5.296 11.782 11.81 \n 0 1.852-1.192 5.152-1.192 5.152z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M43.86 92.528c0 3.523-2.85 \n 6.376-6.367 6.376-3.514 0-6.364-2.\n 853-6.364-6.376 0-3.512 2.85-6.37 \n 6.363-6.37 3.517 0 6.366 2.858 \n 6.366 6.37z\"/>\n\t\t\t\t\t\t\t\t\t\t\t\n <path d = \"M47.99 98.255l-10.843 19.91L26.754 \n 98.17s-1.143-3.215-1.\n 143-5.067c0-6.514 5.275-11.81 \n 11.793-11.81 6.507 0 11.78 5.296 \n 11.78 11.81 0 1.852-1.192 \n 5.152-1.192 5.152z\"/>\n </g>\n\t\t\t\t\t\t\t\t\t\n </svg>\n </div>\n\t\t\t\t\t\t\t\n </div>\n </div>\n </div>\n </div>\n </div>\n\t\t\n <div id = \"fb-root\"></div>\n <script async src = \"//assets.codepen.io/assets/embed/ei.js\">\n </script>\n <script src = \"https://cdn.jsdelivr.net/jquery/1.11.3/jquery.min.js\">\n </script>\n <script \n src = \"https://cdn.jsdelivr.net/jquery.easing/1.3/jquery.easing.1.3.min.js\">\n </script>\n <script src = \"jquery.drawsvg.min.js\"></script>\n\t\t\n <script>\n $(function() {\n\n var $doc = $(document),\n $win = $(window);\n\n var $intro = $('.intro'),\n $items = $intro.find('.item'),\n itemsLen = $items.length,\n\t\t\t\t\n svgs = $intro.find('svg').drawsvg({\n callback: animateIntro,\n easing: 'easeOutQuart'\n }),\n\t\t\t\t\n currItem = 0;\n\n function animateIntro() {\n $items.removeClass('active').eq( currItem++ % itemsLen \n ).addClass('active').find('svg').drawsvg('animate');\n }\n\n animateIntro();\n\n var $header = $('header'),\n headerOffTop = $header.offset().top,\n isFixed = false;\n\n function menu() {\n if ( $win.scrollTop() >= headerOffTop ) {\n if ( !isFixed ) {\n isFixed = true;\n $header.addClass('affix');\n }\n } else if ( isFixed ) {\n isFixed = false;\n $header.removeClass('affix');\n }\n }\n\n $win.on('scroll', menu);\n menu();\n\n $header.on('click', 'a[href^=\"#\"]', function(e) {\n e.preventDefault();\n\n var hash = this.hash,\n offset = $(hash).offset().top;\n\n $('body, html').animate({\n scrollTop: offset\n }, 600, 'easeInOutQuart', function() {\n document.location.hash = hash;\n });\n });\n\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 14738,
"s": 14699,
"text": "This should produce following result −"
},
{
"code": null,
"e": 14771,
"s": 14738,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 14785,
"s": 14771,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 14820,
"s": 14785,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14834,
"s": 14820,
"text": " Pratik Singh"
},
{
"code": null,
"e": 14869,
"s": 14834,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 14886,
"s": 14869,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 14919,
"s": 14886,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 14947,
"s": 14919,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14980,
"s": 14947,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 15001,
"s": 14980,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 15033,
"s": 15001,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 15050,
"s": 15033,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 15057,
"s": 15050,
"text": " Print"
},
{
"code": null,
"e": 15068,
"s": 15057,
"text": " Add Notes"
}
] |
ES6 - getTimezoneOffset() Method
|
Javascript date getTimezoneOffset() method returns the time-zone offset in minutes for the current locale. The time-zone offset is the minutes in difference, the Greenwich Mean Time (GMT) is relative to your local time.
For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time prevents this value from being a constant.
Date.getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.
var dt = new Date("December 25, 1995 23:15:00");
console.log("getTimezoneoffset() : " + dt.getTimezoneOffset());
getTimezoneoffset() : -330
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2497,
"s": 2277,
"text": "Javascript date getTimezoneOffset() method returns the time-zone offset in minutes for the current locale. The time-zone offset is the minutes in difference, the Greenwich Mean Time (GMT) is relative to your local time."
},
{
"code": null,
"e": 2627,
"s": 2497,
"text": "For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time prevents this value from being a constant."
},
{
"code": null,
"e": 2656,
"s": 2627,
"text": "Date.getTimezoneOffset() \n"
},
{
"code": null,
"e": 2720,
"s": 2656,
"text": "Returns the time-zone offset in minutes for the current locale."
},
{
"code": null,
"e": 2835,
"s": 2720,
"text": "var dt = new Date(\"December 25, 1995 23:15:00\"); \nconsole.log(\"getTimezoneoffset() : \" + dt.getTimezoneOffset()); "
},
{
"code": null,
"e": 2865,
"s": 2835,
"text": "getTimezoneoffset() : -330 \n"
},
{
"code": null,
"e": 2900,
"s": 2865,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2914,
"s": 2900,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 2947,
"s": 2914,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2965,
"s": 2947,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 2998,
"s": 2965,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3012,
"s": 2998,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3047,
"s": 3012,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3064,
"s": 3047,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 3097,
"s": 3064,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3113,
"s": 3097,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3148,
"s": 3113,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3156,
"s": 3148,
"text": " Shweta"
},
{
"code": null,
"e": 3163,
"s": 3156,
"text": " Print"
},
{
"code": null,
"e": 3174,
"s": 3163,
"text": " Add Notes"
}
] |
wxPython - Layout Management
|
A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by size argument of its constructor. Position of the widget inside the window is defined by pos argument of its constructor.
import wx
app = wx.App()
window = wx.Frame(None, title = "wxPython Frame", size = (300,200))
panel = wx.Panel(window)
label = wx.StaticText(panel, label = "Hello World", pos = (100,50))
window.Show(True)
app.MainLoop()
This Absolute Positioning however is not suitable because of the following reasons −
The position of the widget does not change even if the window is resized.
The position of the widget does not change even if the window is resized.
The appearance may not be uniform on different display devices with different resolutions.
The appearance may not be uniform on different display devices with different resolutions.
Modification in the layout is difficult as it may need redesigning the entire form.
Modification in the layout is difficult as it may need redesigning the entire form.
wxPython API provides Layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are −
Widgets inside the window are automatically resized.
Ensures uniform appearance on display devices with different resolutions.
Adding or removing widgets dynamically is possible without having to redesign.
Layout manager is called Sizer in wxPython. Wx.Sizer is the base class for all sizer subclasses. Let us discuss some of the important sizers such as wx.BoxSizer, wx.StaticBoxSizer, wx.GridSizer, wx.FlexGridSizer, and wx.GridBagSizer.
This sizer allows the controls to be arranged in row-wise or column-wise manner. BoxSizer’s layout is determined by its orientation argument (either wxVERTICAL or wxHORIZONTAL).
As the name suggests, a GridSizer object presents a two dimensional grid. Controls are added in the grid slot in the left-to-right and top-to-bottom order.
This sizer also has a two dimensional grid. However, it provides little more flexibility in laying out the controls in the cells.
GridBagSizer is a versatile sizer. It offers more enhancements than FlexiGridSizer. Child widget can be added to a specific cell within the grid.
A StaticBoxSizer puts a box sizer into a static box. It provides a border around the box along with a label at the top.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2190,
"s": 1882,
"text": "A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by size argument of its constructor. Position of the widget inside the window is defined by pos argument of its constructor."
},
{
"code": null,
"e": 2417,
"s": 2190,
"text": "import wx \n\napp = wx.App() \nwindow = wx.Frame(None, title = \"wxPython Frame\", size = (300,200)) \npanel = wx.Panel(window) \nlabel = wx.StaticText(panel, label = \"Hello World\", pos = (100,50)) \nwindow.Show(True) \napp.MainLoop()"
},
{
"code": null,
"e": 2502,
"s": 2417,
"text": "This Absolute Positioning however is not suitable because of the following reasons −"
},
{
"code": null,
"e": 2576,
"s": 2502,
"text": "The position of the widget does not change even if the window is resized."
},
{
"code": null,
"e": 2650,
"s": 2576,
"text": "The position of the widget does not change even if the window is resized."
},
{
"code": null,
"e": 2741,
"s": 2650,
"text": "The appearance may not be uniform on different display devices with different resolutions."
},
{
"code": null,
"e": 2832,
"s": 2741,
"text": "The appearance may not be uniform on different display devices with different resolutions."
},
{
"code": null,
"e": 2916,
"s": 2832,
"text": "Modification in the layout is difficult as it may need redesigning the entire form."
},
{
"code": null,
"e": 3000,
"s": 2916,
"text": "Modification in the layout is difficult as it may need redesigning the entire form."
},
{
"code": null,
"e": 3179,
"s": 3000,
"text": "wxPython API provides Layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are −"
},
{
"code": null,
"e": 3232,
"s": 3179,
"text": "Widgets inside the window are automatically resized."
},
{
"code": null,
"e": 3306,
"s": 3232,
"text": "Ensures uniform appearance on display devices with different resolutions."
},
{
"code": null,
"e": 3385,
"s": 3306,
"text": "Adding or removing widgets dynamically is possible without having to redesign."
},
{
"code": null,
"e": 3619,
"s": 3385,
"text": "Layout manager is called Sizer in wxPython. Wx.Sizer is the base class for all sizer subclasses. Let us discuss some of the important sizers such as wx.BoxSizer, wx.StaticBoxSizer, wx.GridSizer, wx.FlexGridSizer, and wx.GridBagSizer."
},
{
"code": null,
"e": 3797,
"s": 3619,
"text": "This sizer allows the controls to be arranged in row-wise or column-wise manner. BoxSizer’s layout is determined by its orientation argument (either wxVERTICAL or wxHORIZONTAL)."
},
{
"code": null,
"e": 3954,
"s": 3797,
"text": "As the name suggests, a GridSizer object presents a two dimensional grid. Controls are added in the grid slot in the left-to-right and top-to-bottom order. "
},
{
"code": null,
"e": 4084,
"s": 3954,
"text": "This sizer also has a two dimensional grid. However, it provides little more flexibility in laying out the controls in the cells."
},
{
"code": null,
"e": 4231,
"s": 4084,
"text": "GridBagSizer is a versatile sizer. It offers more enhancements than FlexiGridSizer. Child widget can be added to a specific cell within the grid. "
},
{
"code": null,
"e": 4351,
"s": 4231,
"text": "A StaticBoxSizer puts a box sizer into a static box. It provides a border around the box along with a label at the top."
},
{
"code": null,
"e": 4358,
"s": 4351,
"text": " Print"
},
{
"code": null,
"e": 4369,
"s": 4358,
"text": " Add Notes"
}
] |
numpy.matrix() in Python - GeeksforGeeks
|
09 Mar, 2022
This class returns a matrix from a string of data or array-like object. Matrix obtained is a specialised 2D array.Syntax :
numpy.matrix(data, dtype = None) :
Parameters :
data : data needs to be array-like or string
dtype : Data type of returned array.
Returns :
data interpreted as a matrix
# Python Program illustrating# numpy.matrix class import numpy as geek # string inputa = geek.matrix('1 2; 3 4')print("Via string input : \n", a, "\n\n") # array-like inputb = geek.matrix([[5, 6, 7], [4, 6]])print("Via array-like input : \n", b)
Output :
Via string input :
[[1 2]
[3 4]]
Via array-like input :
[[[5, 6, 7] [4, 6]]]
References :https://docs.scipy.org/doc/numpy/reference/generated/numpy.mat.html#numpy.mat
Note :These codes won’t run on online IDE’s. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . 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.
vinayedula
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 24425,
"s": 24302,
"text": "This class returns a matrix from a string of data or array-like object. Matrix obtained is a specialised 2D array.Syntax :"
},
{
"code": null,
"e": 24461,
"s": 24425,
"text": "numpy.matrix(data, dtype = None) : "
},
{
"code": null,
"e": 24474,
"s": 24461,
"text": "Parameters :"
},
{
"code": null,
"e": 24566,
"s": 24474,
"text": "data : data needs to be array-like or string \ndtype : Data type of returned array. \n \n"
},
{
"code": null,
"e": 24576,
"s": 24566,
"text": "Returns :"
},
{
"code": null,
"e": 24605,
"s": 24576,
"text": "data interpreted as a matrix"
},
{
"code": "# Python Program illustrating# numpy.matrix class import numpy as geek # string inputa = geek.matrix('1 2; 3 4')print(\"Via string input : \\n\", a, \"\\n\\n\") # array-like inputb = geek.matrix([[5, 6, 7], [4, 6]])print(\"Via array-like input : \\n\", b)",
"e": 24854,
"s": 24605,
"text": null
},
{
"code": null,
"e": 24863,
"s": 24854,
"text": "Output :"
},
{
"code": null,
"e": 24950,
"s": 24863,
"text": "Via string input : \n [[1 2]\n [3 4]] \n\n\nVia array-like input : \n [[[5, 6, 7] [4, 6]]]\n "
},
{
"code": null,
"e": 25040,
"s": 24950,
"text": "References :https://docs.scipy.org/doc/numpy/reference/generated/numpy.mat.html#numpy.mat"
},
{
"code": null,
"e": 25440,
"s": 25040,
"text": "Note :These codes won’t run on online IDE’s. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . 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."
},
{
"code": null,
"e": 25565,
"s": 25440,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25576,
"s": 25565,
"text": "vinayedula"
},
{
"code": null,
"e": 25605,
"s": 25576,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 25618,
"s": 25605,
"text": "Python-numpy"
},
{
"code": null,
"e": 25625,
"s": 25618,
"text": "Python"
},
{
"code": null,
"e": 25723,
"s": 25625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25732,
"s": 25723,
"text": "Comments"
},
{
"code": null,
"e": 25745,
"s": 25732,
"text": "Old Comments"
},
{
"code": null,
"e": 25763,
"s": 25745,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25798,
"s": 25763,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25820,
"s": 25798,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25852,
"s": 25820,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25882,
"s": 25852,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25924,
"s": 25882,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25950,
"s": 25924,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25993,
"s": 25950,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26037,
"s": 25993,
"text": "Reading and Writing to text files in Python"
}
] |
Find the nearest value and the index of NumPy Array - GeeksforGeeks
|
03 Mar, 2021
In this article, let’s discuss finding the nearest value and the index in an array with NumPy. Numpy provides a high-performance multidimensional array object, and tools for working with these arrays. We will make use of two of many functions provided by NumPy library to calculate the nearest value and the index in the array. Those two functions are numpy.abs() and numpy.argmin(). The approach to finding the nearest value and the index in the array is given below:
Approach:
Take an array, say, arr[] and an element, say x to which we have to find the nearest value.
Call the numpy.abs(d) function, with d as the difference between element of array and x, and store the values in a difference array, say difference_array[].
The element, providing minimum difference will be the nearest to the specified value.
Use numpy.argmin(), to obtain the index of the smallest element in difference_array[]. In the case of multiple minimum values, the first occurrence will be returned.
Print the nearest element, and its index from the given array.
Let us look at below examples based on the above approach.
Example 1:
Python3
import numpy as np # arrayarr = np.array([8, 7, 1, 5, 3, 4])print("Array is : ", arr) # element to which nearest value is to be foundx = 2print("Value to which nearest element is to be found: ", x) # calculate the difference arraydifference_array = np.absolute(arr-x) # find the index of minimum element from the arrayindex = difference_array.argmin()print("Nearest element to the given values is : ", arr[index])print("Index of nearest value is : ", index)
Output:
In the above example, we have taken an array from which we need to find the nearest element to the specified value. The specified value is 2. We subtract the given value from each the element of the array and store the absolute value in a different array. The minimum absolute difference will correspond to the nearest value to the given number. In our example, (2-1) yield 1. Thus, the index of minimum absolute difference is 2 and the element from the original array at index 2 is 1. Thus, 1 is nearest to the given number i.e 2.
Example 2:
Python3
import numpy as np # arrayarr = np.array([12, 40, 65, 78, 10, 99, 30])print("Array is : ", arr) # element to which nearest value is to be foundx = 85print("Value to which nearest element is to be found: ", x) # calculate the difference arraydifference_array = np.absolute(arr-x) # find the index of minimum element from the arrayindex = difference_array.argmin()print("Nearest element to the given values is : ", arr[index])print("Index of nearest value is : ", index)
Output:
In the above example, we have taken an array from which we need to find the nearest element to the specified value. The specified value is 85. We subtract the given value from each the element of the array and store the absolute value in a different array. The minimum absolute difference will correspond to the nearest value to the given number. In the above example, (78-85) yields 7. Thus, the index of minimum absolute difference is 3 and the element from the original array at index 3 is 78. Thus, 78 is nearest to the given number i.e 85.
Picked
Python numpy-Sorting Searching
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24370,
"s": 23901,
"text": "In this article, let’s discuss finding the nearest value and the index in an array with NumPy. Numpy provides a high-performance multidimensional array object, and tools for working with these arrays. We will make use of two of many functions provided by NumPy library to calculate the nearest value and the index in the array. Those two functions are numpy.abs() and numpy.argmin(). The approach to finding the nearest value and the index in the array is given below:"
},
{
"code": null,
"e": 24380,
"s": 24370,
"text": "Approach:"
},
{
"code": null,
"e": 24472,
"s": 24380,
"text": "Take an array, say, arr[] and an element, say x to which we have to find the nearest value."
},
{
"code": null,
"e": 24629,
"s": 24472,
"text": "Call the numpy.abs(d) function, with d as the difference between element of array and x, and store the values in a difference array, say difference_array[]."
},
{
"code": null,
"e": 24715,
"s": 24629,
"text": "The element, providing minimum difference will be the nearest to the specified value."
},
{
"code": null,
"e": 24881,
"s": 24715,
"text": "Use numpy.argmin(), to obtain the index of the smallest element in difference_array[]. In the case of multiple minimum values, the first occurrence will be returned."
},
{
"code": null,
"e": 24944,
"s": 24881,
"text": "Print the nearest element, and its index from the given array."
},
{
"code": null,
"e": 25003,
"s": 24944,
"text": "Let us look at below examples based on the above approach."
},
{
"code": null,
"e": 25014,
"s": 25003,
"text": "Example 1:"
},
{
"code": null,
"e": 25022,
"s": 25014,
"text": "Python3"
},
{
"code": "import numpy as np # arrayarr = np.array([8, 7, 1, 5, 3, 4])print(\"Array is : \", arr) # element to which nearest value is to be foundx = 2print(\"Value to which nearest element is to be found: \", x) # calculate the difference arraydifference_array = np.absolute(arr-x) # find the index of minimum element from the arrayindex = difference_array.argmin()print(\"Nearest element to the given values is : \", arr[index])print(\"Index of nearest value is : \", index)",
"e": 25486,
"s": 25022,
"text": null
},
{
"code": null,
"e": 25494,
"s": 25486,
"text": "Output:"
},
{
"code": null,
"e": 26028,
"s": 25494,
"text": "In the above example, we have taken an array from which we need to find the nearest element to the specified value. The specified value is 2. We subtract the given value from each the element of the array and store the absolute value in a different array. The minimum absolute difference will correspond to the nearest value to the given number. In our example, (2-1) yield 1. Thus, the index of minimum absolute difference is 2 and the element from the original array at index 2 is 1. Thus, 1 is nearest to the given number i.e 2. "
},
{
"code": null,
"e": 26039,
"s": 26028,
"text": "Example 2:"
},
{
"code": null,
"e": 26047,
"s": 26039,
"text": "Python3"
},
{
"code": "import numpy as np # arrayarr = np.array([12, 40, 65, 78, 10, 99, 30])print(\"Array is : \", arr) # element to which nearest value is to be foundx = 85print(\"Value to which nearest element is to be found: \", x) # calculate the difference arraydifference_array = np.absolute(arr-x) # find the index of minimum element from the arrayindex = difference_array.argmin()print(\"Nearest element to the given values is : \", arr[index])print(\"Index of nearest value is : \", index)",
"e": 26522,
"s": 26047,
"text": null
},
{
"code": null,
"e": 26530,
"s": 26522,
"text": "Output:"
},
{
"code": null,
"e": 27077,
"s": 26530,
"text": "In the above example, we have taken an array from which we need to find the nearest element to the specified value. The specified value is 85. We subtract the given value from each the element of the array and store the absolute value in a different array. The minimum absolute difference will correspond to the nearest value to the given number. In the above example, (78-85) yields 7. Thus, the index of minimum absolute difference is 3 and the element from the original array at index 3 is 78. Thus, 78 is nearest to the given number i.e 85. "
},
{
"code": null,
"e": 27084,
"s": 27077,
"text": "Picked"
},
{
"code": null,
"e": 27115,
"s": 27084,
"text": "Python numpy-Sorting Searching"
},
{
"code": null,
"e": 27128,
"s": 27115,
"text": "Python-numpy"
},
{
"code": null,
"e": 27135,
"s": 27128,
"text": "Python"
},
{
"code": null,
"e": 27233,
"s": 27135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27242,
"s": 27233,
"text": "Comments"
},
{
"code": null,
"e": 27255,
"s": 27242,
"text": "Old Comments"
},
{
"code": null,
"e": 27287,
"s": 27255,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27343,
"s": 27287,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27385,
"s": 27343,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27427,
"s": 27385,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27463,
"s": 27427,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27485,
"s": 27463,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27524,
"s": 27485,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27551,
"s": 27524,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27582,
"s": 27551,
"text": "Python | os.path.join() method"
}
] |
Quine in Python
|
The Quine is a program, which takes no input, but it produces output. It will show it’s own source code. Additionally, Quine has some conditions. We cannot open the source code file inside the program.
Live Demo
a='a=%r;print (a%%a)';print (a%a)
a='a=%r;print (a%%a)';print (a%a)
Here a simple string formatting is working. We are defining a variable ‘a’, and inside a, we are storing ‘a=%r;print (a%%a)’ Then we are printing the value of a, and also replacing %r with the value of a. Thus the quine is working.
We can do the same task by opening the file like this.
print(open(__file__).read())
But in this case we are violating the rule of Quine. We cannot open file in Quine.
|
[
{
"code": null,
"e": 1264,
"s": 1062,
"text": "The Quine is a program, which takes no input, but it produces output. It will show it’s own source code. Additionally, Quine has some conditions. We cannot open the source code file inside the program."
},
{
"code": null,
"e": 1275,
"s": 1264,
"text": " Live Demo"
},
{
"code": null,
"e": 1309,
"s": 1275,
"text": "a='a=%r;print (a%%a)';print (a%a)"
},
{
"code": null,
"e": 1344,
"s": 1309,
"text": "a='a=%r;print (a%%a)';print (a%a)\n"
},
{
"code": null,
"e": 1576,
"s": 1344,
"text": "Here a simple string formatting is working. We are defining a variable ‘a’, and inside a, we are storing ‘a=%r;print (a%%a)’ Then we are printing the value of a, and also replacing %r with the value of a. Thus the quine is working."
},
{
"code": null,
"e": 1631,
"s": 1576,
"text": "We can do the same task by opening the file like this."
},
{
"code": null,
"e": 1661,
"s": 1631,
"text": "print(open(__file__).read())\n"
},
{
"code": null,
"e": 1744,
"s": 1661,
"text": "But in this case we are violating the rule of Quine. We cannot open file in Quine."
}
] |
Understanding Word N-grams and N-gram Probability in Natural Language Processing | by Sunny Srinidhi | Towards Data Science
|
Originally published on my blog.
N-gram is probably the easiest concept to understand in the whole machine learning space, I guess. An N-gram means a sequence of N words. So for example, “Medium blog” is a 2-gram (a bigram), “A Medium blog post” is a 4-gram, and “Write on Medium” is a 3-gram (trigram). Well, that wasn’t very interesting or exciting. True, but we still have to look at the probability used with n-grams, which is quite interesting.
Before we move on to the probability stuff, let’s answer this question first. Why is it that we need to learn n-gram and the related probability? Well, in Natural Language Processing, or NLP for short, n-grams are used for a variety of things. Some examples include auto completion of sentences (such as the one we see in Gmail these days), auto spell check (yes, we can do that as well), and to a certain extent, we can check for grammar in a given sentence. We’ll see some examples of this later in the post when we talk about assigning probabilities to n-grams.
Let’s take the example of a sentence completion system. This system suggests words which could be used next in a given sentence. Suppose I give the system the sentence “Thank you so much for your” and expect the system to predict what the next word will be. Now you and me both know that the next word is “help” with a very high probability. But how will the system know that?
One important thing to note here is that, as for any other artificial intelligence or machine learning model, we need to train the model with a huge corpus of data. Once we do that, the system, or the NLP model will have a pretty good idea of the “probability” of the occurrence of a word after a certain word. So hoping that we have trained our model with a huge corpus of data, we’ll assume that the model gave us the correct answer.
I spoke about the probability a bit there, but let’s now build on that. When we’re building an NLP model for predicting words in a sentence, the probability of the occurrence of a word in a sequence of words is what matters. And how do we measure that? Let’s say we’re working with a bigram model here, and we have the following sentences as the training corpus:
Thank you so much for your help.I really appreciate your help.Excuse me, do you know what time it is?I’m really sorry for not inviting you.I really like your watch.
Thank you so much for your help.
I really appreciate your help.
Excuse me, do you know what time it is?
I’m really sorry for not inviting you.
I really like your watch.
Let’s suppose that after training our model with this data, I want to write the sentence “I really like your garden.” Now because this is a bigram model, the model will learn the occurrence of every two words, to determine the probability of a word occurring after a certain word. For example, from the 2nd, 4th, and the 5th sentence in the example above, we know that after the word “really” we can see either the word “appreciate”, “sorry”, or the word “like” occurs. So the model will calculate the probability of each of these sequences.
Suppose we’re calculating the probability of word “w1” occurring after the word “w2,” then the formula for this is as follows:
count(w2 w1) / count(w2)
which is the number of times the words occurs in the required sequence, divided by the number of the times the word before the expected word occurs in the corpus.
From our example sentences, let’s calculate the probability of the word “like” occurring after the word “really”:
count(really like) / count(really)= 1 / 3= 0.33
Similarly, for the other two possibilities:
count(really appreciate) / count(really)= 1 / 3= 0.33count(really sorry) / count(really)= 1 / 3= 0.33
So when I type the phrase “I really,” and expect the model to suggest the next word, it’ll get the right answer only once out of three times, because the probability of the correct answer is only 1/3.
As an another example, if my input sentence to the model is “Thank you for inviting,” and I expect the model to suggest the next word, it’s going to give me the word “you,” because of the example sentence 4. That’s the only example the model knows. As you can imagine, if we give the model a bigger corpus (or a bigger dataset) to train on, the predictions will improve a lot. Similarly, we’re only using a bigram here. We can use a trigram or even a 4-gram to improve the model’s understanding of the probabilities.
Using these n-grams and the probabilities of the occurrences of certain words in certain sequences could improve the predictions of auto completion systems. Similarly, we use can NLP and n-grams to train voice-based personal assistant bots. For example, using a 3-gram or trigram training model, a bot will be able to understand the difference between sentences such as “what’s the temperature?” and “set the temperature.”
I hope this was a clear enough explanation to understand the pretty easy concept of n-grams in Natural Language Processing. We’ll use this knowledge of n-grams and use it to optimise our machine learning model for text classification that we built earlier in the intro to the fastText library post.
Follow me on Twitter for more Data Science, Machine Learning, and general tech updates. Also, you can follow my personal blog.
If you like my posts here on Medium or on my personal blog, and would wish for me to continue doing this work, consider supporting me on Patreon.
|
[
{
"code": null,
"e": 205,
"s": 172,
"text": "Originally published on my blog."
},
{
"code": null,
"e": 622,
"s": 205,
"text": "N-gram is probably the easiest concept to understand in the whole machine learning space, I guess. An N-gram means a sequence of N words. So for example, “Medium blog” is a 2-gram (a bigram), “A Medium blog post” is a 4-gram, and “Write on Medium” is a 3-gram (trigram). Well, that wasn’t very interesting or exciting. True, but we still have to look at the probability used with n-grams, which is quite interesting."
},
{
"code": null,
"e": 1187,
"s": 622,
"text": "Before we move on to the probability stuff, let’s answer this question first. Why is it that we need to learn n-gram and the related probability? Well, in Natural Language Processing, or NLP for short, n-grams are used for a variety of things. Some examples include auto completion of sentences (such as the one we see in Gmail these days), auto spell check (yes, we can do that as well), and to a certain extent, we can check for grammar in a given sentence. We’ll see some examples of this later in the post when we talk about assigning probabilities to n-grams."
},
{
"code": null,
"e": 1564,
"s": 1187,
"text": "Let’s take the example of a sentence completion system. This system suggests words which could be used next in a given sentence. Suppose I give the system the sentence “Thank you so much for your” and expect the system to predict what the next word will be. Now you and me both know that the next word is “help” with a very high probability. But how will the system know that?"
},
{
"code": null,
"e": 2000,
"s": 1564,
"text": "One important thing to note here is that, as for any other artificial intelligence or machine learning model, we need to train the model with a huge corpus of data. Once we do that, the system, or the NLP model will have a pretty good idea of the “probability” of the occurrence of a word after a certain word. So hoping that we have trained our model with a huge corpus of data, we’ll assume that the model gave us the correct answer."
},
{
"code": null,
"e": 2363,
"s": 2000,
"text": "I spoke about the probability a bit there, but let’s now build on that. When we’re building an NLP model for predicting words in a sentence, the probability of the occurrence of a word in a sequence of words is what matters. And how do we measure that? Let’s say we’re working with a bigram model here, and we have the following sentences as the training corpus:"
},
{
"code": null,
"e": 2528,
"s": 2363,
"text": "Thank you so much for your help.I really appreciate your help.Excuse me, do you know what time it is?I’m really sorry for not inviting you.I really like your watch."
},
{
"code": null,
"e": 2561,
"s": 2528,
"text": "Thank you so much for your help."
},
{
"code": null,
"e": 2592,
"s": 2561,
"text": "I really appreciate your help."
},
{
"code": null,
"e": 2632,
"s": 2592,
"text": "Excuse me, do you know what time it is?"
},
{
"code": null,
"e": 2671,
"s": 2632,
"text": "I’m really sorry for not inviting you."
},
{
"code": null,
"e": 2697,
"s": 2671,
"text": "I really like your watch."
},
{
"code": null,
"e": 3239,
"s": 2697,
"text": "Let’s suppose that after training our model with this data, I want to write the sentence “I really like your garden.” Now because this is a bigram model, the model will learn the occurrence of every two words, to determine the probability of a word occurring after a certain word. For example, from the 2nd, 4th, and the 5th sentence in the example above, we know that after the word “really” we can see either the word “appreciate”, “sorry”, or the word “like” occurs. So the model will calculate the probability of each of these sequences."
},
{
"code": null,
"e": 3366,
"s": 3239,
"text": "Suppose we’re calculating the probability of word “w1” occurring after the word “w2,” then the formula for this is as follows:"
},
{
"code": null,
"e": 3391,
"s": 3366,
"text": "count(w2 w1) / count(w2)"
},
{
"code": null,
"e": 3554,
"s": 3391,
"text": "which is the number of times the words occurs in the required sequence, divided by the number of the times the word before the expected word occurs in the corpus."
},
{
"code": null,
"e": 3668,
"s": 3554,
"text": "From our example sentences, let’s calculate the probability of the word “like” occurring after the word “really”:"
},
{
"code": null,
"e": 3716,
"s": 3668,
"text": "count(really like) / count(really)= 1 / 3= 0.33"
},
{
"code": null,
"e": 3760,
"s": 3716,
"text": "Similarly, for the other two possibilities:"
},
{
"code": null,
"e": 3862,
"s": 3760,
"text": "count(really appreciate) / count(really)= 1 / 3= 0.33count(really sorry) / count(really)= 1 / 3= 0.33"
},
{
"code": null,
"e": 4063,
"s": 3862,
"text": "So when I type the phrase “I really,” and expect the model to suggest the next word, it’ll get the right answer only once out of three times, because the probability of the correct answer is only 1/3."
},
{
"code": null,
"e": 4580,
"s": 4063,
"text": "As an another example, if my input sentence to the model is “Thank you for inviting,” and I expect the model to suggest the next word, it’s going to give me the word “you,” because of the example sentence 4. That’s the only example the model knows. As you can imagine, if we give the model a bigger corpus (or a bigger dataset) to train on, the predictions will improve a lot. Similarly, we’re only using a bigram here. We can use a trigram or even a 4-gram to improve the model’s understanding of the probabilities."
},
{
"code": null,
"e": 5003,
"s": 4580,
"text": "Using these n-grams and the probabilities of the occurrences of certain words in certain sequences could improve the predictions of auto completion systems. Similarly, we use can NLP and n-grams to train voice-based personal assistant bots. For example, using a 3-gram or trigram training model, a bot will be able to understand the difference between sentences such as “what’s the temperature?” and “set the temperature.”"
},
{
"code": null,
"e": 5302,
"s": 5003,
"text": "I hope this was a clear enough explanation to understand the pretty easy concept of n-grams in Natural Language Processing. We’ll use this knowledge of n-grams and use it to optimise our machine learning model for text classification that we built earlier in the intro to the fastText library post."
},
{
"code": null,
"e": 5429,
"s": 5302,
"text": "Follow me on Twitter for more Data Science, Machine Learning, and general tech updates. Also, you can follow my personal blog."
}
] |
Tryit Editor v3.7
|
Tryit: ABC with utf8
|
[] |
Python Web Scraping - Data Extraction
|
Analyzing a web page means understanding its sructure . Now, the question arises why it is important for web scraping? In this chapter, let us understand this in detail.
Web page analysis is important because without analyzing we are not able to know in which form we are going to receive the data from (structured or unstructured) that web page after extraction. We can do web page analysis in the following ways −
This is a way to understand how a web page is structured by examining its source code. To implement this, we need to right click the page and then must select the View page source option. Then, we will get the data of our interest from that web page in the form of HTML. But the main concern is about whitespaces and formatting which is difficult for us to format.
This is another way of analyzing web page. But the difference is that it will resolve the issue of formatting and whitespaces in the source code of web page. You can implement this by right clicking and then selecting the Inspect or Inspect element option from menu. It will provide the information about particular area or element of that web page.
The following methods are mostly used for extracting data from a web page −
They are highly specialized programming language embedded in Python. We can use it through re module of Python. It is also called RE or regexes or regex patterns. With the help of regular expressions, we can specify some rules for the possible set of strings we want to match from the data.
If you want to learn more about regular expression in general, go to the link https://www.tutorialspoint.com/automata_theory/regular_expressions.htm and if you want to know more about re module or regular expression in Python, you can follow the
link https://www.tutorialspoint.com/python/python_reg_expressions.htm.
In the following example, we are going to scrape data about India from
http://example.webscraping.com after matching the contents of <td> with the help of regular expression.
import re
import urllib.request
response =
urllib.request.urlopen('http://example.webscraping.com/places/default/view/India-102')
html = response.read()
text = html.decode()
re.findall('<td class="w2p_fw">(.*?)</td>',text)
The corresponding output will be as shown here −
[
'<img src="/places/static/images/flags/in.png" />',
'3,287,590 square kilometres',
'1,173,108,018',
'IN',
'India',
'New Delhi',
'<a href="/places/default/continent/AS">AS</a>',
'.in',
'INR',
'Rupee',
'91',
'######',
'^(\\d{6})$',
'enIN,hi,bn,te,mr,ta,ur,gu,kn,ml,or,pa,as,bh,sat,ks,ne,sd,kok,doi,mni,sit,sa,fr,lus,inc',
'<div>
<a href="/places/default/iso/CN">CN </a>
<a href="/places/default/iso/NP">NP </a>
<a href="/places/default/iso/MM">MM </a>
<a href="/places/default/iso/BT">BT </a>
<a href="/places/default/iso/PK">PK </a>
<a href="/places/default/iso/BD">BD </a>
</div>'
]
Observe that in the above output you can see the details about country India by using regular expression.
Suppose we want to collect all the hyperlinks from a web page, then we can use a parser called BeautifulSoup which can be known in more detail at https://www.crummy.com/software/BeautifulSoup/bs4/doc/. In simple words, BeautifulSoup is a Python library for pulling data out of HTML and XML files. It can be used with requests, because it needs an input (document or url) to create a soup object asit cannot fetch a web page by itself. You can use the following Python script to gather the title of web page and hyperlinks.
Using the pip command, we can install beautifulsoup either in our virtual environment or in global installation.
(base) D:\ProgramData>pip install bs4
Collecting bs4
Downloading
https://files.pythonhosted.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89
a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz
Requirement already satisfied: beautifulsoup4 in d:\programdata\lib\sitepackages
(from bs4) (4.6.0)
Building wheels for collected packages: bs4
Running setup.py bdist_wheel for bs4 ... done
Stored in directory:
C:\Users\gaurav\AppData\Local\pip\Cache\wheels\a0\b0\b2\4f80b9456b87abedbc0bf2d
52235414c3467d8889be38dd472
Successfully built bs4
Installing collected packages: bs4
Successfully installed bs4-0.0.1
Note that in this example, we are extending the above example implemented with requests python module. we are using r.text for creating a soup object which will further be used to fetch details like title of the webpage.
First, we need to import necessary Python modules −
import requests
from bs4 import BeautifulSoup
In this following line of code we use requests to make a GET HTTP requests for the url:
https://authoraditiagarwal.com/ by making a GET request.
r = requests.get('https://authoraditiagarwal.com/')
Now we need to create a Soup object as follows −
soup = BeautifulSoup(r.text, 'lxml')
print (soup.title)
print (soup.title.text)
The corresponding output will be as shown here −
<title>Learn and Grow with Aditi Agarwal</title>
Learn and Grow with Aditi Agarwal
Another Python library we are going to discuss for web scraping is lxml. It is a highperformance HTML and XML parsing library. It is comparatively fast and straightforward. You can read about it more on https://lxml.de/.
Using the pip command, we can install lxml either in our virtual environment or in global installation.
(base) D:\ProgramData>pip install lxml
Collecting lxml
Downloading
https://files.pythonhosted.org/packages/b9/55/bcc78c70e8ba30f51b5495eb0e
3e949aa06e4a2de55b3de53dc9fa9653fa/lxml-4.2.5-cp36-cp36m-win_amd64.whl
(3.
6MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 3.6MB 64kB/s
Installing collected packages: lxml
Successfully installed lxml-4.2.5
In the following example, we are scraping a particular element of the web page from authoraditiagarwal.com by using lxml and requests −
First, we need to import the requests and html from lxml library as follows −
import requests
from lxml import html
Now we need to provide the url of web page to scrap
url = 'https://authoraditiagarwal.com/leadershipmanagement/'
Now we need to provide the path (Xpath) to particular element of that web page −
path = '//*[@id="panel-836-0-0-1"]/div/div/p[1]'
response = requests.get(url)
byte_string = response.content
source_code = html.fromstring(byte_string)
tree = source_code.xpath(path)
print(tree[0].text_content())
The corresponding output will be as shown here −
The Sprint Burndown or the Iteration Burndown chart is a powerful tool to communicate
daily progress to the stakeholders. It tracks the completion of work for a given sprint
or an iteration. The horizontal axis represents the days within a Sprint. The vertical
axis represents the hours remaining to complete the committed work.
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": 2082,
"s": 1912,
"text": "Analyzing a web page means understanding its sructure . Now, the question arises why it is important for web scraping? In this chapter, let us understand this in detail."
},
{
"code": null,
"e": 2328,
"s": 2082,
"text": "Web page analysis is important because without analyzing we are not able to know in which form we are going to receive the data from (structured or unstructured) that web page after extraction. We can do web page analysis in the following ways −"
},
{
"code": null,
"e": 2693,
"s": 2328,
"text": "This is a way to understand how a web page is structured by examining its source code. To implement this, we need to right click the page and then must select the View page source option. Then, we will get the data of our interest from that web page in the form of HTML. But the main concern is about whitespaces and formatting which is difficult for us to format."
},
{
"code": null,
"e": 3043,
"s": 2693,
"text": "This is another way of analyzing web page. But the difference is that it will resolve the issue of formatting and whitespaces in the source code of web page. You can implement this by right clicking and then selecting the Inspect or Inspect element option from menu. It will provide the information about particular area or element of that web page."
},
{
"code": null,
"e": 3119,
"s": 3043,
"text": "The following methods are mostly used for extracting data from a web page −"
},
{
"code": null,
"e": 3410,
"s": 3119,
"text": "They are highly specialized programming language embedded in Python. We can use it through re module of Python. It is also called RE or regexes or regex patterns. With the help of regular expressions, we can specify some rules for the possible set of strings we want to match from the data."
},
{
"code": null,
"e": 3727,
"s": 3410,
"text": "If you want to learn more about regular expression in general, go to the link https://www.tutorialspoint.com/automata_theory/regular_expressions.htm and if you want to know more about re module or regular expression in Python, you can follow the\nlink https://www.tutorialspoint.com/python/python_reg_expressions.htm."
},
{
"code": null,
"e": 3903,
"s": 3727,
"text": "In the following example, we are going to scrape data about India from\nhttp://example.webscraping.com after matching the contents of <td> with the help of regular expression."
},
{
"code": null,
"e": 4130,
"s": 3903,
"text": "import re\nimport urllib.request\nresponse =\n urllib.request.urlopen('http://example.webscraping.com/places/default/view/India-102')\nhtml = response.read()\ntext = html.decode()\nre.findall('<td class=\"w2p_fw\">(.*?)</td>',text)\n"
},
{
"code": null,
"e": 4179,
"s": 4130,
"text": "The corresponding output will be as shown here −"
},
{
"code": null,
"e": 4849,
"s": 4179,
"text": "[\n '<img src=\"/places/static/images/flags/in.png\" />',\n '3,287,590 square kilometres',\n '1,173,108,018',\n 'IN',\n 'India',\n 'New Delhi',\n '<a href=\"/places/default/continent/AS\">AS</a>',\n '.in',\n 'INR',\n 'Rupee',\n '91',\n '######',\n '^(\\\\d{6})$',\n 'enIN,hi,bn,te,mr,ta,ur,gu,kn,ml,or,pa,as,bh,sat,ks,ne,sd,kok,doi,mni,sit,sa,fr,lus,inc',\n '<div>\n <a href=\"/places/default/iso/CN\">CN </a>\n <a href=\"/places/default/iso/NP\">NP </a>\n <a href=\"/places/default/iso/MM\">MM </a>\n <a href=\"/places/default/iso/BT\">BT </a>\n <a href=\"/places/default/iso/PK\">PK </a>\n <a href=\"/places/default/iso/BD\">BD </a>\n </div>'\n]\n"
},
{
"code": null,
"e": 4955,
"s": 4849,
"text": "Observe that in the above output you can see the details about country India by using regular expression."
},
{
"code": null,
"e": 5478,
"s": 4955,
"text": "Suppose we want to collect all the hyperlinks from a web page, then we can use a parser called BeautifulSoup which can be known in more detail at https://www.crummy.com/software/BeautifulSoup/bs4/doc/. In simple words, BeautifulSoup is a Python library for pulling data out of HTML and XML files. It can be used with requests, because it needs an input (document or url) to create a soup object asit cannot fetch a web page by itself. You can use the following Python script to gather the title of web page and hyperlinks."
},
{
"code": null,
"e": 5591,
"s": 5478,
"text": "Using the pip command, we can install beautifulsoup either in our virtual environment or in global installation."
},
{
"code": null,
"e": 6201,
"s": 5591,
"text": "(base) D:\\ProgramData>pip install bs4\nCollecting bs4\n Downloading\nhttps://files.pythonhosted.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89\na94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz\nRequirement already satisfied: beautifulsoup4 in d:\\programdata\\lib\\sitepackages\n(from bs4) (4.6.0)\nBuilding wheels for collected packages: bs4\n Running setup.py bdist_wheel for bs4 ... done\n Stored in directory:\nC:\\Users\\gaurav\\AppData\\Local\\pip\\Cache\\wheels\\a0\\b0\\b2\\4f80b9456b87abedbc0bf2d\n52235414c3467d8889be38dd472\nSuccessfully built bs4\nInstalling collected packages: bs4\nSuccessfully installed bs4-0.0.1\n"
},
{
"code": null,
"e": 6422,
"s": 6201,
"text": "Note that in this example, we are extending the above example implemented with requests python module. we are using r.text for creating a soup object which will further be used to fetch details like title of the webpage."
},
{
"code": null,
"e": 6474,
"s": 6422,
"text": "First, we need to import necessary Python modules −"
},
{
"code": null,
"e": 6521,
"s": 6474,
"text": "import requests\nfrom bs4 import BeautifulSoup\n"
},
{
"code": null,
"e": 6666,
"s": 6521,
"text": "In this following line of code we use requests to make a GET HTTP requests for the url:\nhttps://authoraditiagarwal.com/ by making a GET request."
},
{
"code": null,
"e": 6719,
"s": 6666,
"text": "r = requests.get('https://authoraditiagarwal.com/')\n"
},
{
"code": null,
"e": 6768,
"s": 6719,
"text": "Now we need to create a Soup object as follows −"
},
{
"code": null,
"e": 6849,
"s": 6768,
"text": "soup = BeautifulSoup(r.text, 'lxml')\nprint (soup.title)\nprint (soup.title.text)\n"
},
{
"code": null,
"e": 6898,
"s": 6849,
"text": "The corresponding output will be as shown here −"
},
{
"code": null,
"e": 6982,
"s": 6898,
"text": "<title>Learn and Grow with Aditi Agarwal</title>\nLearn and Grow with Aditi Agarwal\n"
},
{
"code": null,
"e": 7203,
"s": 6982,
"text": "Another Python library we are going to discuss for web scraping is lxml. It is a highperformance HTML and XML parsing library. It is comparatively fast and straightforward. You can read about it more on https://lxml.de/."
},
{
"code": null,
"e": 7307,
"s": 7203,
"text": "Using the pip command, we can install lxml either in our virtual environment or in global installation."
},
{
"code": null,
"e": 7657,
"s": 7307,
"text": "(base) D:\\ProgramData>pip install lxml\nCollecting lxml\n Downloading\nhttps://files.pythonhosted.org/packages/b9/55/bcc78c70e8ba30f51b5495eb0e\n3e949aa06e4a2de55b3de53dc9fa9653fa/lxml-4.2.5-cp36-cp36m-win_amd64.whl\n(3.\n6MB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 3.6MB 64kB/s\nInstalling collected packages: lxml\nSuccessfully installed lxml-4.2.5\n"
},
{
"code": null,
"e": 7793,
"s": 7657,
"text": "In the following example, we are scraping a particular element of the web page from authoraditiagarwal.com by using lxml and requests −"
},
{
"code": null,
"e": 7871,
"s": 7793,
"text": "First, we need to import the requests and html from lxml library as follows −"
},
{
"code": null,
"e": 7911,
"s": 7871,
"text": "import requests\nfrom lxml import html \n"
},
{
"code": null,
"e": 7963,
"s": 7911,
"text": "Now we need to provide the url of web page to scrap"
},
{
"code": null,
"e": 8025,
"s": 7963,
"text": "url = 'https://authoraditiagarwal.com/leadershipmanagement/'\n"
},
{
"code": null,
"e": 8106,
"s": 8025,
"text": "Now we need to provide the path (Xpath) to particular element of that web page −"
},
{
"code": null,
"e": 8320,
"s": 8106,
"text": "path = '//*[@id=\"panel-836-0-0-1\"]/div/div/p[1]'\nresponse = requests.get(url)\nbyte_string = response.content\nsource_code = html.fromstring(byte_string)\ntree = source_code.xpath(path)\nprint(tree[0].text_content()) "
},
{
"code": null,
"e": 8369,
"s": 8320,
"text": "The corresponding output will be as shown here −"
},
{
"code": null,
"e": 8700,
"s": 8369,
"text": "The Sprint Burndown or the Iteration Burndown chart is a powerful tool to communicate\ndaily progress to the stakeholders. It tracks the completion of work for a given sprint\nor an iteration. The horizontal axis represents the days within a Sprint. The vertical \naxis represents the hours remaining to complete the committed work.\n"
},
{
"code": null,
"e": 8737,
"s": 8700,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8753,
"s": 8737,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8786,
"s": 8753,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8805,
"s": 8786,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8840,
"s": 8805,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 8862,
"s": 8840,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 8896,
"s": 8862,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8924,
"s": 8896,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8959,
"s": 8924,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 8973,
"s": 8959,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9006,
"s": 8973,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9023,
"s": 9006,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9030,
"s": 9023,
"text": " Print"
},
{
"code": null,
"e": 9041,
"s": 9030,
"text": " Add Notes"
}
] |
UnitTest Framework - Assertion
|
Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure. Other exceptions are treated as Error.
The following three sets of assertion functions are defined in unittest module −
Basic Boolean Asserts
Comparative Asserts
Asserts for Collections
Basic assert functions evaluate whether the result of an operation is True or False. All the assert methods accept a msg argument that, if specified, is used as the error message on failure.
assertEqual(arg1, arg2, msg = None)
Test that arg1 and arg2 are equal. If the values do not compare equal, the test will fail.
assertNotEqual(arg1, arg2, msg = None)
Test that arg1 and arg2 are not equal. If the values do compare equal, the test will fail.
assertTrue(expr, msg = None)
Test that expr is true. If false, test fails
assertFalse(expr, msg = None)
Test that expr is false. If true, test fails
assertIs(arg1, arg2, msg = None)
Test that arg1 and arg2 evaluate to the same object.
assertIsNot(arg1, arg2, msg = None)
Test that arg1 and arg2 don’t evaluate to the same object.
assertIsNone(expr, msg = None)
Test that expr is None. If not None, test fails
assertIsNotNone(expr, msg = None)
Test that expr is not None. If None, test fails
assertIn(arg1, arg2, msg = None)
Test that arg1 is in arg2.
assertNotIn(arg1, arg2, msg = None)
Test that arg1 is not in arg2.
assertIsInstance(obj, cls, msg = None)
Test that obj is an instance of cls
assertNotIsInstance(obj, cls, msg = None)
Test that obj is not an instance of cls
Some of the above assertion functions are implemented in the following code −
import unittest
class SimpleTest(unittest.TestCase):
def test1(self):
self.assertEqual(4 + 5,9)
def test2(self):
self.assertNotEqual(5 * 2,10)
def test3(self):
self.assertTrue(4 + 5 == 9,"The result is False")
def test4(self):
self.assertTrue(4 + 5 == 10,"assertion fails")
def test5(self):
self.assertIn(3,[1,2,3])
def test6(self):
self.assertNotIn(3, range(5))
if __name__ == '__main__':
unittest.main()
When the above script is run, test2, test4 and test6 will show failure and others run successfully.
FAIL: test2 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python27\SimpleTest.py", line 9, in test2
self.assertNotEqual(5*2,10)
AssertionError: 10 == 10
FAIL: test4 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python27\SimpleTest.py", line 13, in test4
self.assertTrue(4+5==10,"assertion fails")
AssertionError: assertion fails
FAIL: test6 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python27\SimpleTest.py", line 17, in test6
self.assertNotIn(3, range(5))
AssertionError: 3 unexpectedly found in [0, 1, 2, 3, 4]
----------------------------------------------------------------------
Ran 6 tests in 0.001s
FAILED (failures = 3)
The second set of assertion functions are comparative asserts −
assertAlmostEqual (first, second, places = 7, msg = None, delta = None)
Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7),
assertAlmostEqual (first, second, places = 7, msg = None, delta = None)
Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7),
assertNotAlmostEqual (first, second, places, msg, delta)
Test that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero.
In both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta.
Supplying both delta and places raises a TypeError.
assertNotAlmostEqual (first, second, places, msg, delta)
Test that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero.
In both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta.
Supplying both delta and places raises a TypeError.
assertGreater (first, second, msg = None)
Test that first is greater than second depending on the method name. If not, the test will fail.
assertGreater (first, second, msg = None)
Test that first is greater than second depending on the method name. If not, the test will fail.
assertGreaterEqual (first, second, msg = None)
Test that first is greater than or equal to second depending on the method name. If not, the test will fail
assertGreaterEqual (first, second, msg = None)
Test that first is greater than or equal to second depending on the method name. If not, the test will fail
assertLess (first, second, msg = None)
Test that first is less than second depending on the method name. If not, the test will fail
assertLess (first, second, msg = None)
Test that first is less than second depending on the method name. If not, the test will fail
assertLessEqual (first, second, msg = None)
Test that first is less than or equal to second depending upon the method name. If not, the test will fail.
assertLessEqual (first, second, msg = None)
Test that first is less than or equal to second depending upon the method name. If not, the test will fail.
assertRegexpMatches (text, regexp, msg = None)
Test that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search().
assertRegexpMatches (text, regexp, msg = None)
Test that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search().
assertNotRegexpMatches (text, regexp, msg = None)
Verifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search() .
assertNotRegexpMatches (text, regexp, msg = None)
Verifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search() .
The assertion functions are implemented in the following example −
import unittest
import math
import re
class SimpleTest(unittest.TestCase):
def test1(self):
self.assertAlmostEqual(22.0/7,3.14)
def test2(self):
self.assertNotAlmostEqual(10.0/3,3)
def test3(self):
self.assertGreater(math.pi,3)
def test4(self):
self.assertNotRegexpMatches("Tutorials Point (I) Private Limited","Point")
if __name__ == '__main__':
unittest.main()
The above script reports test1 and test4 as Failure. In test1, the division of 22/7 is not within 7 decimal places of 3.14. Similarly, since the second argument matches with the text in first argument, test4 results in AssertionError.
=====================================================FAIL: test1 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "asserttest.py", line 7, in test1
self.assertAlmostEqual(22.0/7,3.14)
AssertionError: 3.142857142857143 != 3.14 within 7 places
================================================================
FAIL: test4 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "asserttest.py", line 13, in test4
self.assertNotRegexpMatches("Tutorials Point (I) Private Limited","Point")
AssertionError: Regexp matched: 'Point' matches 'Point' in 'Tutorials Point (I)
Private Limited'
----------------------------------------------------------------------
Ran 4 tests in 0.001s
FAILED (failures = 2)
This set of assert functions are meant to be used with collection data types in Python, such as List, Tuple, Dictionary and Set.
assertListEqual (list1, list2, msg = None)
Tests that two lists are equal. If not, an error message is constructed that shows only the differences between the two.
assertTupleEqual (tuple1, tuple2, msg = None)
Tests that two tuples are equal. If not, an error message is constructed that shows only the differences between the two.
assertSetEqual (set1, set2, msg = None)
Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets.
assertDictEqual (expected, actual, msg = None)
Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries.
The following example implements the above methods −
import unittest
class SimpleTest(unittest.TestCase):
def test1(self):
self.assertListEqual([2,3,4], [1,2,3,4,5])
def test2(self):
self.assertTupleEqual((1*2,2*2,3*2), (2,4,6))
def test3(self):
self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})
if __name__ == '__main__':
unittest.main()
In the above example, test1 and test3 show AssertionError. Error message displays the differences in List and Dictionary objects.
FAIL: test1 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "asserttest.py", line 5, in test1
self.assertListEqual([2,3,4], [1,2,3,4,5])
AssertionError: Lists differ: [2, 3, 4] != [1, 2, 3, 4, 5]
First differing element 0:
2
1
Second list contains 2 additional elements.
First extra element 3:
4
- [2, 3, 4]
+ [1, 2, 3, 4, 5]
? +++ +++
FAIL: test3 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "asserttest.py", line 9, in test3
self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})
AssertionError: {1: 11, 2: 22} != {1: 11, 2: 22, 3: 33}
- {1: 11, 2: 22}
+ {1: 11, 2: 22, 3: 33}
? +++++++
----------------------------------------------------------------------
Ran 3 tests in 0.001s
FAILED (failures = 2)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2359,
"s": 2098,
"text": "Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure. Other exceptions are treated as Error."
},
{
"code": null,
"e": 2440,
"s": 2359,
"text": "The following three sets of assertion functions are defined in unittest module −"
},
{
"code": null,
"e": 2462,
"s": 2440,
"text": "Basic Boolean Asserts"
},
{
"code": null,
"e": 2482,
"s": 2462,
"text": "Comparative Asserts"
},
{
"code": null,
"e": 2506,
"s": 2482,
"text": "Asserts for Collections"
},
{
"code": null,
"e": 2697,
"s": 2506,
"text": "Basic assert functions evaluate whether the result of an operation is True or False. All the assert methods accept a msg argument that, if specified, is used as the error message on failure."
},
{
"code": null,
"e": 2733,
"s": 2697,
"text": "assertEqual(arg1, arg2, msg = None)"
},
{
"code": null,
"e": 2824,
"s": 2733,
"text": "Test that arg1 and arg2 are equal. If the values do not compare equal, the test will fail."
},
{
"code": null,
"e": 2863,
"s": 2824,
"text": "assertNotEqual(arg1, arg2, msg = None)"
},
{
"code": null,
"e": 2954,
"s": 2863,
"text": "Test that arg1 and arg2 are not equal. If the values do compare equal, the test will fail."
},
{
"code": null,
"e": 2983,
"s": 2954,
"text": "assertTrue(expr, msg = None)"
},
{
"code": null,
"e": 3028,
"s": 2983,
"text": "Test that expr is true. If false, test fails"
},
{
"code": null,
"e": 3058,
"s": 3028,
"text": "assertFalse(expr, msg = None)"
},
{
"code": null,
"e": 3103,
"s": 3058,
"text": "Test that expr is false. If true, test fails"
},
{
"code": null,
"e": 3136,
"s": 3103,
"text": "assertIs(arg1, arg2, msg = None)"
},
{
"code": null,
"e": 3189,
"s": 3136,
"text": "Test that arg1 and arg2 evaluate to the same object."
},
{
"code": null,
"e": 3225,
"s": 3189,
"text": "assertIsNot(arg1, arg2, msg = None)"
},
{
"code": null,
"e": 3284,
"s": 3225,
"text": "Test that arg1 and arg2 don’t evaluate to the same object."
},
{
"code": null,
"e": 3315,
"s": 3284,
"text": "assertIsNone(expr, msg = None)"
},
{
"code": null,
"e": 3363,
"s": 3315,
"text": "Test that expr is None. If not None, test fails"
},
{
"code": null,
"e": 3397,
"s": 3363,
"text": "assertIsNotNone(expr, msg = None)"
},
{
"code": null,
"e": 3445,
"s": 3397,
"text": "Test that expr is not None. If None, test fails"
},
{
"code": null,
"e": 3478,
"s": 3445,
"text": "assertIn(arg1, arg2, msg = None)"
},
{
"code": null,
"e": 3505,
"s": 3478,
"text": "Test that arg1 is in arg2."
},
{
"code": null,
"e": 3541,
"s": 3505,
"text": "assertNotIn(arg1, arg2, msg = None)"
},
{
"code": null,
"e": 3572,
"s": 3541,
"text": "Test that arg1 is not in arg2."
},
{
"code": null,
"e": 3611,
"s": 3572,
"text": "assertIsInstance(obj, cls, msg = None)"
},
{
"code": null,
"e": 3647,
"s": 3611,
"text": "Test that obj is an instance of cls"
},
{
"code": null,
"e": 3689,
"s": 3647,
"text": "assertNotIsInstance(obj, cls, msg = None)"
},
{
"code": null,
"e": 3729,
"s": 3689,
"text": "Test that obj is not an instance of cls"
},
{
"code": null,
"e": 3807,
"s": 3729,
"text": "Some of the above assertion functions are implemented in the following code −"
},
{
"code": null,
"e": 4272,
"s": 3807,
"text": "import unittest\n\nclass SimpleTest(unittest.TestCase):\n def test1(self):\n self.assertEqual(4 + 5,9)\n def test2(self):\n self.assertNotEqual(5 * 2,10)\n def test3(self):\n self.assertTrue(4 + 5 == 9,\"The result is False\")\n def test4(self):\n self.assertTrue(4 + 5 == 10,\"assertion fails\")\n def test5(self):\n self.assertIn(3,[1,2,3])\n def test6(self):\n self.assertNotIn(3, range(5))\n\nif __name__ == '__main__':\n unittest.main()"
},
{
"code": null,
"e": 4372,
"s": 4272,
"text": "When the above script is run, test2, test4 and test6 will show failure and others run successfully."
},
{
"code": null,
"e": 5463,
"s": 4372,
"text": "FAIL: test2 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:\\Python27\\SimpleTest.py\", line 9, in test2\n self.assertNotEqual(5*2,10)\nAssertionError: 10 == 10\n\nFAIL: test4 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:\\Python27\\SimpleTest.py\", line 13, in test4\n self.assertTrue(4+5==10,\"assertion fails\")\nAssertionError: assertion fails\n\nFAIL: test6 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:\\Python27\\SimpleTest.py\", line 17, in test6\n self.assertNotIn(3, range(5))\nAssertionError: 3 unexpectedly found in [0, 1, 2, 3, 4]\n\n---------------------------------------------------------------------- \nRan 6 tests in 0.001s \n \nFAILED (failures = 3)\n"
},
{
"code": null,
"e": 5527,
"s": 5463,
"text": "The second set of assertion functions are comparative asserts −"
},
{
"code": null,
"e": 5762,
"s": 5527,
"text": "assertAlmostEqual (first, second, places = 7, msg = None, delta = None)\nTest that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7),"
},
{
"code": null,
"e": 5834,
"s": 5762,
"text": "assertAlmostEqual (first, second, places = 7, msg = None, delta = None)"
},
{
"code": null,
"e": 5997,
"s": 5834,
"text": "Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7),"
},
{
"code": null,
"e": 6436,
"s": 5997,
"text": "assertNotAlmostEqual (first, second, places, msg, delta)\nTest that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero.\nIn both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta.\nSupplying both delta and places raises a TypeError."
},
{
"code": null,
"e": 6493,
"s": 6436,
"text": "assertNotAlmostEqual (first, second, places, msg, delta)"
},
{
"code": null,
"e": 6660,
"s": 6493,
"text": "Test that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero."
},
{
"code": null,
"e": 6823,
"s": 6660,
"text": "In both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta."
},
{
"code": null,
"e": 6875,
"s": 6823,
"text": "Supplying both delta and places raises a TypeError."
},
{
"code": null,
"e": 7014,
"s": 6875,
"text": "assertGreater (first, second, msg = None)\nTest that first is greater than second depending on the method name. If not, the test will fail."
},
{
"code": null,
"e": 7056,
"s": 7014,
"text": "assertGreater (first, second, msg = None)"
},
{
"code": null,
"e": 7153,
"s": 7056,
"text": "Test that first is greater than second depending on the method name. If not, the test will fail."
},
{
"code": null,
"e": 7308,
"s": 7153,
"text": "assertGreaterEqual (first, second, msg = None)\nTest that first is greater than or equal to second depending on the method name. If not, the test will fail"
},
{
"code": null,
"e": 7355,
"s": 7308,
"text": "assertGreaterEqual (first, second, msg = None)"
},
{
"code": null,
"e": 7463,
"s": 7355,
"text": "Test that first is greater than or equal to second depending on the method name. If not, the test will fail"
},
{
"code": null,
"e": 7595,
"s": 7463,
"text": "assertLess (first, second, msg = None)\nTest that first is less than second depending on the method name. If not, the test will fail"
},
{
"code": null,
"e": 7634,
"s": 7595,
"text": "assertLess (first, second, msg = None)"
},
{
"code": null,
"e": 7727,
"s": 7634,
"text": "Test that first is less than second depending on the method name. If not, the test will fail"
},
{
"code": null,
"e": 7879,
"s": 7727,
"text": "assertLessEqual (first, second, msg = None)\nTest that first is less than or equal to second depending upon the method name. If not, the test will fail."
},
{
"code": null,
"e": 7923,
"s": 7879,
"text": "assertLessEqual (first, second, msg = None)"
},
{
"code": null,
"e": 8031,
"s": 7923,
"text": "Test that first is less than or equal to second depending upon the method name. If not, the test will fail."
},
{
"code": null,
"e": 8318,
"s": 8031,
"text": "assertRegexpMatches (text, regexp, msg = None)\nTest that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search()."
},
{
"code": null,
"e": 8365,
"s": 8318,
"text": "assertRegexpMatches (text, regexp, msg = None)"
},
{
"code": null,
"e": 8605,
"s": 8365,
"text": "Test that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search()."
},
{
"code": null,
"e": 8911,
"s": 8605,
"text": "assertNotRegexpMatches (text, regexp, msg = None)\nVerifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search() ."
},
{
"code": null,
"e": 8961,
"s": 8911,
"text": "assertNotRegexpMatches (text, regexp, msg = None)"
},
{
"code": null,
"e": 9217,
"s": 8961,
"text": "Verifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search() ."
},
{
"code": null,
"e": 9284,
"s": 9217,
"text": "The assertion functions are implemented in the following example −"
},
{
"code": null,
"e": 9688,
"s": 9284,
"text": "import unittest\nimport math\nimport re\n\nclass SimpleTest(unittest.TestCase):\n def test1(self):\n self.assertAlmostEqual(22.0/7,3.14)\n def test2(self):\n self.assertNotAlmostEqual(10.0/3,3)\n def test3(self):\n self.assertGreater(math.pi,3)\n def test4(self):\n self.assertNotRegexpMatches(\"Tutorials Point (I) Private Limited\",\"Point\")\n\nif __name__ == '__main__':\n unittest.main()"
},
{
"code": null,
"e": 9923,
"s": 9688,
"text": "The above script reports test1 and test4 as Failure. In test1, the division of 22/7 is not within 7 decimal places of 3.14. Similarly, since the second argument matches with the text in first argument, test4 results in AssertionError."
},
{
"code": null,
"e": 10945,
"s": 9923,
"text": "=====================================================FAIL: test1 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 7, in test1\n self.assertAlmostEqual(22.0/7,3.14)\nAssertionError: 3.142857142857143 != 3.14 within 7 places\n================================================================\nFAIL: test4 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 13, in test4\n self.assertNotRegexpMatches(\"Tutorials Point (I) Private Limited\",\"Point\")\nAssertionError: Regexp matched: 'Point' matches 'Point' in 'Tutorials Point (I)\nPrivate Limited'\n----------------------------------------------------------------------\n\nRan 4 tests in 0.001s \n \nFAILED (failures = 2)\n"
},
{
"code": null,
"e": 11074,
"s": 10945,
"text": "This set of assert functions are meant to be used with collection data types in Python, such as List, Tuple, Dictionary and Set."
},
{
"code": null,
"e": 11117,
"s": 11074,
"text": "assertListEqual (list1, list2, msg = None)"
},
{
"code": null,
"e": 11238,
"s": 11117,
"text": "Tests that two lists are equal. If not, an error message is constructed that shows only the differences between the two."
},
{
"code": null,
"e": 11284,
"s": 11238,
"text": "assertTupleEqual (tuple1, tuple2, msg = None)"
},
{
"code": null,
"e": 11406,
"s": 11284,
"text": "Tests that two tuples are equal. If not, an error message is constructed that shows only the differences between the two."
},
{
"code": null,
"e": 11446,
"s": 11406,
"text": "assertSetEqual (set1, set2, msg = None)"
},
{
"code": null,
"e": 11562,
"s": 11446,
"text": "Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets."
},
{
"code": null,
"e": 11609,
"s": 11562,
"text": "assertDictEqual (expected, actual, msg = None)"
},
{
"code": null,
"e": 11735,
"s": 11609,
"text": "Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries."
},
{
"code": null,
"e": 11788,
"s": 11735,
"text": "The following example implements the above methods −"
},
{
"code": null,
"e": 12107,
"s": 11788,
"text": "import unittest\n\nclass SimpleTest(unittest.TestCase):\n def test1(self):\n self.assertListEqual([2,3,4], [1,2,3,4,5])\n def test2(self):\n self.assertTupleEqual((1*2,2*2,3*2), (2,4,6))\n def test3(self):\n self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})\n\nif __name__ == '__main__':\n unittest.main()"
},
{
"code": null,
"e": 12237,
"s": 12107,
"text": "In the above example, test1 and test3 show AssertionError. Error message displays the differences in List and Dictionary objects."
},
{
"code": null,
"e": 13391,
"s": 12237,
"text": "FAIL: test1 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 5, in test1\n self.assertListEqual([2,3,4], [1,2,3,4,5])\nAssertionError: Lists differ: [2, 3, 4] != [1, 2, 3, 4, 5]\n\nFirst differing element 0:\n2\n1\n\nSecond list contains 2 additional elements.\nFirst extra element 3:\n4\n\n- [2, 3, 4]\n+ [1, 2, 3, 4, 5]\n? +++ +++\n\nFAIL: test3 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 9, in test3\n self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})\nAssertionError: {1: 11, 2: 22} != {1: 11, 2: 22, 3: 33}\n- {1: 11, 2: 22}\n+ {1: 11, 2: 22, 3: 33}\n? +++++++\n \n---------------------------------------------------------------------- \nRan 3 tests in 0.001s \n \nFAILED (failures = 2)\n"
},
{
"code": null,
"e": 13398,
"s": 13391,
"text": " Print"
},
{
"code": null,
"e": 13409,
"s": 13398,
"text": " Add Notes"
}
] |
2D Transformation | Rotation of objects - GeeksforGeeks
|
02 Dec, 2021
We have to rotate an object by a given angle about a given pivot point and print the new co-ordinates.Examples:
Input : {(100, 100), (150, 200), (200, 200),
(200, 150)} is to be rotated about
(0, 0) by 90 degrees
Output : (-100, 100), (-200, 150), (-200, 200), (-150, 200)
Input : {(100, 100), (100, 200), (200, 200)}
is to be rotated about (50, -50) by
-45 degrees
Output : (191.421, 20.7107), (262.132, 91.4214),
(332.843, 20.7107)
In order to rotate an object we need to rotate each vertex of the figure individually. On rotating a point P(x, y) by an angle A about the origin we get a point P'(x’, y’). The values of x’ and y’ can be calculated as follows:-
We know that, x = rcosB, y = rsinBx’ = rcos(A+B) = r(cosAcosB – sinAsinB) = rcosBcosA – rsinBsinA = xcosA – ysinA y’ = rsin(A+B) = r(sinAcosB + cosAsinB) = rcosBsinA + rsinBcosA = xsinA + ycosARotational Matrix Equation:-
C
CPP
Python3
// C program to rotate an object by// a given angle about a given point#include <math.h>#include <stdio.h> // Using macros to convert degree to radian// and call sin() and cos() as these functions// take input in radians#define SIN(x) sin(x * 3.141592653589 / 180)#define COS(x) cos(x * 3.141592653589 / 180) // To rotate an objectvoid rotate(float a[][2], int n, int x_pivot, int y_pivot, int angle){ int i = 0; while (i < n) { // Shifting the pivot point to the origin // and the given points accordingly int x_shifted = a[i][0] - x_pivot; int y_shifted = a[i][1] - y_pivot; // Calculating the rotated point co-ordinates // and shifting it back a[i][0] = x_pivot + (x_shifted * COS(angle) - y_shifted * SIN(angle)); a[i][1] = y_pivot + (x_shifted * SIN(angle) + y_shifted * COS(angle)); printf("(%f, %f) ", a[i][0], a[i][1]); i++; }} // Driver Codeint main(){ // 1st Example // The following figure is to be // rotated about (0, 0) by 90 degrees int size1 = 4; // No. of vertices // Vertex co-ordinates must be in order float points_list1[][2] = { { 100, 100 }, { 150, 200 }, { 200, 200 }, { 200, 150 } }; rotate(points_list1, size1, 0, 0, 90); // 2nd Example // The following figure is to be // rotated about (50, -50) by -45 degrees /*int size2 = 3;//No. of vertices float points_list2[][2] = {{100, 100}, {100, 200}, {200, 200}}; rotate(points_list2, size2, 50, -50, -45);*/ return 0;}
// C++ program to rotate an object by// a given angle about a given point#include <iostream>#include <math.h>using namespace std; // Using macros to convert degree to radian// and call sin() and cos() as these functions// take input in radians#define SIN(x) sin(x * 3.141592653589 / 180)#define COS(x) cos(x * 3.141592653589 / 180) // To rotate an object given as order set of points in a[]// (x_pivot, y_pivot)void rotate(float a[][2], int n, int x_pivot, int y_pivot, int angle){ int i = 0; while (i < n) { // Shifting the pivot point to the origin // and the given points accordingly int x_shifted = a[i][0] - x_pivot; int y_shifted = a[i][1] - y_pivot; // Calculating the rotated point co-ordinates // and shifting it back a[i][0] = x_pivot + (x_shifted * COS(angle) - y_shifted * SIN(angle)); a[i][1] = y_pivot + (x_shifted * SIN(angle) + y_shifted * COS(angle)); cout << "(" << a[i][0] << ", " << a[i][1] << ") "; i++; }} // Driver Codeint main(){ // 1st Example // The following figure is to be // rotated about (0, 0) by 90 degrees int size1 = 4; // No. of vertices // Vertex co-ordinates must be in order float points_list1[][2] = { { 100, 100 }, { 150, 200 }, { 200, 200 }, { 200, 150 } }; rotate(points_list1, size1, 0, 0, 90); // 2nd Example // The following figure is to be // rotated about (50, -50) by -45 degrees /*int size2 = 3;//No. of vertices float points_list2[][2] = {{100, 100}, {100, 200}, {200, 200}}; rotate(points_list2, size2, 50, -50, -45);*/ return 0;}
# Python3 program to rotate an object by# a given angle about a given pointimport math SIN=lambda x: int(math.sin(x * 3.141592653589 / 180))COS=lambda x: int(math.cos(x * 3.141592653589 / 180)) # To rotate an objectdef rotate(a, n, x_pivot, y_pivot, angle): i = 0 while (i < n) : # Shifting the pivot point to the origin # and the given points accordingly x_shifted = a[i][0] - x_pivot y_shifted = a[i][1] - y_pivot # Calculating the rotated point co-ordinates # and shifting it back a[i][0] = x_pivot + (x_shifted * COS(angle) - y_shifted * SIN(angle)) a[i][1] = y_pivot + (x_shifted * SIN(angle) + y_shifted * COS(angle)) print("({}, {}) ".format(a[i][0], a[i][1]),end=" ") i+=1 # Driver Codeif __name__=='__main__': # 1st Example # The following figure is to be # rotated about (0, 0) by 90 degrees size1 = 4 # No. of vertices # Vertex co-ordinates must be in order points_list1 = [[ 100, 100], [ 150, 200], [ 200, 200], [ 200, 150],] rotate(points_list1, size1, 0, 0, 90) # 2nd Example # The following figure is to be # rotated about (50, -50) by -45 degrees # size2 = 3#No. of vertices # points_list2 = [[100, 100], # [100, 200], # [200, 200]] # rotate(points_list2, size2, 50, -50, -45)
Output:
(-100, 100), (-200, 150), (-200, 200), (-150, 200)
Time Complexity: O(N)Auxiliary Space: O(1) References: Rotation matrix
This article is contributed by Nabaneet Roy. 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.
Nexain
muskan24r
pankajsharmagfg
amartyaghoshgfg
computer-graphics
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Difference between Informed and Uninformed Search in AI
Cyclomatic Complexity
Rail Fence Cipher - Encryption and Decryption
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
Difference Between Symmetric and Asymmetric Key Encryption
Priority CPU Scheduling with different arrival time - Set 2
|
[
{
"code": null,
"e": 24231,
"s": 24203,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 24344,
"s": 24231,
"text": "We have to rotate an object by a given angle about a given pivot point and print the new co-ordinates.Examples: "
},
{
"code": null,
"e": 24526,
"s": 24344,
"text": "Input : {(100, 100), (150, 200), (200, 200), \n (200, 150)} is to be rotated about \n (0, 0) by 90 degrees\nOutput : (-100, 100), (-200, 150), (-200, 200), (-150, 200)"
},
{
"code": null,
"e": 24716,
"s": 24526,
"text": "Input : {(100, 100), (100, 200), (200, 200)} \n is to be rotated about (50, -50) by \n -45 degrees\nOutput : (191.421, 20.7107), (262.132, 91.4214), \n (332.843, 20.7107)"
},
{
"code": null,
"e": 24944,
"s": 24716,
"text": "In order to rotate an object we need to rotate each vertex of the figure individually. On rotating a point P(x, y) by an angle A about the origin we get a point P'(x’, y’). The values of x’ and y’ can be calculated as follows:-"
},
{
"code": null,
"e": 25166,
"s": 24944,
"text": "We know that, x = rcosB, y = rsinBx’ = rcos(A+B) = r(cosAcosB – sinAsinB) = rcosBcosA – rsinBsinA = xcosA – ysinA y’ = rsin(A+B) = r(sinAcosB + cosAsinB) = rcosBsinA + rsinBcosA = xsinA + ycosARotational Matrix Equation:-"
},
{
"code": null,
"e": 25170,
"s": 25168,
"text": "C"
},
{
"code": null,
"e": 25174,
"s": 25170,
"text": "CPP"
},
{
"code": null,
"e": 25182,
"s": 25174,
"text": "Python3"
},
{
"code": "// C program to rotate an object by// a given angle about a given point#include <math.h>#include <stdio.h> // Using macros to convert degree to radian// and call sin() and cos() as these functions// take input in radians#define SIN(x) sin(x * 3.141592653589 / 180)#define COS(x) cos(x * 3.141592653589 / 180) // To rotate an objectvoid rotate(float a[][2], int n, int x_pivot, int y_pivot, int angle){ int i = 0; while (i < n) { // Shifting the pivot point to the origin // and the given points accordingly int x_shifted = a[i][0] - x_pivot; int y_shifted = a[i][1] - y_pivot; // Calculating the rotated point co-ordinates // and shifting it back a[i][0] = x_pivot + (x_shifted * COS(angle) - y_shifted * SIN(angle)); a[i][1] = y_pivot + (x_shifted * SIN(angle) + y_shifted * COS(angle)); printf(\"(%f, %f) \", a[i][0], a[i][1]); i++; }} // Driver Codeint main(){ // 1st Example // The following figure is to be // rotated about (0, 0) by 90 degrees int size1 = 4; // No. of vertices // Vertex co-ordinates must be in order float points_list1[][2] = { { 100, 100 }, { 150, 200 }, { 200, 200 }, { 200, 150 } }; rotate(points_list1, size1, 0, 0, 90); // 2nd Example // The following figure is to be // rotated about (50, -50) by -45 degrees /*int size2 = 3;//No. of vertices float points_list2[][2] = {{100, 100}, {100, 200}, {200, 200}}; rotate(points_list2, size2, 50, -50, -45);*/ return 0;}",
"e": 26906,
"s": 25182,
"text": null
},
{
"code": "// C++ program to rotate an object by// a given angle about a given point#include <iostream>#include <math.h>using namespace std; // Using macros to convert degree to radian// and call sin() and cos() as these functions// take input in radians#define SIN(x) sin(x * 3.141592653589 / 180)#define COS(x) cos(x * 3.141592653589 / 180) // To rotate an object given as order set of points in a[]// (x_pivot, y_pivot)void rotate(float a[][2], int n, int x_pivot, int y_pivot, int angle){ int i = 0; while (i < n) { // Shifting the pivot point to the origin // and the given points accordingly int x_shifted = a[i][0] - x_pivot; int y_shifted = a[i][1] - y_pivot; // Calculating the rotated point co-ordinates // and shifting it back a[i][0] = x_pivot + (x_shifted * COS(angle) - y_shifted * SIN(angle)); a[i][1] = y_pivot + (x_shifted * SIN(angle) + y_shifted * COS(angle)); cout << \"(\" << a[i][0] << \", \" << a[i][1] << \") \"; i++; }} // Driver Codeint main(){ // 1st Example // The following figure is to be // rotated about (0, 0) by 90 degrees int size1 = 4; // No. of vertices // Vertex co-ordinates must be in order float points_list1[][2] = { { 100, 100 }, { 150, 200 }, { 200, 200 }, { 200, 150 } }; rotate(points_list1, size1, 0, 0, 90); // 2nd Example // The following figure is to be // rotated about (50, -50) by -45 degrees /*int size2 = 3;//No. of vertices float points_list2[][2] = {{100, 100}, {100, 200}, {200, 200}}; rotate(points_list2, size2, 50, -50, -45);*/ return 0;}",
"e": 28721,
"s": 26906,
"text": null
},
{
"code": "# Python3 program to rotate an object by# a given angle about a given pointimport math SIN=lambda x: int(math.sin(x * 3.141592653589 / 180))COS=lambda x: int(math.cos(x * 3.141592653589 / 180)) # To rotate an objectdef rotate(a, n, x_pivot, y_pivot, angle): i = 0 while (i < n) : # Shifting the pivot point to the origin # and the given points accordingly x_shifted = a[i][0] - x_pivot y_shifted = a[i][1] - y_pivot # Calculating the rotated point co-ordinates # and shifting it back a[i][0] = x_pivot + (x_shifted * COS(angle) - y_shifted * SIN(angle)) a[i][1] = y_pivot + (x_shifted * SIN(angle) + y_shifted * COS(angle)) print(\"({}, {}) \".format(a[i][0], a[i][1]),end=\" \") i+=1 # Driver Codeif __name__=='__main__': # 1st Example # The following figure is to be # rotated about (0, 0) by 90 degrees size1 = 4 # No. of vertices # Vertex co-ordinates must be in order points_list1 = [[ 100, 100], [ 150, 200], [ 200, 200], [ 200, 150],] rotate(points_list1, size1, 0, 0, 90) # 2nd Example # The following figure is to be # rotated about (50, -50) by -45 degrees # size2 = 3#No. of vertices # points_list2 = [[100, 100], # [100, 200], # [200, 200]] # rotate(points_list2, size2, 50, -50, -45)",
"e": 30142,
"s": 28721,
"text": null
},
{
"code": null,
"e": 30151,
"s": 30142,
"text": "Output: "
},
{
"code": null,
"e": 30202,
"s": 30151,
"text": "(-100, 100), (-200, 150), (-200, 200), (-150, 200)"
},
{
"code": null,
"e": 30273,
"s": 30202,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) References: Rotation matrix"
},
{
"code": null,
"e": 30694,
"s": 30273,
"text": "This article is contributed by Nabaneet Roy. 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": 30701,
"s": 30694,
"text": "Nexain"
},
{
"code": null,
"e": 30711,
"s": 30701,
"text": "muskan24r"
},
{
"code": null,
"e": 30727,
"s": 30711,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 30743,
"s": 30727,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 30761,
"s": 30743,
"text": "computer-graphics"
},
{
"code": null,
"e": 30772,
"s": 30761,
"text": "Algorithms"
},
{
"code": null,
"e": 30783,
"s": 30772,
"text": "Algorithms"
},
{
"code": null,
"e": 30881,
"s": 30783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30890,
"s": 30881,
"text": "Comments"
},
{
"code": null,
"e": 30903,
"s": 30890,
"text": "Old Comments"
},
{
"code": null,
"e": 30952,
"s": 30903,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30977,
"s": 30952,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31004,
"s": 30977,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 31060,
"s": 31004,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 31082,
"s": 31060,
"text": "Cyclomatic Complexity"
},
{
"code": null,
"e": 31128,
"s": 31082,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 31171,
"s": 31128,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 31200,
"s": 31171,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 31259,
"s": 31200,
"text": "Difference Between Symmetric and Asymmetric Key Encryption"
}
] |
How to compare two strings using regex in Python?
|
We can compare given strings using the following code
import re
s1 = 'Pink Forest'
s2 = 'Pink Forrest'
if bool(re.search(s1,s2))==True:
print 'Strings match'
else:
print 'Strings do not match'
This gives the output
Strings do not match
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "We can compare given strings using the following code"
},
{
"code": null,
"e": 1261,
"s": 1116,
"text": "import re\ns1 = 'Pink Forest'\ns2 = 'Pink Forrest'\nif bool(re.search(s1,s2))==True:\n print 'Strings match'\nelse:\n print 'Strings do not match'"
},
{
"code": null,
"e": 1283,
"s": 1261,
"text": "This gives the output"
},
{
"code": null,
"e": 1304,
"s": 1283,
"text": "Strings do not match"
}
] |
Create a full search engine via Flask, ElasticSearch, javascript, D3js, asynchrous request (xml http request) and Bootstrap | by Adrien Sieg | Towards Data Science
|
A search engine is a system — displaying some filters — in order to customize your search results and allows you to find exactly what you want. When a user queries a search engine, relevant results are returned based on the search engine’s algorithm.
Filters turn out to a list (dropdown list), a table, ... any elements allowing to broaden or tighten a search in order to get relevant results (results you are actually interested in).
Google is the reigning king of ‘spartan searching’, and is the single most used search engine in the world. Google offers a full free text search filter. A user enters keywords or key phrases into a search engine and receives a personal and relevant result. In this article, we are going to pass Google.
Let’s consider a dataset coming from WineEnthusiast when it comes to wine reviews. The code for the scraper can be found here. The search engine still won’t be able to taste the wine, but theoretically, it could retrieve the wine based on a description that a sommelier could give.
Country: The country that the wine comes from
Description: A few sentences from a sommelier describing the wine’s taste, smell, look, feel, etc.
Designation: The vineyard within the winery where the grapes that made the wine are from
Points: The number of points WineEnthusiast rated the wine on a scale of 1–100 (though they say they only post reviews for wines that score >=80)
Price: The cost for a bottle of the wine
Province: The province or state that the wine is from
Variety: The type of grapes used to make the wine (ie Pinot Noir)
Winery: The winery that made the wine
To kick off the journey, we will focus on three specific countries and three regions of wines.
It works well if you know that Bordeaux or Champagne are regions within France, that Lombardy and Tuscany are regions of Italy and finally that Andalucia and Catalunia are regions of Spain. If you don’t, you are stuck and get nothing. That’s a huge problem because you have to try all possibilities to luckily get something. How to deal with this issue? By implementing a parent/children logic within filters.
When it comes to app itself — there is a back-end (app.py) and a front-end (index.html). When you select an element within dropdown field, an XMLHttpRequest is sent to the server, and results are returned (from the server). The XMLHttpRequest object can be used to request data from a web server.
App.py
The XMLHttpRequest object is a developers dream, because you can:
Update a web page without reloading the page
Request data from a server — after the page has loaded
Receive data from a server — after the page has loaded
Send data to a server — in the background
The onreadystatechange property specifies a function to be executed every time the status of the XMLHttpRequest object changes:
Templates/index.html
This is not very pleasant to have all options possible when a given dropdown list depends on another one. If you click on France and then Catalunia, we are stuck and get nothing because Catalunia is not in France... Too bad. Either you try all possibilities to get something or we implement parent-children properties as below:
Parent-children properties:
Connect ElasticSearch database to python. Elasticsearch is a search engine based on Lucene library. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents. Elasticsearch has quickly become the most popular search engine, and is commonly used for log analytics, full-text search, security intelligence, business analytics, and operational intelligence use cases.
from time import timefrom elasticsearch import Elasticsearchfrom elasticsearch.helpers import bulkimport pandas as pdimport requestsres = requests.get(‘http://localhost:9200')print(res.content)#connect to our clusterfrom elasticsearch import Elasticsearches = Elasticsearch([{‘host’: ‘localhost’, ‘port’: 9200}])
Transform a csv file into json format to put it into ElasticSearch.
def index_data(data_path, index_name, doc_type): import json f = open(data_path) csvfile = pd.read_csv(f, iterator=True, encoding=”utf8") r = requests.get(‘http://localhost:9200') for i,df in enumerate(csvfile): records=df.where(pd.notnull(df), None).T.to_dict() list_records=[records[it] for it in records] try : for j, i in enumerate(list_records): es.index(index=index_name, doc_type=doc_type, id=j, body=i) except : print(‘error to index data’)
Useful to access the desired page directly without having to navigate from the home page. The route() decorator is used to bind URL to a function.
@app.route(‘/hello’)def hello_world(): return ‘hello world’
URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser.
The add_url_rule() function of an application object is also available to bind a URL with a function as below:
def hello_world(): return ‘hello world’app.add_url_rule(‘/’, ‘hello’, hello_world)
Http protocol is the foundation of data communication in world wide web.
Templates/index.html
<html> <body> <form action = "http://localhost:5000/login" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body></html>
app.py
from flask import Flask, redirect, url_for, requestapp = Flask(__name__)@app.route('/success/<name>')def success(name): return 'welcome %s' % name@app.route('/login',methods = ['POST', 'GET'])def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success',name = user)) else: user = request.args.get('nm') return redirect(url_for('success',name = user))if __name__ == '__main__': app.run(debug = True)
It is possible to return the output of a function bound to a certain URL in the form of HTML.
hello() function will render ‘Hello World’ with <h1> tag attached to it.
from flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return '<html><body><h1>'Hello World'</h1></body></html>'if __name__ == '__main__': app.run(debug = True)
Generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML.
This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function.
from flask import Flask, render_templateapp = Flask(__name__)@app.route('/hello/<user>')def hello_name(user): return render_template('hello.html', name = user)if __name__ == '__main__': app.run(debug = True)
‘Web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor.
Flask uses jinga2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered.
The following code is saved as hello.html in the templates folder.
<!doctype html><html> <body> <h1>Hello {{ name }}!</h1> </body></html>
The Jinga2 template engine uses the following delimiters for escaping from HTML.
{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements
The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered.
from flask import Flask, render_templateapp = Flask(__name__)@app.route('/result')def result(): dict = {'phy':50,'che':60,'maths':70} return render_template('result.html', result = dict)if __name__ == '__main__': app.run(debug = True)<!doctype html><html> <body> <table border = 1> {% for key, value in result.iteritems() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body></html>
|
[
{
"code": null,
"e": 423,
"s": 172,
"text": "A search engine is a system — displaying some filters — in order to customize your search results and allows you to find exactly what you want. When a user queries a search engine, relevant results are returned based on the search engine’s algorithm."
},
{
"code": null,
"e": 608,
"s": 423,
"text": "Filters turn out to a list (dropdown list), a table, ... any elements allowing to broaden or tighten a search in order to get relevant results (results you are actually interested in)."
},
{
"code": null,
"e": 912,
"s": 608,
"text": "Google is the reigning king of ‘spartan searching’, and is the single most used search engine in the world. Google offers a full free text search filter. A user enters keywords or key phrases into a search engine and receives a personal and relevant result. In this article, we are going to pass Google."
},
{
"code": null,
"e": 1194,
"s": 912,
"text": "Let’s consider a dataset coming from WineEnthusiast when it comes to wine reviews. The code for the scraper can be found here. The search engine still won’t be able to taste the wine, but theoretically, it could retrieve the wine based on a description that a sommelier could give."
},
{
"code": null,
"e": 1240,
"s": 1194,
"text": "Country: The country that the wine comes from"
},
{
"code": null,
"e": 1339,
"s": 1240,
"text": "Description: A few sentences from a sommelier describing the wine’s taste, smell, look, feel, etc."
},
{
"code": null,
"e": 1428,
"s": 1339,
"text": "Designation: The vineyard within the winery where the grapes that made the wine are from"
},
{
"code": null,
"e": 1574,
"s": 1428,
"text": "Points: The number of points WineEnthusiast rated the wine on a scale of 1–100 (though they say they only post reviews for wines that score >=80)"
},
{
"code": null,
"e": 1615,
"s": 1574,
"text": "Price: The cost for a bottle of the wine"
},
{
"code": null,
"e": 1669,
"s": 1615,
"text": "Province: The province or state that the wine is from"
},
{
"code": null,
"e": 1735,
"s": 1669,
"text": "Variety: The type of grapes used to make the wine (ie Pinot Noir)"
},
{
"code": null,
"e": 1773,
"s": 1735,
"text": "Winery: The winery that made the wine"
},
{
"code": null,
"e": 1868,
"s": 1773,
"text": "To kick off the journey, we will focus on three specific countries and three regions of wines."
},
{
"code": null,
"e": 2278,
"s": 1868,
"text": "It works well if you know that Bordeaux or Champagne are regions within France, that Lombardy and Tuscany are regions of Italy and finally that Andalucia and Catalunia are regions of Spain. If you don’t, you are stuck and get nothing. That’s a huge problem because you have to try all possibilities to luckily get something. How to deal with this issue? By implementing a parent/children logic within filters."
},
{
"code": null,
"e": 2575,
"s": 2278,
"text": "When it comes to app itself — there is a back-end (app.py) and a front-end (index.html). When you select an element within dropdown field, an XMLHttpRequest is sent to the server, and results are returned (from the server). The XMLHttpRequest object can be used to request data from a web server."
},
{
"code": null,
"e": 2582,
"s": 2575,
"text": "App.py"
},
{
"code": null,
"e": 2648,
"s": 2582,
"text": "The XMLHttpRequest object is a developers dream, because you can:"
},
{
"code": null,
"e": 2693,
"s": 2648,
"text": "Update a web page without reloading the page"
},
{
"code": null,
"e": 2748,
"s": 2693,
"text": "Request data from a server — after the page has loaded"
},
{
"code": null,
"e": 2803,
"s": 2748,
"text": "Receive data from a server — after the page has loaded"
},
{
"code": null,
"e": 2845,
"s": 2803,
"text": "Send data to a server — in the background"
},
{
"code": null,
"e": 2973,
"s": 2845,
"text": "The onreadystatechange property specifies a function to be executed every time the status of the XMLHttpRequest object changes:"
},
{
"code": null,
"e": 2994,
"s": 2973,
"text": "Templates/index.html"
},
{
"code": null,
"e": 3322,
"s": 2994,
"text": "This is not very pleasant to have all options possible when a given dropdown list depends on another one. If you click on France and then Catalunia, we are stuck and get nothing because Catalunia is not in France... Too bad. Either you try all possibilities to get something or we implement parent-children properties as below:"
},
{
"code": null,
"e": 3350,
"s": 3322,
"text": "Parent-children properties:"
},
{
"code": null,
"e": 3786,
"s": 3350,
"text": "Connect ElasticSearch database to python. Elasticsearch is a search engine based on Lucene library. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents. Elasticsearch has quickly become the most popular search engine, and is commonly used for log analytics, full-text search, security intelligence, business analytics, and operational intelligence use cases."
},
{
"code": null,
"e": 4099,
"s": 3786,
"text": "from time import timefrom elasticsearch import Elasticsearchfrom elasticsearch.helpers import bulkimport pandas as pdimport requestsres = requests.get(‘http://localhost:9200')print(res.content)#connect to our clusterfrom elasticsearch import Elasticsearches = Elasticsearch([{‘host’: ‘localhost’, ‘port’: 9200}])"
},
{
"code": null,
"e": 4167,
"s": 4099,
"text": "Transform a csv file into json format to put it into ElasticSearch."
},
{
"code": null,
"e": 4685,
"s": 4167,
"text": "def index_data(data_path, index_name, doc_type): import json f = open(data_path) csvfile = pd.read_csv(f, iterator=True, encoding=”utf8\") r = requests.get(‘http://localhost:9200') for i,df in enumerate(csvfile): records=df.where(pd.notnull(df), None).T.to_dict() list_records=[records[it] for it in records] try : for j, i in enumerate(list_records): es.index(index=index_name, doc_type=doc_type, id=j, body=i) except : print(‘error to index data’)"
},
{
"code": null,
"e": 4832,
"s": 4685,
"text": "Useful to access the desired page directly without having to navigate from the home page. The route() decorator is used to bind URL to a function."
},
{
"code": null,
"e": 4894,
"s": 4832,
"text": "@app.route(‘/hello’)def hello_world(): return ‘hello world’"
},
{
"code": null,
"e": 5089,
"s": 4894,
"text": "URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser."
},
{
"code": null,
"e": 5200,
"s": 5089,
"text": "The add_url_rule() function of an application object is also available to bind a URL with a function as below:"
},
{
"code": null,
"e": 5285,
"s": 5200,
"text": "def hello_world(): return ‘hello world’app.add_url_rule(‘/’, ‘hello’, hello_world)"
},
{
"code": null,
"e": 5358,
"s": 5285,
"text": "Http protocol is the foundation of data communication in world wide web."
},
{
"code": null,
"e": 5379,
"s": 5358,
"text": "Templates/index.html"
},
{
"code": null,
"e": 5634,
"s": 5379,
"text": "<html> <body> <form action = \"http://localhost:5000/login\" method = \"post\"> <p>Enter Name:</p> <p><input type = \"text\" name = \"nm\" /></p> <p><input type = \"submit\" value = \"submit\" /></p> </form> </body></html>"
},
{
"code": null,
"e": 5641,
"s": 5634,
"text": "app.py"
},
{
"code": null,
"e": 6109,
"s": 5641,
"text": "from flask import Flask, redirect, url_for, requestapp = Flask(__name__)@app.route('/success/<name>')def success(name): return 'welcome %s' % name@app.route('/login',methods = ['POST', 'GET'])def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success',name = user)) else: user = request.args.get('nm') return redirect(url_for('success',name = user))if __name__ == '__main__': app.run(debug = True)"
},
{
"code": null,
"e": 6203,
"s": 6109,
"text": "It is possible to return the output of a function bound to a certain URL in the form of HTML."
},
{
"code": null,
"e": 6276,
"s": 6203,
"text": "hello() function will render ‘Hello World’ with <h1> tag attached to it."
},
{
"code": null,
"e": 6458,
"s": 6276,
"text": "from flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return '<html><body><h1>'Hello World'</h1></body></html>'if __name__ == '__main__': app.run(debug = True)"
},
{
"code": null,
"e": 6664,
"s": 6458,
"text": "Generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML."
},
{
"code": null,
"e": 6870,
"s": 6664,
"text": "This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function."
},
{
"code": null,
"e": 7082,
"s": 6870,
"text": "from flask import Flask, render_templateapp = Flask(__name__)@app.route('/hello/<user>')def hello_name(user): return render_template('hello.html', name = user)if __name__ == '__main__': app.run(debug = True)"
},
{
"code": null,
"e": 7302,
"s": 7082,
"text": "‘Web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor."
},
{
"code": null,
"e": 7521,
"s": 7302,
"text": "Flask uses jinga2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered."
},
{
"code": null,
"e": 7588,
"s": 7521,
"text": "The following code is saved as hello.html in the templates folder."
},
{
"code": null,
"e": 7677,
"s": 7588,
"text": "<!doctype html><html> <body> <h1>Hello {{ name }}!</h1> </body></html>"
},
{
"code": null,
"e": 7758,
"s": 7677,
"text": "The Jinga2 template engine uses the following delimiters for escaping from HTML."
},
{
"code": null,
"e": 7783,
"s": 7758,
"text": "{% ... %} for Statements"
},
{
"code": null,
"e": 7841,
"s": 7783,
"text": "{{ ... }} for Expressions to print to the template output"
},
{
"code": null,
"e": 7900,
"s": 7841,
"text": "{# ... #} for Comments not included in the template output"
},
{
"code": null,
"e": 7929,
"s": 7900,
"text": "# ... ## for Line Statements"
},
{
"code": null,
"e": 8172,
"s": 7929,
"text": "The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered."
}
] |
What is pytest and what are its advantages?
|
Pytest is a test framework in python. To install pytest, we need to use the command pip install pytest. After installation, we can verify if python has been installed by the command pytest –version. The version of pytest shall be known.
Pytest can be used for creating and executing test cases. It can be used in wide
range testing API, UI, database and so on. The test file of pytest has a naming
convention that it starts with test_ or ends with _test keyword and every line of
code should be inside a method which should have a name starting with test
keyword. Also each method should have a unique name.
def test_f():
print("Tutorialspoint")
To run the above code, we need to move to the terminal and use the command py.test. However this will not give much details from an execution point of view. To get information on execution we should use the command py.test –v. Here v stands for verbose.
In order to print the console logs, we need to use the command py.test –v –s. Again, if we want to run tests from a specific pytest file, the command is py.test
<filename> -v.
The advantages of pytest framework are listed below −
Pytest is capable of executing multiple test cases simultaneously, thereby
reducing the execution duration.
Pytest is capable of executing multiple test cases simultaneously, thereby
reducing the execution duration.
Pytest is capable of skipping a test method from a group of test methods
during execution.
Pytest is capable of skipping a test method from a group of test methods
during execution.
Pytest is free and does not have licensing cost.
Pytest is free and does not have licensing cost.
Pytest is quick and easy to learn.
Pytest is quick and easy to learn.
Pytest can choose to run a particular test method or all the test methods of
a particular test file based on conditions.
Pytest can choose to run a particular test method or all the test methods of
a particular test file based on conditions.
Pytest is capable of skipping a few test methods out of all the test methods
during test execution.
Pytest is capable of skipping a few test methods out of all the test methods
during test execution.
Pytest can be used to test a wide range of applications on API, database and
so on.
Pytest can be used to test a wide range of applications on API, database and
so on.
|
[
{
"code": null,
"e": 1299,
"s": 1062,
"text": "Pytest is a test framework in python. To install pytest, we need to use the command pip install pytest. After installation, we can verify if python has been installed by the command pytest –version. The version of pytest shall be known."
},
{
"code": null,
"e": 1670,
"s": 1299,
"text": "Pytest can be used for creating and executing test cases. It can be used in wide\nrange testing API, UI, database and so on. The test file of pytest has a naming\nconvention that it starts with test_ or ends with _test keyword and every line of\ncode should be inside a method which should have a name starting with test\nkeyword. Also each method should have a unique name."
},
{
"code": null,
"e": 1708,
"s": 1670,
"text": "def test_f():\nprint(\"Tutorialspoint\")"
},
{
"code": null,
"e": 1962,
"s": 1708,
"text": "To run the above code, we need to move to the terminal and use the command py.test. However this will not give much details from an execution point of view. To get information on execution we should use the command py.test –v. Here v stands for verbose."
},
{
"code": null,
"e": 2138,
"s": 1962,
"text": "In order to print the console logs, we need to use the command py.test –v –s. Again, if we want to run tests from a specific pytest file, the command is py.test\n<filename> -v."
},
{
"code": null,
"e": 2192,
"s": 2138,
"text": "The advantages of pytest framework are listed below −"
},
{
"code": null,
"e": 2300,
"s": 2192,
"text": "Pytest is capable of executing multiple test cases simultaneously, thereby\nreducing the execution duration."
},
{
"code": null,
"e": 2408,
"s": 2300,
"text": "Pytest is capable of executing multiple test cases simultaneously, thereby\nreducing the execution duration."
},
{
"code": null,
"e": 2499,
"s": 2408,
"text": "Pytest is capable of skipping a test method from a group of test methods\nduring execution."
},
{
"code": null,
"e": 2590,
"s": 2499,
"text": "Pytest is capable of skipping a test method from a group of test methods\nduring execution."
},
{
"code": null,
"e": 2639,
"s": 2590,
"text": "Pytest is free and does not have licensing cost."
},
{
"code": null,
"e": 2688,
"s": 2639,
"text": "Pytest is free and does not have licensing cost."
},
{
"code": null,
"e": 2723,
"s": 2688,
"text": "Pytest is quick and easy to learn."
},
{
"code": null,
"e": 2758,
"s": 2723,
"text": "Pytest is quick and easy to learn."
},
{
"code": null,
"e": 2879,
"s": 2758,
"text": "Pytest can choose to run a particular test method or all the test methods of\na particular test file based on conditions."
},
{
"code": null,
"e": 3000,
"s": 2879,
"text": "Pytest can choose to run a particular test method or all the test methods of\na particular test file based on conditions."
},
{
"code": null,
"e": 3100,
"s": 3000,
"text": "Pytest is capable of skipping a few test methods out of all the test methods\nduring test execution."
},
{
"code": null,
"e": 3200,
"s": 3100,
"text": "Pytest is capable of skipping a few test methods out of all the test methods\nduring test execution."
},
{
"code": null,
"e": 3284,
"s": 3200,
"text": "Pytest can be used to test a wide range of applications on API, database and\nso on."
},
{
"code": null,
"e": 3368,
"s": 3284,
"text": "Pytest can be used to test a wide range of applications on API, database and\nso on."
}
] |
java.util.regex.Matcher.appendReplacement()
|
The java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method implements a non-terminal append-and-replace step.
Following is the declaration for java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method.
public Matcher appendReplacement(StringBuffer sb, String replacement)
sb − The target string buffer.
sb − The target string buffer.
replacement − The replacement string.
replacement − The replacement string.
This matcher.
IllegalStateException − If no match has yet been attempted, or if the previous match operation failed.
IllegalStateException − If no match has yet been attempted, or if the previous match operation failed.
IllegalArgumentException − If the replacement string refers to a named-capturing group that does not exist in the pattern.
IllegalArgumentException − If the replacement string refers to a named-capturing group that does not exist in the pattern.
IndexOutOfBoundsException − If the replacement string refers to a capturing group that does not exist in the pattern.
IndexOutOfBoundsException − If the replacement string refers to a capturing group that does not exist in the pattern.
The following example shows the usage of java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method.
package com.tutorialspoint;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherDemo {
private static String REGEX = "a*b";
private static String INPUT = "aabfooaabfooabfoob";
private static String REPLACE = "-";
public static void main(String[] args) {
Pattern pattern = Pattern.compile(REGEX);
// get a matcher object
Matcher matcher = pattern.matcher(INPUT);
StringBuffer buffer = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(buffer, REPLACE);
}
matcher.appendTail(buffer);
System.out.println(buffer.toString());
}
}
Let us compile and run the above program, this will produce the following result −
-foo-foo-foo-
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2259,
"s": 2124,
"text": "The java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method implements a non-terminal append-and-replace step."
},
{
"code": null,
"e": 2373,
"s": 2259,
"text": "Following is the declaration for java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method."
},
{
"code": null,
"e": 2444,
"s": 2373,
"text": "public Matcher appendReplacement(StringBuffer sb, String replacement)\n"
},
{
"code": null,
"e": 2475,
"s": 2444,
"text": "sb − The target string buffer."
},
{
"code": null,
"e": 2506,
"s": 2475,
"text": "sb − The target string buffer."
},
{
"code": null,
"e": 2544,
"s": 2506,
"text": "replacement − The replacement string."
},
{
"code": null,
"e": 2582,
"s": 2544,
"text": "replacement − The replacement string."
},
{
"code": null,
"e": 2596,
"s": 2582,
"text": "This matcher."
},
{
"code": null,
"e": 2699,
"s": 2596,
"text": "IllegalStateException − If no match has yet been attempted, or if the previous match operation failed."
},
{
"code": null,
"e": 2802,
"s": 2699,
"text": "IllegalStateException − If no match has yet been attempted, or if the previous match operation failed."
},
{
"code": null,
"e": 2925,
"s": 2802,
"text": "IllegalArgumentException − If the replacement string refers to a named-capturing group that does not exist in the pattern."
},
{
"code": null,
"e": 3048,
"s": 2925,
"text": "IllegalArgumentException − If the replacement string refers to a named-capturing group that does not exist in the pattern."
},
{
"code": null,
"e": 3166,
"s": 3048,
"text": "IndexOutOfBoundsException − If the replacement string refers to a capturing group that does not exist in the pattern."
},
{
"code": null,
"e": 3284,
"s": 3166,
"text": "IndexOutOfBoundsException − If the replacement string refers to a capturing group that does not exist in the pattern."
},
{
"code": null,
"e": 3406,
"s": 3284,
"text": "The following example shows the usage of java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method."
},
{
"code": null,
"e": 4071,
"s": 3406,
"text": "package com.tutorialspoint;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class MatcherDemo {\n private static String REGEX = \"a*b\";\n private static String INPUT = \"aabfooaabfooabfoob\";\n private static String REPLACE = \"-\";\n public static void main(String[] args) {\n Pattern pattern = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT);\n StringBuffer buffer = new StringBuffer();\n \n while(matcher.find()) {\n matcher.appendReplacement(buffer, REPLACE);\n }\n matcher.appendTail(buffer);\n System.out.println(buffer.toString());\n }\n}"
},
{
"code": null,
"e": 4154,
"s": 4071,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 4169,
"s": 4154,
"text": "-foo-foo-foo-\n"
},
{
"code": null,
"e": 4176,
"s": 4169,
"text": " Print"
},
{
"code": null,
"e": 4187,
"s": 4176,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.