
!pip install pycaret
"""# Libararies"""

from pycaret.anomaly import *
from google.colab import files
import io
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px

"""#Load data"""

df = pd.read_csv(('iot_data.csv'), parse_dates=['timestamp'])
print(df.head())

"""# Remove column without info and update dataset"""

df = df.drop(columns=['Unnamed: 0'])

df.set_index('timestamp', inplace=True)

df.index = pd.to_datetime(df.index)

"""#Visualize data"""

fig = px.line(df)
fig.show()

"""#See Structure of Dataset"""

s = setup(df, session_id = 123)

# list of available models in pyCaret
models()

"""# Detection"""

#Create model, choosing fractional value  is depending on the feasibility and importance of responding to IOT alerts
ifo = create_model('iforest', fraction = 0.02)
iforest = assign_model(ifo)

"""## Filter out anomolies"""

#filter out anomalous results
anomalousresults = iforest[iforest['Anomaly'] == 1]

anomalousresults.shape

"""#Plot Results"""

# Plot result of selected sensor "sensor1" on y-axis, date information on x-axis
plt = px.line(iforest, x=iforest.index, y=["sensor1"], title='IOT Data ANOMALY DETECTION')

#identify anomolies(outliers) in plot
anomaly = iforest[iforest['Anomaly'] == 1].index

# Plots detection of Sensor1  data
y_values = [iforest.loc[i]['sensor1'] for i in anomaly]
plt.add_trace(go.Scatter(x=anomaly, y=y_values, mode = 'markers', name = 'Anomaly', marker=dict(color='maroon',size=6)))
plt.show()

÷