model = IsolationForest(contamination='auto', random_state=42) model.fit(X)
# Predict the anomalies
predictions = model.predict(X)
# Add the anomaly predictions as a new column in the original dataset
data['Anomaly'] = predictions
# Filter the dataset to show only the anomalous records
anomalies = data[data['Anomaly'] == -1]
# Identify the time periods with abnormal operations
abnormal_periods = [] current_period = []
for index, row in anomalies.iterrows():
if len(current_period) == 0: current_period.append(index) elif index == current_period[-1] + 1: current_period.append(index) else: abnormal_periods.append(current_period) current_period = [index]
# Print the time periods with abnormal operations
for period in abnormal_periods: start_time = data.loc[period[0], 'Timestamp'] end_time = data.loc[period[-1], 'Timestamp'] print(f"Abnormal period: {start_time} to {end_time}")