Sunday, April 5, 2020

Kotlin - Functions Concept

Functions:

So far we have seen the main function. So if you want to split your code into separate functions. So main function is actually launched your application as it the function that gets executed when you run it.So how to create a function.

For example;

fun test()
{
  println("Test")
}

So once you have written the function you can call it from elsewhere in your application:

fun main(args: Arrays<String>)
{
 test()
}

you can also send things to a function.you can tell the compiler what values a function can accept by your specification one or more parameters you can pass:

fun test(param: Int)
{
  println("Paramater is $param")
}

// you can call it like

test(6)

You can also pass variables to a function so long as the variable type matches the parameter type:

fun main(args: Array<Strings>)
{
  val x: Int =7
  val y:Int =8

  printSum(x,y)
}

fun printSum(int1: Int, int2:Int)
{
   val result = int1 + int2
   println(result)
}

You can also get things back from a function:

So if you want to get something back from a function.you need to declare it.for example:

fun max(a: Int, b:Int) : Int   // this tells the compiler that the function returns an Int value
{
   val maxValue = if(a > b) a else b
  return maxValue;  // you can not return string here you have to return Int only
}

Functions with no return value:

if you do not want to return a value you can either omit the return type from the function declaration or specify a return type Unit. Declaring ta return type Unit means that the function returns no value as in the example:

fun printSum(int1 : Int , int : Int2)
{
  val result = int1 + int2
   println(result)
}

or

fun printSum(int1 : Int, int2 : Int): Unit
{
  val result = int 1 + int 2
    println(result)
}

But if you try to return a value in function with no declared return type or a return type of Unit, your code won't compile.

Functions with single-expression bodies:

if you have a function whose body consists of a single expression. you can simplify the code by removing the curly braces and return statement from the function declaration. for example:

fun max(a: Int,b:Int) : Int
{
  val maxValue = if(a > b) a else b
  return maxValue
}

The function returns the result of a single expression which means that we can rewrite the function like below:

fun max(a:Int , b:Int):Int = if (a > b ) a else b

// here we have used = to say what the function returns and remove the {}'s

because the compiler can infer the function return type from the if expression we can make the code even shorter by omitting the : Int

fun max(a:Int,b:Int) = if (a > b) a else b

 here the compiler knows that a and b are Ints So it can work out of the function return type from the expression

So you can ask more questions here like :

  1. Can I return more than one value from a function?. A function can declare only one return value but if you want to say return three Int values then the declared type can be an array of Ints(Array<Int>). Put those Ints into the array and pass it back.
  2. Do I have to do something with the return value of a function? Can I just ignore it? Kotlin does not require you to acknowledge a return value. you might want to call a function with a return type even though you do not care about the return value.in this case, you are calling the function for the work it does inside the function rather than for what it returns. you do not have to assign or use the return value.
Example:

fun main(args: Array<Strings>)
{
  val options = arrayOf("One","Two","three")
  val gameChoice = getGameChoice(options)
 val userChoice = getUserChoice(options)
  pritnResult(userChoice,ganeChoice)
}

fun getGameChoice(optionsParam:Array<String>) = optionsParam[Math.random() * optionsParam.size).toInt()]

fun getUserChoice(optionParams:Array<String>) : String
{
   var isValidChoice = false
   var userChoice = ""
   while(!isValidChoice)
  {
     print("Please enter one of the following:")
     for(item in optionParams) print(" $item")

     val userInput = readLine()
     if(userInput!=null  && userInput in optionParam)
    {
       isValidChoice = true
        userChoice = userInput
    }

    if(!isvalidChoice) println("you must enter a valid choice.")
  }
  return userChoice
}

fun printresult()
{
  val result  : String
  if(userChoice == ganeChoice) result = "Anything you would like to print"
  else if((userChoice == "One" && userChoice == "Two" && userChoice == "Three")
  {
    print("print something here")
  }
  else result = "You wnated"
println("You chose $ userChoice . I chose $gameChoice . $result ")
}


Bullet Points to remember:


  • use function to organize your code and make it more reusable.
  • A function can have parameters so that you can pass more than one value to it
  • The number and type of values you pass to function must match the order and type of the parameters declared by the function.
  • A function can return a value. you must define the type of value it returns
  • A Unit return type means that the function does not return anything.
  • Choose for loops over while loops when you know how many times you want to repeat the loop code.
  • The ReadLine() function reads a line of input from the standard input system.it returns a String value, the text entered by the user.
  • If the input system has been redirected to a file and the end of the line has been reached, the readLine() function returns null, null means it has no value or its missing.
  • && means "and". || means "or" . !means "not".











Kotlin - Basic Types and Variables

Basic Types and Variables

Here I wills how you how Kotlin variables really work. So you will know about Kotlin's basic types such as Ints, Floats, and Booleans. I will also tell how to create arrays to hold multiple values and Finally you will discover why Objects are so important in Kotlin.

Your code needs a variable like

var x =5

So what is behind the scene ?.

So variables are like cup right. it can be small, Big based on our requirements but it will have one thing in common that it will hold the value.

So here if you say like x = 5 that means

1)What the variable name is.
2)whether or not the viable can be reused.
3)What type of variable it is.

