문제 1

  1. 거짓 / -> 결정계수 R^2은 예측이 타깃의 평균정도로 예측할 때 0에 가까운 값이 된다. 또한, 결정계수(R^2)은 대표적인 회귀 문제의 성능 측정 도구로써, 1에 가까울수록 성능이 좋은 모델이다.

  2. 거짓 / -> multiple-regression은 독립변수가 두개이상 으로써, 이러한 여러 특성들을 조합하는 것을 특성공학이라고 하고, polynomial-regression은 독립변수의 차수를 높이는 형태로, polynomial-regression은 multiple-regression의 일종이라고 할 수 있다.

  3. 거짓 / -> 왼쪽에서부터 순서대로 그래프 1, 2, 3이라고 할 때, 그래프 1 - Underfitting, 그래프 2 - Appropriate fitting, 그래프 3 - Overfitting 이라고 할 수 있다.

  4. 거짓 / -> 규제는 오버피팅을 방지할 수 있다.

  5. 참 /사이킷런의 변환기에서는 훈련(fit)다음 변환(transform)을 해야 한다.

  6. 선형회귀로 풀 수 있는 문제는 O, 풀 수 없는 문제는 X 표시해주세요.

    1. 침실 수, 위치 등의 특징을 바탕으로 주택 가격 예측 -> O

    2. 기업의 광고비 지출과 매출액과의 관계 파악 -> O

    3. 직원의 직무만족에 기여하는 요인의 파악 -> X

    4. 구매 내역을 기준으로 고객이 동요할 가능성 예측 -> O

    5. 픽셀 값을 기준으로 이미지를 다른 범주로 분류 -> X

문제 2

  1. print(list1)과 print(array1) 한 값은 일치한다. -> o
  2. array1 의 크기를 (5, 1) 이라고 표현한다. -> x (5, )
  3. 사이킷 런의 train set로 적합한 형태는 array2이다. -> o
  4. array3 = array1.reshape(1,5) 를 한다면 array1의 크기도 변경된다. -> x (array3에만 적용)

문제 3

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
import matplotlib.pyplot as plt
from sklearn.metrics import mean_absolute_error

# 농어 데이터
perch_length = np.array([8.4, 13.7, 15.0, 16.2, 17.4, 18.0, 18.7, 19.0, 19.6, 20.0, 21.0,
       21.0, 21.0, 21.3, 22.0, 22.0, 22.0, 22.0, 22.0, 22.5, 22.5, 22.7,
       23.0, 23.5, 24.0, 24.0, 24.6, 25.0, 25.6, 26.5, 27.3, 27.5, 27.5,
       27.5, 28.0, 28.7, 30.0, 32.8, 34.5, 35.0, 36.5, 36.0, 37.0, 37.0,
       39.0, 39.0, 39.0, 40.0, 40.0, 40.0, 40.0, 42.0, 43.0, 43.0, 43.5,
       44.0])
perch_weight = np.array([5.9, 32.0, 40.0, 51.5, 70.0, 100.0, 78.0, 80.0, 85.0, 85.0, 110.0,
       115.0, 125.0, 130.0, 120.0, 120.0, 130.0, 135.0, 110.0, 130.0,
       150.0, 145.0, 150.0, 170.0, 225.0, 145.0, 188.0, 180.0, 197.0,
       218.0, 300.0, 260.0, 265.0, 250.0, 250.0, 300.0, 320.0, 514.0,
       556.0, 840.0, 685.0, 700.0, 700.0, 690.0, 900.0, 650.0, 820.0,
       850.0, 900.0, 1015.0, 820.0, 1100.0, 1000.0, 1100.0, 1000.0,
       1000.0])

# 주어진 데이터를 train과 test로 분리한다.
train_input,test_input,train_target,test_target=train_test_split(perch_length,perch_weight,random_state=42)

# input 배열의 크기를 2차원 배열로 재조정한다.
train_input = train_input.reshape(-1, 1)
test_input = test_input.reshape(-1, 1)

