My Blog for coding and note

https://github.com/hesthers

0%

Machine Learning Project day 1

  • Topic: EV (Electronic Vehicle) charging station
  • 여러 주제들을 생각했으나 자세한 사항들은 수요일(11/23) 회의 때 논의
  • 내가 생각해낸 아이디어들.. (수상작 레퍼런스 참고해서)
    • 지역별 충전소의 개수와 위치
    • 충전소와 상관성이 있는 요인들 파악 — 상관성 파악
    • 전기차 사업 현황 추이 (인프라 구축)
    • 인구, 도로, 미세먼지?????, 주변환경 시설(시민 편의 시설), 교통량
    • 전기차가 필요한 목적 (왜 필요한가..) 다른 교통수단을 이용할 수 있지 않나??? 친환경 버스와 같은…??? — 통근(유동인구)
    • 완속/급속 충전소 — 필요한 목적
    • 머신러닝 기법: KNN(clustering), XGBoost (편집됨)
    • 그린뉴딜 정책, 현대 자동차 멀티 충전 전기차 (초급속 충전 가능)
    • 온실가스 배출량 데이터

Today What I Studied

This post is for TIS page.

  • Watched two online lecture about machine learning
  • Practiced machine learning
  • Finished crawling assignment on Naver news webpage

Text Analysis (텍스트 분석)

  • Sentimental Analysis
    • Analyzing Sentiment: 긍/부정 여부 혹은 글 속에 있는 감정들 (Positive/Negative or Feelings that are in documents)
    • Data for Review (about movies, dramas, … any digital contents)
  • use RNN method

    Time series is important in sentimental analysis. 시간적/순서적인 정보가 담겨있음.
    Data is trained through hidden layter in serial order, then when this data has the output, the next data with the output begin training. This sequence keeps repetition.
    Sequence = X-features
    when preprocessing the words, the unused words(unnecessary words) are first removed, then encoded by onehotencoding method and vectorized about the relation between words.

  • use LSTM method

    pad_sequence: in the Simple RNN method case, the hidden layers are needed a lot, so the relation between words in a document are gradually lower correlated. The modeling performance would be underestimated, so the vacant space (because all of the words in sentences do not have the same length) would be padded with any number(generally 0) to cover this flaws.

  • RNN & LSTM = non-linear model

Regular Expression

  • 특정한 문서 안에서 표현을 찾고자 할 때 정규 표현식을 사용.
    1
    2
    3
    import re
    re.findall(정규표현식으로 찾을 대상 (object that you want to find as the regular expression), document or variable name)
    re.sub(regular expression, the letters that you would replace, document or variable name)
  1. 어떤 문자 하나 찾기: x. (마침표 등의 점이 아닌 정규표현식에서 문자 한 개를 의미)
  2. 특정 문자(x) 1개 미만 (예. abacbabacb 중에서 c가 등장한 횟수가 1회 미만인 경우): x?
  3. 특정 문자(x) 1회 이상 등장한 경우: x+
  4. 특정 문자(x) 0회 이상 등장한 경우: x*
  5. 원하는 것들중 하나를 선택: [원하는 문자들] (단, 나열할 때 구분자는 생략)
  6. 원하지 않는 것들을 제외한 나머지 중에서 하나: [^원하지 않는 문자들]
  7. 하나의 묶음을 표시할 때 혹은 묶음 안에 있는 것만을 나타낼 때: (대상 문자)
  8. 회피 용법:
    1) 찾고자 하는 대상이 특수 기호인 경우:

    • 해당 글 안에서 ‘?, +’등의 문자를 찾고 싶은 경우 – re.findall('\(특수문자)', docs)
      2) space, tab, enter를 찾고 싶은 경우: \s, \t, \n
  9. 어떤 문자열을 찾고 싶은 경우 (길이 제한이 없음)

    • 최대한 길게 찾고 싶을 때: .+
  10. 최대한 짧게 여러 번 찾고 싶을 때: .+?

