I have written this small machine learning code of a simple random forest regression in the class Model. After creating an object of this class I have printed the predictions and the accuracy score along with that I have written a code to schedule training every 30 days and testing every 7 days. But I'm facing an error
Code:
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)
On this line schedule.every(30).days.at("05:00").do(model_instance.fit())
I'm getting the following error: the first argument must be callable
I'm not familiar with the schedule package, but I guess the argument to do
must be a callable. Which means you shouldn't actually call that function. Try this:
schedule.every(30).days.at("05:00").do(model_instance.fit)
schedule.every(7).days.at("05:00").do(model_instance.predict)
Note I removed the parentheses after fit
and predict
.
I figured it out. Created separate modules for training and testing and then imported the Model class and then created a function which will perform the scheduling.
Function for Training:
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)
Function for testing:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.