상세 컨텐츠

본문 제목

[머신러닝 기초] Your First ML Model

로봇-AI

by happynaraepapa 2025. 1. 10. 14:28

본문

sources :
https://www.kaggle.com/code/dansbecker/your-first-machine-learning-model

Your First Machine Learning Model

Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources

www.kaggle.com

Selecting Data for Modeling

Your dataset had too many variables to wrap your head around, or even to print out nicely. How can you pare down this overwhelming amount of data to something you can understand?
데이터셋이 너무 많은 변수를 가지고 있어서 정리가 힘들다고 한다면 변수를 줄일 수 있는 방법은 무엇일까?

We'll start by picking a few variables using our intuition. Later courses will show you statistical techniques to automatically prioritize variables.
일단은 직관적으로 몇가지 변수를 골라내는 것 부터 시작하고 나중에는 통계학적으로 변수의 우선 순위를 찾아낼 것.

To choose variables/columns, we'll need to see a list of all columns in the dataset. That is done with the columns property of the DataFrame (the bottom line of code below).
변수(컬럼;열)를 선택하기 위해 우리는 우선 데이터셋으로 부터 이 컬럼의 리스트를 얻어야 한다.
이것은 Pandas 데이터셋 타입의 column이 가지고 있는 Property 로 해결된다.

...(중략)...
# The Melbourne data has some missing values (some houses for which some variables weren't recorded.)
멜본 데이터는 결측치가 있다. (일부 변수에 기록값이 없다.)
# We'll learn to handle missing values in a later tutorial.  
(결측치 다루는 법은 다음 강의에 배운다.)
# Your Iowa data doesn't have missing values in the columns you use.
너의 IoWA 데이터에는 니가 다루는 컬럼에 결측치 없다.
# So we will take the simplest option for now, and drop houses from our data.
일단. 여기서는 가장 손쉽게 결측치를 데이터에서 배제하는 (drop out) 방법 사용하자.
# Don't worry about this much for now, though the code is:현재로서는 이정도 drop outㅣ 발생해도 문제가 없다


# dropna drops missing values (think of na as "not available")
#dropna는 na를 drop한다는 정도로 이해할 수 있는데 여기서 na는 Not Available 의미.

..중략..

그리고 pandas에서는 다양한 방법으로 데이터셋의 하부 데이터셋(subset of data)을 선택할 수 있게 해준다.
다양한 방법이 있겠지만 우선 여기서는 두가지 방식에 집중한다.
1. Dot notation,
2. Selecting with a column list


Selecting The Prediction Target

You can pull out a variable with dot-notation. This single column is stored in a Series, which is broadly like a DataFrame with only a single column of data.
한 개의 컬럼은 Series(시리즈 데이터형)형태에 저장되고, 이는 넓은 의미로 보자면 데이터 컬럼이 한 개로 이루어진 DataFrame 범주에 속한다.

We'll use the dot notation to select the column we want to predict, which is called the prediction target. By convention, the prediction target is called y. So the code we need to save the house prices in the Melbourne data is
dot notation을 이용해서 예측하고자 하는 변수 컬럼을 선택할 건데, 이 변수를 prediction
target(예측 목표)라고 부르고 y로 표기할 수 있겠다. 그래서 멜번 데이터에서 우리가 예측하려는 집값을 다음과 같이 정의할 수 있다.
>
y = melbourne_data.Price
#자 여기서 복습 및 추가적인 정보다.
DataFrame은 엑셀 테이블과 비슷하다고 했다.
수학의 matrix 행렬에서는 쓰여진 열의 이름이 없다고 한다면 dataframe에서는 반드시 column name이 필요하다. 이 컬럼명이 바로 변수명이고, 동시에 나중에 우리가 예측하려는 예측값도 이 변수 중 하나가 될 것이고, 그 예측값에 영향을 주는 다른 변수들 우리는 나중에 그것을 Features(특성값)로 부를텐데, 그 값들도 이 컬럼명으로 부를 수 있는 거다.
즉, 컬럼헤더(Column header)인 컬럼명을 지칭하면 그 아래 속한 모든 행이 한번에 선택된다. 그리고 그림을 머릿속에 그려보면, 이 컬럼헤더를 시작으로 자료가 인덱싱(indexing)에 따라서 방향성을 갖고 아래로  확장되므로 일종의 벡터처럼 보인다. 그래서 컬럼을 컬럼벡터(Column Vector)로 부르기도 한다.
column name = column header, which includes features, prediction target


