Numpy matrix must be 2-dimensional error - python

I have the following code:
import numpy as np
def J(x, y):
return np.matrix([[8-(4 * y), -4 * y], [y, -5 + x]])
x_0 = np.matrix([[1], [1]])
test = J(x_0[0], x_0[1])
When I go to run it I receive the following error:
Traceback (most recent call last):
File "broyden.py", line 15, in <module>
test = J(x_0[0][0], x_0[1][0])
File "broyden.py", line 12, in J
return np.matrix([[8-(4 * y), -4 * y], [y, -5 + x]])
File "/home/collin/anaconda/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 261, in __new__
raise ValueError("matrix must be 2-dimensional")
ValueError: matrix must be 2-dimensional
I don't understand why I'm getting this error. Everything appears to be 2-d.

The type of x_0[0] is still numpy.matrixlib.defmatrix.matrix, not a scalar value.
You need get a scale value to treat as a matrix element. Try this code
test = J(x_0.item(0), x_0.item(1))

Related

Dimension mismatch error in python while evaluating a function of two arguments

The function evaluates if I input a pair of arguments. But when I try to evaluate the function at grid points, it fails, saying "ValueError: dimension mismatch". I paste the code below. Could anyone help with the problem?
import numpy as np
from qutip import*
import pylab as plt
from numpy import eye,pi,kron,random,vdot,absolute,power,sqrt,matmul
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
j0= tensor(sigmaz(),identity(2),identity(2))
def otoc(k0,n):
u0=(-1j*k0/6 *(tensor(sigmaz(),sigmaz(),identity(2)))).expm()
jn= u0.inv()**n*j0*u0**n
return ((commutator(jn,j0)* commutator(j0,jn)).tr()/8)
k0 = np.arange(0,4,0.1)
n = np.linspace(0,50,50)
X,Y = meshgrid(k0, n)
Z = otoc(X, Y)
The error showing is the following
Traceback (most recent call last):
File "/Users/sreerampg/Dropbox/myself/programs/levy's lemma/untitled8.py", line 27, in <module>
Z = otoc(X, Y)
File "/Users/sreerampg/Dropbox/myself/programs/levy's lemma/untitled8.py", line 20, in otoc
u0=(-1j*k0/6 *(tensor(sigmaz(),sigmaz(),identity(2)))).expm()
File "/Applications/anaconda3/lib/python3.7/site-packages/qutip/qobj.py", line 599, in __rmul__
return other * self.data
File "/Applications/anaconda3/lib/python3.7/site-packages/scipy/sparse/base.py", line 550, in __rmul__
return (self.transpose() * tr).transpose()
File "/Applications/anaconda3/lib/python3.7/site-packages/cvxpy/interface/scipy_wrapper.py", line 31, in new_method
return method(self, other)
File "/Applications/anaconda3/lib/python3.7/site-packages/scipy/sparse/base.py", line 516, in __mul__
raise ValueError('dimension mismatch')
ValueError: dimension mismatch

TypeError: Can not understand

I am fitting a very simple curve having three points. with leastsq method, following all the rules. But still I am getting error. I cannot understand. Can anyone help. Thank you so much
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq
x = np.array([2.0,30.2,15.0])
y = np.array([45.0,56.2,30.0])
print(x)
print(y)
# model
def t(x,a,b,c):
return a*x**2 + b*x + c
#residual fucntion
def residual_t(x,y,a,b,c):
return y-t(x,a,b,c)
#initial parameters
g0 = np.array([0.0,0.0,0.0])
#leastsq method
coeffs, cov = leastsq(residual_t, g0, args=(x,y))
plt.plot(x,t(x,*coeffs),'r')
plt.plot(x,y,'b')
plt.show()
#finding out Rsquared and Radj squared value
absError = residual_t(y,x,*coeffs)
se = np.square(absError) # squared errors
Rsquared = 1.0 - (np.var(absError) / np.var(y))
n = len(x)
k = len(coeffs)
Radj_sq = (1-((1-Rsquared)/(n-1)))/(n-k-1)
print (f'Rsquared value: {Rsquared} adjusted R saquared value: {Radj_sq}')
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'
Why??
coeffs is already a array containing best it values of a, b,c. coeffs is also showing undefined and residual_t is also showing problem. Could you please help me to understand.
With a copy-n-paste of your code (including the *coeffs change), I get
1135:~/mypy$ python3 stack58206395.py
[ 2. 30.2 15. ]
[45. 56.2 30. ]
Traceback (most recent call last):
File "stack58206395.py", line 24, in <module>
coeffs, cov = leastsq(residual_t, g0, args=(x,y))
File "/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py", line 383, in leastsq
shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
File "/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py", line 26, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'
That is the error is in the use of residual_t within the leastsq call.
If I add
residual_t(g0, x, y)
right after the g0 definition I get the same error:
1136:~/mypy$ python3 stack58206395.py
[ 2. 30.2 15. ]
[45. 56.2 30. ]
Traceback (most recent call last):
File "stack58206395.py", line 23, in <module>
residual_t(g0, x, y)
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'
So you need to define residual_t to work with a call like this. I'm not going to take a guess as to what you really want, so I'll leave the fix up to you.
Just remember that residual_t will be called with the x0, spliced with the args tuple. This is typical usage for scipy.optimize functions. Review the docs if necessary.
edit
Defining the function as:
def residual_t(abc, x, y):
a,b,c = abc
return y-t(x,a,b,c)
runs without error.

Matrix Exponential for two similar matrices

