Apply model to data stream
Let's now apply your trained machine learning Pipeline to streaming data, and categorize the values immediately.
You'll then use predict() on the incoming messages to determine the category.
Based on the result of the prediction you will take action, and close the windows in your house (or not).
Remember that category 1 means good weather, whereas category 0 signifies bad, cold weather.
Additionally, the pipeline returns an array of predictions. As you passed in only one element, you need to access the first element using category[0].
The function close_window() will handle this for you, and will additionally log the record for further study.
pandas as pd and json have been preloaded the session for you, and the model is available as pl.
Cet exercice fait partie du cours
Analyzing IoT Data in Python
Instructions
- Parse the dictionary into a pandas DataFrame with
DataFrame.from_records()"timestamp"as index, andcolsas columns. - Determine the category of this record by using
predict()from the pipeline object and assign the result tocategory. - Call
close_window()with the DataFramedfas the first argument, andcategoryas the 2nd argument.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
def model_subscribe(client, userdata, message):
data = json.loads(message.payload)
# Parse to DataFrame
df = pd.____.____([data], index=____, columns=____)
# Predict result
category = ____
if category[0] < 1:
# Call business logic
____
else:
print("Nice Weather, nothing to do.")
# Subscribe model_subscribe to MQTT Topic
subscribe.callback(model_subscribe, topic, hostname=MQTT_HOST)