Choosing "Features"

The columns that are inputted into our model (and later used to make predictions) are called "features." In our case, those would be the columns used to determine the home price. Sometimes, you will use all columns except the target as features. Other times you'll be better off with fewer features.
모델에 입력되는 컬럼값들을 Feature (피쳐;특성값)라고 한다.
여기서는 부동산의 가격을 결정하는 요소들이 피쳐가 될 것이다.
우리는 때로 타겟값을 제외한 모든 컬럼을 피쳐값으로 사용하는 경우도 있다.
그런 경우를 제외하자면 적은 수의 피쳐를 넣는 것이 유리해 보인다.

For now, we'll build a model with only a few features. Later on you'll see how to iterate and compare models built with different features.
여기서는 일단 몇 개의 피쳐만 가지고 모델을 만들 계획이다. 나중에 반복적인 모델 생성과 비교를 통해 최적의 피쳐를 선택할 수 있을 것이다.

We select multiple features by providing a list of column names inside brackets. Each item in that list should be a string (with quotes).
Here is an example:
우리는 컬럼명을  문자열로 처리한 리스트를 피쳐 리스트로 사용한다. 예시를 보면
>
melbourne_features = ['Rooms', 'Bathroom', 'Landsize', 'Lattitude', 'Longtitude']

By convention, this data is called X.
편의를 위해 모델에 넣을 전체 데이터셋을 X라고 하자.
>
X = melbourne_data[melbourne_features]
#이렇게 하면 선택된 피쳐, 즉 컬럼명 리스트에 해당하는 데이터만 잘려서 X 로 모인다.

Let's quickly review the data we'll be using to predict house prices using the describe method and the head method, which shows the top few rows.
주택 가격을 예측하기 위해 사용할 데이터 X를 간략히 살펴보자.
>
X.describe()
...중략...
Visually checking your data with these commands is an important part of a data scientist's job. You'll frequently find surprises in the dataset that deserve further inspection.
사용될 데이터를 눈으로 살펴보고 데이터의 이상여부를 체크하자. 가끔씩 예상외의 것을 발견할때도 많다.


Building Your Model


You will use the scikit-learn library to create your models. When coding, this library is written as sklearn, as you will see in the sample code. Scikit-learn is easily the most popular library for modeling the types of data typically stored in DataFrames.
머신러닝 모델을 작성하기 위해서는 scikit-learn(사이킷 런)이라는 라이브러리를 사용할 것이다. 머신러닝을 위한 가장 대표적인 파이썬 라이브러리로 보면 딘다.
The steps to building and using a model are:
모델을 만드는 과정은 다음과 같다.

Define: What type of model will it be? A decision tree? Some other type of model? Some other parameters of the model type are specified too.
Fit: Capture patterns from provided data. This is the heart of modeling.
Predict: Just what it sounds like
Evaluate: Determine how accurate the model's predictions are.

DefineI(정의) : 어떤 종류의 모델을 사용할 것인가
Fit (피팅) : 주어진 데이터로 부터 패턴을 찾는다. #좀 더 정확히 이야기하자면, 분류와 회귀등에서 주어진 파라미터를 적합하게 조정한다 (피팅한다).
Predict: 피팅된 모델에 데이터를 넣어서 결과를 예측한다.
Evaluate : 위의 예측값이 얼마나 정확한지 평가한다.

