在 Keras 中对数值数据集使用自动编码器

Using Autoencoder on numerical dataset in Keras

我正在尝试使用 Keras 开发基于深度学习的入侵检测系统。

我们模拟了正常的网络流量,并在 CSV 文件(网络数据包字段(IP 源、端口等)的数字数据集)中准备了它。但是我没有用于训练神经网络的异常(恶意)数据包。

我搜索了类似的问题,发现 Autoencoder 在无监督学习中是一种很好的方法,但问题是我是深度学习的新手,我只在它们所在的地方找到了这个例子 https://blog.keras.io/building-autoencoders-in-keras.html在图像数据集上使用自动编码器。

我想将自动编码器(或任何对我有用的东西)与数字 CSV 数据集结合使用,以预测传入数据包是正常数据包还是恶意数据包。

有什么推荐吗?

我找到答案了:

您可以使用例如将数值数据集加载到 python numpy 加载文本。然后,指定编码器和解码器网络(基本上只是使用 Keras Layers 模块来设计神经网络)。确保编码器的输入层接受你的数据,并且解码器的输出层具有相同的维度。然后,再次使用 Keras 损失指定适当的损失函数(最小二乘法、交叉熵等)。最后,使用(惊喜!)Keras 优化器指定您的优化器。

就是这样,大功告成!点击“运行”,然后观察您的自动编码器自动编码(因为自动编码器就是这样做的)。如果你想要一个关于如何构建这个的很棒的教程。

from keras.layers import Input,Dense
from keras.models import Model

# number of neurons in the encoding hidden layer
encoding_dim = 5
# input placeholder
input_data = Input(shape=(6,)) # 6 is the number of features/columns
# encoder is the encoded representation of the input
encoded = Dense(encoding_dim, activation ='relu')(input_data)
# decoder is the lossy reconstruction of the input
decoded = Dense(6, activation ='sigmoid')(encoded) # 6 again number of features and should match input_data


# this model maps an input to its reconstruction
autoencoder = Model(input_data, decoded)




# this model maps an input to its encoded representation
encoder = Model(input_data, encoded)
# model optimizer and loss
autoencoder = Model(input_data, decoded)

# loss function and optimizer
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

# train test split
from sklearn.model_selection import train_test_split
x_train, x_test, = train_test_split(data, test_size=0.1, random_state=42)


# train the model
autoencoder.fit(x_train,
                x_train,
                epochs=50,
                batch_size=256,
                shuffle=True)

autoencoder.summary()

# predict after training
# note that we take them from the *test* set
encoded_data = encoder.predict(x_test)