Esempio n. 1
0
 def calculate_loss(self, batch, epoch=0, batch_seen=0):
     """
     输入一个batch的数据,返回训练过程这个batch数据的loss,也就是需要定义一个loss函数。
     :param batch: 输入数据,类字典,可以按字典的方法取数据
     :return: training loss (tensor)
     """
     y_true = batch['y']
     self._logger.debug(f"EPOCH = {epoch}, bep={batch_seen}")
     y_predicted, mid_output = self.forward(batch, batch_seen)
     y_true = self._scaler.inverse_transform(y_true[..., :self.output_dim])
     y_predicted = self._scaler.inverse_transform(
         y_predicted[..., :self.output_dim])
     # print(f"Y_TRUE = {y_true}")
     # print(f"Y_PRED = {y_predicted}")
     # print(f"y_true = {y_true.shape}, y_pred = {y_predicted.shape}")
     # 根据训练轮数,选择性地加入正则项
     loss_1 = loss.masked_mae_torch(y_predicted, y_true)
     if epoch < self.epoch_use_regularization:
         pred = torch.sigmoid(
             mid_output.view(mid_output.shape[0] * mid_output.shape[1]))
         # print(f"shape = {mid_output.shape}")
         # print(f"aview = {self.adj_mx.view(mid_output.shape[0] * mid_output.shape[1])}")
         true_label = self.adj_mx.view(mid_output.shape[0] *
                                       mid_output.shape[1]).to(self.device)
         compute_loss = torch.nn.BCELoss()
         loss_g = compute_loss(pred, true_label)
         self._logger.debug(f"loss_g = {loss_g}, loss_1 = {loss_1}")
         loss_t = loss_1 + loss_g
         return loss_t
     else:
         self._logger.debug(f"loss_1 = {loss_1}")
         return loss_1
Esempio n. 2
0
 def calculate_loss(self, batch, batches_seen=None):
     y_true = batch['y']
     y_predicted = self.predict(batch, batches_seen)
     y_true = self._scaler.inverse_transform(y_true[..., :self.output_dim])
     y_predicted = self._scaler.inverse_transform(
         y_predicted[..., :self.output_dim])
     return loss.masked_mae_torch(y_predicted, y_true, 0)
 def calculate_loss(self, batch):
     y_true = batch['y']
     y_predicted = self.predict(batch)
     # print('y_true', y_true.shape)
     # print('y_predicted', y_predicted.shape)
     y_true = self._scaler.inverse_transform(y_true[..., :self.output_dim])
     y_predicted = self._scaler.inverse_transform(y_predicted[..., :self.output_dim])
     return loss.masked_mae_torch(y_predicted, y_true, 0)
Esempio n. 4
0
 def calculate_loss(self, batch):
     """
     输入一个batch的数据,返回训练过程这个batch数据的loss,也就是需要定义一个loss函数。
     :param batch: 输入数据,类字典,可以按字典的方法取数据
     :return: training loss (tensor)
     """
     # 1.取出真值 ground_truth
     y_true = batch['y']
     # 2.取出预测值
     y_predicted = self.predict(batch)
     # 3.使用self._scaler将进行了归一化的真值和预测值进行反向归一化(必须)
     y_true = self._scaler.inverse_transform(y_true[..., :self.output_dim])
     y_predicted = self._scaler.inverse_transform(
         y_predicted[..., :self.output_dim])
     # 4.调用loss函数计算真值和预测值的误差
     # trafficdl/model/loss.py中定义了常见的loss函数
     # 如果模型源码用到了其中的loss,则可以直接调用,以MSE为例:
     res = loss.masked_mae_torch(y_predicted, y_true)
     # 如果模型源码所用的loss函数在loss.py中没有,则需要自己实现loss函数
     # ...(自定义loss函数)
     # 5.返回loss的结果
     return res
Esempio n. 5
0
    def collect(self, batch):
        """
        收集一 batch 的评估输入

        Args:
            batch(dict): 输入数据,字典类型,包含两个Key:(y_true, y_pred):
                batch['y_true']: (num_samples/batch_size, timeslots, ..., feature_dim)
                batch['y_pred']: (num_samples/batch_size, timeslots, ..., feature_dim)
        """
        if not isinstance(batch, dict):
            raise TypeError('evaluator.collect input is not a dict of user')
        y_true = batch['y_true']  # tensor
        y_pred = batch['y_pred']  # tensor
        print("evalutate", y_true.shape, y_pred.shape)
        if y_true.shape != y_pred.shape:
            raise ValueError(
                "batch['y_true'].shape is not equal to batch['y_pred'].shape")
        self.len_timeslots = y_true.shape[1]
        for i in range(1, self.len_timeslots + 1):
            for metric in self.metrics:
                if metric + '@' + str(i) not in self.intermediate_result:
                    self.intermediate_result[metric + '@' + str(i)] = []
        if self.mode.lower() == 'average':  # 前i个时间步的平均loss
            for i in range(1, self.len_timeslots + 1):
                for metric in self.metrics:
                    if metric == 'masked_MAE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mae_torch(y_pred[:, :i], y_true[:, :i],
                                                  0).item())
                    elif metric == 'masked_MSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mse_torch(y_pred[:, :i], y_true[:, :i],
                                                  0).item())
                    elif metric == 'masked_RMSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_rmse_torch(y_pred[:, :i],
                                                   y_true[:, :i], 0).item())
                    elif metric == 'masked_MAPE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mape_torch(y_pred[:, :i],
                                                   y_true[:, :i], 0).item())
                    elif metric == 'MAE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mae_torch(y_pred[:, :i],
                                                  y_true[:, :i]).item())
                    elif metric == 'MSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mse_torch(y_pred[:, :i],
                                                  y_true[:, :i]).item())
                    elif metric == 'RMSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_rmse_torch(y_pred[:, :i],
                                                   y_true[:, :i]).item())
                    elif metric == 'MAPE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mape_torch(y_pred[:, :i],
                                                   y_true[:, :i]).item())
                    elif metric == 'R2':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.r2_score_torch(y_pred[:, :i],
                                                y_true[:, :i]).item())
                    elif metric == 'EVAR':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.explained_variance_score_torch(
                                y_pred[:, :i], y_true[:, :i]).item())
        elif self.mode.lower() == 'single':  # 第i个时间步的loss
            for i in range(1, self.len_timeslots + 1):
                for metric in self.metrics:
                    if metric == 'masked_MAE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mae_torch(y_pred[:, i - 1],
                                                  y_true[:, i - 1], 0).item())
                    elif metric == 'masked_MSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mse_torch(y_pred[:, i - 1],
                                                  y_true[:, i - 1], 0).item())
                    elif metric == 'masked_RMSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_rmse_torch(y_pred[:, i - 1],
                                                   y_true[:, i - 1], 0).item())
                    elif metric == 'masked_MAPE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mape_torch(y_pred[:, i - 1],
                                                   y_true[:, i - 1], 0).item())
                    elif metric == 'MAE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mae_torch(y_pred[:, i - 1],
                                                  y_true[:, i - 1]).item())
                    elif metric == 'MSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mse_torch(y_pred[:, i - 1],
                                                  y_true[:, i - 1]).item())
                    elif metric == 'RMSE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_rmse_torch(y_pred[:, i - 1],
                                                   y_true[:, i - 1]).item())
                    elif metric == 'MAPE':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.masked_mape_torch(y_pred[:, i - 1],
                                                   y_true[:, i - 1]).item())
                    elif metric == 'R2':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.r2_score_torch(y_pred[:, i - 1],
                                                y_true[:, i - 1]).item())
                    elif metric == 'EVAR':
                        self.intermediate_result[metric + '@' + str(i)].append(
                            loss.explained_variance_score_torch(
                                y_pred[:, i - 1], y_true[:, i - 1]).item())
        else:
            raise ValueError(
                'Error parameter evaluator_mode={}, please set `single` or `average`.'
                .format(self.mode))