Here is a simple example.
import theano
v = theano.tensor.scalar("variable")
factorial = ?
# Calculate factorial of v , like numpy.math.factorial(v), but it didn't work,
# Actually it should be a integer as a parameter of numpy.math.factorial function
result = theano.function([v], factorial)
There is few useful information on Internet. Something I found like
http://matthewrocklin.com/blog//work/2013/08/14/SymPy-Theano-part-4
which told me it belonged to "the future work", which means there is no solution for this problem.
How could that possible? I mean is there no body need calculate factorial in your theano project?
I had this problem when I designed a RBM with Poisson conditional possibility which needs calculate factorial of visible units in the energy function.
I have found the answer that we use gamma function to solve the factorial problem.
:( Sorry for bothering everybody!
Here is the detail:
https://groups.google.com/forum/#!msg/theano-users/ytqep8AickA/cE7QeJZxXzUJ
So here should be:
import theano
v = theano.tensor.scalar("variable")
factorial = theano.tensor.gamma(v)
# Calculate factorial of v , like numpy.math.factorial(v), but it didn't work,
# Actually it should be a integer as a parameter of numpy.math.factorial function
result = theano.function([v], factorial)
def factorial(x):
y = x-1
temp = x*y
it = y-1
for i in range(it):
y -= 1
temp = temp*y
print temp
Here is the edited solution without the Boolean operators. I know you found another answer but this may be helpful to you as well as others in the future.
Related
Write a function to compute the quantity
F(n) = n^2 Σ i=1 (i^3)
Read the problem as n squared over Sigma, with i = 1 under the sigma and I cubed at the end of the function.
I am not sure how to approach this idea. I tried setting up a function but I do not know how to use a function in Python to compute the problem we were given.
As mentioned above, I am sorry, but I do not know how to approach this problem.
I suppose the expected output here would be some quantity but because I haven't been able to make much progress, I have no clue what to expect exactly. To give more background, I understand how functions work but do not know how to approach this type of problem. Any help/guidance in writing this code would be greatly appreciated.
With a list comprehension:
Use the built-in functions, sum and range
def my_sigma(n_start: int, n_end: int) -> int:
return sum([i**3 for i in range(n_start, (n_end**2) + 1)])
# usage
print(my_sigma(1, 3))
>>> 2025
You can use the Math library to take the powers, and use a for loop for the sigma.
I think this would give you an idea,
for i in range (a , int(math.pow(n, 2))):
list_1.append(int(math.pow(i, 3)))
You can just put this inside a function with two variables a and n a representing the i in the sigma and n representing the n in the sigma.
You can use the sum function for summing up all the elements in the list if that is what you want.
I was wondering if i could make a multiple objective function in PuLP, by doing this Can I make a Min Z = max(a,b,c) in PuLP, however when using this code
ilp_prob = pulp.LpProblem("Miniimize Problem", pulp.LpMinimize)
x = []
if m >3:
return 1,1
for i in range(m):
temp = []
for j in range(len(jobs)):
temp += [pulp.LpVariable("x_%s_%s" %((i+1),(j+1)),0,1, cat = 'Binary')]
x+= [temp]
ilp_prob += max([pulp.lpSum([jobs[j]*x[i][j] for j in range(len(jobs))] for i in range(m))])
for i in range(len(jobs)):
ilp_prob += pulp.lpSum([x[j][i] for j in range(m)])==1
ilp_prob.solve()
It just returns all 1 in x[0], and all 0 in x[0].
I'm pretty sure you can't just use python's (!) max on pulp's internal expressions! Those solvers are working on a very specific problem-specification, LP standard form, where is no concept for that!
The exception would be if pulp would overload this max-function for it's data-structures (don't know if that's possible at all in python), but i'm pretty sure pulp does not support re-formulations like that (there is some needed; as again: the target is the Standard-form).
cvxpy for example does not overload, but introduces customized max-functions, which internally transform your problem.
That being said: i'm surprised your code runs without a critical error. But i'm too lazy to check pulps sources here.
Have a look at the usual LP/IP formulation-guides.
A first idea would be:
target: min (max(a,b,c))
reformulation:
introduce a new variable z
add constraints:
z >= a
z >= b
z >= c
assumption: the objective somehow want's to minimize z (maximizing will get you in trouble as the problem will get unbounded!)
this is the case here, as the final objective for our target would look like:
min(z)
Remark: One has to be careful that the problem will still be linear/convex (depending on the solver). In this case (our simple example; i did not check your whole model) i don't see a problem, but in more complex cases, min(max(complex_expression)) subjective to complex constraints, this might introduce non-convexity (and can't be solved by Conic solvers incl. LP-solvers).
And just throwing a keyword in the ring: your approach/objective sounds a bit like robust-optimization, where usually some worst-case scenario is optimized. Not all multi-objective optimization problems are treating multiple objective-components like that.
Using Sympy, I would like to define a function of one variable where the variable is the upper limit of some integral.
I tried the following, which works
import sympy as sp
def g(a,x):
y = sp.Symbol('y')
expr = sp.Integral( f(y,p), [y,a,x] )
return expr.doit()
However, I ask myself if this is gonna be efficient when evaluated on many points. I have been reading about lambdify and would like to use it for this case, but am not sure how.
I am actually not sure if lambdify is the right way to go. In alternative, one could think of computing the indefinite integral once, and then only apply the limits to evaluate the definite integral.
Let me show an example. I have a function of one variable with some parameters, say a polynomial in y
def f(y, p):
c0,c1,c2=p
return c0+c1*y+c2*y**2
I want to define another function by integrating this polynomial, where the function is going to depend on the upper limit of the integration (Latex because I don't have enough reputation...),
g_{a,p}(x) = \int_{a}^{x} f(y,p)dy
So, in this simple case, g(x) would be polynomial or order 3 which needs to be evaluated between a and x. Once I have g(x), I want to evaluate it on "many" points, so my question is if I can do this efficiently.
I made a naive implementation of the solution and one using sympy.lambdify. Only timed it once, so not the most accurate results. However, using sympy.lambdify seems 100x faster.
Naive implementation
import sympy as sp
import numpy as np
import time
def f(y, p):
c0,c1,c2,c3,c4,c5 = p
return c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + c5*x**5
def g(a,x):
y = sp.Symbol('y')
expr = sp.Integral( f(y,p), [y,a,x] )
return expr.doit()
start = time.clock()
l = []
for x in np.arange(a,b,0.001):
l.append(g(a,x))
end = time.clock()
print end-start
Improved implementation
import sympy as sp
import numpy as np
import time
def f(y, p):
c0,c1,c2,c3,c4,c5 = p
return c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + c5*x**5
x=sp.Symbol('x')
itgx = sp.Integral( f(y,p), [y,a, x] )
start = time.clock()
g = sp.lambdify(x, itgx.doit(), "numpy")
l = g(np.arange(a,b,0.001))
end = time.clock()
print end-start
On my architecture (i7-3770 #3.40GHz, Ubuntu 14.04),
the naive implementation times 12.086627s while the lambdify implementation times 0.054799s, that looks like a significant speed up. Sympy manual also suggests to use lambdify when possible
So my question, which maybe is not clear enough, is:
Is there a better way of doing this kind of computation? If so, please let me know
Of course the lambdified version is faster. Not only is it vectorizing the result over a numpy array rather than using a Python for loop, you're also being very inefficient in the other version by recomputing the integral each time.
I don't see an actual question here. Your lambdified version looks correct. I don't see any issues with it.
First of, I'm sorry if the title is not entirely fitting, I had a hard time finding an appropriate one (which might have also effect my searching efficiency for already asked questions like this :/ ).
The problem is the following. While it is comparably easy to solve coupled ODE's in python with Scipy, I still have to write down my ODE in the form explicitly. For example for a coupled ODE of the form
d/dt(c_0)=a(c_0)+b(c_1) and d/dt(c_1)=c(c_0)
I would set up sth like:
import numpy as np
from scipy.integrate import ode
a=1
b=2
c=3
val=[]
def dC_dt(t, C):
return [a*C[0]+b*C[1],
c*C[0]]
c0, t0 = [1.0,0.0], 0
r = ode(dC_dt).set_integrator('zvode', method='bdf',with_jacobian=False)
r.set_initial_value(c0, t0)
t1 = 0.001
dt = 0.000005
while r.successful() and r.t < t1:
r.integrate(r.t+dt)
val.append(r.y)
However, now I have coupled ODE's of the rough form
d/dt(c_{m,n})=a(c_{m,n})+b(c_{m+1,n-1})+k(c_{m-1,n+1})
with c_{0,0}=1 and I have to include orders with m^2+n^2-mn smaller than a max value.
For a small max, what I did, is using a dictionary to use a notation with two indices and map it on a 1D list
dict_in={'0,0':0,'-1,0':2,...}
and then I entered the ODE for each order
def dC_dt(t,C):
return[a*C[dict_in['0,0']]+b*C[dict_in['1,-1']]...
Now I basically have to do that for some 100 coupled equations, which I ofc do not want to hard code, so I was trying to figure out a way, to realize the ODE's with a loop or sth. However I couldn't yet find a way around the fact of having two indices in my coefficients together with the condition of only including orders with m^2+n^2-mn smaller than a max value.
As I am running in some deadlines, I figured it is time to ask smarter people for help.
Thanks for reading my question!
I had a similar problem. If you fill you dictionary you can just redeclare the function more times inside the loop. This is a silly example of how it works:
dict_in={'0,0':0,'-1,0':2}
for elem in dict_in:
def dC_dt(t,C):
#return[a*C[dict_in['0,0']]+b*C[dict_in['1,-1']]
return dict_in[elem]
t, C = 0, 0
print(dC_dt(t,C))
#r = ode(dC_dt).set_integrator('zvode', method='bdf',with_jacobian=False)
If you need to use more functions together you can use anonymous functions and store them in memory. Another example:
functions_list = list()
for i in range(4):
f = lambda n = i: n
functions_list.append(f)
for j in range(4):
print(functions_list[j]())
You can use a list or a generator too. For example you can write down the value on a txt file and read that with the readline function each time.
As pointed in the comments below, if you use lamda functions you should pay attention to references. See also https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
I am trying to calculate the trimmed mean, which excludes the outliers, of an array.
I found there is a module called scipy.stats.tmean, but it requires the user specifies the range by absolute value instead of percentage values.
In Matlab, we have m = trimmean(X,percent), that does exactly what I want.
Do we have the counterpart in Python?
At least for scipy v0.14.0, there is a dedicated function for this (scipy.stats.trim_mean):
from scipy import stats
m = stats.trim_mean(X, 0.1) # Trim 10% at both ends
which used stats.trimboth inside.
From the source code it is possible to see that with proportiontocut=0.1 the mean will be calculated using 80% of the data. Note that the scipy.stats.trim_mean can not handle np.nan.
(Edit: the context for this answer was that scipy.stats.trim_mean wasn't documented yet. Now that it's publicly available, use that function instead of rolling your own. My answer below is kept for historical purpose.)
You can also implement the whole thing yourself, following the instruction in the MatLab documentation.
Here's the code in Python 2:
from numpy import mean
def trimmean(arr, percent):
n = len(arr)
k = int(round(n*(float(percent)/100)/2))
return mean(arr[k+1:n-k])
Here's a manual implementation using floor from the math library...
def trimMean(tlist,tperc):
removeN = int(math.floor(len(tlist) * tperc / 2))
tlist.sort()
if removeN > 0: tlist = tlist[removeN:-removeN]
return reduce(lambda a,b : a+b, tlist) / float(len(tlist))