# KNN 회귀로 농어의 무게를 예측
knr = KNeighborsRegressor()
nlist = [1,2,3,4,5,6,7,8,9,10] # 이웃한 개수 list
train_score = []
test_score = []
mae = []

# 이웃한 개수 1~10 까지 train set과 test set의 점수 비교하기
for n in range(1,11):
  knr.n_neighbors = n
  knr.fit(train_input, train_target)

  # test set에 대한 예측값
  test_prediction = knr.predict(test_input)

  # test set에 대한 평균 절댓값 오차
  mae.append(mean_absolute_error(test_target, test_prediction))

  # train, test 점수
  train_score.append(knr.score(train_input, train_target))
  test_score.append(knr.score(test_input, test_target))

# 훈련 세트와 테스트 세트 그래프 그리기
plt.plot(nlist, train_score,marker='^')
plt.plot(nlist, test_score,marker='o')
plt.xlim((1,10))
plt.xlabel("n_neighbors")
plt.ylabel("score")
plt.show()

# MAE 그래프 그리기
plt.plot(nlist, mae, marker='o')
plt.xlim((1,10))
plt.xlabel("n_neighbors")
plt.ylabel("MAE")
plt.show()

문제 4

from google.colab import drive
import pandas as pd
import numpy as np
drive.mount('/content/drive')
data_path = './Fish.csv'
df = pd.read_csv(data_path)
## data에 'Length1','Length2','Length3','Height','Width' 정보를 추출
fish_data=df[ ['Length1','Length2','Length3','Height','Width']]
## target으로 weight을 추출.
fish_weight=df['Weight']

from sklearn.model_selection import  train_test_split
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
train_input,test_input,train_target,test_target=train_test_split(fish_data,fish_weight,random_state=42)
##degree1,2,3중 가장 훈련세트에 대해서 점수가 높은 degree를 구해서 훈련시키고 점수를 구하는 코드를 완성!
poly=PolynomialFeatures(degree=3,include_bias=False)
poly.fit(train_input)
train_poly=poly.transform(train_input)
test_poly=poly.transform(test_input)
lr=LinearRegression()
lr.fit(train_poly,train_target)
print(lr.score(train_poly,train_target))
print(lr.score(test_poly,test_target))

문제 5

import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
import matplotlib.pyplot as plt
###degree 5일 때는 테스트 세트 점수가 음수임.->이 때의 문제점을 릿지 회귀로 해결.
poly=PolynomialFeatures(degree=5,include_bias=False)
poly.fit(train_input)
train_poly=poly.transform(train_input)
test_poly=poly.transform(test_input)
###정규화를 먼저 진행.
ss=StandardScaler()
ss.fit(train_poly)
train_scaled=ss.transform(train_poly)
test_scaled=ss.transform(test_poly)
ridge=Ridge()
ridge.fit(train_scaled,train_target)
print(ridge.score(train_scaled,train_target))
print(ridge.score(test_scaled,test_target))
train_score=[]
test_score=[]
##가장 최적화된 alpha계수를 구하고, 이 계수를 적용하여, 점수를 출력.
alpha_list=[0.0001,0.001,0.01,0.1,1,10,100,1000]
for alpha in alpha_list:
  ridge=Ridge(alpha)
  ridge.fit(train_scaled,train_target)
  train_score.append(ridge.score(train_scaled,train_target))
  test_score.append(ridge.score(test_scaled,test_target))
plt.plot(np.log10(alpha_list),train_score)
plt.plot(np.log10(alpha_list),test_score)
plt.xlabel('alpha')
plt.ylabel('R**2')
plt.show()
ridge=Ridge(alpha=0.01)
ridge.fit(train_scaled,train_target)
print(ridge.score(train_scaled,train_target))
print(ridge.score(test_scaled,test_target))

전체 코드

2주차 4조 문제풀이 코드