MACHINE LEARNING

  • KNN (K-Nearest Neighbors)

    좌표 공간을 기준으로 해당 데이터에서 가장 가까운 데이터의 라벨을 확인하고 해당 라벨로 예측하는 기법
    K 값에 따라서 학습 결과가 달라짐.

Clustering

unsupervised learning

분류 모델인 classification과 비슷해보이나 비교하는 것은 무의미함. 비지도학습 자체로 모델링 기법으로 바라봐야함.

  • x값이 비슷한 그룹들끼리 grouping하는 기법.
  • X와 Y의 라벨 혹은 관계를 구분/파악하기 위한 학습방식이 아니라 비슷한 X끼리 라벨을 분류하기 위한 기법
  • 비슷한 군집들끼리 분석해서 학습시키는 기법으로 inertia value를 기준으로 k값 선별(k의 값 = 변곡점)
1. K-Means
  - 각 군집의 중심값 (혹은 초깃값)을 랜덤으로 설정 및 계산하고 모델 학습 시작.
  - 임의의 k개 초깃값 선별해서 학습하는 기법.
  - Expectation: 각각의 군집에서 가장 가까운 군집과 중심을 찾아서 군집화로 분류하는 과정
  - Maximization: 중심값을 업데이트 하는 과정
   summary: k개의 임의의 중심값을 업데이트하는 과정을 반복하면서 최적의 군집 중심값을 찾아가는 기법

2. K-Means ++
  - 임의로 아닌 처음부터 군집간의 거리가 가장 많이 떨어져있는 상태에서 초깃값을 찾는 학습과정을 선택하는 기법
  - 초기에 군집을 하나만 랜덤으로 선택
  - 첫번째 초깃값과 가장 먼 거리의 데이터를 중심으로 이 때의 거리를 확률값으로 판단해서 학습.

Unsupervised transformation model

Dimensional Reduction problem: PCA (Principle Component Analysis)

차원 축소가 필요한 이유: 차원의 저주 문제

  • 데이터 학습에 도움되지 않은 정보들이 너무 많으면 오히려 학습에 방해가 됨.
  • x 피처 데이터들의 분포가 전체적으로 잘 퍼져있어서 보여줄 수 있는 경우 데이터의 특성을 잘 설명해준다고 해석할 수 있음.
  • 주성분들은 제 1주성분을 제외한 나머지 주성분들은 제1주성분과 수직으로 관계가 존재함. 수직의 관계는 서로 상관관계가 없다는 것을 의미함. (수직인 직선을 그래프를 통해 찾을 때 기울기 곱이 -1임을 생각해본다면 도움되지 않을까??)
  • PC: 기존의 피쳐들로 성분을 select하는 것이 아닌 새로운 성분을 만들어 내서 차원을 축소하는 기법.
  • PCA code 중 n_components의 값으로 주성분의 개수를 선택해서 모델링
  • 1st component 가 가장 우선적인 성분으로 모델에서 가장 영향력이 큰 성분이라 할 수 있기 때문에 성분들 중 제거해야하는 경우라면 첫번째 주성분을 살려야함.
  • 전처리할 때 자주 쓰이는 기법으로 비지도학습은 주로 지도학습 모델링을 support할 때 사용함.
  • PCA는 여러 피처들의 조합을 통해 차원을 줄였기 때문에 학습결과가 좋게 나오는 편임.

Extra info about MACHINE LEARNING

  • Grid Search

    파라미터 후보들을 사용자가 지정해주면 알아서 최적의 파라미터 값을 찾아주는 방법
    딕셔너리 형태로 입력해서 학습

