I have written the following code but it fails with a ValueError.
from numpy import *
from pylab import *
t = arange(-10, 10, 20/(1001-1))
x = 1./sqrt(2*pi)*exp(power(-(t*t), 2))
Specifically, the error message I'm receiving is:
ValueError: a <= 0
x = 1./sqrt(2*pi)*exp(power(-(t*t), 2))
File "mtrand.pyx", line 3214, in mtrand.RandomState.power (numpy\random\mtrand\mtrand.c:24592)
Traceback (most recent call last):
File "D:\WinPython-64bit-3.4.4.3Qt5\notebooks\untitled1.py", line 6, in <module>
Any idea what the issue might be here?
Both numpy and pylab define a function called power, but they are completely different. Because you imported pylab after numpy using import *, the pylab version is the one you end up with. What is pylab.power? From the docstring:
power(a, size=None)
Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
The moral of the story: don't use import *. In this case, it is common to use import numpy as np:
import numpy as np
t = np.arange(-10, 10, 20/(1001-1))
x = 1./np.sqrt(2*np.pi)*np.exp(np.power(-(t*t), 2))
Further reading:
Why is "import *" bad?
Idioms and Anti-Idioms in Python (That's in the Python 2 documentation, but it also applies to Python 3.)
Related
According to Python Documentation a TypeError is defined as
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
exception TypeError
The reason I got this Error was because my code looked like this:
import math as m
import pylab as pyl
import numpy as np
#normal distribution function
def normal(x,mu,sigma):
P=(1/(m.sqrt(2*m.pi*sigma**2)))*(m.exp((-(x-mu)**2)/2*sigma**2))
return P
#solution
x = np.linspace(-5,5,1000)
P = normal(x,0,1)
#plotting the function
pyl.plot(x,P)
pyl.show()
P=(1/(m.sqrt(2***m**.pisigma2)))(**m.exp((-(x-mu)2)/2*sigma2))
Notice the m. - This is incorrect, because math. can only handle scalars. And the Error said that a TypeError had occurred.
np. (Numpy) can handle scalers as well as arrays and the problem is solved.
The right code looks like this:
import math as m
import pylab as pyl
import numpy as np
# normal distribution function
def normal(x,mu,sigma):
P = (1/(np.sqrt(2*np.pi*sigma**2))) * (np.exp((-(x-mu)**2)/2*sigma**2))
return P
# solution
x = np.linspace(-5,5,1000)
P = normal(x,0,1)
# plotting the function
pyl.plot(x,P)
pyl.show()
In the end we get a great normal distribution function that looks like this:
This Error occurred in Spyder IDE.
I use (just the standards) Win10, Anaconda-2018.12, Python-3.7, MKL-2019.1, mkl-service-1.1.2, Jupyter ipython-7.2. see here e.g.
I"m wondering why the following syntax works for import statements with the numpy modules but does not work for scipy or sklearn modules:
import scipy as sp
import numpy as np
A = np.random.random_sample((3, 3)) + np.identity(3)
b = np.random.rand((3))
x = sp.sparse.linalg.bicgstab(A,b)
> AttributeError Traceback (most recent call
> last) <ipython-input-1-35204bb7c2bd> in <module>()
> 3 A = np.random.random_sample((3, 3)) + np.identity(3)
> 4 b = np.random.rand((3))
> ----> 5 x = sp.sparse.linalg.bicgstab(A,b)
> AttributeError: module 'scipy' has no attribute 'sparse'
or with sklearn
import sklearn as sk
iris = sk.datasets.load_iris()
> AttributeError Traceback (most recent call
> last) <ipython-input-2-f62557c44a49> in <module>()
> 2 import sklearn as sk
> ----> 3 iris = sk.datasets.load_iris() AttributeError: module 'sklearn' has no attribute 'datasets
This syntax however does work (but are for rare commands not really lean):
import sklearn.datasets as datasets
iris = datasets.load_iris()
and
from scipy.sparse.linalg import bicgstab as bicgstab
x = bicgstab(A,b)
x[0]
array([ 0.44420803, -0.0877137 , 0.54352507])
What type of problem is that ? Could it be eliminated with reasonable effort ?
The "problem"
The behavior you're running into is actually a feature of Scipy, though it may seem like a bug at first glance. Some of the subpackages of scipy are quite large and have many members. Thus, in order to avoid lag when running import scipy (as well as to save on usage of system memory), scipy is structured so that most subpackages are not automatically imported. You can read all about it in the docs right here.
The fix
You can work around the apparent problem by exercising the standard Python import syntax/semantics a bit:
import numpy as np
A = np.random.random_sample((3, 3)) + np.identity(3)
b = np.random.rand((3))
import scipy as sp
# this won't work, raises AttributeError
# x = sp.sparse.linalg.bicgstab(A,b)
import scipy.sparse.linalg
# now that same line will work
x = sp.sparse.linalg.bicgstab(A,b)
print(x)
# output: (array([ 0.28173264, 0.13826848, -0.13044883]), 0)
Basically, if a call to sp.pkg_x.func_y is raising an AttributeError, then you can fix it by adding a line before it like:
import scipy.pkg_x
Of course, this assumes that scipy.pkg_x is a valid scipy subpackage to begin with.
from numpy import *
from pylab import *
from scipy import *
from scipy.signal import *
from scipy.stats import *
testimg = imread('path')
hist = hist(testimg.flatten(), 256, range=[0.0,1.0])[0]
hist = hist + 0.000001
prob = hist/sum(hist)
entropia = -1.0*sum(prob*log(prob))#here is error
print 'Entropia: ', entropia
I have this code and I do not know what could be the problem, thanks for any help
This is an example of why you should never use from module import *. You lose sight of where functions come from. When you use multiple from module import * calls, one module's namespace may clobber another module's namespace. Indeed, based on the error message, that appears to be what is happening here.
Notice that when log refers to numpy.log, then -1.0*sum(prob*np.log(prob)) can be computed without error:
In [43]: -1.0*sum(prob*np.log(prob))
Out[43]: 4.4058820963782122
but when log refers to math.log, then a TypeError is raised:
In [44]: -1.0*sum(prob*math.log(prob))
TypeError: only length-1 arrays can be converted to Python scalars
The fix is to use explicit module imports and explicit references to functions from the module's namespace:
import numpy as np
import matplotlib.pyplot as plt
testimg = np.random.random((10,10))
hist = plt.hist(testimg.flatten(), 256, range=[0.0,1.0])[0]
hist = hist + 0.000001
prob = hist/sum(hist)
# entropia = -1.0*sum(prob*np.log(prob))
entropia = -1.0*(prob*np.log(prob)).sum()
print 'Entropia: ', entropia
# prints something like: Entropia: 4.33996609845
The code you posted does not produce the error, but somewhere in your actual code log must be getting bound to math.log instead of numpy.log. Using import module and referencing functions with module.function will help you avoid this kind of error in the future.
import math
import matplotlib
import numpy as np
from numpy import linspace
tmax=10.0
n=2000
G=4
D=-1
m=2
t=np.linspace (0,400,n+1)
phi=10
dphi=delta=phi_dot=np.linspace(0,400,n+1)
def f(delta_dot,t):
return ((G)*(D*delta+m))
def iterate (func,phi,delta,tmax,n):
dt=tmax/(n-1)
t=0.0
for i in range(n):
phi,delta = func (phi,delta,t,dt)
t += dt
return phi
def rk_iter(phi,delta,t,dt):
k1=f(t,phi)
k2=f(t+dt*0.5,phi+k1*0.5*dt)
k3=f(t+dt*0.5,phi*k2*0.5*dt)
k4=f(t*dt,phi*k3*dt)
delta +=dt*(k1+2*k2+2*k3+k4)/6
k1=k2=k3=k4=delta=phi_dot
phi += dt*(k1+2*k2+2*k3+k4)/6
return phi,delta
runge_kutta = lambda delta, phi,tmax,n:iterate(rk_iter,delta,phi,tmax,n)
def plot_result (delta,phi,tmax,n):
dt=tmax/(n-1)
error_rk=[]
r_rk=[]
t=0.0
phi=phi_rk=phi
delta=delta_rk=delta
for i in range(n):
phi_rk,delta_rk=rk_iter(phi_rk,delta_rk,t,dt=tmax/(n-1))
t+=dt
_plot("error.png","Error","time t", "error e",error_rk)
def _plot(title,xlabel,ylabel,rk):
import matplotlib.pyplot as plt
plt.title(title)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.plot(rk,"r--",label="Runge-Kutta")
plt.legend(loc=4)
plt.grid(True)
plt.plot(runge_kutta,t)
print "runge_kutta=", runge_kutta(phi,delta,tmax,n)
print "tmax=",t
I have no idea how to get the function plt.show() to work. What do I have to do to open a plot window?
You haven't defined f; instead, f is being imported from matplotlib by the statement from matplotlib import *:
In [10]: import matplotlib
In [11]: matplotlib.f
Out[11]: Forward: "a"
In [12]: matplotlib.f(1,1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-5843007d7dbe> in <module>()
----> 1 matplotlib.f(1,1)
TypeError: __call__() takes at most 2 arguments (3 given)
You will save yourself many headaches like this in the future if you never use the * form of the import statement in your scripts. For example, instead of from math import *, use one of these two forms:
import math
# Now refer to math.sin, math.pi, etc.
or, explicilty import only the names that you will use:
from math import sin, pi
At no point do you call the plot_result procedure. And even if you called it, you do not fill the rk and error_rk lists. You could simply use the result from the runge_kutta call,...
As commented in the other, duplicate post, you define the system equation as f(y,t) but use it as f(t,y).
There is some confusion in the usage of delta, sometimes it is the integration variable, sometimes the rk4-step update.
In the rk4-step, there are some misplaced multiplications where there should be additions. And the line
k1=k2=k3=k4=delta=phi_dot
is complete nonsense and invalidates the previous computations and makes the rk4-update in the next step meaningless.
Remove the imports of math and linspace, neither is used in the code. Move the aliasing of plt to the top and merge it with the unnecessary import of matplotlib.
I have tried to find the answer to this question, maybe its very easy and thats why i cant.
If I have made a Gaussian function and I want to plot it with Matplotlib.pyplot.plot, how can i do that with float values. I.e. values from -20<=x<=20 in increments of 0.1
import matplotlib.pyplot as plt
import math
from math import exp
import numpy
#Parameters for the Gaussian
A=1
c=10
t=0
a=1
x=[]
p=-20.
while p<=20:
x.append(p)
p+=0.1
def Gaussian(A,c,t,a,x):
return A*exp(-((c*t-x)^2 /(4*a*c^2)))
plt.plot(x,Gaussian(A,c,t,a,x))
plt.show()
The Error i get is:
Traceback (most recent call last):
File "C:--------/Gaussian Function.py", line 21, in <module>
plt.plot(x,Gaussian(A,c,t,a,x))
File "C:--------/Gaussian Function.py", line 19, in Gaussian
return A*exp(-((c*t-x)^2 /(4*a*c^2)))
TypeError: unsupported operand type(s) for -: 'int' and 'list'
The problem has nothing to do with matplotlib. You will get the same error if you just call Gaussian(A, c, t, a, x) without using matplotlib at all. Your function accepts an argument x that is a list, and then tries to do stuff like c*t-x. You can't subtract a list from a number. As the error message suggests, you should probably make x a numpy array, which will allow you to do these kinds of vectorized operations on it.
There are some mistakes in your code. The corrected one is below:
import matplotlib.pyplot as plt
import numpy as np
#Parameters for the Gaussian
A, c, t, a = 1, 10, 0, 1
x = np.arange(-20,20,0.1) #use this instead
def Gaussian(A,c,t,a,x):
return A*np.exp(-((c*t-x)**2/(4*a*c**2))) #power in Python is ** not ^
plt.plot(x,Gaussian(A,c,t,a,x))
plt.show()
and result is: