# -*- coding: utf-8 -*-
"""NaiveBayes.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/18h3EggmsVBPptpucFMGC-yXbaLIMNTr0
"""

import pandas as pd
from sklearn.model_selection import train_test_split

from google.colab import drive
#drive.mount('/content/drive')
drive.mount("/content/drive", force_remount=True)

data = pd.read_pickle('drive/MyDrive/Colab Notebooks/working_balanced_df.pkl')

data['FOREST_AREA'] = data['FOREST_AREA'].apply(lambda x: 1 if x >= 0 else 0)  # 1 = fire | 0 = Not fire

data['FOREST_AREA'].value_counts()  # The balanced dataset

working_data = data.to_numpy()

x = data[['TEMPERATURE', 'SPEED', 'DEW']]
y = data['FOREST_AREA']

x = x.to_numpy()
y = y.to_numpy()

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

from sklearn.naive_bayes import GaussianNB

clf = GaussianNB()

clf.fit(x_train, y_train)

score = clf.score(x_test, y_test)
score

clf.predict_proba([[32,5,5]])

import pickle
# save the classifier
pickle.dump(clf, open('naive_bayes_gb.pkl', 'wb'))

predictions = clf.predict(x_test)

from sklearn import metrics

cm = metrics.confusion_matrix(y_test, predictions)

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(20,10))
sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square = True, cmap = 'Blues_r');
plt.ylabel('Actual label');
plt.xlabel('Predicted label');
all_sample_title = 'Accuracy Score: {0}'.format(score)
plt.title(all_sample_title, size = 15);

probs = clf.predict_proba(x)

risk_levels = {
    'very_low': 0.10,
    'low': 0.30,
    'medium': 0.40,
    'high': 0.60,
    'very_high': 0.70
}

very_low = 0
low = 0
medium = 0
high = 0
very_high = 0

probs = probs.tolist()

for x in probs:
    #print(x[1])
    if x[1] <= risk_levels.get('very_low'):
        very_low += 1
    elif x[1] <= risk_levels.get('low'):
        low += 1
    elif x[1] <= risk_levels.get('medium'):
        medium += 1
    elif x[1] <= risk_levels.get('high'):
        high += 1
    else:
        very_high += 1

all = very_low + low + medium + high + very_high

p_very_low = round(very_low/all*100, 2)
p_low = round(low/all*100, 2)
p_medium = round(medium/all*100, 2)
p_high = round(high/all*100, 2)
p_very_high = round(very_high/all*100, 2)

print(f"Very Low: {p_very_low} %")
print(f"Low: {p_low} %")
print(f"Medium: {p_medium} %")
print(f"High: {p_high} %")
print(f"Very High: {p_very_high} %")

predictions_proba = clf.predict_proba(x_test)
predictions = predictions_proba[:, 1]

predictions_2 = predictions > 0.5

predictions_2 = predictions_2.tolist()

for x in range(0, len(predictions_2)):
  if predictions_2[x] is True:
    predictions_2[x] = 1
  else:
    predictions_2[x] = 0

import numpy as np

predictions_2 = np.asarray(predictions_2)

from sklearn import metrics

cm = metrics.confusion_matrix(y_test, predictions_2)

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(20,10))
sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square = True, cmap = 'Blues_r');
plt.ylabel('Actual label');
plt.xlabel('Predicted label');
all_sample_title = 'Accuracy Score: {0}'.format(score)
plt.title(all_sample_title, size = 15);