鱼C论坛

 找回密码
 立即注册
查看: 943|回复: 1

[已解决]Inception Time 中组合Inception网络

[复制链接]
发表于 2023-10-13 20:11:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
第一段代码包含inception网络;第二段代码包含集成一组 Inception 网络的代码。请问如何将自己的数据应用于NNE,有train和test两个数据集。


  1. class Classifier_INCEPTION:

  2.     def __init__(self, output_directory, input_shape, nb_classes, verbose=True, build=True, batch_size=64,
  3.                  nb_filters=32, use_residual=True, use_bottleneck=True, depth=6, kernel_size=41, nb_epochs=15):

  4.         self.output_directory = output_directory
  5.         self.nb_filters = nb_filters
  6.         self.use_residual = use_residual
  7.         self.use_bottleneck = use_bottleneck
  8.         self.depth = depth
  9.         self.kernel_size = kernel_size - 1
  10.         self.callbacks = None
  11.         self.batch_size = batch_size
  12.         self.bottleneck_size = 32
  13.         self.nb_epochs = nb_epochs

  14.         if build == True:
  15.             self.model = self.build_model(input_shape, nb_classes)
  16.             if (verbose == True):
  17.                 self.model.summary()
  18.             self.verbose = verbose
  19.             self.model.save_weights(self.output_directory + 'model_init.hdf5')

  20.     def _inception_module(self, input_tensor, stride=1, activation='linear'):

  21.         if self.use_bottleneck and int(input_tensor.shape[-1]) > 1:
  22.             input_inception = keras.layers.Conv1D(filters=self.bottleneck_size, kernel_size=1,
  23.                                                   padding='same', activation=activation, use_bias=False)(input_tensor)
  24.         else:
  25.             input_inception = input_tensor

  26.         # kernel_size_s = [3, 5, 8, 11, 17]
  27.         kernel_size_s = [self.kernel_size // (2 ** i) for i in range(3)]

  28.         conv_list = []

  29.         for i in range(len(kernel_size_s)):
  30.             conv_list.append(keras.layers.Conv1D(filters=self.nb_filters, kernel_size=kernel_size_s[i],
  31.                                                  strides=stride, padding='same', activation=activation, use_bias=False)(
  32.                 input_inception))

  33.         max_pool_1 = keras.layers.MaxPool1D(pool_size=3, strides=stride, padding='same')(input_tensor)

  34.         conv_6 = keras.layers.Conv1D(filters=self.nb_filters, kernel_size=1,
  35.                                      padding='same', activation=activation, use_bias=False)(max_pool_1)

  36.         conv_list.append(conv_6)

  37.         x = keras.layers.Concatenate(axis=2)(conv_list)
  38.         x = keras.layers.BatchNormalization()(x)
  39.         x = keras.layers.Activation(activation='relu')(x)
  40.         return x

  41.     def _shortcut_layer(self, input_tensor, out_tensor):
  42.         shortcut_y = keras.layers.Conv1D(filters=int(out_tensor.shape[-1]), kernel_size=1,
  43.                                          padding='same', use_bias=False)(input_tensor)
  44.         shortcut_y = keras.layers.BatchNormalization()(shortcut_y)

  45.         x = keras.layers.Add()([shortcut_y, out_tensor])
  46.         x = keras.layers.Activation('relu')(x)
  47.         return x

  48.     def build_model(self, input_shape, nb_classes):
  49.         input_layer = keras.layers.Input(input_shape)

  50.         x = input_layer
  51.         input_res = input_layer

  52.         for d in range(self.depth):

  53.             x = self._inception_module(x)

  54.             if self.use_residual and d % 3 == 2:
  55.                 x = self._shortcut_layer(input_res, x)
  56.                 input_res = x

  57.         gap_layer = keras.layers.GlobalAveragePooling1D()(x)

  58.         output_layer = keras.layers.Dense(nb_classes, activation='softmax')(gap_layer)

  59.         model = keras.models.Model(inputs=input_layer, outputs=output_layer)

  60.         model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(),
  61.                       metrics=['acc'])

  62.         reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.5, patience=50,
  63.                                                       min_lr=0.0001)

  64.         file_path = self.output_directory + 'best_model.hdf5'

  65.         model_checkpoint = keras.callbacks.ModelCheckpoint(filepath=file_path, monitor='loss',
  66.                                                            save_best_only=True)

  67.         self.callbacks = [reduce_lr, model_checkpoint]

  68.         return model

  69.     def fit(self, x_train, y_train, x_val, y_val, y_true, plot_test_acc=True):
  70.         if self.batch_size is None:
  71.             mini_batch_size = int(min(x_train.shape[0] / 10, 16))
  72.         else:
  73.             mini_batch_size = self.batch_size

  74.         start_time = time.time()

  75.         if plot_test_acc:

  76.             hist = self.model.fit(x_train, y_train, batch_size=mini_batch_size, epochs=self.nb_epochs,
  77.                                   verbose=self.verbose, validation_data=(x_val, y_val), callbacks=self.callbacks)
  78.         else:

  79.             hist = self.model.fit(x_train, y_train, batch_size=mini_batch_size, epochs=self.nb_epochs,
  80.                                   verbose=self.verbose, callbacks=self.callbacks)

  81.         duration = time.time() - start_time

  82.         self.model.save(self.output_directory + 'last_model.hdf5')

  83.         y_pred = self.predict(x_val, y_true, x_train, y_train, y_val,
  84.                               return_df_metrics=False)

  85.         # save predictions
  86.         np.save(self.output_directory + 'y_pred.npy', y_pred)

  87.         # convert the predicted from binary to integer
  88.         y_pred = np.argmax(y_pred, axis=1)

  89.         df_metrics = save_logs(self.output_directory, hist, y_pred, y_true, duration,
  90.                                plot_test_acc=plot_test_acc)

  91.         keras.backend.clear_session()

  92.         return df_metrics

  93.     def predict(self, x_test, y_true, x_train, y_train, y_test, return_df_metrics=True):
  94.         start_time = time.time()
  95.         model_path = self.output_directory + 'best_model.hdf5'
  96.         model = keras.models.load_model(model_path)
  97.         y_pred = model.predict(x_test, batch_size=self.batch_size)
  98.         if return_df_metrics:
  99.             y_pred = np.argmax(y_pred, axis=1)
  100.             df_metrics = calculate_metrics(y_true, y_pred, 0.0)
  101.             return df_metrics
  102.         else:
  103.             test_duration = time.time() - start_time
  104.             save_test_duration(self.output_directory + 'test_duration.csv', test_duration)
  105.             return y_pred
  106.         

  107. df1 = pd.read_csv("train.csv")
  108. df1 = np.array(df1)
  109. X = np.expand_dims(df1[:, 1:891].astype(float), axis=2)  # 对数据进行增维并转化为32为
  110. #X = np.expand_dims(df1[:, 1:891].astype(float), axis=1)
  111. Y = df1[:, 0]
  112. X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.2, random_state=42)

  113. y_train, y_val = transform_labels(y_train, y_val)
  114. # save orignal y because later we will use binary
  115. y_true = y_val.astype(np.int64)
  116. y_true_train = y_train.astype(np.int64)
  117. # transform the labels from integers to one hot vectors
  118. enc = sklearn.preprocessing.OneHotEncoder()
  119. enc.fit(np.concatenate((y_train, y_val), axis=0).reshape(-1, 1))
  120. y_train = enc.transform(y_train.reshape(-1, 1)).toarray()
  121. y_val = enc.transform(y_val.reshape(-1, 1)).toarray()

  122. '''y_train = to_categorical(y_train)  # one-hot encoding
  123. y_val= to_categorical(y_val)
  124. y_true = y_val'''
  125. df2 = pd.read_csv("test.csv")
  126. df2 = np.array(df1)
  127. X_test = np.expand_dims(df2[:, 1:891].astype(float), axis=2)
  128. y_test=df2[:, 0]
  129. y_true1 = y_test.astype(np.int64)
  130. y_test = enc.transform(y_test.reshape(-1, 1)).toarray()
  131. # 创建模型
  132. model = Classifier_INCEPTION(output_directory='output_directory', input_shape=X_train.shape[1:], nb_classes=8)

  133. # 训练模型
  134. model.fit(X_train, y_train, X_val, y_val,y_true)
  135. df_metrics=model.predict(X_test, y_true1, X_train, y_train, y_test)
  136. print(df_metrics)
