Fix Prediction Code Quiz Calculator

Find subtle prediction bugs across advanced code scenarios. Choose precise fixes and review detailed explanations. Strengthen deployment decisions with practical scoring and targeted feedback.

Advanced Prediction Code Debugging Quiz

Inspect each snippet carefully. Choose the strongest production-safe correction.

0 of 18 answered
Time: 20:00
Question 1 3 points
Preprocessing

Why does this prediction code produce unstable results after every request?

scaler = StandardScaler()
X_live = scaler.fit_transform(request_rows)
prediction = model.predict(X_live)
Question 2 2 points
Shapes

A single sample causes a shape error. Which repair is correct?

sample = np.array([42, 7.5, 1])
prediction = model.predict(sample)
Question 3 3 points
Probability

The application needs the positive-class probability. What should replace the final line?

proba = classifier.predict_proba(X_live)
risk = proba[0]
Question 4 3 points
Data Integrity

The model receives correct values but wrong predictions. Which fix protects feature order?

payload = {'income': 90000, 'age': 38, 'debt': 12000}
X_live = np.array(list(payload.values()))
prediction = model.predict(X_live.reshape(1, -1))
Question 5 3 points
Preprocessing

An unseen category crashes the encoder. Which production fix is strongest?

encoder = OneHotEncoder()
X_train = encoder.fit_transform(train[['city']])
X_live = encoder.transform(live[['city']])
Question 6 3 points
Framework Mode

Dropout remains active during PyTorch predictions. Which repair is required?

model = torch.load('model.pt')
output = model(batch)
Question 7 2 points
Preprocessing

The target was trained with a logarithmic transform. Which output repair is correct?

y_train_log = np.log1p(y_train)
model.fit(X_train, y_train_log)
y_pred = model.predict(X_live)
Question 8 3 points
Probability

A fraud model uses unequal error costs. What is wrong with this decision code?

probability = model.predict_proba(X_live)[:, 1]
flag = probability >= 0.50
Question 9 3 points
Shapes

Which correction returns one class per sequence from logits shaped batch, time, classes?

logits = model(tokens)
predicted = torch.argmax(logits, dim=1)
Question 10 2 points
Data Integrity

Why can this batch code attach predictions to incorrect customers?

clean = customers.dropna().sort_values('income')
preds = model.predict(clean[features])
customers['prediction'] = preds
Question 11 3 points
Deployment

The service loads a newer model but an older scaler. Which safeguard prevents this?

model = joblib.load('model_v8.pkl')
scaler = joblib.load('scaler_v6.pkl')
Question 12 2 points
Data Integrity

A web form submits numeric values as strings. Which repair is safest?

age = request.form['age']
income = request.form['income']
X_live = [[age, income]]
Question 13 3 points
Preprocessing

Why is this imputation code a leakage risk during evaluation?

combined = pd.concat([train, test])
combined['income'] = combined['income'].fillna(combined['income'].median())
Question 14 2 points
Framework Mode

A Keras binary model returns values outside zero and one. What should be checked first?

model.add(Dense(1))
score = model.predict(X_live)
Question 15 3 points
Deployment

A transformer prediction changes when padding length changes. Which input is probably missing?

ids = tokenizer(texts, padding=True, return_tensors='pt')['input_ids']
logits = model(input_ids=ids).logits
Question 16 2 points
Probability

This multiclass code returns a single class for the entire batch. Which fix is correct?

proba = model.predict_proba(X_batch)
labels = np.argmax(proba)
Question 17 3 points
Shapes

A multi-output regressor returns two targets. Why is this line incorrect?

prediction = model.predict(X_live)
price = float(prediction)
Question 18 3 points
Deployment

Which improvement best detects silent prediction failures after release?

prediction = model.predict(X_live)
return {'prediction': prediction.tolist()}

Formula Used

Correct points = sum of weights for correct answers.

Penalty = wrong-answer points × 0.25, when enabled.

Adjusted points = maximum of zero or correct points minus penalty.

Percentage = adjusted points ÷ maximum points × 100.

Unanswered questions receive zero points and no penalty. Category percentages use earned category points divided by available category points.

How to Use This Calculator

  1. Choose a passing target and optional negative marking.
  2. Start the timer when timed practice is useful.
  3. Inspect every code snippet and select one correction.
  4. Enable detailed review when explanations are required.
  5. Press the result button after completing the questions.
  6. Review category scores and repeat weak debugging areas.

