2016-06-19 6 views
0

den folgenden Code Ausführen gibt einen Valueerror:fmin_cg: erhält einen Valueerror wegen Typenkonflikt

def f(theta): 
    theta = theta.reshape(2, 1) 
    return np.linalg.norm(x*theta -y)**2 

def fprime(theta): 
    theta = theta.reshape(2,1) 
    return (x.T*(x*theta - y)) 

x = np.matrix('1, 2; 3, 4; 5, 6') 
y = np.matrix('4; 2; 1') 
thetainit = np.matrix('0; 0') 

scipy.optimize.fmin_cg(f, np.ravel(thetainit), fprime=fprime) 

Aber die Dimensionen sind in Ordnung und das x0 Argument für fmin_cg abgeflacht ist mit np.ravel wie in der Dokumentation beschrieben. Hier die Fehlermeldung:

1169  gnorm = vecnorm(gfk, ord=norm) 
    1170  while (gnorm > gtol) and (k < maxiter): 
-> 1171   deltak = numpy.dot(gfk, gfk) 
    1172 
    1173   try: 

Ich schätze jede Hilfe.

+0

Versuchen anstelle von np.matrix –

+0

tryied Verwendung np.array die folgenden: 'def f (theta): theta = theta.reshape (2, 1) return np.linalg.norm (x.dot (theta) -y) ** 2 def fprime (theta): theta.shape = (2,1) return (xTdot (x.dot (theta) - y)) x = np.array ([[1, 2], [3, 4], [5, 6]]) y = np.array ([[4], [2], [1]]) thetainit = np.array ([[ 0], [0]]) scipy.optimize.fmin_cg (f, n.p.ravel (thetainit), fprime = fprime) ' Der folgende Fehler ist aufgetreten: 'ValueError: Shapes (2,1) und (2,1) nicht ausgerichtet: 1 (dim 1)! = 2 (dim 0)' – tobmei05

+0

Entschuldigung mit meinem früheren Kommentar. Ich hatte Probleme beim Bearbeiten von Notizen. Ich habe den gleichen Fehler wie zuvor: 'ValueError: Shapes (2,1) und (2,1) nicht ausgerichtet: 1 (dim 1)! = 2 (dim 0)' – tobmei05

Antwort

0

Dieser Code funktioniert:

def f(theta): 
    theta = theta.reshape(2, 1) 
    return np.linalg.norm(x*theta -y)**2 
# return np.linalg.norm(x*theta -y)**2 

def fprime(theta): 
    theta = theta.reshape(2,1) 
    g = np.array(x.T*(x*theta - y)).flatten() 
    return g 

x = np.matrix('1, 2; 3, 4; 5, 6') 
y = np.matrix('4; 2; 1') 
thetainit = np.matrix('0; 0') 

scipy.optimize.fmin_cg(f, np.ravel(thetainit), fprime=fprime) 

Der entscheidende Punkt hinzuzufügen war 'abflachen()'!

Verwandte Themen