https://www.baeldung.com/kotlin-sealed-classes
Sealed Classes in Kotlin

.

.

.

.

https://youtu.be/o1Occux4qR8

.

.

.

.

https://youtu.be/o1Occux4qR8./

.

.

.

.

https://www.charlezz.com/?p=43886

.

.

.

.

https://youtu.be/E-yXefhLjNU

https://www.journaldev.com/18688/kotlin-enum-class

가장 좋은 설명

Enumerations in Kotlin are data types that hold a set of constants. Enums are defined by adding the modifier enum in front of a class as shown below. Yes, in Kotlin, Enums are classes.


enum class Months{
    January,
    February,
    March
}

Here are some important points about enum classes in kotlin.

  • Each enum constant is an object. Enum constants are separated by commas.
  • Each of the enum constants acts as separate instances of the class.
  • Enums are useful in enhancing the readability of your code since it assigns pre-defined names to constants.
  • Unlike classes, an instance of enum classes cannot be created using constructors.
  • Hence, we can assert that enum classes are abstract.

Let’s see how the enum class is initialized in the main function of our class.


fun main(args: Array<String>) {

    println(Months.January) //prints January
    println(Months.values().size) //prints 3
    println(Months.valueOf("March")) //prints March

    for (enum in Months.values()) {
        println(enum.name)
    }

    println(Months.valueOf("Mar")) //throws java.lang.IllegalArgumentException: No enum constant Months.Mar
}

Few inferences from the above code:

Let’s see how to tackle this scenario.


fun enumContains(name: String): Boolean {
    return enumValues<Months>().any { it.name == name }
}

fun main(args: Array<String>) {

    if (enumContains("")) {
        println(Months.valueOf(""))
    } else {
        println("The string value does not match with any of the enum constants.") //this gets printed.
    }

}

enumContains is a function that calls the lambda function any which iterates over the enum constants to check if any of them matches the string and returns a boolean.

Enum Properties

Every enum constant has properties: name, ordinal to retrieve the name and position of the constant.


fun main(args: Array<String>) {
    
    println(Months.January.name) //prints January
    println(Months.March.ordinal) // prints 2
    for (enum in Months.values()) {
        println(enum.name)
    }
}

Enum toString()

We can override the toString() function in the enum class as shown below.


enum class Months {
    January,
    February,
    March;

    override fun toString(): String {
        return super.toString().toUpperCase()
    }
}

fun main(args: Array<String>) {
    println(Months.January) //prints JANUARY
    println(Months.January.name) //prints January
     println(Months.valueOf("March")) //prints MARCH
}

Enums are classes. So besides defining the constants we can define other things as well that can be present in a class. To do so we need to first end the enum part with a semi colon.
Note: Month.January invokes the toString() method of the class whereas Month.January.name directly prints the enum constant’s name.

Enum Initialisation

Enum constants can be initialized using primary constructors as shown below.


enum class Months(var shorthand: String) {
    January("JAN"),
    February("FEB"),
    March("MAR");
}

fun main(args: Array<String>) {

    var x = Months.January
    println(x.shorthand) //prints JAN
    x.shorthand = "Shorthand changed to J."
    println(Months.January.shorthand) //prints Shorthand changed to J.
}

Enums as Anonymous classes

Enum constants can behave as anonymous classes be implementing their own functions along with overriding base functions from the class as shown below.


enum class Months(var shorthand: String) {
    January("JAN"){
        override fun printSomething() {
            println("First month of the year.")
        }
    },
    February("FEB"){
        override fun printSomething() {
            println("Second month of the year.")
        }
    },
    March("MAR"){
        override fun printSomething() {
            println("Third month of the year.")
        }
    };
    var a: String = "Hello, Kotlin Enums"
    abstract fun printSomething()
}

fun main(args: Array<String>) {
    Months.February.printSomething() //prints Second month of the year.
    println(Months.February.a) //prints Hello, Kotlin Enums
}

Each of the enum constants must override

Enum inside an Enum

It’s possible to define another enum class in the current enum class as shown below.


enum class Months {
    January,
    February,
    March;

    enum class Day{
        Monday,
        Tuesday,
        Wednesday
    }
}

fun main(args: Array<String>) {
    println(Months.Day.Tuesday) //prints Tuesday
}

Only an enum class can invoke another one. The inner class Day cannot be invoked from the enum constants.

Enums and when

when is Kotlin equivalent of switch in Java. We’ve covered the workings of it in the Control Flow tutorial.
An example showing how when statements are used with enums is given below.


enum class Months {
    January,
    February,
    March;
}

fun main(args: Array<String>) {

    var m = Months.February

    when (m) {
        Months.January  -> print("Matches with Jan")
        Months.February -> print("Matches with Feb") //prints this.
        Months.March -> print("Matches with Mar")
    }
}

This brings an end to kotlin enum tutorial.

References: Kotlin Docs

.

.

.

.

https://youtu.be/or_HJ6NGLxc
kotlin enum basic 설명

image
image

.

.

.

.

https://youtu.be/jc9AZfZs7kY

enum class

image
image
image

.

image
image

.

image
image

.

.

.

.

https://www.baeldung.com/kotlin-enum
Working with Enums in Kotlin

.

.

.

.

내가 정리한 enum class

  • child class는 parent constructor 를 그대로 구현해야 한다. 
  • parent constructor가 없으면 child에도 constructor는 없다.
  • parent class안에 abstract로 정의된 func은 모든 child 가 구현해야 한다.
  • parent class안에 abstract로 정의되지 않은 함수를 child안에 새로 만들수 있다.
  • child class는 각각 , 로 구분한다. child class정의 마지막은 ;를 사용한다. 
  • parent class는 abstract method, abstract property를 가질수 있다. (sealed class도 같다)


