为什么numpy.dot()在我的代码中应该返回数组,但却返回一个矩阵对象?

llew8vvj  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(83)

我正在为本文中的局部加权线性回归编写代码。
在其中,用于在特定点进行预测的代码行是: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()看起来运行得很好,但在局部加权代码中却不是这样。

eqoofvh9

eqoofvh91#

w = wm(point_, X_, tau)

字符串
wnp.matrix。它是在wm()中由以下代码生成的:

w = np.mat(np.eye(m))


将其改为数组。当你把一个矩阵乘以一个数组时,结果是一个矩阵,因为矩阵只是一个数组,它只做一些数组的事情。不要使用np.mat

相关问题