What is the numpy way to conditionally merge arrays?

457 views python
2

I have two numpy arrays (1000,) filled with predictions from two models:

pred_1 = model_1.predict(x_test)
pred_2 = model_2.predict(x_test)

model_1 is attractive due to extremely low FP, but consequently high FN.

model_2 is attractive due to overall accuracy and recall.

How can I conditionally apply predictions to take advantage of these strengths and weaknesses?

I'd like to take all positive (1) predictions from the first model, and let the second model deal with the rest.

Essentially I'm looking for something like this:

final_pred = model_1.predict() if model_1.predict() > 0.5 else model_2.predict()

This fails: The truth value of an array with more than one element is ambiguous.

What is the numpy way to combine these arrays as above?

answered question

2 Answers

8

You can try a list comprehension as following and then cast the list to array using np.array. You loop over the independent variable, here x_test, and then for each value of x_test, you compute the model prediction from two models and depending on the if condition, you store the output.

final_pred = np.array([model_1.predict(i) if model_1.predict(i) > 0.5 else model_2.predict(i) for i in x_test])

posted this
8

You're looking for numpy.where:

a = model_1.predict(x_test)
b = model_2.predict(x_test)

out = np.where(a > 0.5, a, b)

posted this

Have an answer?

JD

Please login first before posting an answer.