我正在尝试为我的日志分析项目开发一个序列RNN。
输入是一个日志序列,例如 [1,2,3,4,5,6,1,5,2,7,8,2,1]
目前我使用的是keras库中的to_categorical函数,它将序列转换为独热编码。
def to_categorical(y, num_classes=None, dtype='float32'): """Converts a class vector (integers) to binary class matrix. E.g. for use with categorical_crossentropy. # Arguments y: class vector to be converted into a matrix (integers from 0 to num_classes). num_classes: total number of classes. dtype: The data type expected by the input, as a string (`float32`, `float64`, `int32`...) # Returns A binary matrix representation of the input. The classes axis is placed last. # Example ```python # Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}: > labels array([0, 2, 1, 2, 0]) # `to_categorical` converts this into a matrix with as many # columns as there are classes. The number of rows # stays the same. > to_categorical(labels) array([[ 1., 0., 0.], [ 0., 0., 1.], [ 0., 1., 0.], [ 0., 0., 1.], [ 1., 0., 0.]], dtype=float32) ``` """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1 and len(input_shape) > 1: input_shape = tuple(input_shape[:-1]) y = y.ravel() if not num_classes: num_classes = np.max(y) + 1 n = y.shape[0] categorical = np.zeros((n, num_classes), dtype=dtype) categorical[np.arange(n), y] = 1 output_shape = input_shape + (num_classes,) categorical = np.reshape(categorical, output_shape) return categorical
我面临的问题是,可能会有一些日志不属于训练数据,比如 [9,10,11]
如果我有一个包含2000个日志键和275个唯一日志的序列。
总是会有未见过的日志,但如果我想保存这个模型并在新数据上重用它,它可能无法将其转换为相同的分类格式,因为原本我的RNN中只有275个唯一日志类别,而现在我有了275 + 3个新类别。
我们如何解决这个问题?
回答:
关于@【隐藏姓名】对类别一致性的回答,您可以将训练序列中未出现的任何值替换为np.nan
,并按如下方式使用pd.get_dummies
。
train_seq = np.array([1,2,3,4,5])test_seq = np.array([1,2,3,4,5,6,7,8,9,10], dtype=np.float32)test_seq[~np.isin(test_seq, train_seq)] = np.nandf = pd.get_dummies(test_seq, dummy_na=True)print(df)
这会为未见过的数据生成一个单独的类别。
1.0 2.0 3.0 4.0 5.0 NaN0 1 0 0 0 0 01 0 1 0 0 0 02 0 0 1 0 0 03 0 0 0 1 0 04 0 0 0 0 1 05 0 0 0 0 0 16 0 0 0 0 0 17 0 0 0 0 0 18 0 0 0 0 0 19 0 0 0 0 0 1