Related
I have been trying to get over this error for a while and can't quite find a way to fix it. I'm trying to minimize a function, but whenever I call it I get the error in the title. I've looked at several other posts and have tried several different tactics, but no dice. here's the snippet in question here:
def objective_func(a, x_sum,y_sum):
alpha_sum = np.sum(a)
alpha_dot_sum= np.sum(np.dot(a[i],a[j]) for i in range(len(a)) for j in range(len(a)))
return (1/2) * (x_sum*y_sum*alpha_dot_sum)-alpha_sum
def Dual_SVM(data,c,a):
inputs = []
for example in data:
inputs.append(example[0:5])
outputs = []
for example in data:
outputs.append(example[len(example)-1])
bound = [(0,c)]
cons_function = np.sum(a*outputs)
cons = ({'type':'eq','fun':cons_function})
# inputs = []
x_sum= np.sum(np.dot(inputs[i],inputs[j]) for i in range(len(inputs)) for j in range(len(inputs)))
y_sum= np.sum(np.dot(outputs[i],outputs[j]) for i in range(len(outputs)) for j in range(len(outputs)))
sol = minimize(objective_func,x0=a,args=(x_sum,y_sum,),method='SLSQP',constraints=cons,bounds=bound)
return sol
Any feedback on this would be greatly appreciated. I know that the first argument needs to be a function and not just a function call, but I feel like I'm following the proper syntax. Not sure what to do here.
Fixed it. The problem was that cons_function was returning as a float, and not a function. A lambda function in its place fixed the problem.
Ive been working on some code recently for a project in python and im confused by the output im getting from this code
def sigmoid(input_matrix):
rows = input_matrix.shape[0]
columns = input_matrix.shape[1]
for i in range(0,rows):
for j in range(0,columns):
input_matrix[i,j] = (1 / (1 + math.exp(-(input_matrix[i,j]))))
return input_matrix
def feed_forward(W_L_1 , A_L_0 , B_L_1):
weighted_sum = np.add(np.dot(W_L_1,A_L_0), B_L_1)
activation = sigmoid(weighted_sum)
return [weighted_sum,activation]
a = np.zeros((1,1))
b = feed_forward(a,a,a)
print(b[0])
print(b[1])
when I print both b[0] and b[1] give values of .5 even though b[0] should equal 0. Also in addition to this when I place the '''weighted_sum = np.add(np.dot(W_L_1,A_L_0), B_L_1)''' again after the 'actvation' line it provides the correct result. Its as if the 'activation' line has changed the value of the weighted sum value.
Was wondering if anyone could spread some light on this I can work around this but am interested as to why this is happening. Thanks!!
Inside sigmoid, you're changing the value of the matrix passed as parameter, in this line:
input_matrix[i,j] = ...
If you want to prevent this from happening, create a copy of the matrix before calling sigmoid, and call it like this: sigmoid(copy_of_weighted_sum).
I am trying to minimize ‖Ax−b‖ through the scipy.optimize.fmin function. The data we use is:
A = np.row_stack([[1,1,2],[1,2,1],[2,1,1],[2,2,1]])
B = np.row_stack([[1],[-1],[1],[-1]])
x is found by x=(AtA)^(−1)Atb, and below is my code for this task.
def find_x(A,B):
At = np.transpose(A) # Transpose A
AtA = np.matmul(At, A) # Multiply A with At
return np.matmul(np.matmul(np.linalg.inv(AtA),At),B)
The assigntment says that I should compare this result with the result of scipy.optimize.fmin(), and from what I have read I need a object/ function for fmin to solve. But I don't really get how I would write the code for that function without it containing x, which is the vector I want to find through the optimization.
I've tried to do the basic thing of defining a function like this:
def f(x):
k = np.subtract(np.matmul(A, x), B)
return np.linalg.norm(k)
And the run it through:
def fmin(x0):
return scipy.optimize.fmin(f(x),x0)
where x0 is some initial guess (same shape as the result from find_x), but I only get a error message "'numpy.float64' object is not callable"
I have a question regarding my code (sorry if it is really easy or stupid, I have never coded before and tried this for a project). I tried running a probability weighting function for certain probability vector. I however get an error and I do not know how to fix it. When i run the argument of the function first seperatly and then call it in the function it works, but why does it not work in the function itself?
Code Below
I hope you can help me.
Thanks a lot!
import numpy as np
p = np.arange(0.01, 1, 0.01) # probalities equaly spread between 0 & 1 in steps of 0.01
alpha_1 = 0.5
alpha = np.zeros((1, 99)) + alpha_1 # vector of same length as p with all entries being 0.5
term_in_exopnential_of_weighting_function = - (- np.log(p))**alpha
w = np.exp(term_in_exopnential_of_weighting_function) # weighted probability function
# probability weighting function
#w(p)=np.exp(-(- np.log(p))**alpha)
# --> error, but why?`
It looks like what you're trying to do is to create a function which is named w. In Python the syntax for a function definition is
def f(a, b, c):
# do something here
result = <something involving a, b, and c>
return result
Then you can call the function as f(1, 2, 3) or whatever for a, b, and c.
In the example you gave, I think maybe what you need is
>>> def w(alpha, p):
... return np.exp(-(- np.log(p))**alpha)
...
Where >>> is the Python interpreter input prompt. Note that the function body must be indented, as enforced by the interpreter. The ... with nothing following it means I just hit the Enter key without typing anything. With that definition of w, I get the following result, given alpha and p as you specified:
>>> w(alpha, p)
array([[0.116955 , 0.13836178, 0.15372645, 0.16627328, 0.17713938,
0.18687366, 0.19578782, 0.20407777, 0.21187567, 0.21927533,
0.2263461 , 0.23314086, 0.23970099, 0.24605961, 0.25224365,
0.25827542, 0.26417363, 0.26995416, 0.27563063, 0.28121487,
0.28671721, 0.29214677, 0.29751164, 0.30281908, 0.30807562,
0.31328717, 0.31845916, 0.32359653, 0.32870387, 0.33378542,
0.33884514, 0.34388676, 0.34891376, 0.35392947, 0.35893704,
0.36393949, 0.36893972, 0.37394054, 0.37894464, 0.38395468,
0.38897324, 0.39400286, 0.39904606, 0.40410531, 0.40918309,
0.41428186, 0.41940411, 0.42455233, 0.42972903, 0.43493677,
0.44017815, 0.44545582, 0.45077251, 0.45613099, 0.46153416,
0.466985 , 0.4724866 , 0.47804216, 0.48365505, 0.48932878,
0.49506703, 0.50087369, 0.50675283, 0.5127088 , 0.51874619,
0.52486989, 0.53108512, 0.53739747, 0.54381293, 0.55033797,
0.55697957, 0.56374529, 0.57064336, 0.57768275, 0.58487331,
0.59222586, 0.59975235, 0.60746605, 0.61538177, 0.62351608,
0.63188769, 0.64051783, 0.64943073, 0.65865431, 0.66822097,
0.67816868, 0.68854243, 0.69939617, 0.71079551, 0.72282159,
0.73557672, 0.74919294, 0.76384569, 0.77977671, 0.79733511,
0.81705854, 0.8398553 , 0.86750307, 0.90461 ]])
I am new to SymPy and Python in general, and I am currently working with Python 2.7 and SymPy 0.7.5 with the objective to:
a) read a system of differential equations from a text file
b) solve the system
I already read this question and this other question, and they are almost what I am looking for, but I have an additional issue: I do not know in advance the form of the system of equations, so I cannot create the corresponding function using def inside the script, as in this example. The whole thing has to be managed at run-time.
So, here are some snippets of my code. Suppose I have a text file system.txt containing the following:
dx/dt = 0.0387*x - 0.0005*x*y
dy/dt = 0.0036*x*y - 0.1898*y
What I do is:
# imports
import sympy
import scipy
import re as regex
# define all symbols I am going to use
x = sympy.Symbol('x')
y = sympy.Symbol('y')
t = sympy.Symbol('t')
# read the file
systemOfEquations = []
with open("system.txt", "r") as fp :
for line in fp :
pattern = regex.compile(r'.+?\s+=\s+(.+?)$')
expressionString = regex.search(pattern, line) # first match ends in group(1)
systemOfEquations.append( sympy.sympify( expressionString.group(1) ) )
At this point, I am stuck with the two symbolic expressions inside the systemOfEquation list. Provided that I can read the initial conditions for the ODE system from another file, in order to use scipy.integrate.odeint, I would have to convert the system into a Python-readable function, something like:
def dX_dt(X, t=0):
return array([ 0.0387*X[0] - 0.0005*X[0]*X[1] ,
-0.1898*X[1] + 0.0036*X[0]*X[1] ])
Is there a nice way to create this at run-time? For example, write the function to another file and then import the newly created file as a function? (maybe I am being stupid here, but remember that I am relatively new to Python :-D)
I've seen that with sympy.utilities.lambdify.lambdify it's possible to convert a symbolic expression into a lambda function, but I wonder if this can help me...lambdify seems to work with one expression at the time, not with systems.
Thank you in advance for any advice :-)
EDIT:
With minimal modifications, Warren's answer worked flawlessly. I have a list of all symbols inside listOfSymbols; moreover, they appear in the same order as the columns of data X that will be used by odeint. So, the function I used is
def dX_dt(X, t):
vals = dict()
for index, s in enumerate(listOfSymbols) :
if s != time :
vals[s] = X[index]
vals[time] = t
return [eq.evalf(subs=vals) for eq in systemOfEquations]
I just make an exception for the variable 'time' in my specific problem. Thanks again! :-)
If you are going to solve the system in the same script that reads the file (so systemOfEquations is available as a global variable), and if the only variables used in systemOfEquations are x, y and possibly t, you could define dX_dt in the same file like this:
def dX_dt(X, t):
vals = dict(x=X[0], y=X[1], t=t)
return [eq.evalf(subs=vals) for eq in systemOfEquations]
dX_dt can be used in odeint. In the following ipython session, I have already run the script that creates systemOfEquations and defines dX_dt:
In [31]: odeint(dX_dt, [1,2], np.linspace(0, 1, 5))
Out[31]:
array([[ 1. , 2. ],
[ 1.00947534, 1.90904183],
[ 1.01905178, 1.82223595],
[ 1.02872997, 1.73939226],
[ 1.03851059, 1.66032942]]