【问题标题】:Schedule training and testing machine learning安排训练和测试机器学习
【发布时间】:2020-07-01 07:44:40
【问题描述】:

我在 Model 类中编写了这个简单随机森林回归的小型机器学习代码。在创建了这个类的一个对象之后,我打印了预测和准确度分数,同时我编写了一个代码来安排每 30 天的训练和每 7 天的测试。但我遇到了一个错误

代码:

import schedule
import time
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np

import pandas as pd
from main import data as df

class Model():
    def __init__(self):
        self.df = df
        self.linear_reg = LinearRegression()
        self.random_forest = RandomForestRegressor()
    def split(self, test_size):
        X = np.array(self.df[['age','experience','certificates']])
        y = np.array(self.df['salary'])
        self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size = test_size, random_state = 42)

    def fit(self):
        self.model = self.random_forest.fit(self.X_train, self.y_train)

    def predict(self):

        self.result = self.random_forest.predict(self.X_test)
        print(self.result)
        print("Accuracy: ", self.model.score(self.X_test, self.y_test))


if __name__ == '__main__':
    model_instance = Model()
    model_instance.split(0.2)
    schedule.every(30).days.at("05:00").do(model_instance.fit())
    schedule.every(7).days.at("05:00").do(model_instance.predict())
    while 1:
        schedule.run_pending()
        time.sleep(1)

在这一行 schedule.every(30).days.at("05:00").do(model_instance.fit()) 我收到以下错误:the first argument must be callable

【问题讨论】:

    标签: python class oop machine-learning scikit-learn


    【解决方案1】:

    我不熟悉 schedule 包,但我猜do 的参数必须是可调用的。这意味着您实际上不应该调用该函数。试试这个:

    schedule.every(30).days.at("05:00").do(model_instance.fit)
    schedule.every(7).days.at("05:00").do(model_instance.predict)
    

    注意我删除了fitpredict 之后的括号。

    【讨论】:

    • 执行此操作后我收到此错误name 'model_instance' is not defined
    • 我的意思是,替换原始代码中的匹配行,在那里定义它。
    【解决方案2】:

    我想通了。为训练和测试创建了单独的模块,然后导入了 Model 类,然后创建了一个执行调度的函数。

    训练功能:

    import schedule
    import time
    
    def job():
        model_instance.split(0.2)
        model_instance.fit()
        print("Training Completed")
    schedule.every().minute.at(":17").do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    测试功能:

    import schedule
    import time
    
    def job():
        model_instance.predict()
        print(model_instance.result)
        print("Accuracy: ", model_instance.model.score(model_instance.X_test, model_instance.y_test))
        print("Testing Completed")
    schedule.every().minute.at(":17").do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2019-07-03
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2017-10-09
      • 2011-02-15
      • 2015-12-21
      • 2018-06-12
      相关资源
      最近更新 更多