<jupyter_start><jupyter_text><jupyter_code>!pip install pd
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import plot_confusion_matrix

def replay(data):
  features = [list(i) for i in data[0]]
  labels = list(data[1])
  new_features = []
  new_labels = []

  for i in features:
    if np.random.random() < 0.2:
      repeats = np.random.randint(10, 20)
      for j in range(repeats):
        new_features.append(i)
        new_labels.append(1)
    else:
      new_features.append(i)
      new_labels.append(0)
  return (np.array(new_features), np.array(new_labels))
df = pd.read_csv(r'LoadMinPower.csv')
df.drop(df.columns[[0,1]], axis=1, inplace=True)
replayed = replay((df.to_numpy(), [0 for i in range(len(df))]))
features, labels = replayed[0], replayed[1]

y = np.array([i[0] for i in features][:200])
y2 = np.array([i[4] for i in features][:200])
y3 = np.array([i[10] for i in features][:200])

print(f" Sensor 1 Mean: {y.mean()}, Variance: {y.var()}")
print(f" Sensor 5 Mean: {y2.mean()}, Variance: {y2.var()}")
print(f" Sensor 11 Mean: {y3.mean()}, Variance: {y3.var()}")
x = np.arange(0, len(y))

plt.figure(figsize=(10,8))
plt.xlabel('Reading No.',fontsize=14)
plt.ylabel('Sensor Reading',fontsize=14)
plt.title('Sensor Readings After Replay Attack',fontsize=16)
plt.plot(x,y,label='Sensor 1')
plt.plot(y2, label = 'Sensor 5')
plt.plot(y3, label = 'Sensor 11')
plt.legend(loc='upper right')
plt.savefig('LoadMinSensorsafterReplayAttack')
plt.show()
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=1, shuffle=True)
knn_model = KNeighborsClassifier()

knn_model.fit(X_train, y_train)

knn_predictions = knn_model.predict(X_test)

print(f"Accuracy of KNN: {round(accuracy_score(y_test, knn_predictions)*100)}%")
svm = SVC()
svm.fit(X_train, y_train)
svm_predictions = svm.predict(X_test)
print(f"Accuracy of SVM: {round(accuracy_score(y_test, svm_predictions)*100)}%")
support_vectors = svm.support_vectors_
plt.scatter(X_train[:,0], X_train[:,1])
plt.scatter(support_vectors[:,0], support_vectors[:,1], color='red')
plt.title('Support Vectors')
plt.figure(figsize=(8,6))
plt.show()
df = pd.read_csv(r'LoadMaxPower.csv')
df.drop(df.columns[[0,1]], axis=1, inplace=True)
replayed = replay((df.to_numpy(), [0 for i in range(len(df))]))
max_features, max_labels = replayed[0], replayed[1]
knn_pred = knn_model.predict(max_features)
print(f" KNN: {accuracy_score(max_labels, knn_pred)}")

tn, fp, fn, tp = confusion_matrix(max_labels, knn_pred).ravel()
print(f"TN: {tn}, FP: {fp}, FN: {fn}, TP: {tp}")

svm_pred = svm.predict(max_features)
print(f" SVM: {accuracy_score(max_labels, svm_pred)}")
tn, fp, fn, tp = confusion_matrix(max_labels, svm_pred).ravel()
print(f"TN: {tn}, FP: {fp}, FN: {fn}, TP: {tp}")
confusion_matrix(y_test, knn_predictions)
confusion_matrix(y_test, svm_predictions)
matrix = plot_confusion_matrix(knn_model, X_test, y_test)
matrix.ax_.set_title('Confusion Matrix', color='black')
plt.xlabel('Predicted label', color='black')
plt.ylabel('True label',color='black')
plt.gcf().axes[0].tick_params(colors='black')
plt.gcf().axes[1].tick_params(colors='black')
plt.gcf().set_size_inches(10,6)
plt.show()
matrix = plot_confusion_matrix(svm, X_test, y_test)
matrix.ax_.set_title('Confusion Matrix', color='black')
plt.xlabel('Predicted label', color='black')
plt.ylabel('True label',color='black')
plt.gcf().axes[0].tick_params(colors='black')
plt.gcf().axes[1].tick_params(colors='black')
plt.gcf().set_size_inches(10,6)
plt.show()<jupyter_output>/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
  warnings.warn(msg, category=FutureWarning)
{'fraction_non_alphanumeric': 0.1623686723973257, 'fraction_numerical': 0.022445081184336198, 'mean_word_length': 6.888888888888889, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '332372', 'license': 'MIT', 'n_tokens_mistral': 1685, 'n_tokens_neox': 1601, 'n_words': 320, 'path': 'replay.ipynb', 'repo_name': 'sandhigupta/Sandhi', 'size': '4188'}