patternpythonMinor
Plotting a 2D iso-probability curve
Viewed 0 times
plottingcurveprobabilityiso
Problem
I have a library function that returns a pair of two numbers like this
(Actually, it is a function that returns predicted probabilities of two classes for some object, but it doesn't matter, so I created an artificial one.) I want to draw contours where the difference between two numbers returned by
I have the following possibilities:
This approach is concise but I have to introduce
Another way:
I have to introduce temporary two-dimensional list and this approach is longer.
Are there any ideas how to do it better (more concise and readable)?
def library_function(x0, x1):
return x0**2 + x1**2, 10*x0*x1 + 1(Actually, it is a function that returns predicted probabilities of two classes for some object, but it doesn't matter, so I created an artificial one.) I want to draw contours where the difference between two numbers returned by
library_function is zero. To do so, I have to create a two-dimensional list (or array) with the differences.I have the following possibilities:
X0 = np.linspace(-10, 10, 200)
X1 = np.linspace(-10, 10, 200)
results = [[(lambda u: u[0]-u[1])(library_function(x0, x1))
for x0 in X0] for x1 in X1]
plt.contour(X0, X1, results, [0])This approach is concise but I have to introduce
lambda which seem to be considered not so Pythonic.Another way:
values = [[library_function(x0, x1) for x0 in X0] for x1 in X1]
results = [[a-b for a, b in row] for row in values]I have to introduce temporary two-dimensional list and this approach is longer.
Are there any ideas how to do it better (more concise and readable)?
Solution
Since you are using NumPy, you should deal with grids the NumPy way instead of performing list comprehensions.
I wouldn't try to get too clever with the lambdas.
Also, since the grid happens to be a square, you could use
def probability_diff(x0, x1):
probs = library_function(x0, x1)
return probs[0] - probs[1]
results = np.vectorize(probability_diff)(X0[:, np.newaxis], X1)I wouldn't try to get too clever with the lambdas.
Also, since the grid happens to be a square, you could use
X0 again instead of defining X1.Code Snippets
def probability_diff(x0, x1):
probs = library_function(x0, x1)
return probs[0] - probs[1]
results = np.vectorize(probability_diff)(X0[:, np.newaxis], X1)Context
StackExchange Code Review Q#148039, answer score: 3
Revisions (0)
No revisions yet.