复制代码
  1. import keras
  2. import numpy as np
  3. from utils.utils import calculate_metrics
  4. from utils.utils import create_directory
  5. from utils.utils import check_if_file_exits
  6. import gc
  7. from utils.constants import UNIVARIATE_ARCHIVE_NAMES  as ARCHIVE_NAMES
  8. import time


  9. class Classifier_NNE:

  10.     def create_classifier(self, model_name, input_shape, nb_classes, output_directory, verbose=False,
  11.                           build=True):
  12.         if self.check_if_match('inception*', model_name):
  13.             from classifiers import inception
  14.             return inception.Classifier_INCEPTION(output_directory, input_shape, nb_classes, verbose,
  15.                                                   build=build)

  16.     def check_if_match(self, rex, name2):
  17.         import re
  18.         pattern = re.compile(rex)
  19.         return pattern.match(name2)

  20.     def __init__(self, output_directory, input_shape, nb_classes, verbose=False, nb_iterations=5,
  21.                  clf_name='inception'):
  22.         self.classifiers = [clf_name]
  23.         out_add = ''
  24.         for cc in self.classifiers:
  25.             out_add = out_add + cc + '-'
  26.         self.archive_name = ARCHIVE_NAMES[0]
  27.         self.iterations_to_take = [i for i in range(nb_iterations)]
  28.         for cc in self.iterations_to_take:
  29.             out_add = out_add + str(cc) + '-'
  30.         self.output_directory = output_directory.replace('nne',
  31.                                                          'nne' + '/' + out_add)
  32.         create_directory(self.output_directory)
  33.         self.dataset_name = output_directory.split('/')[-2]
  34.         self.verbose = verbose
  35.         self.models_dir = output_directory.replace('nne', 'classifier')

  36.     def fit(self, x_train, y_train, x_test, y_test, y_true):
  37.         # no training since models are pre-trained
  38.         start_time = time.time()

  39.         y_pred = np.zeros(shape=y_test.shape)

  40.         ll = 0

  41.         # loop through all classifiers
  42.         for model_name in self.classifiers:
  43.             # loop through different initialization of classifiers
  44.             for itr in self.iterations_to_take:
  45.                 if itr == 0:
  46.                     itr_str = ''
  47.                 else:
  48.                     itr_str = '_itr_' + str(itr)

  49.                 curr_archive_name = self.archive_name + itr_str

  50.                 curr_dir = self.models_dir.replace('classifier', model_name).replace(
  51.                     self.archive_name, curr_archive_name)

  52.                 model = self.create_classifier(model_name, None, None,
  53.                                                curr_dir, build=False)

  54.                 predictions_file_name = curr_dir + 'y_pred.npy'
  55.                 # check if predictions already made
  56.                 if check_if_file_exits(predictions_file_name):
  57.                     # then load only the predictions from the file
  58.                     curr_y_pred = np.load(predictions_file_name)
  59.                 else:
  60.                     # then compute the predictions
  61.                     curr_y_pred = model.predict(x_test, y_true, x_train, y_train, y_test,
  62.                                                 return_df_metrics=False)
  63.                     keras.backend.clear_session()

  64.                     np.save(predictions_file_name, curr_y_pred)

  65.                 y_pred = y_pred + curr_y_pred

  66.                 ll += 1

  67.         # average predictions
  68.         y_pred = y_pred / ll

  69.         # save predictions
  70.         np.save(self.output_directory + 'y_pred.npy', y_pred)

  71.         # convert the predicted from binary to integer
  72.         y_pred = np.argmax(y_pred, axis=1)

  73.         duration = time.time() - start_time

  74.         df_metrics = calculate_metrics(y_true, y_pred, duration)

  75.         df_metrics.to_csv(self.output_directory + 'df_metrics.csv', index=False)

  76.         gc.collect()
复制代码
最佳答案
2023-10-13 21:36:34
本帖最后由 陶远航 于 2023-10-13 21:37 编辑

这段代码中,首先定义了一个名为Classifier_INCEPTION的类,该类实现了Inception网络的构建和训练。然后,通过读取训练集和测试集的数据,将数据应用到Inception网络中进行训练和预测。

以下是如何将自己的数据应用于这个网络的步骤:

1. 数据准备:首先,你需要准备你的数据。在这个例子中,数据是从CSV文件中读取的。你需要将你的数据格式化为一个可以被网络接受的形式。在这个例子中,输入数据被转换为一个三维的numpy数组,其中第一维是样本数,第二维是特征数,第三维是1(因为这是一个单变量的时间序列分类任务)。标签被转换为one-hot编码的形式。

  1. df1 = pd.read_csv("train.csv")
  2. df1 = np.array(df1)
  3. X = np.expand_dims(df1[:, 1:891].astype(float), axis=2)  # 对数据进行增维并转化为32为
  4. Y = df1[:, 0]
  5. X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.2, random_state=42)

  6. y_train, y_val = transform_labels(y_train, y_val)
  7. # save orignal y because later we will use binary
  8. y_true = y_val.astype(np.int64)
  9. y_true_train = y_train.astype(np.int64)
  10. # transform the labels from integers to one hot vectors
  11. enc = sklearn.preprocessing.OneHotEncoder()
  12. enc.fit(np.concatenate((y_train, y_val), axis=0).reshape(-1, 1))
  13. y_train = enc.transform(y_train.reshape(-1, 1)).toarray()
  14. y_val = enc.transform(y_val.reshape(-1, 1)).toarray()
