自动编码器(Autoencoder)是一种无监督学习模型,主要用于数据降维、特征学习和数据重建。其基本结构由两个主要部分组成:编码器(Encoder)和解码器(Decoder)。
编码器:负责将输入数据映射到一个低维的潜在空间(latent space),通常通过多个神经网络层实现。编码器的目标是提取输入数据的主要特征。
解码器:将潜在空间中的表示重建回原始输入数据。解码器的目标是尽可能准确地重构输入数据。
自动编码器的训练过程是通过最小化输入数据与重建数据之间的差异(通常使用均方误差或交叉熵损失)来优化模型参数。
自动编码器的应用包括但不限于:
1、数据降维
2、特征提取
3、噪声消除(去噪自动编码器)
4、异常检测
5、图像生成(变分自动编码器)
自动编码器具有灵活性,可以根据需要设计不同的网络架构和激活函数,以适应特定的任务和数据类型。
#导入相关的库并生成数据
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyod.utils.data import generate_data
contamination = 0.05 # percentage of outliers
n_train = 500 # number of training points
n_test = 500 # number of testing points
n_features = 25 # number of features
X_train, X_test, y_train, y_test = generate_data(
n_train=n_train,
n_test=n_test,
n_features= n_features,
contamination=contamination,
random_state=123)
X_train_pd = pd.DataFrame(X_train)
X_train_pd.head()
# Plot
plt.scatter(X_train_pd[0], X_train_pd[1], c=y_train, alpha=0.8)
plt.title('Scatter plot')
plt.xlabel('x0')
plt.ylabel('x1')
plt.show()
from pyod.models.auto_encoder import AutoEncoder # pyod后续版本是基于torch的
atcdr = AutoEncoder(contamination=0.05, hidden_neuron_list= [2, 2])
atcdr.fit(X_train) #内部会自动进行标准化# Training data 训练数据的分数 和预测值
y_train_scores = atcdr.decision_function(X_train)
y_train_pred = atcdr.predict(X_train)
# Test data 测试数据的分数和预测值
y_test_scores = atcdr.decision_function(X_test)
y_test_pred = atcdr.predict(X_test) # outlier labels (0 or 1)
# Threshold for the defined comtanimation rate contamination 5% 对应的值;
print("The threshold for the defined contamination rate:" , atcdr.threshold_)
def count_stat(vector):
# Because it is '0' and '1', we can run a count statistic.
unique, counts = np.unique(vector, return_counts=True)
return dict(zip(unique, counts))
print("The training data:", count_stat(y_train_pred))
print("The training data:", count_stat(y_test_pred))结果:
The threshold for the defined contamination rate: 4.2399105072015875
The training data: {0: 475, 1: 25}
The training data: {0: 475, 1: 25}plt.figure(figsize=(6, 4), dpi=300)
import matplotlib.pyplot as plt
plt.hist(y_train_scores, bins='auto') # arguments are passed to np.histogram
plt.title("Outlier score")
plt.show()
threshold = atcdr.threshold_ # Or other value from the above histogram
threshold
4.2399105072015875
可见,大部分数据的分数在5左边,异常的分数在15右边,因此,可以取值 4.23作为阈值,为了得到更稳定的阈值,还可以对autoencoder的参数-隐藏层配置:hidden_neuron_list 进行多种配置,然后分别训练不同的autoencoder实例,再取平均,这样可以获取稳定的阈值做为可靠的结果。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。