Here is an example of defining a decision tree model with scikit-learn and fitting it with the features and target variable.
다음은 사이킷런의 의사결정나무 DT모델 예시다.
>> #이하 파이썬 코드를 설명하겠다.
from sklearn.tree import DecisionTreeRegressor
# ' import 모듈' 로 쓰기도 하지만, 'from 상위모듈 import 하위모듈'로 작성되는 경우임. 여기서 모듈은 라이브러리, 메서드,  변수, 클래스.

# Define model. Specify a number for random_state to ensure same results each run
#모델 정의 : 모델을 정의함. 단 여기서 random_state는 난수(random number) 생성에 대한 파라미터로 그 숫자를 정해주면 각 실행마다 동일한 난수가 나오게 됨. DecisionTreeRegressor는 갑자기 나온 메서드가 아니라 위의 from import 문에서 미리 import 되어 있다. 그대로 읽는다면 의사결정나무회귀함수 정도가 되겠다. 이름의 의미는 나중에 따져보자.

melbourne_model = DecisionTreeRegressor(random_state=1)

# Fit model
melbourne_model.fit(X, y)
#앞서 피쳐가 X라고 했던점 기억하시고, y는 prediction value 였다. 만들어진 모델에 피팅하는 메서드인 fit을 호출하기 위해  .fit을 뒤에 붙였고 해당 메서드에서 요구하는 최소 파라미터로 피쳐값과 예측값(컬럼벡터)을 준것.

...

Many machine learning models allow some randomness in model training. Specifying a number for random_state ensures you get the same results in each run. This is considered a good practice. You use any number, and model quality won't depend meaningfully on exactly what value you choose.
#앞서 다 한 설명이니 생략,
# random_state는 항상 적는 것이 좋은 습관.


We now have a fitted model that we can use to make predictions.
이제 우리는 피팅된 모델을 갖게 되었으며 이걸 이용하여 예측을 할 차례다.

In practice, you'll want to make predictions for new houses coming on the market rather than the houses we already have prices for. But we'll make predictions for the first few rows of the training data to see how the predict function works.
실제 상황이라면 아마 새로운 집의 피쳐 정보를 얻어서 모델에 집어 넣어봐야겠지만, 당장에 그럴 정보가 없을 수 있다. 더군다나 이 모델은 아직 검증되지 않은 모델이다. 대신에 우리는 트레이닝 데이터셋의 처음 몇개 정도를 이 모델에 넣고 어떻게 예측되는지 검증해보는 방법을 사용할 것이다.
#이것은 좋은 방법이 아니지만 가능하다.
>>
print("Making predictions for the following 5 houses:")
>>
print(X.head())
#X는 데이터셋인데 head()는 최초 몇개의 행 데이터만 보여주는 메서드다.
>>
print(melbourne_model.predict(X.head()))
#여기서 작성한 모델 뒤에 .predict를 하면 예측 값을 구하는 메서드이고 피팅된 파라미터를 기준으로 해서 거기에 X.head() 로 호출되는 5개의 자료를 넣어서 그 결과값을 주게 된다. 넣는 자료도 data.frame 형식인점 주의.

...이하중략...

실행 결과 튀어나온값은 모델이 예측한 가격인데, 실제 Price 정보와 비교하면 모델을 검증하게 될 것이다.
(자 우리가 넣은 predict 데이터가 X 데이터셋의 일부분이라는 점 잊지 말자. 다만 이런 방법은 X 데이터로 피팅한 모델에 X 데이터를 다시 넣는 다는 점에서 분명히 편향적인 결과가 나올 리스크가 있다. 향후 다루겠지만 이 때문에 처음부터 데이터셋에서 학습용 데이터셋과 테스트용 데이터셋을 별도로 분리하여 사용하는 경우가 대부분이다.
(Continue..)

관련글 더보기