复制代码


2. 模型创建:然后,你需要创建你的模型。在这个例子中,我们创建了一个Inception网络的实例。

  1. model = Classifier_INCEPTION(output_directory='output_directory', input_shape=X_train.shape[1:], nb_classes=8)
复制代码


3. 模型训练:接下来,你需要训练你的模型。在这个例子中,我们使用训练数据和验证数据来训练我们的模型。

  1. model.fit(X_train, y_train, X_val, y_val,y_true)
复制代码


4. 模型预测:最后,你可以使用你的模型进行预测。在这个例子中,我们使用测试数据来进行预测,并打印出预测的结果。

  1. df_metrics=model.predict(X_test, y_true1, X_train, y_train, y_test)
  2. print(df_metrics)
复制代码


请注意,你需要根据你自己的数据来调整这些步骤。例如,你可能需要调整数据的读取和预处理方式,以适应你自己的数据格式。你也可能需要调整模型的参数,以适应你的任务需求。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-10-13 21:36:34 | 显示全部楼层    本楼为最佳答案   
本帖最后由 陶远航 于 2023-10-13 21:37 编辑

这段代码中,首先定义了一个名为Classifier_INCEPTION的类,该类实现了Inception网络的构建和训练。然后,通过读取训练集和测试集的数据,将数据应用到Inception网络中进行训练和预测。

以下是如何将自己的数据应用于这个网络的步骤:

1. 数据准备:首先,你需要准备你的数据。在这个例子中,数据是从CSV文件中读取的。你需要将你的数据格式化为一个可以被网络接受的形式。在这个例子中,输入数据被转换为一个三维的numpy数组,其中第一维是样本数,第二维是特征数,第三维是1(因为这是一个单变量的时间序列分类任务)。标签被转换为one-hot编码的形式。

  1. df1 = pd.read_csv("train.csv")
  2. df1 = np.array(df1)
  3. X = np.expand_dims(df1[:, 1:891].astype(float), axis=2)  # 对数据进行增维并转化为32为
  4. Y = df1[:, 0]
  5. X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.2, random_state=42)

  6. y_train, y_val = transform_labels(y_train, y_val)
  7. # save orignal y because later we will use binary
  8. y_true = y_val.astype(np.int64)
  9. y_true_train = y_train.astype(np.int64)
  10. # transform the labels from integers to one hot vectors
  11. enc = sklearn.preprocessing.OneHotEncoder()
  12. enc.fit(np.concatenate((y_train, y_val), axis=0).reshape(-1, 1))
  13. y_train = enc.transform(y_train.reshape(-1, 1)).toarray()
  14. y_val = enc.transform(y_val.reshape(-1, 1)).toarray()
复制代码


2. 模型创建:然后,你需要创建你的模型。在这个例子中,我们创建了一个Inception网络的实例。

  1. model = Classifier_INCEPTION(output_directory='output_directory', input_shape=X_train.shape[1:], nb_classes=8)
复制代码


3. 模型训练:接下来,你需要训练你的模型。在这个例子中,我们使用训练数据和验证数据来训练我们的模型。

  1. model.fit(X_train, y_train, X_val, y_val,y_true)
复制代码


4. 模型预测:最后,你可以使用你的模型进行预测。在这个例子中,我们使用测试数据来进行预测,并打印出预测的结果。

  1. df_metrics=model.predict(X_test, y_true1, X_train, y_train, y_test)
  2. print(df_metrics)
复制代码


请注意,你需要根据你自己的数据来调整这些步骤。例如,你可能需要调整数据的读取和预处理方式,以适应你自己的数据格式。你也可能需要调整模型的参数,以适应你的任务需求。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-20 08:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表