【问题标题】:How to generalise a custom plotting function to plot multiple different things如何概括自定义绘图函数以绘制多个不同的事物
【发布时间】:2021-07-01 05:12:03
【问题描述】:

我已经建立了一个模型类,我可以在其中拟合各种模型,一个简单的 RNN,一个 LSTM RNN,目标是添加更多模型。历史记录存储在self.<model>_history 中。我希望能够绘制训练和验证准确性:

self.<model>_history.history['accuracy']self.<model>_history.history['val_accuracy']

或训练和验证损失:

self.<model>_history.history['loss']self.<model>_history.history['val_loss']

每个模型只使用一个绘图函数。请在下面查看我的解决方法,它确实有效,但看起来不太好。项目可以是“损失”或“准确度”

  def plot_model(self, model, item='accuracy'):
    if model == 'lstm':
      plt.plot(self.lstm_history.history[f'{item}'])
      plt.plot(self.lstm_history.history[f'val_{item}'])
      plt.legend([f'Training {item.title()}', f'Validation {item}'])
      plt.xlabel('Epoch')
      plt.ylabel(f'{item}')
      plt.show()
    if model == 'rnn':
      plt.plot(self.rnn_history.history[f'{item}'])
      plt.plot(self.rnn_history.history[f'val_{item}'])
      plt.legend([f'Training {item.title()}', f'Validation {item}'])
      plt.xlabel('Epoch')
      plt.ylabel(f'{item}')
      plt.show()

【问题讨论】:

    标签: python function class plot


    【解决方案1】:

    试试这样的:

    def plot_model(self, model, item='accuracy'):
        _model = getattr(self, '%s_history' % model)
        plt.plot(_model.history[f'{item}'])
        plt.plot(_model.history[f'val_{item}'])
        plt.legend([f'Training {item.title()}', f'Validation {item}'])
        plt.xlabel('Epoch')
        plt.ylabel(f'{item}')
        plt.show()
    

    gettattr 应该会帮你获取你需要的对象<model>_history

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多