HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Interpolate then maximize

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
interpolatemaximizethen

Problem

I need to optimize the following function:

$$ \max_{a',\ m'}\ f(a, m, e, m', a') $$

I have approximated \$f\$ with a grid \$F\$, which has a shape \$(nA, nM, nE, nM, nA)\$. Now, I want to interpolate over the last two dimensions (the ones I need to maximize over), and then maximize.

The following code block is the one I want comments on. It looks to be too complicated and to inefficient to be the best way to do this. For example, there should be a way such that I do not need to iterate over all the given states (dimensions 0–2). I'm open for any input to improve it.

# takes grid indices (first three dimensions) idx and interpolates on V
def interpolateV(idx, V, Grid, Param):
    from scipy.interpolate import interp2d

    f = interp2d(Grid.mGrid, Grid.aGrid, V[idx])
    return f

(...)
    # the code in a different function
    v1Max = empty(s2)
    v1ArgMaxA = empty(s2)
    v1ArgMaxM = empty(s2)
    from scipy import optimize
    for idx in np.ndindex(V0[..., 0,0]):
        V0i = interpolateV(idx, V0, Grid, Param)
        x, f, d = optimize.fmin_l_bfgs_b(lambda x: -V0i(x[0], x[1]), array([1, 1]), bounds=[(Grid.aMin, Grid.aMax), (Grid.mMin, Grid.mMax)], approx_grad=True)
        v1Max[idx] = f
        v1ArgMaxA[idx], v1ArgMaxM[idx] = x


This is part of a way more complex project. The next code block is added in order to make the code reproducable. Please refrain from commenting structure and code in this block, as it is messy on purpose (in order to make it as short as possible).

I reduced state size here to the minimum that makes sense, and pasted the matrix V0 in the last code block, as it would be too much code to add creation code here. Maximizer does for now return (0,1) for all states, this should be correct — I think (do not judge the following, poor code already sad about having been conglomerated).

```
from scipy.stats import norm
from numpy import *
# i know this is bad, I'm working with code from several instances here - will clean up

Solution

It's not useful to have class Parameters just store constants...simply place those constants at the top of the code, after the import statements.

Place all of your import statements at the beginning of the code. They can be accessed by any functions or methods below them.

I'd combine the lines

yMax = m*sdY
yMin = -yMax


to

yMax, yMin = m*sdY, -1*(m*sdY)


which seems a bit more readable to me.

Run the script with a __main__ statement at the end.

if __name__=='__main__':
    grid = Grids()

Code Snippets

yMax = m*sdY
yMin = -yMax
yMax, yMin = m*sdY, -1*(m*sdY)
if __name__=='__main__':
    grid = Grids()

Context

StackExchange Code Review Q#57577, answer score: 2

Revisions (0)

No revisions yet.