Convert Odds to Probabilities in NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
In logistic regression, the odds of an event with probability $p$ are $p / (1 - p)$, computed by `prob_to_odds(p) = p / (1 - p)`. Implement `odds_to_prob(odds)`, the inverse of `prob_to_odds`. Given a 1-D `float64` NumPy array of non-negative odds, return a new `float64` array of the same shape where element `i` is `odds[i] / (1 + odds[i])`.
The function must:
- leave the input array unchanged;
- compute element-wise, ideally vectorized;
- return values that lie in [0, 1) for every valid input;
- round-trip with `prob_to_odds`: converting probabilities to odds and back returns the original probabilities, up to floating-point rounding.
Example:
```python
odds = np.array([0.0, 0.25, 1.0, 3.0, 4.0, 9.0])
odds_to_prob(odds)
# array([0. , 0.2, 0.5, 0.75, 0.8, 0.9])
```
```hint Watch the pitfalls
An expression like `a / b` allocates a new array, while `a /= b` writes into the caller's buffer. Also try your expression on very large and very small odds before you trust it.
```
### Constraints & Assumptions
- The input is a 1-D `float64` NumPy array and may be empty.
- Valid odds are finite and non-negative.
- The output has the same shape and dtype as the input.
### What a Strong Answer Covers
- Deriving the inverse formula from the definition of odds and explaining why the result stays in [0, 1).
- A vectorized implementation that returns a new array and never writes into the input.
- How to test the round trip with `prob_to_odds` given floating-point rounding.
- Edge cases: zero odds, an empty array, very large or infinite odds, and negative or NaN input.
### Follow-up Questions
- A logistic regression model outputs log-odds. How would you turn those into probabilities without overflow?
- Why is `odds / (1 + odds)` more accurate for tiny odds than the algebraically equal `1 - 1 / (1 + odds)`?
- What should the function return for `np.inf`, and how would you handle it without a warning?
- How would you reject negative or NaN odds without adding a Python loop?
Overview: Implement a vectorized NumPy function that converts an array of non-negative odds into probabilities, the inverse of the logistic regression odds transform. It tests deriving the inverse formula, returning a new array without mutating the input, and handling floating-point edge cases such as very large or tiny odds.