I don't think I fully understand the use of intermediate variables in arrays and would love some help with my code.
Along with the error this equation is posted ((-1)*((((((0.95)*(i371)))*(9))-((int_v2)*(4))))), it looks like my objective function
yh = model.Array(model.Intermediate,(10),equation=None)
for i in range(10):
yh[i] = model.Intermediate(x[i]*f[i]*0.1) #x,f are variable arrays of size 10
y1 = model.Array(model.if3, (10), x1=1, x2=0, condition=sum(yh)-d) #d is a constant array of size 10
y2 = model.Array(model.if3, (10), x1=1, x2=0, condition=-1*(sum(yh)-lb)) #lb is a constant array of size 10
model.Equation(sum(x)==10)
model.options.IMODE = 3
model.options.SOLVER = 1
m2 = model.Array(model.Intermediate,(10,10),equation=None)
for i in range(10):
for j in range(10):
m2[i][j] = model.Intermediate(m[i][j]*x[i]*0.1*y1[j]*y2[j]) #m is a 10x10 constant array, i'm trying to multiply every element in a row
#with the corresponding x value, and every element in a column with the corresponding y value
r = model.Array(model.Intermediate,(10),equation=None)
for i in range(10):
r[i]= model.Intermediate(sum(m2[j][i] for j in range(10))) #im trying to get the sum of each column
model.Obj(-1*(0.95*r*c2-x*c1)) #c1,c2 are constant arrays; x is a variable array
model.solve()
Here is a complete script that demonstrates the two issues with your current program.
from gekko import GEKKO
model = GEKKO()
x = model.Array(model.Var,10)
yh = model.Array(model.Intermediate,10,equation=None)
for i in range(10):
yh[i] = model.Intermediate(x[i]**2)
model.Equation(sum(x)==10)
model.Obj(yh)
model.solve()
The first is that you are creating an array of Intermediate types and then creating them again in your loop. This gives the error:
#error: Model Expression
*** Error in syntax of function string: Invalid element: none
Position: 1
none
?
because the first Intermediates that you create have blank equations. You can avoid this error by just defining a list of None values.
yh = [None]*10
for i in range(10):
yh[i] = model.Intermediate(x[i]**2)
The second error is because you are using an array in the objective statement (as you already noted in your answer). This gives the error:
Warning: there is insufficient data in CSV file 136.36.211.159_gk_model0.csv
#error: Model Expression
*** Error in syntax of function string: Missing operator
Position: 2
0,0,0,0,0,0,0,0,0,0
?
As you correctly noted, you can add a summation to add the terms into a single term. You can also have multiple model.Obj() functions or model.Minimize() as a more descriptive version of the same function.
from gekko import GEKKO
model = GEKKO()
x = model.Array(model.Var,10)
yh = [None]*10
for i in range(10):
yh[i] = model.Intermediate(x[i]**2)
model.Equation(sum(x)==10)
model.Minimize(model.sum(yh))
model.solve()
```model.Obj(-1*(0.95*sum(r*c2)-sum(x*c1)))```
solved the issue as the objective function returns one value now not an array
Related
temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
I am stuck in this assignment and unable to find a relevant answer to help.
I’ve used .split(",") and float()
and I am still stuck here.
temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
li = temp.split(",")
def avr(li):
av = 0
for i in li:
av += float(i)
return av/len(li)
print(avr(li))
You can use sum() to add the elements of a tuple of floats:
temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
def average (s_vals):
vals = tuple ( float(v) for v in s_vals.split(",") )
return sum(vals) / len(vals)
print (average(temp))
Admittedly similar to the answer by #emacsdrivesmenuts (GMTA).
However, opting to use the efficient map function which should scale nicely for larger strings. This approach removes the for loop and explicit float() conversion of each value, and passes these operations to the lower-level (highly optimised) C implementation.
For example:
def mean(s):
vals = tuple(map(float, s.split(',')))
return sum(vals) / len(vals)
Example use:
temp = '75.1,77.7,83.2,82.5,81.0,79.5,85.7'
mean(temp)
>>> 80.67142857142858
From this
import sympy as sp
x,y,z = sp.symbols("x y z")
sp.Ep(x,y/z)
To this
#varibles = array
#equation = ????
def solver(variables,equation):
#Looping through variables array and converting variables to sympy objects
for var in variables:
var = sp.symbols(var)
#Generate sympy Equation
equation = sp.Ep(equation)
variables = [x,y,z]
equation = x,y/z #invalid code
solver(variables,equation)
I'm creating a function that is able to take in an equation with x amount of variables and x-1 number of values then solve for the missing variable symbolically then return a numerical answer using the values provided.
I only included a small portion of code where I'm having trouble understanding how to pass through an equation. Any solutions or pointers would be greatly appericated. Thanks.
There are several layers of potential confusion here concerning Python variables and SymPy objects (Symbols) used for variables.
Here is an example of what you are saying:
# 3 variables
syms = x, y, z = var('x:z')
# 2 values
vals = {x:1, y:2}
# an equations
eq = Eq(x, y/z)
# solve for the missing value symbolically
missing = set(syms) - set(vals) # == {z}
solve(eq, missing)
[y/x]
# solve for the missing value after substituting in the known values
solve(eq.subs(vals))
[2]
You could make a solver to accept an equation and then specified values and figure out the missing one and return that value by doing something like this:
>>> def solver(eq, **vals):
... from sympy.core.containers import Dict
... from sympy.solvers.solvers import solve
... free = eq.free_symbols
... vals = Dict(vals)
... x = free - set(vals)
... if len(x) != 1:
... raise ValueError('specify all but one of the values for %s' % free)
... x = x.pop()
... return solve(eq.subs(vals), x, dict=True)
...
>>> solver(eq, x=1, z=2)
[{y: 2}]
Does that give you some ideas of how to continue?
i keep seeing the following in Python and i don't quite understand how it is working:
...
for label in range(1,5):
indices = (y == label)
mu[label] = np.mean(x[indices,:], axis=0)
...
specifically y==label i expect to assign a boolean value to indices but then that var is used as a slice subscript?
appreciate any insight.
I know this question has been answered. But I do not understand something in the code. I am trying to find unique rows in a numpy array. The solution using structured arrays given as follows:
x is your input array
y = np.ascontiguousarray(x).view(np.dtype((np.void, x.dtype.itemsize * x.shape[1])))
_, idx = np.unique(y, return_index=True)
unique_result = x[idx]
My question is that why we need this line:
y = np.ascontiguousarray(x).view(np.dtype((np.void, x.dtype.itemsize * x.shape[1])))
why cannot we use only:
_, idx = np.unique(x, return_index=True)
unique_result = x[idx]
You are asking a couple of questions. I am not sure where you found the solution you mention but I will explain why that probably was done. This:
_, idx = np.unique(x, return_index=True)
unique_result = x[idx]
does not work to find unique rows in an np.array because np.unique will flatten the given array if no axis is given. I then imagine that the y = np.ascontiguousarray(x).view(np.dtype((np.void, x.dtype.itemsize * x.shape[1]))) line was added so that, even when flattened, the inner arrays, which they are trying to compare, would each be represented as individual items (of type void). Then, using np.unique would indeed return unique rows.
However, I do not see why any of that is necessary. You can just use unique directly while passing the axis you are interested in:
unique_result = np.unique(x, axis=0)
I am seriously stuck with something for ages now. I need some help.
I am running a theano conv network on GPU.
The network has a loss function as such
def mse(x, t):
return T.mean((x - t) ** 2)
Here x is the predicted value of a rectified liner unit and t is the expected value.
Now for a particular learning problem I am trying to modify the function such that I want to threshold the value of x. So essentially something simple as this
x[x>ts] = ts
But I am really struggling with this. I tried so many things
ts = 0.91
Y = T.vector()
#x_update = (x, T.set_subtensor(x[(x > ts).eval()], Y))
#f = function([Y], updates=[x_update])
#v=np.empty(len((x > ts).eval()))
#v.fill(ts)
#f(v)
#x.shape.eval()
x_arr = x.flatten()
print type(x_arr)
print type(t)
print type(x)
#print T.shape(x_arr).eval()
#print x.shape.eval()
#print x_arr.shape.eval()
#print t.shape.eval()
#print x.eval()
#print x_arr.get_value()
#x_newarr = x_arr.eval()
#x_newarr[x_newarr>ts] = ts
#x = T.shared(x_newarr)
return T.mean((x - t) ** 2)
Apart from the three prints, which all print <class 'theano.tensor.var.TensorVariable' > everything else gives me error.
So I am at my wits end how to do this simple stuff.
Is it because this stuff is on GPU ?
I did test the code on local python prompt, by constructing a numpy array and converting it into a tensor shared variable. The different stuff above works.
But I am conscious that the type is theano.tensor.sharedvar.TensorSharedVariable and not theano.tensor.var.TensorVariable.
I would really appreciate if some one gives me a helping hand here.
Regards
Please find the answer to this question given by pascal at
https://groups.google.com/forum/#!topic/theano-users/cNnvw2rUHc8
The failures are correct because the input values are not being provided at the time the function is being called, since it is symbolic.
The answer is to use T.minimum(x,threshold)