ValueError: matrix must be 2-dimensional - python

I have following codes to plot a gassian-2d contour,but I get this Error:
Traceback (most recent call last):
File "question.py", line 15, in <module>
Z0=gaussian_2d(X0,Y0,2,3,cov)
File "question.py", line 4, in gaussian_2d
return exp(-0.5*mat([x-x0,y-y0])*sigmaMatrix.I*mat([x-x0,y-y0]).T)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/matrixlib/defmatrix.py", line 96, in asmatrix
return matrix(data, dtype=dtype, copy=False)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/matrixlib/defmatrix.py", line 272, in __new__
raise ValueError("matrix must be 2-dimensional")
ValueError: matrix must be 2-dimensional
This my code:
import matplotlib.pyplot as plt
from numpy import *
def gaussian_2d(x, y, x0, y0, sigmaMatrix):
return exp(-0.5*mat([x-x0,y-y0])*sigmaMatrix.I*mat([x-x0,y-y0]).T)
cov=mat([[1,0],[0,2]])
delta=0.025
xgrid=arange(-2, 6, delta)
ygrid=arange(-2, 6, delta)
X0, Y0 = meshgrid(xgrid, ygrid)
Z0=gaussian_2d(X0,Y0,2,3,cov)
Can anyone tell me what am i doing wrong here?

Error starts from the concatenation but also your matrix dimensions don't match.
You are performing a quadratic form multiplication x^T A x but your meshgrid variables are square matrices of 320x320. Your A matrix cov is 2x2 hence you get an error.
If the sizes matches you can column concatenate mat(c_[x-x0,y-y0]) or use any other stacking option.

Related

I am attempting to integrate a sine wave. I am getting a valueError: invalid callable given

import numpy as np
import scipy.integrate as integrate
time = np.arange(0.0, 1, 0.0001)
test = np.sin(time)
test2 = integrate.quad(test,0,0.01)
I set up time with np.arange
I then create the sin function
I then attempt to integrate the function
Traceback:
Traceback (most recent call last):
File "/home/andrew/PycharmProjects/memresistor/test.py", line 8, in <module>
test = integrate.quad(test,0,0.01)
File "/home/andrew/PycharmProjects/memresistor/venv/lib/python3.8/site-packages/scipy/integrate/_quadpack_py.py", line 351, in quad
retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
File "/home/andrew/PycharmProjects/memresistor/venv/lib/python3.8/site-packages/scipy/integrate/_quadpack_py.py", line 463, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
ValueError: invalid callable given
I think this is the misunderstanding: np.sin is a function. np.sin() is not. When the () is added to the end, the function is called and will be evaluated, thus no longer being a function. Does this work for you?
import numpy as np
import scipy.integrate as integrate
test = integrate.quad(np.sin, 0, 1)

The TextBackend supports only expressions over a 1D range: Implicit plotting in Sympy

On doing the following,
from sympy import *
x, y = symbols('x y')
p1 = plot_implicit((Eq(x**2 + y**2, 5)))
I get the following traceback:
Traceback (most recent call last):
File "test.py", line 3, in <module>
p1 = plot_implicit((Eq(x**2 + y**2, 5)))
File "/home/tinkidinki/.local/lib/python3.6/site-packages/sympy/plotting/plot_implicit.py", line 377, in plot_implicit
p.show()
File "/home/tinkidinki/.local/lib/python3.6/site-packages/sympy/plotting/plot.py", line 187, in show
self._backend.show()
File "/home/tinkidinki/.local/lib/python3.6/site-packages/sympy/plotting/plot.py", line 1101, in show
'The TextBackend supports only expressions over a 1D range')
ValueError: The TextBackend supports only expressions over a 1D range
It doesn't seem to get affected by making it a one-variable expression. How do you plot implicitly in Sympy?
If you install matplotlib it will use that for plotting instead of TextBackend. I ran pip install matplotlib and when I tried your expression/command it worked.

Strange behaviour in scipy.solve_ivp when using an implicit method