Figma with Design Thinking

  • 마스터 & 인스턴스 => programming화 되어있음
  • 레이어: 페이지별 이름 설정 (변수)
  • 프레임과 도형은 다른 것. -> 어떤 것을 선택하냐에 따른 물리적 역할이 달라짐.
  • 도형을 드래그해서 프레임 안에 넣을 수 있음.
  • 도형 안의 도형은 만들 수 없으므로 프레임 안에 프레임으로 종속 (기능적 UI)
  • frame selection으로 한 번에 프레임에 넣을 수 있음
  • 프레임 속에 텍스트가 기준이 되어 입력됨.
  • 항목 추가 +, 빼기 -
  • 피그마는 자신만의 앱스토어를 가지고 있어서 원하는 기능을 다운받아 이용할 수 있다. 동시 협업 또한 가능하며 일반 포토샵과 같은 그래픽 툴에서는 이용하기 힘들었던 실용적이고 유용한 기능들을 이용할 수 있다.
  • 마스터에서 인스턴스를 찍어내면 마스터에서 수정했을 때 동시에 인스턴스에서도 수정이 가능함.
  • 마름모 모양의 메뉴 = 인스턴스
  • 인스턴스 부분 클릭하고 design에서 ...에서 detach instance 클릭하면 인스턴스 해제
  • combine as variant => 그룹화
  • ctrl + D 누르면 복제 여러 개 가능함.
  • json 키 값에 맞추어서 json 파일을 ui 부분에 넣을 수 있음.
  • 프로토타이핑 기능: 화면 전환설정

Why Figma is useful in Design Thinking?

  • 보이지 않는 문제점들을 찾아내는 것이 중요하며 정성적인 관찰이 상당히 중요함. 공감을 통한 아이디어 전개

  • 정성적으로 만들어서 실용적으로 이용할 수 있음. 피그마를 통해 구현 가능함.

Machine Learning pt.6

  1. Decision Tree
    • non-linear model
    • Through the trained model, this model predicts the result values.
    • Using step-by-step questions, the groups are divided by the similar groups hat have the similar size.
    • Information Gain: How many information you can get as you also ask many questions?
    • Impurity metrics: Entropy & Gini coefficient (purity = 100% means impurity = 0, so stop the modeling)
      Following that the cost is lowering, find the questions that lower the entropy, but specify the number of features.
      According to the depth, the complexity of a model is decided.
    • recursive partitioning = repeatedly split the data because overfitting problem can occur
  • summary:
    • Decision Tree is simple when the depth of question is low, vice versa. However, the degree of training for the training data is high but for the test data is not.
    • Decision Tree is explainable that the reason is obvious about the result of prediction (how it classifies the data using which criteria)
    • Decision Tree can be used as the Regressional model. Variance is the error of
      decision tree regressor.
    • the value of entropy is large when the labels are even.
  1. Ensemble
  • Bagging(Bootstrap Aggregating)

    Bootstrap means extracting the copy data from the original data.
    Aggregating means extracting the results from the different models with the majority vote.
    example: The results from three different models are the following:

  • A: X with 0.4 probability, B: O with 0.9 probability, C: X with 0.3 probability
  • Average probability is about 0.5. The result ratio is 2:1 = X:O.
  • Q: Which result of models is correct?

    Like above an example, you can choose soft or hard voting method in Bagging.
    When extracting the copy data, extract it with sampling with replacement (random sampling).

  • Random Forest: combining various decision tree models with reinforcing the generalization by training the models independently and voting the one of the results, but underfitting problem often occurs.
  • Boosting

    Adaboost / GBM / XGBoost / Light GBM

    • the way to train is the same as Bagging, but the process of training is different.
      one model is trained first and then after the results of modeling are identified, imposing the weights on the wrong prediction and start training the next model (repeating these process)
    • As influenced by the previous model training, the models are not independent.
      The models of boosting are different from the performance. The performance of Light GBM is the fastest model in the training.

Machine Learning Basics