Building Reliable Prediction Code

Why Prediction Code Breaks

Prediction code often fails after a model trains successfully. Training success does not guarantee correct production behavior. Small mismatches can silently distort every returned prediction.

Input shape errors are common in deployed applications. Models usually expect rows with fixed feature counts. Extra dimensions may produce failures or misleading outputs.

Feature order also matters during prediction. A correct array can still contain misplaced values. Named columns reduce this risk when pipelines support them.

Preserving Training Logic

Preprocessing must match the training workflow exactly. Scaling values twice changes their learned numerical meaning. Skipping scaling can push inputs outside familiar ranges.

Encoders require the same fitted category mapping. Refitting an encoder creates different numeric representations. Unknown categories need planned handling before deployment begins.

Data leakage can appear inside prediction code. Future information may accidentally enter feature construction. Leakage creates impressive tests but unreliable real outcomes.

Handling Outputs Correctly

Classification models may return probabilities instead of labels. Developers must choose thresholds for operational decisions. Default thresholds rarely fit every business cost.

Multiclass outputs need careful axis handling. The highest probability usually identifies the predicted class. Using the wrong axis returns incorrect labels silently.

Regression predictions require sensible unit checks. A model may output transformed target values. Inverse transformations restore the original business scale.

Protecting Data Quality

Missing values need consistent imputation logic. Production nulls may differ from training nulls. Pipelines should preserve every fitted imputation rule.

Model loading errors can select outdated artifacts. Versioned files help connect code with training data. Metadata should record features, metrics, and dependencies.

Type conversion bugs frequently affect web forms. Numeric strings may contain spaces or separators. Validation should reject malformed inputs before model execution.

Testing Real Workflows

Batch prediction code must preserve row alignment. Sorting or filtering can disconnect outputs from records. Stable identifiers help verify every result assignment.

Prediction services also need range validation. Impossible ages or negative quantities signal bad inputs. Guardrails protect models from unsupported operating conditions.

Reliable tests cover normal and unusual inputs. Include empty values, unseen categories, and extreme ranges. Compare outputs against trusted baseline examples.

Maintaining Production Reliability

Monitoring continues after prediction code ships under real traffic. Data drift can reduce accuracy without exceptions. Track distributions, confidence, latency, and business outcomes.

A debugging quiz builds pattern recognition quickly. Realistic snippets reveal mistakes hidden by clean theory. Immediate explanations connect each fix with its consequence.

Careful prediction code protects users and decisions. Strong pipelines reduce silent failures across changing environments. Regular reviews keep fixes aligned with model updates.

Frequently Asked Questions

What skills does this quiz measure?

It measures debugging across preprocessing, shapes, probabilities, framework modes, data integrity, and deployment. Questions reward production-safe fixes rather than temporary patches.

Why are questions weighted differently?

Some bugs require deeper reasoning or create greater production risk. Weighted scoring gives those scenarios more influence while keeping simpler checks valuable.

How does negative marking work?

When enabled, wrong-answer points create a twenty-five percent penalty. Unanswered questions receive no penalty. The adjusted score never falls below zero.

Can I change the passing score?

Yes. Select sixty, seventy, eighty, or ninety percent before submission. The chosen target determines the displayed pass result.

Does the timer submit automatically?

No. The timer supports practice pacing without forcing submission. Your selected answers remain available until you submit or reset the form.

Why should preprocessing objects be reused?

Fitted preprocessors contain learned statistics, mappings, and feature structures. Refitting them on live data changes the model input meaning and causes inconsistent predictions.

What does category performance show?

It compares earned weighted points with available points inside each debugging category. Low percentages reveal focused areas for further practice.

Are unanswered questions treated as wrong?

They receive zero points but remain separate from wrong answers. Negative marking never applies to unanswered questions.

Can the result be printed?

Yes. Submit the quiz, then use the print result button. The print layout removes interactive controls and preserves key scoring details.

Related Calculators

Predict the Python Output QuizFind the ML Code Error QuizComplete the Missing Code QuizArrange ML Code in Order QuizMatch Code with Algorithm QuizFix Data Preprocessing Code QuizFix Model Training Code QuizFix Evaluation Metric Code QuizInterpret Scikit-Learn Output QuizConvert Mathematical Formula to Code Quiz

Important Note: All the Calculators listed in this site are for educational purpose only and we do not guarentee the accuracy of results. Please do consult with other sources as well.