在需要单个值的地方传递数组?

2024-06-01 03:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python实现简单的优化问题。我目前正在努力解决以下错误:

值错误:包含多个元素的数组的真值不明确。使用a.any()或a.all()

据我所知,这意味着我正在尝试插入一个数组,其中只能接受单个值。尽管如此,我还没有想出解决办法,也没有发现问题出在哪里。你知道吗

我的代码如下

def validationCurve(X, y, Xval, yval):
    #[lmbda_vec, error_train, error_val] = 
    # VALIDATIONCURVE(X, y, Xval, yval) returns the train and 
    # validation errors (in error_train, error_val) for different
    # values of lmbda. Given the training set (X,y) and validation 
    # set (Xval, yval).

    lmbda_vec = [0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1];
    m = len(y);
    X = numpy.concatenate((numpy.ones((m,1)), X), axis = 1);
    n = len(Xval);
    Xval = numpy.concatenate((numpy.ones((n,1)), Xval), axis = 1);

    error_train = numpy.zeros((len(lmbda_vec), 1));
    error_val = numpy.zeros((len(lmbda_vec), 1));


    for i in range(0,len(lmbda_vec)):
        lmbda = lmbda_vec[i];
        theta = trainLinearReg(X, y, lmbda);
        error_train[i] = linearRegCostFunction(X, y, theta, lmbda);
        error_val[i] = linearRegCostFunction(Xval, yval, theta, lmbda);
    return lmbda_vec, error_train, error_val


def trainLinearReg(X, y, lmbda):
    #[theta] = TRAINLINEARREG (X, y, lmbda) trains linear 
    # regression usingthe dataset (X, y) and regularization 
    # parameter lmbda. Returns the trained parameters theta.

    alpha = 1 # learning rate
    num_iters = 200 # number of iterations
    initial_theta = (numpy.zeros((len(X[0,:]),1))) #initial guess

    #Create "short hand" for the cost function to be minimized
    costFunction = lambda t: linearRegCostFunction(X, y, t, lmbda);
    #Minimize using Conjugate Gradient
    theta = minimize(costFunction, initial_theta, method = 'Newton-CG',
    jac = True, options = {'maxiter': 200})
    return theta

def linearRegCostFunction(X, y, theta, lmbda):
    # [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lmbda)
    # computes the cost of using theta as the parameter for 
    # linear regression to fit the data points in X and y. 
    # Returns the cost in J and the gradient in grad.

    # Initialize some useful values
    m, n = X.shape; # number of training examples
    J = 0;
    grad = numpy.zeros((n ,1))

    J = numpy.dot((y- X @ theta).T, (y-X @ theta)) + 
    lmbda*(theta[1:].T @ theta[1:])
    J = J/m

    grad = (X.T @ (y - X @ theta))/m
    grad [1:] += (lmbda*theta[1:])/m


    grad = grad[:];
    return grad

通过计算代价函数和对θ的极小化,得到一个最优的正则化参数。 我的输入值是:

X.shape = (100,25), y.shape = (100,1)
Xval.shape = (55,25), yval.shape = (55,1)

输出错误为:

    --> 129 lmbda_vec , error_train, error_val = validationCurve(Xtrain, ytrain, Xva
    lid, yvalid )
    ---> 33 theta = trainLinearReg(X, y, lmbda);
    ---> 49 theta = minimize(costFunction, initial_theta, 
                    method = 'Newton-CG', jac = True, options = {'maxiter': 200})

稍后我将不使用优化模型来预测新X上的y。 您能告诉我代码中的问题在哪里吗?

另外,如果你在我的代码中发现了任何需要改进的地方,请告诉我。我将很高兴听到和改进。你知道吗

谢谢你!你知道吗


Tags: andtheinnumpylentrainerrorval
1条回答
网友
1楼 · 发布于 2024-06-01 03:37:18

Nimitz14给出了一般性的解释:您提供了一个需要标量的数组。这导致运行时错误。问题是如何从这里解决它。你知道吗

首先,试着用你最喜欢的调试器来处理这个问题,这样你就可以在有用的地方停止这个程序,并准确地找出是什么数组导致了这个问题。这将帮助您确定它的起源。你知道吗

如果做不到这一点,可以沿着调用路径放置一些策略性的print语句,在函数调用之前打印每个参数。然后检查每个函数的签名(调用序列),看看您可能在何处指定了一个数组来代替标量。我看不出来,但是。。。你知道吗

有没有可能你重新定义了True作为一个数组?你知道吗

相关问题 更多 >