Linear Classification Model Metrics

  • Different from linear regression, Logistics regression and SVM needs the metrics to test their performance.
  • the metrics of Linear Regression = $\displaystyle R^2$ score

    Be careful! Do not say $\displaystyle R^2$ score as accuracy score.

  • the metrics of Classification model = when the label is imbalanced

    the case when the accuracy score is high but is not able to ensure the performance
    Example: The medical test kit of the accuracy is 99%. Do you trust this score? IF the data is imbalanced, it is difficult to predict accurately the data. (Lower modeling performance)

  • Confusion Matrix

(Real) Positive (Real) Negative
(Prediction) Positive TP FP
(Prediction) Negative FN TN

Precision(정밀도, evaluation as prediction = positive) = $\displaystyle \frac{TP}{(TP + FP)}$
Recall(재현율, evaluation as real = positive) = $\displaystyle \frac{TP}{(TP + FN)}$

Regulation of Classification model

  • the case when regulation is necessary: when the number of weight is a lot in order to restrain overfitting problem (the model is complicated = reinforcement of regulation = lowering C)
  • cost function formula of classification model =
    $\displaystyle error + \frac{1}{C} \times \vert w \vert = \\\\
    C(error + \frac{1}{C} \times \vert w \vert) = \\\\
    C \times error + \vert w \vert$

    C = the rate of error tolerance

  • SVM & SVC

    SVC (Support Vector Classifier)

    • linear & non-linear as parameter
    • set parameter through kernel to impose the non-linearity
    • margin = $\displaystyle \frac{1}{C}$
    • To maximize the margin, allow the error by lessening the value of C to lower overfitting problem and the error
    • Hard SVM (perform the modeling without allowing the error at all) vs Soft SVM (select the optimized margin with allowing the error and selecting the data that is in the margin)
prediction value error range of error
Logistic Regression $\displaystyle \frac{1}{(1 + e^{-wx})}$ (the value of probability) log loss $\displaystyle 0 < n < \infty$
SVM $\displaystyle \begin{cases} 1 \\ 0 \end{cases}$ hinge loss $\displaystyle 0 \leq n < \infty$
  • Kernel: change non-linear coordinates into linear coordinates
    $\displaystyle \implies$ MLP classifier (using rbf formula and various ways, find the linear relation) $\displaystyle \rightarrow$ Deep learning and NN(Neural Network)
  • Perceptron: 비선형성이 굉장히 복잡한 경우 층을 쌓아가면서 비선형성 문제를 풀릴수 있도록 해줌.

Machine Learning basics pt.4

comparison of Lasso and Ridge

Lasso Ridge
모델링을 하다보면 규제항0이 되는 값들이 존재함 아무리 모델링을 해도 규제항이 0에 가까워지지 않음
$\displaystyle 기울기(G) = 오차’ + C$ $\displaystyle 기울기(G) = ( 오차’ + \vert w \vert )$
$\displaystyle W_{t} - a(오차’ + C)$ $\displaystyle W_{t} - a( 오차’ + \vert w \vert )$
피처가 많은 경우 (= weight가 많은 경우)에 강하게 규제를 걸어야할 때 피처선택을 위해 사용

