這是我的代碼,但是當我運行它時,我沒有得到正確的形狀。我需要它回傳一個 numpy 形狀的陣列(4,100)。
為了了解我在做什么,我LinearRegression在訓練資料上擬合指定度數的多項式模型,然后通過將 100 行單列輸出轉置為單行 100 列陣列來生成多項式值的預測。
np.random.seed(0)
C = 15
n = 60
x = np.linspace(0, 20, n) # x is drawn from a fixed range
y = x ** 3 / 20 - x ** 2 - x C * np.random.randn(n)
x = x.reshape(-1, 1) # convert x and y from simple array to a 1-column matrix for input to sklearn regression
y = y.reshape(-1, 1)
# Create the training and testing sets and their targets
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)
def model():
degs = (1, 3, 7, 11)
#Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it
#contains a single sample.
def poly_y(i):
poly = PolynomialFeatures(degree = i)
x_poly = poly.fit_transform(X_train.reshape(-1,1))
linreg = LinearRegression().fit(x_poly, y_train)
#x_orig = np.linspace(0, 20, 100)
y_pred = linreg.predict(poly.fit_transform(np.linspace(0, 20, 100).reshape(-1,1)))
y_pred = y_pred.T
return(y_pred.reshape(-1,1))
ans = poly_y(1)
for i in degs:
temp = poly_y(i)
ans = np.vstack([ans, temp])
return ans
model()
輸出影像:

uj5u.com熱心網友回復:
結合對您的問題的評論,并簡要說明:
你目前正在做
ans = poly_y(1)
for i in degs:
temp = poly_y(i)
ans = np.vstack([ans, temp])
您將ans結果設定為度數,然后回圈遍歷所有度數并將它們堆疊到ans. 但是,所有度數都包含 1,因此您兩次獲得度數 1 ,最終得到 500 x 1 陣列。因此,您可以洗掉第一行。然后,您有這個回圈,您ans可以在其中重復堆疊到 ,這可以使用串列推導式(例如,with [poly_y(deg) for deg in degs])一次性完成。堆疊會產生一個 400 x 1 的陣列,這不是您想要的。你可以重塑它,或者你可以使用hstack. 后者回傳一個 100 x 4 的陣列;要獲得一個 4 x 100 的陣列,只需將其轉置即可。
所以最終的解決方案是將上述四行替換為
ans = np.hstack([poly_y(deg) for deg in degs]).T
(如果您想更花哨,請將這些行替換return ans為
return np.hstack([poly_y(deg) for deg in degs]).T
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410476.html
標籤:
