Regressor test with Skflow and Sklearn - 2

Test two different types of learning methods - offline learning and online learning

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# -*- coding: utf-8 -*-
from sqlalchemy import *
from threading import Timer
import signal, sys, time, threading
import configparser
from datetime import datetime
###
import pandas
import pickle
from sklearn import datasets, cross_validation, metrics
from sklearn import preprocessing
###
from sklearn.linear_model import PassiveAggressiveRegressor
from sklearn.svm import SVR
###############################################################################
class PredictData:
def __init__(self, partial_fit_flag=True):
self.partial_fit_flag = partial_fit_flag
self.regressor = None

def fit(self, X_train, y_train):
if self.partial_fit_flag:
self.regressor.partial_fit(X_train, y_train)
else:
self.regressor.fit(X_train, y_train)

def train(self, X_train, y_train):
if self.regressor == None:
if self.partial_fit_flag:
self.regressor = PassiveAggressiveRegressor(random_state=42)
# regressor = SGDRegressor(random_state=42)
else:
self.regressor = SVR(kernel='rbf', C=1000, gamma=0.1)
self.fit(X_train, y_train)
else:
if self.partial_fit_flag:
self.fit(X_train, y_train)

def predict(self, X_test):
return self.regressor.predict(X_test)

def metrics_errror(self, y_predict, y_test):
return metrics.mean_squared_error(y_predict,y_test)

def save_model(self, name):
if self.regressor != None:
with open(name, 'wb') as m:
pickle.dump(self.regressor, m)

def load_model(self, name):
with open(name, 'rb') as m:
self.regressor = pickle.load(m)
###############################################################################
class ProcessData:
def __init__(self, scaler_partialfit_flag=True):
self.scaler_partialfit_flag = scaler_partialfit_flag
self.scaler = None

def fit(self, X_train):
#if self.scaler_partialfit_flag:
self.scaler.partial_fit(X_train)
#else:
# self.scaler.fit(X_train)

def train_test_split_scale(self, data, target, testSize=0):
X_train, X_test, y_train, y_test = cross_validation.train_test_split(data, target,
test_size=testSize, random_state=42)
if self.scaler == None:
self.scaler = preprocessing.MinMaxScaler(feature_range=(-1, 1))
# preprocessing.StandardScaler()
self.fit(X_train)
if len(X_test) == 0:
X_train = self.scaler.transform(X_train)
return X_train, y_train
else:
X_train = self.scaler.transform(X_train)
X_test = self.scaler.transform(X_test)
return X_train, y_train, X_test, y_test

def validate_date(self,datetime_string):
try:
return datetime.strptime(datetime_string,"%Y-%m-%d %H:%M:%S")
except ValueError:
return False

def set_dateTime(self,datetime_string):
if self.validate_date(datetime_string) != False:
configW = configparser.RawConfigParser()
configW.optionxform = str
configW.add_section('DB')
configW.set('DB', 'LatestTime', datetime_string)
with open('DB.ini', 'w') as configfile:
configW.write(configfile)

def get_dateTime(self):
configR = configparser.RawConfigParser()
configR.read("DB.ini")
db_time=configR.get("DB","LatestTime")
if self.validate_date(db_time) == False:
return 0
else:
return db_time

def load_data_from_db(self, alwaysLatestFlag=False):
pass

def load_data_from_file(self, path):
try:
data = pandas.read_csv(path)
X = data[['Date','Time','Global_reactive_power','Voltage','Global_intensity','Sub_metering_1','Sub_metering_2','Sub_metering_3']]
y = data['Global_active_power']

D = pandas.to_datetime(X["Date"], format="%d/%m/%Y")
X["Month"] = D.apply(lambda x: x.month)
X = X.drop(["Date"], axis=1)

T = pandas.to_datetime(X["Time"], format="%H:%M:%S")
X["Hour"] = T.apply(lambda x: x.hour)
X = X.drop(["Time"], axis=1)
return X,y
except:
print('ERROR load_data_from_file!!!' )
return [],[]

def save_scaler(self, scalerName):
if self.scaler != None:
with open(scalerName, 'wb') as s:
pickle.dump(self.scaler, s)

def load_scaler(self, scalerName):
with open(scalerName, 'rb') as s:
self.scaler = pickle.load(s)
###############################################################################
def Online_Learning_Train():
pd = ProcessData()
X,y = pd.load_data_from_file('pw3.csv')
Xt,Xyt = pd.train_test_split_scale(X,y)
pdd = PredictData()
pdd.train(Xt, Xyt)
Xy_predict = pdd.predict(Xt)
scoreX = pdd.metrics_errror(Xy_predict,Xyt)
pd.save_scaler('scaler.pkl')
pdd.save_model('model.pkl')
print('MSE: {0:f}'.format(scoreX))

def Online_Learning_Test():
pd = ProcessData()
pd.load_scaler('scaler.pkl')
X,y = pd.load_data_from_file('pw5.csv')
Xt,Xyt = pd.train_test_split_scale(X,y)
pdd = PredictData()
pdd.load_model('model.pkl')
pdd.train(Xt, Xyt)
Xy_predict = pdd.predict(Xt)
scoreX = pdd.metrics_errror(Xy_predict,Xyt)
print('MSE: {0:f}'.format(scoreX))

def Offline_Learning_Train():
pd = ProcessData()
X,y = pd.load_data_from_file('pw.csv')
Xt,Xyt = pd.train_test_split_scale(X,y)
pdd = PredictData(False)
pdd.train(Xt, Xyt)
Xy_predict = pdd.predict(Xt)
scoreX = pdd.metrics_errror(Xy_predict,Xyt)
pd.save_scaler('scaler.pkl')
pdd.save_model('model.pkl')
print('MSE: {0:f}'.format(scoreX))

def Offline_Learning_Test():
pd = ProcessData()
pd.load_scaler('scaler.pkl')
X,y = pd.load_data_from_file('pw5.csv')
Xt,Xyt = pd.train_test_split_scale(X,y)
pdd = PredictData(False)
pdd.load_model('model.pkl')
Xy_predict = pdd.predict(Xt)
scoreX = pdd.metrics_errror(Xy_predict,Xyt)
print('MSE: {0:f}'.format(scoreX))

def Main():
Online_Learning_Train()
Online_Learning_Test()
'''
Offline_Learning_Train()
Offline_Learning_Test()
'''

if __name__ == '__main__':
Main()

Data preprocessing
pw.csv from Data Set

Date,Time,Global_active_power,Global_reactive_power,Voltage,Global_intensity,Sub_metering_1,
Sub_metering_2,Sub_metering_3
16/12/2006,17:24:00,4.216,0.418,234.840,18.400,0.000,1.000,17.000