You have to tell these things to the compiler.

So our compiler cares about the type of our variables. For this type safety to work, the compiler needs to know.

Let see how this works:

when you declare a variable using code like:

var x = 5 

the value you are assigning to the variable is used to create a new object And the compiler infers the variable's type from the object. So the compiler knows that you need a variable with a type of int so that it matches the type of object.

The variable holds a reference to the object when an object is assigned to a variable, the object itself doesn't go into the variable. A reference to the object goes into the variable instead.

val vs. var 

if you declare the variable using val, the reference to the object stays in the variable forever and can not be replaced but if you use the var keyword instead you can assign another value to the variable.

var x = 5
x = 6

So we can replace the reference held by the variable because its been declared using var but at the same time, it would not be possible if it declared the variable using val.

Bullet Points:


  • In java numbers are primitives so a variable holds the actual number. Is that not the case with Kotlin? No, it is not the case with Kotlin because in  Kotlin , numbers are objects and the variables hold a reference to the object, not the object itself.
  • Why does kotlin care so much about the variable's type? Because it makes your code safer and less prone to error.
  • In java, you can treat Char primitives as numbers. Can you do the same for Chars in kotlin.No Chars in Kotlin are characters not he numbers.
Some Examples:

fun main(args: Arrays<String>)
{
   var x : Int = 65.2  // this is not valid Int value
   var isPunk = true
   var message = 'Hellow'   // Single quotes are used to define Chars which holds single charecters.

    var y =7
    var bigNum: Long = y.toLong()
    var b: Byte = 2
  
 }

Now we see how to create an Array:

you can create an array using the arrayOf() function. for example:

fun main(args: Array<String>)
{
   val wordArray = arrayOf("24/7","Multi-Tier","B-To-B")
   var arraySize = wordArray.size
   
   val rand = (Math.random * arraySize).toInt  // This generates a random number returns a random number between 0 and 1 .We sue use Int() to force the result to be an integer.

   val phrase = "${wordArray[rand]}"
   println(phrase)
}

Note: Arrays hold items of a specific type.you can either let the compiler infer the type from the array's values or explicitly define the type using Array<Type>.

var vs val concept in Array :

So we need to understand the effect val and var have when you declare an array.
As you know a variable holds a reference to an object. when you declare a variable using var you can update the variable so that it holds a reference to a different instead.
If the variable holds a reference to an array this means that you can update the variable so that if it refers to a different array of the same type. for example:

var myArray = arrayOf(1,2,3)
myArray = arrayOf(4,5)

So let's understand what happens:

var myArray = arrayOf(1,2,3) This creates an array of Ints and a variable names myArray that holds a reference to it.

myArray = arrayOf(4,5) This creates a new array of Ints. A reference to the new array gets put into the myArray variable, replacing the previous references.

So what happens if we use the variable val instead?

val means the variable points to the same array forever. when you declare an array using val.you no longer update the variable so that it holds a reference to a different array. for example:

val myArray = arrayOf(1,2,3)
my Array = (4,5,6)

Once the viable is assigned an array. it holds a reference to that array forever but even though the variable maintains to the same array. the array itself update the variables in the array.

But there is catch you can still update the variables in the array.

Declaring a variable using val means that you can not reuse the variable for another object.you can however still update the object itself.

for example:

val myArray = arrayOf(1,2,3)
mayArray[2] = 6    // This updates the 3rd item in the array

Bullet Points:

  1. If the variable type is not explicitly defined the compiler infers it from its value.
  2. A variable holds a reference to an object
  3. An object has state and behavior. its behavior is exposed through its functions.
  4. Kotlin has a number of basics types: Byte,Short,Int,Long,Float,Double,boolean,Char and String.
  5. You can only assign a value to a variable that has a compatible type.
  6. If you define an array using val. you can still update the items in the array.
















Kotlin Concepts and Programming

Kotlin is making waves. The question is why?

Kotlin is syntax friendly, conciseness, flexibility and powerful language. The compiler keeps you safe like unsafe, buggy code and kotline's compiler puts a lot of effort into making sure your code is as clean as possible, preventing many of the errors that can occur in other programming languages.

