📘
Logistic Regression Prediction
MediumClassification
Implement the prediction step of logistic regression.
Given a feature matrix X (without bias), a weight vector w, and a bias b, compute the probability for each sample using:
P(y=1∣x)=σ(x⋅w+b)=1+e−(x⋅w+b)1
Then classify each sample: if P≥0.5, predict 1; otherwise predict 0.
Return a list of tuples [(probability, prediction), ...] with probabilities rounded to 4 decimal places.
Example:
Input:
X = [[1, 2], [3, 4], [-1, -2]] w = [0.5, -0.3] b = 0.1
Output:
[(0.5, 1), (0.5987, 1), (0.5498, 1)]
Reasoning:
- We compute the dot product of each sample in X with the weight vector w and add the bias b:
- For the first sample: 1⋅0.5+2⋅−0.3+0.1=0.5−0.6+0.1=0
- For the second sample: 3⋅0.5+4⋅−0.3+0.1=1.5−1.2+0.1=0.4
- For the third sample: −1⋅0.5+−2⋅−0.3+0.1=−0.5+0.6+0.1=0.2
- Then, we apply the sigmoid function σ(x)=1+e−x1 to each result:
- For the first sample: σ(0)=1+e01=1+11=0.5
- For the second sample: σ(0.4)=1+e−0.41≈0.5987
- For the third sample: σ(0.2)=1+e−0.21≈0.5498
- We classify each sample based on the predicted probability, with P≥0.5 resulting in a prediction of 1, and P<0.5 resulting in a prediction of 0.
- The final output is a list of tuples containing the predicted probabilities rounded to 4 decimal places and the corresponding predictions: (0.5,1),(0.5987,1),(0.5498,1)
Constraints:
- X is a 2D list (n_samples x n_features)
- w is a list of n_features weights
- b is a scalar bias
- Return list of (probability, prediction) tuples
- Probabilities rounded to 4 decimal places
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.