I have constructed two matrices. For one I calculate matrix exponential, but for the other one I can not. They are similarly constructed and have the same structure and dimension. I really don't know why one can work but the other can not. I put my code below.
import numpy as np
import math as math
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import *
sigmax = [[0, 1], [1, 0]]
sigmay = [[0, -1j], [1j, 0]]
sigmaz = [[1, 0], [0, -1]]
sigmaxx = np.kron(sigmax,sigmax)
sigmayy = np.kron(sigmay,sigmay)
sigmazz = np.kron(sigmaz,sigmaz)
sigmaxxyy = np.mat(sigmaxx) + np.mat(sigmayy)
N = 6
Hxxyy = 0
for i in range (0,N-2+1):
Hxxyy = np.mat(Hxxyy) + np.mat(np.kron(np.kron(np.identity(2**i),2*np.mat(sigmaxxyy)),np.identity(2**(N-i-2)) ))
Hxxyy = np.mat(Hxxyy) + np.mat(np.kron(np.kron(2*np.mat(sigmax),np.identity(2**(N-2))),sigmax))+np.mat(np.kron(np.kron(2*np.mat(sigmay),np.identity(2**(N-2))),sigmay))
print(expm(Hxxyy))
Hhi = 0
for j in range (0,N-1+1):
Hhi = np.mat(Hhi) + np.mat(np.kron( np.kron(np.identity(2**j),3*np.mat(sigmaz)),np.identity(2**(N-1-j))) )
print(expm(Hhi))
The error message is:
Traceback (most recent call last):
File "new test.py", line 20, in <module>
print(expm(Hhi))
File "/Users/sherlock/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/sparse/linalg/matfuncs.py", line 582, in expm
return _expm(A, use_exact_onenorm='auto')
File "/Users/sherlock/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/sparse/linalg/matfuncs.py", line 637, in _expm
X = _fragment_2_1(X, h.A, s)
File "/Users/sherlock/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/sparse/linalg/matfuncs.py", line 755, in _fragment_2_1
X[k, k] = exp_diag[k]
ValueError: setting an array element with a sequence.
Your code works in Python3 (Python 3.4.5) but fails in Python2 (Python 2.7.12).
There were a few changes in scipy/sparse/linalg/matfuncs.py between these two versions that cleaned all code paths to support both dense and sparse matrices.
Since the dimensions are not very big, a quick fix would be to
replace
expm(Hhi)
with
expm(np.array(Hhi))

input/output error in scipy.optimize.fsolve

I seem to be getting an error when I use the root-finder in scipy. I was wondering if anyone could point out what I'm doing wrong.
The function I'm finding the root of is just an easy example, and not particularly important.
If I run this code with scipy 0.9.0:
import numpy as np
from scipy.optimize import fsolve
tmpFunc = lambda xIn: (xIn[0]-4)**2 + (xIn[1]-5)**2 + (xIn[2]-7)**3
x0 = [3,4,5]
xFinal = fsolve(tmpFunc, x0 )
print xFinal
I get the following error message:
Traceback (most recent call last):
File "tmpStack.py", line 7, in <module>
xFinal = fsolve(tmpFunc, x0 )
File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 115, in fsolve
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 26, in _check_func
raise TypeError(msg)
TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument '<lambda>'.
Well it looks like I was trying to use this routine incorrectly. This routine requires the same number of equations and variables vs. the one equation with three variables I gave it. So if the input to the function to be minimized is a 3-D array the output should be a 3-D array. This code works:
import numpy as np
from scipy.optimize import fsolve
tmpFunc = lambda xIn: np.array( [(xIn[0]-4)**2 + xIn[1], (xIn[1]-5)**2 - xIn[2]) \
, (xIn[2]-7)**3 + xIn[0] ] )
x0 = [3,4,5]
xFinal = fsolve(tmpFunc, x0 )
print xFinal
Which represents solving three equations simultaneously.

Python and Scipy programming

I'm getting this error message:
Traceback (most recent call last):
File "C:/Python27/test", line 14, in <module>
tck = interpolate.bisplrep(X,Y,Z)
File "C:\Python27\lib\site-packages\scipy\interpolate\fitpack.py", line 850, in bisplrep
raise TypeError('m >= (kx+1)(ky+1) must hold')
TypeError: m >= (kx+1)(ky+1) must hold
The error says that len(X) = m is <=(kx+1)(ky+1). How can I solve this? Here's my program:
import scipy
import math
import numpy
from scipy import interpolate
x= [1000,2000,3000,4000,5000,6000]
y= [1000]
Y = numpy.array([[i]*len(x) for i in y])
X = numpy.array([x for i in y])
Z = numpy.array([[21284473.74,2574509.71,453334.97,95761.64,30580.45,25580.60]])
tck = interpolate.bisplrep(x,y,Z)
print interpolate.bisplev(3500,1000,tck)
Have you read the documentation?
If you don't specify kx and ky, default values will be 3:
scipy.interpolate.bisplrep(x, y, z, w=None, xb=None, xe=None, yb=None, ye=None,
kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None,
full_output=0, nxest=None, nyest=None, quiet=1)
And of course, len(X) = 6 < 16 = (3+1)(3+1).
Even if you give kx=1 and ky=1 explicitly while calling, you have another problem. Your (x,y) values form a line, and you can not define a surface from a line. Therefore it gives you ValueError: Invalid inputs.. First, you should fix your data. If this is your data, as you have no variation in Y, skip it and do a spline in 2D with X and Z.

Categories