04wk-18: Predictor의 깊은 이해, 기호정리

Author

최규빈

Published

September 26, 2023

1. 강의영상

2. Imports

import numpy as np
import pandas as pd
import sklearn.linear_model
import itertools

3. Data 에 대한 정리

- 주어진 자료가 아래와 같다고 하자.

df = pd.DataFrame({'X':np.arange(20,30),'y':-np.arange(10)+1+np.random.randn(10)*0.1})
df
X y
0 20 1.015134
1 21 0.000955
2 22 -1.015068
3 23 -2.086323
4 24 -3.040758
5 25 -3.947854
6 26 -4.957609
7 27 -5.980239
8 28 -6.849769
9 29 -8.136956

- 훈련에는 자료 0~7까지 사용하고 테스트에는 자료 8,9를 사용하기로 하자.

df_train = df[:8]
df_test = df[8:]
df_train
X y
0 20 1.015134
1 21 0.000955
2 22 -1.015068
3 23 -2.086323
4 24 -3.040758
5 25 -3.947854
6 26 -4.957609
7 27 -5.980239
df_test
X y
8 28 -6.849769
9 29 -8.136956

- 아래와 같은 자료를 정리하자.

df_train_X = df_train[['X']]
df_train_y = df_train[['y']]
df_test_X = df_test[['X']]
df_test_y = df_test[['y']]

4. Predictor 에 대하여

A. 학습 이후에 예측/평가 가능

- Predictor의 list생성

predictors = [sklearn.linear_model.LinearRegression() for i in range(2)]
predictors
[LinearRegression(), LinearRegression()]
  • 두개의 predictor를 만들어서 리스트로 정리함

- 첫번째 predictor에 접근

predictors[0]
LinearRegression()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

- 두번째 predictor에 접근

predictors[1]
LinearRegression()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

- 첫번째 predictor를 학습

predictors[0].fit(df_train_X,df_train_y)
LinearRegression()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

- 학습이후에는 .coef_, .intercept_ 값이 생성됨

predictors[0].coef_, predictors[0].intercept_
(array([[-0.99420514]]), array([20.86235044]))
predictors[1].coef_, predictors[1].intercept_
AttributeError: 'LinearRegression' object has no attribute 'coef_'

- .coef_.intercept_값이 생겨야 .predict(X)를 통하여 예측을 할 수 있음

predictors[0].predict(df_train_X)
array([[ 0.97824769],
       [-0.01595745],
       [-1.01016259],
       [-2.00436772],
       [-2.99857286],
       [-3.992778  ],
       [-4.98698314],
       [-5.98118827]])
predictors[1].predict(df_train_X)
NotFittedError: This LinearRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

- 예측을 해야 평가를 할 수 있음

predictors[0].score(df_train_X,df_train_y)
0.9996857763812423
predictors[1].score(df_train_X,df_train_y)
NotFittedError: This LinearRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

B. .fit(X,y)에서 X,y의 형식

predictr = predictors[0]
Xs = {'DataFrame(2d)': df_train_X, 
      'Seires(1d)': df_train_X.X,
      'ndarray(2d)': np.array(df_train_X),
      'ndarray(1d)': np.array(df_train_X).reshape(-1),
      'list(2d)': np.array(df_train_X).tolist(),
      'list(1d)': np.array(df_train_X).reshape(-1).tolist()}
ys = {'DataFrame(2d)': df_train_y, 
      'Seires(1d)': df_train_y.y,
      'ndarray(2d)': np.array(df_train_y),
      'ndarray(1d)': np.array(df_train_y).reshape(-1),
      'list(2d)': np.array(df_train_y).tolist(),
      'list(1d)': np.array(df_train_y).reshape(-1).tolist()}
def test(X,y):
    try: 
        predictr.fit(X,y)
        return 'no error'
    except:
        return 'error'
{('X='+i,'y='+j): test(Xs[i],ys[j]) for i,j in itertools.product(Xs.keys(),ys.keys())}
{('X=DataFrame(2d)', 'y=DataFrame(2d)'): 'no error',
 ('X=DataFrame(2d)', 'y=Seires(1d)'): 'no error',
 ('X=DataFrame(2d)', 'y=ndarray(2d)'): 'no error',
 ('X=DataFrame(2d)', 'y=ndarray(1d)'): 'no error',
 ('X=DataFrame(2d)', 'y=list(2d)'): 'no error',
 ('X=DataFrame(2d)', 'y=list(1d)'): 'no error',
 ('X=Seires(1d)', 'y=DataFrame(2d)'): 'error',
 ('X=Seires(1d)', 'y=Seires(1d)'): 'error',
 ('X=Seires(1d)', 'y=ndarray(2d)'): 'error',
 ('X=Seires(1d)', 'y=ndarray(1d)'): 'error',
 ('X=Seires(1d)', 'y=list(2d)'): 'error',
 ('X=Seires(1d)', 'y=list(1d)'): 'error',
 ('X=ndarray(2d)', 'y=DataFrame(2d)'): 'no error',
 ('X=ndarray(2d)', 'y=Seires(1d)'): 'no error',
 ('X=ndarray(2d)', 'y=ndarray(2d)'): 'no error',
 ('X=ndarray(2d)', 'y=ndarray(1d)'): 'no error',
 ('X=ndarray(2d)', 'y=list(2d)'): 'no error',
 ('X=ndarray(2d)', 'y=list(1d)'): 'no error',
 ('X=ndarray(1d)', 'y=DataFrame(2d)'): 'error',
 ('X=ndarray(1d)', 'y=Seires(1d)'): 'error',
 ('X=ndarray(1d)', 'y=ndarray(2d)'): 'error',
 ('X=ndarray(1d)', 'y=ndarray(1d)'): 'error',
 ('X=ndarray(1d)', 'y=list(2d)'): 'error',
 ('X=ndarray(1d)', 'y=list(1d)'): 'error',
 ('X=list(2d)', 'y=DataFrame(2d)'): 'no error',
 ('X=list(2d)', 'y=Seires(1d)'): 'no error',
 ('X=list(2d)', 'y=ndarray(2d)'): 'no error',
 ('X=list(2d)', 'y=ndarray(1d)'): 'no error',
 ('X=list(2d)', 'y=list(2d)'): 'no error',
 ('X=list(2d)', 'y=list(1d)'): 'no error',
 ('X=list(1d)', 'y=DataFrame(2d)'): 'error',
 ('X=list(1d)', 'y=Seires(1d)'): 'error',
 ('X=list(1d)', 'y=ndarray(2d)'): 'error',
 ('X=list(1d)', 'y=ndarray(1d)'): 'error',
 ('X=list(1d)', 'y=list(2d)'): 'error',
 ('X=list(1d)', 'y=list(1d)'): 'error'}

- 결론: X는 2d만 가능, y는 2d,1d 모두 가능

5. Notations에 대한 우리끼리의 약속

- df_train_X는 흔하게 쓰는 표현임. 이는 아래의 점에서 우수함

  • 형식이 df임이 명시되어 있음.
  • train에 사용된다는 것이 명시되어있음.
  • 설명변수라는 것이 명시되어 있음.

- 그렇지만 이러한 식으로 한다면 아래와 같은 이름들을 사용해야함

  • df_train_X
  • nparray2d_train_X
  • list2d_train_X

이것은 너무 복잡하므로 앞으로 이러한 경우를 모두 합쳐서 X 라고 표현할 것임

- 마찬가지의 논리로 아래와 같은 기호를 약속하자.

  • X: df_train_X, ndarray2d_train_X,list2d_train_X
  • y: df_train_y, series_train_y, … , list_2d_train_y
  • XX: df_test_X, ndarray2d_test_X,list2d_test_X
  • yy: df_test_y, series_test_y, … , list_2d_test_y

- 또한 아래와 같은 기호를 약속하자.

  • yhat: predictr.predict(X)
  • yyhat: predictr.predict(XX)

- 참고: 일반적으로 predictor가 기대하는 형태는 아래와 같음

X = np.array(df_train_X)
y = np.array(df_train_y).reshape(-1)
X,y
(array([[20],
        [21],
        [22],
        [23],
        [24],
        [25],
        [26],
        [27]]),
 array([ 1.01513436e+00,  9.55420403e-04, -1.01506823e+00, -2.08632342e+00,
        -3.04075803e+00, -3.94785353e+00, -4.95760949e+00, -5.98023942e+00]))
predictr.fit(X,y)
LinearRegression()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
predictr.predict(X) # 이게 원래 기대하는 형태임
array([ 0.97824769, -0.01595745, -1.01016259, -2.00436772, -2.99857286,
       -3.992778  , -4.98698314, -5.98118827])