inflearn logo
강의

Course

Instructor

[Revised Edition] The Complete Guide to Python Machine Learning

Understanding Underfitting and Overfitting Using Polynomial Regression

무슨 문제인지 모르겠어요

8194

yhk23382599

6 asked

0

선생님! 소스코드 pipe.fit(x.reshape(-1,1),y) 이 부분에서

'numpy.ndarray' object has no attribute 'fit' 이런 오류가 떠요. 
나머지 부분들은 다 교재와 똑같이 썼는데, 왜 이런 오류가 떳는지 모르겠습니다..

동영상 06:09분 입니다.

머신러닝 배워볼래요? 통계 python

Answer 4

0

yhk23382599

해결되었습니다! 감사합니다 선생님!

0

dooleyz3525

클래스 명이 아니라 객체 변수 명을 인자로 넣어 줘야 합니다. pipe=Pipeline([('polynomial_features',PolynomialFeatures),('linear_regression',LinearRegression)])
부분을 아래와 같이 변경해 주십시요.
pipe=Pipeline([('polynomial_features', polynomial_features),('linear_regression',linear_regression)])
그리고 아래도 X_test.가 아니라 X_test, 으로 변경해 주십시요
plt.plot(X_test,pipe.predict(X_test[:,np.newaxis]),label="Model")

0

yhk23382599

import matplotlib.pyplot as plt

from sklearn.pipeline import Pipeline 

from sklearn.model_selection import train_test_split

from sklearn.model_selection import cross_val_score

from sklearn.preprocessing import PolynomialFeatures

from sklearn.linear_model import LinearRegression

import numpy as np

from sklearn.metrics import mean_squared_error, r2_score

%matplotlib inline

def true_fun(x):

    return np.cos(1.5 *np.pi * x) 

# random 값으로 구성된 X값에 대해 Cosine 변환값을 반환  

np.random.seed(0)

n_samples=30

x=np.sort(np.random.rand(n_samples))

y=true_fun(x)+np.random.randn(n_samples)*0.1

plt.figure(figsize=(14,5))

degrees=[1,4,15]

for i in range(len(degrees)):

    ax=plt.subplot(1,len(degrees),i+1)

    plt.setp(ax,xticks=(),yticks=())

    

    # 개별 degree별로 polynomial 변환합니다.

    polynomial_features=PolynomialFeatures(degree=degrees[i],include_bias=False)   # 상수항 포함 X

    linear_regression=LinearRegression()

    pipe=Pipeline([('polynomial_features',PolynomialFeatures),('linear_regression',LinearRegression)])

    pipe.fit(x.reshape(-1,1),y)

    

    scores=cross_val_score(pipe,x.reshape(-1,1),y,scoring='neg_mean_squared_error',cv=10)

    

    #pipeline을 구성하는 세부 객체를 접근하는 named_steps['객체명']을 이용해 회귀계수 추출

    coefficients=pipe.named_steps['linear_regression'].coef_

    

    print("\n Degree {0} 회귀 계수는 {1} 입니다.".format(degrees[i],np.round(coefficients,2)))

    print('\n Degree {0} MSE는 {1}입니다.'.format(degrees[i],-1*np.mean(scores)))

    

    # 0부터 1까지 테스트 데이터 세트를 100개로 나눠 예측을 수행합니다. 

    # 테스트 데이터 세트에 회귀 예측을 수행하고 예측 곡선과 실제 곡선을 그려서 비교합니다.

    

    X_test=np.linspace(0,1,100)

    # 예측값 곡선

    plt.plot(X_test,pipe.predict(X_test[:,np.newaxis]),label="Model")

    # 실제값 곡선

    plt.plot(X_test.true_fun(X_test),'--',label="True function")

    plt.scatter(X,y,edgecolor='b',s=20,label="Samples")

    plt.xlabel("X");plt.ylabel("y");plt.xlim((0,1));plt.ylim((-2,2));plt.legend(loc='best') # 최적의 위치에 범례 위치시킴

    plt.title("Degree {}\nMSE={:.2e}(+/-{:.2e})".formate(degrees[i],-scores.mean(),scores.std()))

    

plt.show()

0

dooleyz3525

안녕하십니까,

작성하신 전체 소스코드를 여기에 올려봐 주시겠습니까?

모델 서빙과 관련된 강좌가 출시되는지 질문드립니다.

0

44

2

안녕하세요 열심히 수강중인 학생입니다

0

80

2

정수 인덱싱

0

81

2

넘파이 오류

0

104

2

11강 numpy의 axis 축 질문 드립니다.

0

100

2

Kaggle 에서 Santander customer satisfaction data 를 다운로드 되지가 않습니다.

0

87

2

Feature importances 를 보여주는 barplot 이 그래프로 안보여져요.

0

75

2

타이타닉 csv 파일이 주피터 화면에 보이지 않습니다.

0

80

2

타이타닉 csv 파일이 주피터 화면에 보이지 않습니다.

0

69

2

5강 강의 오류가 있어요.

0

88

1

실무에서 LTV 관련 모델 선택 질문입니다!

0

77

2

14강 강의 듣는중에 궁금한게 있어서 질문합니다~

0

72

3

파이썬 다운그레이 후 사이킷런 재설치

0

124

2

좋은 강의 감사합니다.

0

77

2

scoring 함수 음수값

0

71

2

6번 강의에 사이킷런, 파이썬, 아나콘다 각각 버전 일치 안 시키고 진행해도 강의 따라가 지나요?

0

108

2

분류 평가 정확도 예측

0

84

2

안녕하세요. 강의 들으면서 업무에 적용하고 싶은 수강생입니다.

0

108

1

카카오톡 채널 있나요

0

113

1

혹시 강의에서 사용하시는 ppt 받을 수 있는건가요

0

191

2

pca 스케일링 관련하여 질문드립니다.

0

106

2

주피터 대신 구글 코랩

0

179

2

강의에서 사용하는 pdf or ppt자료는 따로 없는 건가요?

0

149

2

실루엣 스코어..

0

90

2