liveBook · Manning

Deep learning

As explained in Data-Driven Cybersecurity

Deep learning is a machine-learning approach that uses neural networks with multiple learned layers to represent complex patterns.

Deep learning is a subset of machine learning that uses neural networks with multiple layers to model complex patterns. In cybersecurity, it can help detect sophisticated threats by learning from large amounts of data. section 12.5

Cybersecurity applications include:

  • Classifying malware from code patterns; convolutional neural networks can treat code samples as images. section 12.5
  • Detecting suspicious sequences in network traffic or logs with recurrent neural networks or LSTMs. section 12.5
  • Flagging unusual user activity, such as unexpected access to sensitive files, for review. section 12.5

A network-traffic exercise demonstrates a practical workflow: handle missing values, encode labels, split training and test data, standardize features, train a three-layer neural network, and evaluate its predictions. Classification reports and confusion matrices help assess performance; review threat detection results carefully rather than relying on accuracy alone. section 12.5.1 section 10.3.4

Listing 12.5 Using neural networks to classify network traffic data
# Import required libraries
import pandas as pd  #1
import numpy as np   #1
import tensorflow as tf   #1
from tensorflow.keras.layers import Input, Dense   #1
from tensorflow.keras.models import Sequential   #1
from sklearn.model_selection import train_test_split   #1
from sklearn.preprocessing import StandardScaler   #1
from sklearn.metrics import classification_report, #1
    confusion_matrix   #1
import matplotlib.pyplot as plt   #1
import seaborn as sns   #1
 #1
# Step 1: Generate synthetic network traffic data #1
np.random.seed(42)  #2
data = {  #3
    'Packet_Size': np.random.randint(50, 1500, size=1000),   #3
    'Connection_Duration': np.random.uniform(0.1, #3
                                             10.0, size=1000),   #3
    'Protocol_Type': np.random.choice( #3
        [0, 1, 2], size=1000),   #3
    'Threat': np.random.choice( #3
    [0, 1], size=1000, p=[0.7, 0.3])   #3
} #3
df = pd.DataFrame(data)  #4

# Step 2: Split data into features and labels
X = df.drop(columns=['Threat'])  #5
y = df['Threat']   #5

# Step 3: Preprocess the data
scaler = StandardScaler()  #6
X_scaled = scaler.fit_transform(X)   #6
X_train, X_test, y_train, y_test = train_test_split(
    X_scaled, y, test_size=0.2, random_state=42)  #7

# Step 4: Define the neural network
model = Sequential([  #8
    Input(shape=(X_train.shape[1],)),   #8
    Dense(64, activation='relu'),   #8
    Dense(32, activation='relu'),   #8
    Dense(1, activation='sigmoid')   #8
]) #8

# Step 5: Compile the model
model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])  #9

# Step 6: Train the model
history = model.fit(X_train, y_train, epochs=20,
                    batch_size=32,
                    validation_data=(X_test, y_test),
                    verbose=0)  #10

# Step 7: Evaluate the model
y_pred = (model.predict(X_test) > 0.5).astype(int)  #11
print(classification_report( #11
    y_test, y_pred, zero_division=1))   #11

# Step 8: Plot the confusion matrix
conf_matrix = confusion_matrix(y_test, y_pred)  #12
plt.figure(figsize=(8, 6))   #12
sns.heatmap(conf_matrix, annot=True, fmt='d', #12
            cmap='Greys', xticklabels=['Normal', 'Threat'], #12
            yticklabels=['Normal', 'Threat'])   #12
plt.title('Confusion Matrix')   #12
plt.xlabel('Predicted Labels')   #12
plt.ylabel('True Labels')   #12
plt.show()   #12

Inspect the example code for a neural-network workflow that classifies network traffic and evaluates potential threats. section 12.5.1

How Data-Driven Cybersecurity covers it

How deep it goes
Defines layered neural networks and explains applications, then works through training and evaluation without detailing model internals.
Examples
Uses malware classification, suspicious network sequences, unusual file access, and a network-traffic threat-classification exercise.
What you can do after
Build from scratch: preprocess network data, train a TensorFlow/Keras neural network, and evaluate predictions with classification metrics.
How it connects
Connects machine learning with neural networks, convolutional and recurrent networks, anomaly detection, and malware classification.

Also explained in

Compare how 11 books explain deep learning →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Driven Cybersecurity. The section links point to the parts of the book it draws on.