Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to load the PyTorch model for inference.
PyTorch
import torch model = torch.load('[1]') model.eval()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to load a script file instead of the model file.
Using a data file instead of the model file.
✗ Incorrect
The model file is usually saved with a .pth extension. Loading 'model.pth' loads the trained model.
2fill in blank
mediumComplete the code to convert input JSON data into a PyTorch tensor for inference.
PyTorch
import torch import json input_json = '{"data": [1.0, 2.0, 3.0]}' input_data = json.loads(input_json) input_tensor = torch.tensor([1])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to index the JSON string instead of the parsed dictionary.
Using the wrong key name.
✗ Incorrect
After loading JSON, the data is accessed by the key 'data' in the dictionary input_data.
3fill in blank
hardFix the error in the code to perform inference and get the output tensor.
PyTorch
with torch.no_grad(): output = model([1]) prediction = output.argmax(dim=1).item()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing raw JSON or dictionary instead of tensor.
Converting tensor to numpy array before passing to model.
✗ Incorrect
The model expects a tensor input, so we pass input_tensor to the model.
4fill in blank
hardFill both blanks to create a Flask route that accepts POST requests and returns JSON predictions.
PyTorch
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/predict', methods=[[1]]) def predict(): data = request.get_json() input_tensor = torch.tensor(data['input']) with torch.no_grad(): output = model(input_tensor) pred = output.argmax(dim=1).item() return jsonify([2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using GET method which does not send JSON body.
Returning JSON with unclear or wrong keys.
✗ Incorrect
The route should accept POST requests, and the JSON response should have key 'prediction' with the predicted value.
5fill in blank
hardFill all three blanks to complete the Flask app that runs on port 5000 with debug mode on.
PyTorch
if __name__ == '__main__': app.run(host=[1], port=[2], debug=[3])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '0.0.0.0' which exposes the server externally.
Setting debug to False or a string instead of boolean True.
✗ Incorrect
The app runs on localhost at port 5000 with debug mode enabled (True).