import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
    accuracy_score,
    confusion_matrix,
    precision_score,
    recall_score,
    f1_score,
    classification_report,
)

seed = 32
np.random.seed(seed)
dataFile = (
    "~/complete_API_cat_freq_tfidf.csv"
)

df = pd.read_csv(
    dataFile,
    sep=",",
)
dfL = pd.read_csv(
    "~/complete_malware_class_labels.csv",
    sep="\n",
    header=None,
)

X = df
Y = dfL.loc[:, 0]

Y = pd.get_dummies(Y)
X = X.values
Y = Y.values

X_train, X_test, Y_train, Y_test = train_test_split(
    X, Y, test_size=0.3, random_state=seed
)

# 192 278 64 8
def ann_model():
    model = Sequential()
    model.add(Dense(40, input_dim=60, activation="relu"))
    model.add(Dropout(0.2))
    model.add(Dense(20, activation="relu"))
    model.add(Dense(8, activation="softmax"))
    model.compile(
        loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"]
    )
    return model

# 120 10 1
model = ann_model()
history = model.fit(
    X_train,
    Y_train,
    validation_data=(X_test, Y_test),
    epochs=120,
    batch_size=10,
    verbose=1,
)

Y_pred = model.predict(X_test)

pred = list()
for i in range(len(Y_pred)):
    pred.append(np.argmax(Y_pred[i]))

test = list()
for i in range(len(Y_test)):
    test.append(np.argmax(Y_test[i]))

# normalize="pred"
confusion = confusion_matrix(test, pred)
# print(confusion)
ax = plt.subplot()
sns.heatmap(confusion, annot=True, ax=ax, fmt="d", cmap="YlGnBu")
ax.xaxis.set_ticklabels(
    [
        "Adware",
        "Backdoor",
        "Downloader",
        "Dropper",
        "Spyware",
        "Trojan",
        "Virus",
        "Worms",
    ]
)
ax.yaxis.set_ticklabels(
    [
        "Adware",
        "Backdoor",
        "Downloader",
        "Dropper",
        "Spyware",
        "Trojan",
        "Virus",
        "Worms",
    ]
)
plt.show()

a = accuracy_score(test, pred)
print("Accuracy Score is:", a * 100)
p = precision_score(test, pred, average="weighted")
print("Precision Score is:", p * 100)
r = recall_score(test, pred, average="weighted")
print("Recall Score is:", r * 100)
f = f1_score(test, pred, average="weighted")
print("F1 Score is:", f * 100)
report = classification_report(
    test,
    pred,
    target_names=[
        "Adware",
        "Backdoor",
        "Downloader",
        "Dropper",
        "Spyware",
        "Trojan",
        "Virus",
        "Worms",
    ],
)
print(report)

plt.plot(history.history["accuracy"])
plt.plot(history.history["val_accuracy"])
plt.title("Model Accuracy")
plt.ylabel("Accuracy")
plt.xlabel("Epoch")
plt.legend(["Train", "Test"], loc="upper left")
plt.show()

plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.title("Model Loss")
plt.ylabel("Loss")
plt.xlabel("Epoch")
plt.legend(["Train", "Test"], loc="upper left")
plt.show()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
    accuracy_score,
    confusion_matrix,
    precision_score,
    recall_score,
    f1_score,
    classification_report,
)

seed = 32
np.random.seed(seed)
dataFile = (
    "~/complete_API_cat_freq_tfidf.csv"
)

df = pd.read_csv(
    dataFile,
    sep=",",
)
dfL = pd.read_csv(
    "~/complete_malware_class_labels.csv",
    sep="\n",
    header=None,
)

X = df
Y = dfL.loc[:, 0]

Y = pd.get_dummies(Y)
X = X.values
Y = Y.values

X_train, X_test, Y_train, Y_test = train_test_split(
    X, Y, test_size=0.3, random_state=seed
)

# 192 278 64 8
def ann_model():
    model = Sequential()
    model.add(Dense(40, input_dim=60, activation="relu"))
    model.add(Dropout(0.2))
    model.add(Dense(20, activation="relu"))
    model.add(Dense(8, activation="softmax"))
    model.compile(
        loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"]
    )
    return model

# 120 10 1
model = ann_model()
history = model.fit(
    X_train,
    Y_train,
    validation_data=(X_test, Y_test),
    epochs=120,
    batch_size=10,
    verbose=1,
)

Y_pred = model.predict(X_test)

pred = list()
for i in range(len(Y_pred)):
    pred.append(np.argmax(Y_pred[i]))

test = list()
for i in range(len(Y_test)):
    test.append(np.argmax(Y_test[i]))

# normalize="pred"
confusion = confusion_matrix(test, pred)
# print(confusion)
ax = plt.subplot()
sns.heatmap(confusion, annot=True, ax=ax, fmt="d", cmap="YlGnBu")
ax.xaxis.set_ticklabels(
    [
        "Adware",
        "Backdoor",
        "Downloader",
        "Dropper",
        "Spyware",
        "Trojan",
        "Virus",
        "Worms",
    ]
)
ax.yaxis.set_ticklabels(
    [
        "Adware",
        "Backdoor",
        "Downloader",
        "Dropper",
        "Spyware",
        "Trojan",
        "Virus",
        "Worms",
    ]
)
plt.show()

a = accuracy_score(test, pred)
print("Accuracy Score is:", a * 100)
p = precision_score(test, pred, average="weighted")
print("Precision Score is:", p * 100)
r = recall_score(test, pred, average="weighted")
print("Recall Score is:", r * 100)
f = f1_score(test, pred, average="weighted")
print("F1 Score is:", f * 100)
report = classification_report(
    test,
    pred,
    target_names=[
        "Adware",
        "Backdoor",
        "Downloader",
        "Dropper",
        "Spyware",
        "Trojan",
        "Virus",
        "Worms",
    ],
)
print(report)

plt.plot(history.history["accuracy"])
plt.plot(history.history["val_accuracy"])
plt.title("Model Accuracy")
plt.ylabel("Accuracy")
plt.xlabel("Epoch")
plt.legend(["Train", "Test"], loc="upper left")
plt.show()

plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.title("Model Loss")
plt.ylabel("Loss")
plt.xlabel("Epoch")
plt.legend(["Train", "Test"], loc="upper left")
plt.show()
# 192 278 64 8 # 120 10 1 # normalize="pred" # print(confusion)