Linear Classfication Model

  • classification: 확률/비확률적 모형 & 선형/비선형적 모형
  • 확률적으로 분류한다 = 분류 경계선을 기준으로 데이터 확률값으로 예측한다.
  1. Logistic (= 확률적 예측한다) Regression (= 선형적 모형)
  • 예측값 = 확률값
  • 0과 1로 구성된 데이터 값들을 가지고 집단을 구분짓는 경계선(=> wx = 0)을 찾아 특정 카테고리 값을 예측하는 기법.
  • hypothesis: $\displaystyle \begin{equation} \frac{1}{(1+e^{-wx})}\end{equation}$
  • cost: 절댓값의 오차는 로지스틱 회귀분석에서 의미가 없다. (아무리 최적화를 위해 cost가 낮아지는 방향으로 가중치를 업데이트해도 cost값이 낮기 때문에 학습이 잘 되지 않기 때문.) 그래서 로그함수를 cost 함수로 이용함.

    Local Minimum problem
    image

    • local minimum이 많은 데이터의 경우 학습이 잘 안되어 underfit이 발생할 확률이 높다. 그래서 복잡한 모델인 경우 underfit에 취약한 경우이므로vanishing gradient(기울기 소실) 문제를 만날 수 있다. (cost값을 미분해서 weight값을 업데이트 해나가기 때문임.)
    • Adam optimizer와 같은 모델들을 이를 해결하기 위한 방법으로 발전했다.
  • 다중 분류의 경우는 소프트맥스 함수를 이용해 해결하고 경계선을 기준으로 확률적으로 예측한 값들을 각각 계산한 뒤 최종적으로 큰 확률값을 갖는 카테고리의 값으로 예측함.
  1. SVM (Support Vector Machine)
  • Linear SVM의 경우, 비확률적 선형 모형
  • 로지스틱의 선형 경계선 (wx = 0)은 그대로 이용하면서 hypothesis의 함수를 다른 즉, 비확률적 선형 모형으로 구해야함.
  • hypothesis: $\begin{cases}
    1 & \quad (x \geq 0)\\\\
    0 & \quad (x < 0)
    \end{cases}$
  • 데이터가 경계선과 인접할수록 overfitting의 우려가 있기 때문에 데이터와의 거리를 최대한 확보하면서 경계선을 그리는 것이 좋다.
    • 마진 최대화하며 학습
    • cost = C (오차허용률) x 오차 + 마진의 역수항 (1 / 마진 = 규제항 x (1/2))
    • 라쏘 규제항을 이용하는 경우: $\displaystyle \begin{equation} 오차 + \cfrac{1}{\cfrac{2}{\sum |w|}} \end{equation} \\\\ = 오차 + \frac{1}{2} \times \sum |w|$
    • 오차허용률: 허용률 값이 크면 오차 허용을 안하기 때문에 오차값은 작아지고 마진의 역수값이 커지게 되는데 마진은 작은 값을 갖게 되기 때문에 overfitting이 발생할 수 있다. 그래서 오차가 커지더라도 오차허용률 값을 줄여서 오차허용을 어느 정도 해주는 것이 좋음.

Machine learning pt.3

The reason why the regulation in linear regression is necessary

  • when the weights are too many in linear regression, the sizes of the weights are also bigger.
  • so, the model would be complicated, and then the possibility of overfitting would occur.
  • To restrain this modeling complexity, the regulation is needed.

The regulation

Please refer to a table on the previous post about comparison of ridge, lasso, elastic net.

  • However, too much regulation can lead to the underfitting of the data.
  • Lasso (L1 norm) regulation: if a feature would be not 0 value even though the user imposes the lasso to give a penalty, the feature must be a significant feature. (a role of feature selection to eliminate many of features)
  • formula for Elastic Net‘s cost function:
    $\displaystyle weight(error) + \lambda 1 \times \sum |w| + \lambda 2 \times \sum w^2 \\\\
    = weight(error) + \lambda(l_{l ratio} \sum |w| + (1 - l_{l ratio}) \sum w^2)$

Multi-linear regression

  • A kind of linear regression that has some features, not only one feature.
  • Through the value of weight, it is possible to identify with the influence of each of X features.

types of Linear Classification model

  • Logistic regression
  • SVM (Support Vector Machine)

SPOILER of the next post!!

It would be continued regarding about Linear Classification models. It would also be about python codes for machine learning with some explanation!

Regression model and regulation

This post is about linear regression and regulation part.

  • 전체적인 경향을 판단할 수 있는 지표 혹은 수치는 weight의 크기라 할 수 있다. (the index to identify overall tendency is the size of weight because the overfitting occurs if the data of training test is lessened.)
  • using the value of weight, repeat the training of the machine.
  • the regulation to restrain the modeling complexity

Summary of this post

