>比较中的值错误

2024-09-28 05:15:25 发布

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

# -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 14:56:52 2020

@author: 12064
"""
import numpy as np

k = 0
### size of function
n = 5
######## creating test function
A = np.random.randn(n,n)
B = np.transpose(A)
C = np.matmul(B,A)    # A,B,C working
gradf = np.gradient(C, axis=0)
def myFcn(x):
    return np.dot(C, x)
def gradientmyFcn(x):
    return np.dot(gradf, x)

######## C = Q Rick defines
######## define the point
xT = np.random.randn((n))
x = xT.reshape((n,1))
print('myFcn(x)')
###### define gradient

#####initial alpha, c

###### define descent direction, and set of descent directions
p = np.zeros((n,1))
pT = np.zeros((1,n))
pT = gradientmyFcn(x)
pT.reshape(1,n)
p = np.transpose(pT)
p.reshape(n,1)
#P = {p[0]:p[k]}
#p[0] = gradf initial descent direction
def ArmijoLineSearch(alpha):
    tao = .1
    alpha = 1
    c = 1.e-4
    backtrack_factor = .5
    gradfx = gradientmyFcn(x)
    gradfx = gradfx
    gradTx = np.transpose(gradfx)
    xk1 = (x + (alpha*p))
    check_step = np.dot(gradfx, p) 
    LessThan = myFcn(x) + (c*alpha)*check_step
    if myFcn(xk1) > LessThan:
        alpha = backtrack_factor * alpha
    else:
        if (np.transpose(mygradientFcn(xk1)) @ p) < tao * np.dot(np.transpose(gradfx), p):
            print("weak curvature condition does not hold")
        else:
            return alpha
ArmijoLineSearch(alpha)

错误发生在此行:if myFcn(xk1) > LessThan:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我很难理解这个错误,因为它似乎是随机数的numpy数组(至少最初是随机的),并试图用布尔运算。问题是什么?我应该如何解决


Tags: ofalphaptreturndefnpdottranspose

热门问题