I recently ran into a question about integration and encountered a strange bug. I attempt a very simple problem using solve_ivp:
from scipy.integrate import solve_ivp
import numpy as np
def f(y, t):
return y
y0 = [1,1,1,1]
method = 'RK23'
s = solve_ivp(f, (0,1), y0, method=method, t_eval=np.linspace(0,1))
And it works fine. When I change to method='BDF' or method='Radau' I get an error:
Traceback (most recent call last):
File "<ipython-input-222-f11c4406e92c>", line 10, in <module>
s = solve_ivp(f, (0,1), y0, method=method, t_eval=np.linspace(0,1))
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\integrate\_ivp\ivp.py", line 455, in solve_ivp
solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\integrate\_ivp\radau.py", line 299, in __init__
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\integrate\_ivp\radau.py", line 345, in _validate_jac
J = jac_wrapped(t0, y0, self.f)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\integrate\_ivp\radau.py", line 343, in jac_wrapped
sparsity)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\integrate\_ivp\common.py", line 307, in num_jac
return _dense_num_jac(fun, t, y, f, h, factor, y_scale)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\integrate\_ivp\common.py", line 318, in _dense_num_jac
diff = f_new - f[:, None]
IndexError: too many indices for array
I also get an error with method = 'LSODA', although different (i.e. all implicit integrators). I do not get an error with any of the explicit integrators.
I tried this in spyder with scipy version 1.0.0 and in google colab (scipy version 1.1.0), with the same results.
Is this a bug or am I missing some argument I need for implicit integrators??
It appears that the Radau and BDF methods do not handle single-valued RHS functions. Making the function f above output a 1-D list solves your issue. Additionally, as mentioned by Weckesser in the comments, solve_ivp expects the RHS to be f(t, y) and not f(y, t).
Like this
def f(t, y):
return [y]

Classifier.fit for oneclassSVM complaining about float Type. TypeError float is required

I'm trying to fit two One Class SVMs to a small sets of data. These sets of data are call m1 and m2 respectively. m1 and m2 are lists of decimals which are converted to numpy arrays of type float t1 and t2.
When I attempt to fit the oneclass SVMs to these sets of data I am seeing errors saying that the the fit function will only accept a float. Can someone help me fix this problem?
Example Values:
m1 =[0.020000000000000018, 0.22799999999999998, 0.15799999999999992, 0.18999999999999995, 0.264]
m2 = [0.1279999999999999, 0.07400000000000007, 0.75, 1.0, 1.0]
Code below:
classifier1 =sklearn.svm.OneClassSVM(kernel='linear', nu ='0.5',gamma ='auto')
classifier2 = sklearn.svm.OneClassSVM(kernel='linear', nu ='0.5',gamma='auto')
for x in xrange(len(m1)):
print" Iteration "+str(x)
t1.append(float(m1[x]))
t2.append(float(m2[x]))
tx = np.array(t1).astype(float)
ty = np.array(t2).astype(float)
t1 = np.r_[tx+1.0,tx-1.0]
t2 = np.r_[ty+1.0,ty-1.0]
print t1
print t2
clfit1 = classifier1.fit(t1.astype(float))
clfit2 = classifier2.fit(t2.astype(float))
Error on commandline:
/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
Traceback (most recent call last):
File "normalize_data.py", line 108, in <module>
main()
File "normalize_data.py", line 15, in main
trainSVM(result1[0],yval1,result2[0],yval2,0.04)
File "normalize_data.py", line 99, in trainSVM
clfit1 = classifier1.fit(t1.astype(float))
File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/classes.py", line 1029, in fit
**params)
File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py", line 193, in fit
fit(X, y, sample_weight, solver_type, kernel, random_seed=seed)
File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py", line 251, in _dense_fit
max_iter=self.max_iter, random_seed=random_seed)
File "sklearn/svm/libsvm.pyx", line 59, in sklearn.svm.libsvm.fit (sklearn/svm/libsvm.c:1571)
TypeError: a float is required
made an error and set nu as a string instead of a float.
setting nu=0.05 fixes the problem.

Scipy Interpolate RectBivariateSpline constructor returns an error

I am trying to instantiate a Scipy Interpolate RectBivariateSpline as follows:
import numpy as np
from scipy.interpolate import RectBivariateSpline
x = np.array([1,2,3,4])
y = np.array([1,2,3])
vals = np.array([
[4,1,4],
[4,2,3],
[3,7,4],
[2,4,5]
])
print(x.shape) # (4,)
print(y.shape) # (3,)
print(vals.shape) # (4, 3)
rect_B_spline = RectBivariateSpline(x, y, vals)
However, it returns this error:
Traceback (most recent call last):
File "path/file", line 15, in <module>
rect_B_spline = RectBivariateSpline(x, y, vals)
File "path/file", line 1061, in __init__
ye, kx, ky, s)
dfitpack.error: (my>ky) failed for hidden my: regrid_smth:my=3
Would appreciate any clues as to what the dfitpack error describes and how to resolve.
By default, RectBivariateSpline uses a degree 3 spline. By providing only 3 points along the y-axis it cannot do that. Adding ky=2 to the argument list fixes the problem, as does having more data.

Categories

Resources