Linear Ridge Lasso Elastic Net
hypo <—- wx + b —- —->
cost 오차항 오차항 + L2 Norm 오차항 + L1 Norm 오차항 + L1 Norm + L2 Norm

L1 norm and L2 norm regulation — for model handling

L1 Norm = $\displaystyle \sum |w|$
L2 Norm = $\displaystyle \sum w^2$

Linear Regression

  • relatively simple model
  • the hypothesis of linear regression (for the correlation between X and Y) => wx + b
  • 미지수가 많은 경우, 해가 무수히 많다.라는 말은 새로운 데이터가 입력되었을 때 무엇인지 정확하게 예측하기 어렵다와 같은 말.

    학습데이터는 잘 예측하지만 새로운 데이터가 추가되면 예측도가 떨어지는 것이므로 overfitting이 발생하기 쉽다.
    when the number of weight in linear regression, the regulation is necessary.
    the more the number of weight is added, the more complex the model.

Machine Learning basics

What is Machine Learning?

  • a part of AI field (Artificial Intelligence)
  • Training-based technology: as using data and training data, the machine itself can make own algorithm by finding the rules or patterns.
  • without being explicitly programmed

purpose of machine learning

  • finding the good (or optimized hypothesis) that the cost (or error) is low
  • but, before entering the data, the user has to first design the specific hypothesis when the user does not know about the formula.
  • to avoid the overfitting, regulation for the machine learning (by lessening the size of the weight) is needed.
    argmin =
    $
    \begin{matrix}
    min & cost \\
    weight(= \theta) &
    \end{matrix}
    $

How to train the machine?

  • calculate the value of cost (with the prediction using the first hypothesis set by the user) and then, differentiate the value of cost to find the slope.
  • the initial weight is for lowering the value of cost
  • W(t+1) <= Wt - a * Gradient (Repeating this process)

The dataset for machine learning

  • a part of dataset is for training, the rest of the dataset is for validation.
  • when the result of the training data is good but the result of validation is not, the training is useless.

TIS

  • Watched online lecture about machine learning

    how to treat the missing value
    variable distribution problem
    class imbalance
    curse of dimensionality

  • Will practice the machine learning for big data certificate

전처리 결과

movie_train 데이터의 전처리 결과를 분석했다. (I summarized the result of preprocessing movie_train data here.)

  1. 전처리 이전 num_actor라는 변수는 상관도가 낮은 변수이기 때문에 전처리 이전에 삭제 후 전처리를 진행한다. (I will continue preprocessing after removing num_actor column because this column is less correlated.)

  2. 범주형 데이터를 가진 컬럼들은 인코딩을 해주고 수치형 데이터로 변환되고 난 후 상관관계를 확인했을 때 날짜관련 데이터 부분들은 삭제해준다. (After encoding the columns that has nominal data as label and with onehot encoding and converted into numeric data, the columns related to date are removed.)

  3. 'scaled_director', 'scaled_genre', 'scaled_distributor' columns are also removed because of the low correlation.

  4. 최종적으로 이용해도 될만한 컬럼들은 box_off_num, dir_prve_bfnum, dir_prev_num, num_staff, screening_rat (onehot encoding columns), time이다. (물론 회귀분석에서 다중공선성 여부로 전체 컬럼들을 가지고 다시 확인할 생각이다.)
    (The columns that are able to utilize are ultimately box_off_num, dir_prve_bfnum, dir_prev_num, num_staff, screening_rat (onehot encoding columns), time. (Of course, I also recheck the total columns with multicollinearity later in Linear regression modeling.)

I recommend this website to practice coding with various language.
만약 코딩 연습하고 싶다면 아래의 웹사이트에서 해보는 것을 추천한다. 물론 일반 주피터노트북, 아니콘다 등 실행환경과는 약간 다르기 때문에 처음 사용하면 불편함을 느낄 수 있으나 익숙해지면 괜찮은 것 같다.

Groom IDE

This website is for korean, but you can change the different language, English and Japanese.