我正在为本文中的局部加权线性回归编写代码。
在其中,用于在特定点进行预测的代码行是:pred = np.dot(point_, theta)
其中point_
是形状为(2,)
的数组,例如[-3, 1]
,其中-3
是我想要进行预测的点,1
是偏差项。
def predict(X, y, point, tau):
"""
Predict the target value for a given point using weighted regression.
Args:
X: Input features dataset.
y: Target values dataset.
point: The point of interest.
tau: Bandwidth parameter.
Returns:
float: Predicted target value.
"""
m = X.shape[0]
X_ = np.append(X, np.ones(m).reshape(m, 1), axis=1)
point_ = np.array([point, 1])
w = wm(point_, X_, tau) # function that returns a diagonal weight matrix
theta = np.linalg.pinv(X_.T * (w * X_)) * (X_.T * (w * y))
print("Data type of point_ ",type(point_))
pred = np.dot(point_, theta)
return pred
字符串
现在开始
print("Data type of point_ ",type(point_))
型
给出point_
<class 'numpy.ndarray'>
的数据类型
上面的函数由下面的函数调用:
def plot_predictions(X, y, tau, nval):
"""
nval: Number of points to predict for.
"""
X_test = np.linspace(-3, 3, nval)
preds = []
for point in X_test:
pred = predict(X, y, point, tau)
print("Data type of pred: ",type(pred))
preds.append(pred)
X_test = np.array(X_test).reshape(nval, 1)
preds = np.array(preds).reshape(nval, 1)
# Plot the original data points and predicted values
plt.plot(X, y, 'b.') # Blue dots for original data points
plt.plot(X_test, preds, 'r.') # Red dots for predicted values
plt.show()
# Plot the predictions
plot_predictions(X, y, 0.08, 100)
型
在这种情况下,
print("Data type of pred: ",type(pred))
型
给出pred
的输出数据类型:<class 'numpy.matrix'>
。打印出它的形状就可以得到(1, 1)
。
根据我的理解,pred不应该是一个矩阵。它应该是一个数组,因为point_
的形状是(2,)
,theta
的形状是(2,1)
。由于传递的参数之一不是2d数组或矩阵,因此返回的值也不是矩阵。
为什么pred
是一个矩阵?此外,程序运行完全正常,没有错误。但我不明白为什么矩阵会被退回。
我分别用point_
和theta
的数组形状编写了一个小程序。
import numpy as np
array1 = np.array([1, 2]) # Shape: (2,)
array2 = np.array([[3], [4]]) # Shape: (2,1)
result = np.dot(array1, array2)
print("Result:")
print(result)
print("Shape of the result:", result.shape)
print("Data type of the result:", type(result))
型
输出量:
Result:
Shape of the result: (1,)
Data type of the result: <class 'numpy.ndarray'>
型
在这里,np.dot()
看起来运行得很好,但在局部加权代码中却不是这样。
1条答案
按热度按时间eqoofvh91#
字符串
w
是np.matrix。它是在wm()
中由以下代码生成的:型
将其改为数组。当你把一个矩阵乘以一个数组时,结果是一个矩阵,因为矩阵只是一个数组,它只做一些数组的事情。不要使用
np.mat
。