So Kotlin virtually eliminates the kind of error that regularly occurs in other programming languages that means safer, more reliable code and less time spent chasing bugs.

You can use Kotlin nearly everywhere

This is because you can choose which platform to compile your Kotlin code against.

Java Virtual machines(JVMs)
it can be compiled to JVM bytecode so you can use Kotlin practically anywhere. Kotlin is 100% interoperable with java.

Android
Kotlin has first-class support for Android.

Client-side and server-side JavaScript

you can also transpile -----or translate and compile ---- Kotlin code into JavaScript.So you can run it in a browser. You can use it to work with both client-side and server-side technology such as WebGL or Node.Js

Native Apps
You can also directly compile your kotlin code to native machine code. This allows you to write code that will run for example on iOS or Linux.

Now take a look on few examples:

val name = "Abhinav"  // Declare a variable 'name' and give it a value of "Abhinav"

val height = 9

println("Hellow")

val a = 6
val b = 7

val c = a + b+10
val str = c.toString()

val numList = arrayOf(1,2,3,4,5,6,7)

var x = 0

while(x < 3)
{
   println("Item $x is ${numList[x]}")
   x = x + 1
}

Sample Program: 

App.kt:

fun main(args : Array<String>)
{
  println("ABHINAW")
}

So you can ask a question here like

Do I have to add the main function to every Kotlin file I create?
Ans: No, A kotlin application might use dozens of files but you may only have one with the main function - the one that starts the application.

Now let's run the  above code here:

So when you run the code in IDE :

1) The IDE compiles your kotlin code source code into JVM bytecode.
that means compiling App.kt creates a class file called AppKt.class .

2)The IDE starts the JVM and runs AppKt.class
The JVM translates the Appkt.class bytecode into something the underlying platform understands then runs it.

Bullet Points:


  • Use fun to define a function.
  • Every application needs a function named main.
  • Use // to do single-line comment.
  • A string is a string of characters. You denote a String by closing its characters in double-quotes.
  • Code blocks are defined by a pair of curly braces {}.
  • The assignment operator is one equals ==.
  • The equals operator use two equals signs ==.
  • Use var to define a variable whose value may change.
  • Use all tod define a value whose value will stay the same.
  • you can also use if as an expression so that it returns a value.In this case , he else clause is mandatory.








Saturday, February 15, 2020

Machine Learning - Linear Regression


What is a Linear Regression?

Linear Equation:

Y = a+bX+e

Y = Dependent Variable

X= Independent Variable

a=y-intercept

b= slope

e= error term/Residual

Interpretation of b = one unit change of x will change the average/expected value of y by b unit.

Interpretation of a = often y-intercept does not have any practical meaning as x=0 is beyond the scope of the model.

R-square: 0.8 means 80% variation independent variable(e.g sales) can be explained by the independent variables eg. advertising expenditure.

ANOVA: H0: all regression coefficients in population are zero
                 Ha: At least one of the regression coefficient is non zero

T-test : H0: individual regression coefficient in population is zero.
             Ha: individual regression coefficient in population is non zero

Assumptions of linear regression

  • The error term is normally distributed with zero mean and finite variance. Error ~N(0,σ2).
  • For each fixed value of X, the distribution of Y is normal. The means of all these normal distributions of Y, given X, lie on the fitted regression line(plane).
  • Variance of error term is constant.(homoscedasticity). This variance does not depend on the values assumed by X.
  • Error terms are uncorrelated. In other words, the observations are drawn independently.
  • Uncorrelated error with X.
  • Relationship between y and X is linear.
Unusual and Influential data

A single observation that is substantially different from all other observations can make a large difference in the results of your regression analysis
  • Outliers: In the linear regression, an outlier is an observation with a large residual. In other words, it is an observation whose dependent-variable value is unusual given its values on the predictor variables. An outlier may indicate a sample peculiarity or may indicate a data entry error or other problem.
  •  Leverage: An observation with an extreme value on a predictor variable is called a point with high leverage. Leverage is a measure of how far an observation deviates from the mean of that variable.
  • Influence: An observation is said to be influential if removing the observation substantially changes the estimates of coefficients. Influence can be thought of as the product of leverage and outlierness.








Machine Learning - Regression

Regression

Let's understand what is Regression in Machine Learning?

A case for regression

The Advertising data displays sales for a particular product as a function of advertising budgets for TV, radio and newspaper media. In our role as statistical consultants, we are asked to suggest, on the basis of this data, a marketing plan for next year that will result in high product sales.

here are a few important questions that we might seek to address:


  1. Is there a relationship between the advertising budget and sales?
  2. How strong is the relationship between the advertising budget and sales?
  3. which media contribute to sales?
  4. How accurately can we estimate the effects of each medium on sales?
  5. Is the relationship linear?
If there is approximately a straight-line relationship between advertising expenditure in the various media and sales, then linear regression is an appropriate tool. if not then it may still be possible to transform the predictor or the response So that linear regression can be used.






Machine Learning - Hypothesis Testing

Important terminologies -- Hypothesis testing

  • Population = all possible values
  • Sample = a portion of the population
  • Parameter = a characteristic of a population, e.g., the population mean μ
  • Statistic = calculated from data from the sample, e.g., sample mean

Hypothesis Testing

Hypothesis testing test a claim about a population parameter(characteristics) using evidence from sample data.

Steps of hypothesis testing:

A) State Null and alternative hypothesis
B)Calculate test statistics
C)Decide the levels of Significance
D)p-value and decision

Null and Alternative Hypotheses

  • Convert the research question to null and alternative hypotheses
  • The null hypothesis(H0) is a claim of "no difference in the population"
  • the alternative hypothesis (Ha) claims "H0 is false"
  • Collect data and seek evidence against H0 as a way of bolstering Ha(deduction)

Example: "Body Weight"
The problem: in the 1970s, 20-24-year-old men joining the army had an average body weight of 65kg. The standard deviation of body weight was 10kg. We test whether the average body now differs.

The null hypothesis is H0: μ =65(no difference)
The alternative hypothesis can be either Ha: μ > 65(one-sided test) or Ha:μ not equals 65(two-sided test).

Sampling Distributions of Mean




Errors in hypothesis testing




Test Statistic

This is an example of a one-sample test of a mean when sigma is known.use this statistic to test the problem.


P-value
The p-value is the probability of getting test statistics as extreme as the observed value or more extreme than it when H0 is true?

One-sided P-value for z statistic of 0.6

Interpretation 

p-value answers the question: what is the probability of getting the observed test statistic when H0 is true?

Thus, smaller and smaller .P-values provides stronger and stronger evidence against H0

Small p-value => strong evidence H0 is false and Ha is true

Decision Rule

alpha = probability of rejecting H0 when it is true

Set alpha threshold(eg. 0.0  or 0.10, or 0.05)

Reject H0 and retain Ha when p-value less than and equal to alpha.




Saturday, February 8, 2020

Machine Learning - K-fold cross validation Python

K-fold cross-validation:

In machine learning, we couldn’t fit the model on the training data and can’t say that the model will work accurately for the real data. For this, we must assure that our model got the correct patterns from the data, and it is not getting up too much noise. For this purpose, we use the cross-validation technique.

Cross-validation is a technique in which we train our model using the subset of the data-set and then evaluate using the complementary subset of the data-set.

The three steps involved in cross-validation are as follows :

Reserve some portion of the sample data-set.
Using the rest data-set train the model.
Test the model using the reserve portion of the data-set.

Methods of Cross Validation

Validation

In this method, we perform training on 50% of the given data-set and the rest 50% is used for testing purposes. The major drawback of this method is that we perform training on 50% of the dataset, it may possible that the remaining 50% of the data contains some important information which we are leaving while training our model i.e higher bias.

LOOCV (Leave One Out Cross Validation)
In this method, we perform training on the whole data-set but leaves only one data-point of the available data-set and then iterates for each data-point. It has some advantages as well as disadvantages also.
An advantage of using this method is that we make use of all data points and hence it is low bias.
The major drawback of this method is that it leads to higher variation in the testing model as we are testing against one data point. If the data point is an outlier it can lead to the higher variation. Another drawback is it takes a lot of execution time as it iterates over ‘the number of data points’ times.

K-Fold Cross Validation
In this method, we split the data-set into k number of subsets(known as folds) then we perform training on all the subsets but leave one(k-1) subset for the evaluation of the trained model. In this method, we iterate k times with a different subset reserved for the testing purposes each time.








ML and AI - Regularization Python

What is Regularization in Machine Learning?

Regularization - Regularization in machine learning is a process of introducing additional information in order to prevent overfitting.


  • The green and blue functions both incur zero loss on the given data points.
  • Regularization will induce a model to prefer the green function, which may generalize better to unseen data.
         



Use of  regularization in classification:

One particular use of regularization is in the field of classification. Empirical learning of classifiers(learning from a finite data set) is always an undermined problem.
because in general, we are trying to infer a function of any X given only some example

x1,x2,x3,x4,x5,x6............xn.

A regularization term(or regularization) R(f) is added to the loss function:

 
where V is an underlying loss function that describes the cost of predicting f(x) when the label is y, such as the square loss or hinge loss and lamda is a parameter that controls the importance of the regularization term.R(f) is typically chosen to impose a penalty.