sealed class의 경우 parent constructor가 정의되어있지 않더라도 child class 는 constructor를 가질수 있다. 각 class 정의 사이에 구분자는 없다. (정의부분 뒤에 enum의 경우 , 가 붙는데 sealed class의 경우는 없다는 이야기)

sealed class BasicGarment2(){
   class CLEAN_PRESS(var name:String, var price:BigDecimal): BasicGarment2()
   class CLEAN_ONLY(): BasicGarment2()
}

 

enum class BasicGarment(val na: String, val price:BigDecimal){
   CLEAN_PRESS("a",10.toBigDecimal()){
       override fun calculatePrice(): BigDecimal {
           return 10.toBigDecimal()
       }

       fun foo(){
           println("test func")
       }

       override var testVar: String
           get() = TODO("Not yet implemented")
           set(value) {}
   },
   CLEAN_ONLY("nam", 10.toBigDecimal()){
       override fun calculatePrice(): BigDecimal {
           return 10.toBigDecimal()
       }

       override var testVar: String
           get() = TODO("Not yet implemented")
           set(value) {}
   };
   abstract fun calculatePrice():BigDecimal
   abstract var testVar :String
}

.

.

.

.

https://www.geeksforgeeks.org/enum-classes-in-kotlin/

Swift Typealias: How to use them and Why?

Swift: Understanding Mutating Functions in Two Minutes

https://youtu.be/VNEdufXVMaU6 1 What is Text Classification
https://youtu.be/kxImnFg4ZiQ

image
image
image
image

6 2 Naive Bayes
https://youtu.be/j39c7Gjx2gE

image
image

감마 기호는 function을 의미한다.

6 3 Formalizing the Naive Bayes Classifier

https://youtu.be/VNEdufXVMaU

image
image
image

d 는 document, c는 class를 의미한다.

P(d|c) 는 likelihood probability, P© prior probability 

image

documents는 x features (단어들)의 연속으로 구성되어있다.

image

P(x1, x2, x3 …….  xn | c)의 경우 conditional 에 conditional에 중첩된 conditional probability 계산이 되는데 이런경우 복잡해지게 된다.

image

계산이 복잡해지는데 이를 간소화 시켜서 계산하는 방법을 사용한다. bag of words를 이용하거나 independent probability를 이용(모든 단어는 서로 independent하다고 가정)한다.

image
image

6 4 Naive Bayes Learning
https://youtu.be/3jR8TZG8T88

image

P(cj)는 전체 문서에서 특정 class의 문서가 나올 확률이다.

P(wi | cj)는 특정 class에서 특정 word가 나올 확률이다. 

image

위의 내용을 간단히 정리하면 특정 class의 모든 문서(시그마부분에 해당)를 하나로 만들고 그 안에서 특정단어들이 나오는 횟수를 이용해 P(wi | cj)를 구한다. 

image

training documents에 fantastic이라는 단어가 한번도 사용되지 않았다. 그런데 새로 주어진 문장에서는 이 단어가 사용되었다고 한다면 이전에는 한번도 나온적이 없었으므로 확률이 0이 되버리게 된다. 즉 새로운 단어에 대한 고려가 전혀 없는 것이다. 이 문제의 해결방법은 아래 그림 참조

image

모든 단어의 출현횟수를 1씩 늘려줌으로써 최소횟수가 0이 아닌 1이 되게된다.

image

우측 하단은 add alpha가 적용된 공식이다.

image

training doc에서 한번도 출현하지 않은 단어는 unknown word로 위와 같이 처리한다.

6 5 Naive Bayes Relationship to Language Modeling
https://youtu.be/LRFdF9J__Tc

image
image
image

6 6 Multinomial Naive Bayes A Worked Example
https://youtu.be/OWGVQfuvNMk

image

P©는 전체 문서들중에 class c 문서가 나올 확률이다. 여기서 사용된 P(w | c)는 add one smoothing이 적용된 특정 class에서 특정 단어들이 나올 확률이다. 

위의 예제는 주어진 training data를 이용해 만든 모델로 test doc의 class를 예상하는 과정이다. 오른쪽 하단의 내용은 주어진 문서 d5가 어떤 클래스인지를 비교 추측하는 것이다. 각 c , j class일 확률을 비교 한다. 이때 d5는 공통으로 들어가는 부분이므로 생략했다.  

image

6 7 Precision, Recall, and the F measure
https://youtu.be/81j2nzzBHUw

참조자료)

andrew ng https://youtu.be/wGw6R8AbcuI

https://youtu.be/W5meQnGACGo

image

위그림이 좀더 이해하기 쉽다.

image

accuracy 측정 방법

image
image

6 8 Text Classification Evaluation
https://youtu.be/TdkWIxGoiak

image
image
image
image
image
image

6 9 Practical Issues in Text Classification
https://youtu.be/uIvSHmsLs-U

text classification에 대한 전반적인 내용을 다루고 있다.

training data가 없는 경우 개발자가 직접 손수 rule을 만든다.

knn k nearest neighbors를 말한다.

보통 training data의 양이 많은 경우 classifier간의 성능차는 별로 없어지게 된다. 

자동, 수동 섞어서 처리한다. 

확률의 곱이 많이 이어지는 경우 그 숫자가 매우 작아지는 경우가 생기는데 이를 underflow라고 한다. 이를 방지 하기 위해 log값을 이용한다. log에서는 두 값이 곱이 합으로 계산되기 때문이다. 

upweighting : 단어의 위치나 사용방법에 따라 가중치를 두는 방법이다. 

How to get names of classes inside a jar file?