2017-10-16 101 views
0

我寫下面的代碼使用多項式迴歸。能夠適應模型,但無法預測!使用多項式迴歸擬合模型不允許預測,因爲形狀問題

def polynomial_function(power=5, random_state=9): 
    global X_train 
    global y_train 

    X_train = X_train[['item_1','item_2','item_3','item_4']] 
    rng = np.random.RandomState(random_state) 
    poly = PolynomialFeatures(degree=power, include_bias=False) 
    linreg = LinearRegression(normalize=True) 
    new_X_train = poly.fit_transform(X_train) 
    linreg.fit(new_X_train, y_train) 
    new_x_test = np.array([4, 5, 6, 7]).reshape(1, -1) 
    print linreg.predict(new_x_test) 
    return linreg 

linreg = polynomial_function() 

我得到以下錯誤消息:

ValueError: shapes (1,4) and (125,) not aligned: 4 (dim 1) != 125 (dim 0)  

錯誤發生在這裏,

new_x_test = np.array([4, 5, 6, 7]).reshape(1, -1) 
print linreg.predict(new_x_test) 

我發現new_X_train的形狀=(923,125) 和new_x_test =的形狀( 1,4)

這有什麼關係?

當我嘗試使用(1,4)的形狀來預測該算法是否嘗試將其轉換爲不同的形狀?

它是否試圖找出測試數據的5次多項式?

我想學習多項式迴歸,任何人都可以解釋發生了什麼?

回答

0
from sklearn.pipeline import Pipeline 
from sklearn.linear_model import LinearRegression 
from sklearn.preprocessing import PolynomialFeatures 

pipeline = Pipeline([ 
    ('poly', PolynomialFeatures(degree=5, include_bias=False)), 
    ('linreg', LinearRegression(normalize=True)) 
    ]) 

pipeline.fit(X_train, y_train) 
pipeline.predict(np.array([4, 5, 6, 7]).reshape(1, -1)) 
+0

其實我正在返回「linreg」後擬合模型。其他人使用model = polynomial_function()來調用我的模型; model.predict(np.array([4,5,6,7])。reshape(1,-1)); ,我如何在我的功能中處理這個問題?任何解決方案? –

+0

爲什麼'new_x_test'在你的函數裏面?如果你的目標是返回模型,然後用它來預測,你的例子爲什麼會顯示你在函數內部預測? – Jarad

+0

爲簡單起見,我放了new_x_test。我正在測試這個功能。我認爲我可以在「new_x_test」超出函數時應用解決方案。但現在我不能。如果「new_x_test」來自外部,你可以請建議一個解決方案,如:model.predict(np.array([4,5,6,7])。reshape(1,-1)) –