python - ValueError : shapes (2, 100) 和 (2,1) 未对齐 : 100 (dim 1) ! = 2(暗淡 0)

标签 python machine-learning logistic-regression

我正在做机器学习作业,并且正在制作逻辑回归下降梯度和逻辑回归成本。 我的功能是这样的:

def calcLogRegressionCost(X, y, theta):
    #X is the feature vector
    #Y is the target vector/ output vector
    #theta is the weight vector 

    observations = len(y)
    predictions = sigmoid(np.dot(X, theta))

    #Take the error when label=1
    class1_cost = -y*np.log(predictions)

    #Take the error when label=0
    class2_cost = (1-y)*np.log(1-predictions)

    #Take the sum of both costs
    cost = class1_cost + class2_cost

    #Take the average cost
    cost = cost.sum() / observations

    return cost



def logRegressionGradientDescent(X, y, theta0, alpha):
    #X is the feature vector
    #Y is the target vector/ output vector
    #theta0 is the weight vector 
    #alpha is the learning rate
    #iteration is the steps you want to take 
    #Start you code from here\


    N = len(X)

    #1 - Get Predictions
    predictions = sigmoid(np.dot(X, theta0))

    #2 Transpose features from (100, 2) to (2, 100)
    # So we can multiply w the (100,1)  cost matrix.
    # Returns a (2,1) matrix holding 3 partial derivatives --
    # one for each feature -- representing the aggregate
    # slope of the cost function across all observations
    gradient = np.dot(X.T,  predictions - y)

    #3 Take the average cost derivative for each feature
    gradient /= N

    #4 - Multiply the gradient by our learning rate
    gradient *= lr

    #5 - Subtract from our weights to minimize cost
    weights -= gradient

    #you should return theta or loss or the both depending on your way
    #of implementation

    return weights

他们要求我运行梯度下降算法以使我的参数 theta 适合我的训练集。我做了一个训练函数,如下所示:

W1 = 0.0
W2 = 0.0
weights = np.array([
    [W1],
    [W2]
])


def train(features, labels, weights, lr, iters):
    cost_history = []

    for i in range(iters):
        weights = logRegressionGradientDescent(features, labels, weights, lr)

        #Calculate error for auditing purposes
        cost = cost_function(features, labels, weights)
        cost_history.append(cost)

        # Log Progress
        if i % 1000 == 0:
            print ("iter: " +str(i) + " cost: "+str(cost))

    return weights, cost_history


train([data['First Exam Score'], data['Second Exam Score']], data['Admitted'], weights, 0.00001, 1000)

当我使用数据调用函数 train 时,出现以下错误:

ValueError:形状 (2,100) 和 (2,1) 未对齐:100 (dim 1) != 2 (dim 0)

我不确定如何使参数适合我的数据集。数据集是 100 x 3 数据框。前两列分别是 100 名学生在第一次和第二次考试中获得的成绩数据。第三列显示他们是否被他们想要的大学录取,具体取决于他们的成绩。用0或1表示。

最佳答案

When I call the function train with my data, it gives me the following error:

ValueError: shapes (2,100) and (2,1) not aligned: 100 (dim 1) != 2 (dim 0)

作为程序员必须记住的一件事是错误消息对于调试来说是无价的。它们为您提供有关您的逻辑或代码容易失败或已经失败的宝贵信息。 如果您阅读错误消息,您可以注意以下事项:

  1. 由于错误提到形状未对齐,并且我们知道形状与向量和矩阵相关,因此问题似乎与特征矩阵和权重矩阵的维度有关传递到您的逻辑回归函数中。
  2. 错误消息提到未对齐,这表明矩阵乘法可能存在问题,因为如果矩阵的维度与乘法或它们的顺序不兼容,则未对齐的矩阵预计会引发此错误相乘使得操作不可行。

现在,您可能已经意识到错误指向特征矩阵 X 和权重向量 θ 的 Numpy 点积。
为了修复此错误,您必须确保两件事:矩阵的形状与执行矩阵乘法兼容,并且乘法的顺序是正确的。请记住,在逻辑回归中,特征矩阵中的每个观察都需要一个标量输出,该输出可以作为参数进一步传递到概率映射(如 sigmoid 函数)中,以给出该特定实例的概率属于给定的类。

错误解决办法

为了解决这个问题,转置特征矩阵X,使其形状变为(100,2)。对特征矩阵进行转置后,点积应该变得可行,从而解决您遇到的错误。

建议创建一个单独的特征矩阵,矩阵X,其中仅包含特征列,而不包含目标列,目标列是数据中的最后一列。还建议创建一个标签向量y,它仅存储标签或目标类列。如果我这样做,我会在 Pandas 中完成所有操作,但由于您正在使用 Numpy,因此您可以按照以下方式进行操作。

X = np.transpose([(data['First Exam Score'], data['Second Exam Score']]) #Reshapes the feature matrix from (2,100) to (100,2)
y = data['Admitted']

train(X, y, weights, 0.00001, 1000)

正如您所注意到的,通过这种方式,代码变得更具可读性,并且减少了遇到错误的机会。 希望这会有所帮助。

关于python - ValueError : shapes (2, 100) 和 (2,1) 未对齐 : 100 (dim 1) ! = 2(暗淡 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58172131/

相关文章:

python - keras 中的图像到图像映射

tensorflow - 图像分类的负例?

python - 我应该如何修复 ChunkedEncodingError?

python - 从 csv 返回 python 中的多个值

machine-learning - 机器学习预测和标准化

apache-spark - 使用 PySpark 进行多类分类的逻辑回归问题

python - 控制 Scikit Learn 中逻辑回归的阈值

python - 绘制字符串数组 numpy 和 matplotlib

python - 无法使用 python-nvd3

python - pip 在自定义目录中安装依赖项