簡體   English   中英

使用線性回歸繪制下一個值

[英]Plotting a next value using linear regression

我構建了一個線性回歸 model 來擬合數據集,現在我想看看新值是如何相對於先前的預測定位的。 這是代碼

X = dataframe.iloc[:,1].values.reshape(16, 1)
y = dataframe.iloc[:, -1].values.reshape(16, 1)
Xb = np.hstack((np.ones((X.shape[0], 1)), X))
print(Xb)
theta = np.dot(np.linalg.inv(np.dot(Xb.T, Xb)), np.dot(Xb.T, y))
preds = np.dot(Xb, theta)
plt.scatter(X, y)
plt.plot(X, preds, color='red', lw=2)
plt.xlabel('Gross National Product [GNP]')
plt.ylabel('Number of people employed')

X 和 y 是浮點數的 numpy ndarray。

對於 function a*x+b=y您已經估計abtheta 您已經根據ab計算了預測,即矩陣Xb包含您的x值和1 (點積是 x 乘以 a(theta 的第一個元素)和 1 乘以 b)。

因此,您要做的是創建一個新的Xb矩陣,例如 1 行(如果您只想要 1 個新點)。

因此,如果您有Xb = np.array([10, 1]) your predilection would be on x=10`。 也許你必須稍微改變一下形狀,但我沒有你的數據,所以我無法測試這是否直接適用於你的情況,但這是計算新預測所必須做的。

import numpy as np
X = np.linspace(0, 5, 6) # array([0., 1., 2., 3., 4., 5.])
Y = 2*X + 3 # array([ 3.,  5.,  7.,  9., 11., 13.])
Xb = np.vstack((X, np.ones(X.shape[0]))).T
theta = **np.linalg.inv(Xb.T@Xb)@Xb.T@Y # array([2., 3.]) (note 2, 3 from how we calculated Y)
# I used another format (@ is a dot product) but it is the same as:
theta = np.dot(np.linalg.inv(np.dot(Xb.T, Xb)), np.dot(Xb.T, y))

# Now a new prediction at X=15:
# we know 2*15+3 = 33
X_pred = np.array([15, 1])
y_pred = X_pred@theta # 33

# matrix form makes it possible to do multiple predictions at once, but you can also use:
y_pred = 15 * theta[0] + theta[1] # 33

# but if you want to predict on X = [15, 20, 25]:
X_pred = np.array([15, 20, 25])
# add ones (b component)
X_pred = np.vstack([X_pred, np.ones(X_pred.shape)]).T
y_pred = X_pred @ theta # array([33., 43., 53.])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM