Correções nos códigos para adaptação às refatorações e substituições dos tabs por 4 espaços

This commit is contained in:
Petrônio Cândido de Lima e Silva 2016-12-22 14:36:50 -02:00
parent ccfbd20d72
commit 632b218f62
15 changed files with 943 additions and 925 deletions

View File

@ -7,6 +7,7 @@ from mpl_toolkits.mplot3d import Axes3D
from sklearn.cross_validation import KFold from sklearn.cross_validation import KFold
import Measures import Measures
from pyFTS.partitioners import Grid from pyFTS.partitioners import Grid
from pyFTS.common import Membership,FuzzySet,FLR,Transformations
def Teste(par): def Teste(par):
x = np.arange(1,par) x = np.arange(1,par)
@ -211,7 +212,7 @@ def SelecaoKFold_MenorRMSE(original,parameters,modelo):
min_rmse_fold = 100000.0 min_rmse_fold = 100000.0
bestd = None bestd = None
fc = 0 fc = 0
diff = common.differential(original) diff = Transformations.differential(original)
kf = KFold(len(original), n_folds=nfolds) kf = KFold(len(original), n_folds=nfolds)
for train_ix, test_ix in kf: for train_ix, test_ix in kf:
train = diff[train_ix] train = diff[train_ix]
@ -299,7 +300,7 @@ def SelecaoSimples_MenorRMSE(original,parameters,modelo):
ret.append(forecasted_best) ret.append(forecasted_best)
# Modelo diferencial # Modelo diferencial
print("\nSérie Diferencial") print("\nSérie Diferencial")
difffts = common.differential(original) difffts = Transformations.differential(original)
errors = [] errors = []
forecastedd_best = [] forecastedd_best = []
ax2 = fig.add_axes([0, 0, 0.65, 0.45]) #left, bottom, width, height ax2 = fig.add_axes([0, 0, 0.65, 0.45]) #left, bottom, width, height
@ -465,7 +466,7 @@ def HOSelecaoSimples_MenorRMSE(original,parameters,orders):
for p in parameters: for p in parameters:
oc = 0 oc = 0
for o in orders: for o in orders:
sets = Grid.GridPartitionerTrimf(common.differential(original),p) sets = Grid.GridPartitionerTrimf(Transformations.differential(original),p)
fts = hwang.HighOrderFTS(o,"k = " + str(p)+ " w = " + str(o)) fts = hwang.HighOrderFTS(o,"k = " + str(p)+ " w = " + str(o))
fts.train(original,sets) fts.train(original,sets)
forecasted = [fts.forecastDiff(original, xx) for xx in range(o,len(original))] forecasted = [fts.forecastDiff(original, xx) for xx in range(o,len(original))]

123
chen.py
View File

@ -1,70 +1,69 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet, FLR
import fts
class ConventionalFLRG: class ConventionalFLRG:
def __init__(self,LHS): def __init__(self, LHS):
self.LHS = LHS self.LHS = LHS
self.RHS = set() self.RHS = set()
def append(self,c):
self.RHS.add(c)
def __str__(self): def append(self, c):
tmp = self.LHS.name + " -> " self.RHS.add(c)
tmp2 = ""
for c in sorted(self.RHS, key=lambda s: s.name): def __str__(self):
if len(tmp2) > 0: tmp = self.LHS.name + " -> "
tmp2 = tmp2 + "," tmp2 = ""
tmp2 = tmp2 + c.name for c in sorted(self.RHS, key=lambda s: s.name):
return tmp + tmp2 if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c.name
return tmp + tmp2
class ConventionalFTS(fts.FTS): class ConventionalFTS(fts.FTS):
def __init__(self,name): def __init__(self, name):
super(ConventionalFTS, self).__init__(1,"CFTS") super(ConventionalFTS, self).__init__(1, "CFTS")
self.name = "Conventional FTS" self.name = "Conventional FTS"
self.detail = "Chen" self.detail = "Chen"
self.flrgs = {} self.flrgs = {}
def generateFLRG(self, flrs):
flrgs = {}
for flr in flrs:
if flr.LHS.name in flrgs:
flrgs[flr.LHS.name].append(flr.RHS)
else:
flrgs[flr.LHS.name] = ConventionalFLRG(flr.LHS);
flrgs[flr.LHS.name].append(flr.RHS)
return (flrgs)
def train(self, data, sets): def generateFLRG(self, flrs):
self.sets = sets flrgs = {}
tmpdata = common.fuzzySeries(data,sets) for flr in flrs:
flrs = common.generateNonRecurrentFLRs(tmpdata) if flr.LHS.name in flrgs:
self.flrgs = self.generateFLRG(flrs) flrgs[flr.LHS.name].append(flr.RHS)
else:
def forecast(self,data): flrgs[flr.LHS.name] = ConventionalFLRG(flr.LHS);
flrgs[flr.LHS.name].append(flr.RHS)
ndata = np.array(data) return (flrgs)
l = len(ndata) def train(self, data, sets):
self.sets = sets
ret = [] tmpdata = FuzzySet.fuzzySeries(data, sets)
flrs = FLR.generateNonRecurrentFLRs(tmpdata)
for k in np.arange(0,l): self.flrgs = self.generateFLRG(flrs)
mv = common.fuzzyInstance(ndata[k], self.sets) def forecast(self, data):
actual = self.sets[ np.argwhere( mv == max(mv) )[0,0] ] ndata = np.array(data)
if actual.name not in self.flrgs: l = len(ndata)
ret.append(actual.centroid)
else: ret = []
flrg = self.flrgs[actual.name]
mp = self.getMidpoints(flrg) for k in np.arange(0, l):
ret.append(sum(mp)/len(mp)) mv = FuzzySet.fuzzyInstance(ndata[k], self.sets)
return ret actual = self.sets[np.argwhere(mv == max(mv))[0, 0]]
if actual.name not in self.flrgs:
ret.append(actual.centroid)
else:
flrg = self.flrgs[actual.name]
mp = self.getMidpoints(flrg)
ret.append(sum(mp) / len(mp))
return ret

65
fts.py
View File

@ -1,41 +1,42 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS import *
class FTS: class FTS:
def __init__(self,order,name): def __init__(self, order, name):
self.sets = {} self.sets = {}
self.flrgs = {} self.flrgs = {}
self.order = order self.order = order
self.shortname = name self.shortname = name
self.name = name self.name = name
self.detail = name self.detail = name
self.isSeasonal = False self.isSeasonal = False
self.isInterval = False self.isInterval = False
self.isDensity = False self.isDensity = False
def fuzzy(self,data):
best = {"fuzzyset":"", "membership":0.0}
for f in self.sets: def fuzzy(self, data):
fset = self.sets[f] best = {"fuzzyset": "", "membership": 0.0}
if best["membership"] <= fset.membership(data):
best["fuzzyset"] = fset.name
best["membership"] = fset.membership(data)
return best for f in self.sets:
fset = self.sets[f]
if best["membership"] <= fset.membership(data):
best["fuzzyset"] = fset.name
best["membership"] = fset.membership(data)
def forecast(self,data): return best
pass
def train(self, data, sets): def forecast(self, data):
pass pass
def getMidpoints(self,flrg):
ret = np.array([s.centroid for s in flrg.RHS])
return ret
def __str__(self): def train(self, data, sets):
tmp = self.name + ":\n" pass
for r in sorted(self.flrgs):
tmp = tmp + str(self.flrgs[r]) + "\n" def getMidpoints(self, flrg):
return tmp ret = np.array([s.centroid for s in flrg.RHS])
return ret
def __str__(self):
tmp = self.name + ":\n"
for r in sorted(self.flrgs):
tmp = tmp + str(self.flrgs[r]) + "\n"
return tmp

176
hofts.py
View File

@ -1,94 +1,96 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet,FLR
import fts
class HighOrderFLRG: class HighOrderFLRG:
def __init__(self,order): def __init__(self, order):
self.LHS = [] self.LHS = []
self.RHS = {} self.RHS = {}
self.order = order self.order = order
self.strlhs = "" self.strlhs = ""
def appendRHS(self, c):
if c.name not in self.RHS:
self.RHS[c.name] = c
def strLHS(self):
if len(self.strlhs) == 0:
for c in self.LHS:
if len(self.strlhs) > 0:
self.strlhs = self.strlhs + ", "
self.strlhs = self.strlhs + c.name
return self.strlhs
def appendLHS(self, c):
self.LHS.append(c)
def __str__(self):
tmp = ""
for c in sorted(self.RHS):
if len(tmp) > 0:
tmp = tmp + ","
tmp = tmp + c
return self.strLHS() + " -> " + tmp
def appendRHS(self,c):
if c.name not in self.RHS:
self.RHS[c.name] = c
def strLHS(self):
if len(self.strlhs) == 0:
for c in self.LHS:
if len(self.strlhs) > 0:
self.strlhs = self.strlhs + ", "
self.strlhs = self.strlhs + c.name
return self.strlhs
def appendLHS(self,c):
self.LHS.append(c)
def __str__(self):
tmp = ""
for c in sorted(self.RHS):
if len(tmp) > 0:
tmp = tmp + ","
tmp = tmp + c
return self.strLHS() + " -> " + tmp
class HighOrderFTS(fts.FTS): class HighOrderFTS(fts.FTS):
def __init__(self,name): def __init__(self, name):
super(HighOrderFTS, self).__init__(1,"HOFTS" + name) super(HighOrderFTS, self).__init__(1, "HOFTS" + name)
self.name = "High Order FTS" self.name = "High Order FTS"
self.detail = "Chen" self.detail = "Chen"
self.order = 1 self.order = 1
self.setsDict = {} self.setsDict = {}
def generateFLRG(self, flrs):
flrgs = {}
l = len(flrs)
for k in np.arange(self.order +1, l):
flrg = HighOrderFLRG(self.order)
for kk in np.arange(k - self.order, k):
flrg.appendLHS( flrs[kk].LHS )
if flrg.strLHS() in flrgs:
flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
else:
flrgs[flrg.strLHS()] = flrg;
flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
return (flrgs)
def train(self, data, sets, order): def generateFLRG(self, flrs):
self.order = order flrgs = {}
self.sets = sets l = len(flrs)
for s in self.sets: self.setsDict[s.name] = s for k in np.arange(self.order + 1, l):
tmpdata = common.fuzzySeries(data,sets) flrg = HighOrderFLRG(self.order)
flrs = common.generateRecurrentFLRs(tmpdata)
self.flrgs = self.generateFLRG(flrs) for kk in np.arange(k - self.order, k):
flrg.appendLHS(flrs[kk].LHS)
def getMidpoints(self,flrg):
ret = np.array([self.setsDict[s].centroid for s in flrg.RHS]) if flrg.strLHS() in flrgs:
return ret flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
else:
def forecast(self,data): flrgs[flrg.strLHS()] = flrg;
flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
ret = [] return (flrgs)
l = len(data) def train(self, data, sets, order):
self.order = order
if l <= self.order: self.sets = sets
return data for s in self.sets: self.setsDict[s.name] = s
tmpdata = FuzzySet.fuzzySeries(data, sets)
for k in np.arange(self.order, l): flrs = FuzzySet.generateRecurrentFLRs(tmpdata)
tmpdata = common.fuzzySeries(data[k-self.order : k],self.sets) self.flrgs = self.generateFLRG(flrs)
tmpflrg = HighOrderFLRG(self.order)
def getMidpoints(self, flrg):
for s in tmpdata: tmpflrg.appendLHS(s) ret = np.array([self.setsDict[s].centroid for s in flrg.RHS])
return ret
if tmpflrg.strLHS() not in self.flrgs:
ret.append(tmpdata[-1].centroid) def forecast(self, data):
else:
flrg = self.flrgs[tmpflrg.strLHS()] ret = []
mp = self.getMidpoints(flrg)
l = len(data)
ret.append(sum(mp)/len(mp))
if l <= self.order:
return ret return data
for k in np.arange(self.order, l):
tmpdata = FuzzySet.fuzzySeries(data[k - self.order: k], self.sets)
tmpflrg = HighOrderFLRG(self.order)
for s in tmpdata: tmpflrg.appendLHS(s)
if tmpflrg.strLHS() not in self.flrgs:
ret.append(tmpdata[-1].centroid)
else:
flrg = self.flrgs[tmpflrg.strLHS()]
mp = self.getMidpoints(flrg)
ret.append(sum(mp) / len(mp))
return ret

View File

@ -1,37 +1,38 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet,FLR,Transformations
import fts
class HighOrderFTS(fts.FTS): class HighOrderFTS(fts.FTS):
def __init__(self,order,name): def __init__(self, order, name):
super(HighOrderFTS, self).__init__(order,name) super(HighOrderFTS, self).__init__(order, name)
def forecast(self,data,t):
cn = np.array([0.0 for k in range(len(self.sets))])
ow = np.array([[0.0 for k in range(len(self.sets))] for z in range(self.order-1)])
rn = np.array([[0.0 for k in range(len(self.sets))] for z in range(self.order-1)])
ft = np.array([0.0 for k in range(len(self.sets))])
for s in range(len(self.sets)): def forecast(self, data, t):
cn[s] = self.sets[s].membership(data[t]) cn = np.array([0.0 for k in range(len(self.sets))])
for w in range(self.order-1): ow = np.array([[0.0 for k in range(len(self.sets))] for z in range(self.order - 1)])
ow[w,s] = self.sets[s].membership(data[t-w]) rn = np.array([[0.0 for k in range(len(self.sets))] for z in range(self.order - 1)])
rn[w,s] = ow[w,s] * cn[s] ft = np.array([0.0 for k in range(len(self.sets))])
ft[s] = max(ft[s],rn[w,s])
mft = max(ft)
out = 0.0
count = 0.0
for s in range(len(self.sets)):
if ft[s] == mft:
out = out + self.sets[s].centroid
count = count + 1.0
return out / count
for s in range(len(self.sets)):
cn[s] = self.sets[s].membership(data[t])
for w in range(self.order - 1):
ow[w, s] = self.sets[s].membership(data[t - w])
rn[w, s] = ow[w, s] * cn[s]
ft[s] = max(ft[s], rn[w, s])
mft = max(ft)
out = 0.0
count = 0.0
for s in range(len(self.sets)):
if ft[s] == mft:
out = out + self.sets[s].centroid
count = count + 1.0
return out / count
def train(self, data, sets): def train(self, data, sets):
self.sets = sets self.sets = sets
def predict(self,data,t):
return self.forecast(data,t)
def predictDiff(self,data,t): def predict(self, data, t):
return data[t] + self.forecast(common.differential(data),t) return self.forecast(data, t)
def predictDiff(self, data, t):
return data[t] + self.forecast(Transformations.differential(data), t)

218
ifts.py
View File

@ -1,111 +1,113 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet,FLR
import hofts, fts, tree
class IntervalFTS(hofts.HighOrderFTS): class IntervalFTS(hofts.HighOrderFTS):
def __init__(self,name): def __init__(self, name):
super(IntervalFTS, self).__init__("IFTS " + name) super(IntervalFTS, self).__init__("IFTS " + name)
self.shortname = "IFTS " + name self.shortname = "IFTS " + name
self.name = "Interval FTS" self.name = "Interval FTS"
self.detail = "Silva, P.; Guimarães, F.; Sadaei, H." self.detail = "Silva, P.; Guimarães, F.; Sadaei, H. (2016)"
self.flrgs = {} self.flrgs = {}
self.isInterval = True self.isInterval = True
def getUpper(self,flrg): def getUpper(self, flrg):
if flrg.strLHS() in self.flrgs: if flrg.strLHS() in self.flrgs:
tmp = self.flrgs[ flrg.strLHS() ] tmp = self.flrgs[flrg.strLHS()]
ret = max(np.array([self.setsDict[s].upper for s in tmp.RHS])) ret = max(np.array([self.setsDict[s].upper for s in tmp.RHS]))
else: else:
ret = flrg.LHS[-1].upper ret = flrg.LHS[-1].upper
return ret return ret
def getLower(self,flrg): def getLower(self, flrg):
if flrg.strLHS() in self.flrgs: if flrg.strLHS() in self.flrgs:
tmp = self.flrgs[ flrg.strLHS() ] tmp = self.flrgs[flrg.strLHS()]
ret = min(np.array([self.setsDict[s].lower for s in tmp.RHS])) ret = min(np.array([self.setsDict[s].lower for s in tmp.RHS]))
else: else:
ret = flrg.LHS[-1].lower ret = flrg.LHS[-1].lower
return ret return ret
def getSequenceMembership(self, data, fuzzySets): def getSequenceMembership(self, data, fuzzySets):
mb = [ fuzzySets[k].membership( data[k] ) for k in np.arange(0,len(data)) ] mb = [fuzzySets[k].membership(data[k]) for k in np.arange(0, len(data))]
return mb return mb
def buildTree(self,node, lags, level): def buildTree(self, node, lags, level):
if level >= self.order: if level >= self.order:
return return
for s in lags[level]: for s in lags[level]:
node.appendChild(tree.FLRGTreeNode(s)) node.appendChild(tree.FLRGTreeNode(s))
for child in node.getChildren(): for child in node.getChildren():
self.buildTree(child,lags,level+1) self.buildTree(child, lags, level + 1)
def forecast(self,data): def forecast(self, data):
ndata = np.array(data) ndata = np.array(data)
l = len(ndata) l = len(ndata)
ret = [] ret = []
for k in np.arange(self.order-1,l): for k in np.arange(self.order - 1, l):
affected_flrgs = [] affected_flrgs = []
affected_flrgs_memberships = [] affected_flrgs_memberships = []
up = [] up = []
lo = [] lo = []
# Achar os conjuntos que tem pert > 0 para cada lag # Achar os conjuntos que tem pert > 0 para cada lag
count = 0 count = 0
lags = {} lags = {}
if self.order > 1: if self.order > 1:
subset = ndata[k-(self.order-1) : k+1 ] subset = ndata[k - (self.order - 1): k + 1]
for instance in subset: for instance in subset:
mb = common.fuzzyInstance(instance, self.sets) mb = FuzzySet.fuzzyInstance(instance, self.sets)
tmp = np.argwhere( mb ) tmp = np.argwhere(mb)
idx = np.ravel(tmp) #flat the array idx = np.ravel(tmp) # flat the array
lags[count] = idx lags[count] = idx
count = count + 1 count = count + 1
# Constrói uma árvore com todos os caminhos possíveis # Constrói uma árvore com todos os caminhos possíveis
root = tree.FLRGTreeNode(None) root = tree.FLRGTreeNode(None)
self.buildTree(root,lags,0) self.buildTree(root, lags, 0)
# Traça os possíveis caminhos e costrói as HOFLRG's # Traça os possíveis caminhos e costrói as HOFLRG's
for p in root.paths(): for p in root.paths():
path = list(reversed(list(filter(None.__ne__, p)))) path = list(reversed(list(filter(None.__ne__, p))))
flrg = hofts.HighOrderFLRG(self.order) flrg = hofts.HighOrderFLRG(self.order)
for kk in path: flrg.appendLHS(self.sets[ kk ]) for kk in path: flrg.appendLHS(self.sets[kk])
affected_flrgs.append(flrg) affected_flrgs.append(flrg)
# Acha a pertinência geral de cada FLRG # Acha a pertinência geral de cada FLRG
affected_flrgs_memberships.append(min(self.getSequenceMembership(subset, flrg.LHS))) affected_flrgs_memberships.append(min(self.getSequenceMembership(subset, flrg.LHS)))
else: else:
mv = common.fuzzyInstance(ndata[k],self.sets) mv = FuzzySet.fuzzyInstance(ndata[k], self.sets)
tmp = np.argwhere( mv ) tmp = np.argwhere(mv)
idx = np.ravel(tmp) idx = np.ravel(tmp)
for kk in idx: for kk in idx:
flrg = hofts.HighOrderFLRG(self.order) flrg = hofts.HighOrderFLRG(self.order)
flrg.appendLHS(self.sets[ kk ]) flrg.appendLHS(self.sets[kk])
affected_flrgs.append(flrg) affected_flrgs.append(flrg)
affected_flrgs_memberships.append(mv[kk]) affected_flrgs_memberships.append(mv[kk])
count = 0 count = 0
for flrg in affected_flrgs: for flrg in affected_flrgs:
# achar o os bounds de cada FLRG, ponderados pela pertinência # achar o os bounds de cada FLRG, ponderados pela pertinência
up.append( affected_flrgs_memberships[count] * self.getUpper(flrg) ) up.append(affected_flrgs_memberships[count] * self.getUpper(flrg))
lo.append( affected_flrgs_memberships[count] * self.getLower(flrg) ) lo.append(affected_flrgs_memberships[count] * self.getLower(flrg))
count = count + 1 count = count + 1
# gerar o intervalo # gerar o intervalo
norm = sum(affected_flrgs_memberships) norm = sum(affected_flrgs_memberships)
ret.append( [ sum(lo)/norm, sum(up)/norm ] ) ret.append([sum(lo) / norm, sum(up) / norm])
return ret return ret

View File

@ -1,83 +1,85 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet,FLR
import fts
class ImprovedWeightedFLRG: class ImprovedWeightedFLRG:
def __init__(self,LHS): def __init__(self, LHS):
self.LHS = LHS self.LHS = LHS
self.RHS = {} self.RHS = {}
self.count = 0.0 self.count = 0.0
def append(self,c): def append(self, c):
if c.name not in self.RHS: if c.name not in self.RHS:
self.RHS[c.name] = 1.0 self.RHS[c.name] = 1.0
else: else:
self.RHS[c.name] = self.RHS[c.name] + 1.0 self.RHS[c.name] = self.RHS[c.name] + 1.0
self.count = self.count + 1.0 self.count = self.count + 1.0
def weights(self):
return np.array([self.RHS[c] / self.count for c in self.RHS.keys()])
def __str__(self):
tmp = self.LHS.name + " -> "
tmp2 = ""
for c in sorted(self.RHS):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c + "(" + str(round(self.RHS[c] / self.count, 3)) + ")"
return tmp + tmp2
def weights(self):
return np.array([ self.RHS[c]/self.count for c in self.RHS.keys() ])
def __str__(self):
tmp = self.LHS.name + " -> "
tmp2 = ""
for c in sorted(self.RHS):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c + "(" + str(round(self.RHS[c]/self.count,3)) + ")"
return tmp + tmp2
class ImprovedWeightedFTS(fts.FTS): class ImprovedWeightedFTS(fts.FTS):
def __init__(self,name): def __init__(self, name):
super(ImprovedWeightedFTS, self).__init__(1,"IWFTS") super(ImprovedWeightedFTS, self).__init__(1, "IWFTS")
self.name = "Improved Weighted FTS" self.name = "Improved Weighted FTS"
self.detail = "Ismail & Efendi" self.detail = "Ismail & Efendi"
self.setsDict = {} self.setsDict = {}
def generateFLRG(self, flrs):
flrgs = {}
for flr in flrs:
if flr.LHS.name in flrgs:
flrgs[flr.LHS.name].append(flr.RHS)
else:
flrgs[flr.LHS.name] = ImprovedWeightedFLRG(flr.LHS);
flrgs[flr.LHS.name].append(flr.RHS)
return (flrgs)
def train(self, data, sets): def generateFLRG(self, flrs):
self.sets = sets flrgs = {}
for flr in flrs:
for s in self.sets: self.setsDict[s.name] = s if flr.LHS.name in flrgs:
flrgs[flr.LHS.name].append(flr.RHS)
tmpdata = common.fuzzySeries(data,self.sets) else:
flrs = common.generateRecurrentFLRs(tmpdata) flrgs[flr.LHS.name] = ImprovedWeightedFLRG(flr.LHS);
self.flrgs = self.generateFLRG(flrs) flrgs[flr.LHS.name].append(flr.RHS)
return (flrgs)
def getMidpoints(self,flrg):
ret = np.array([self.setsDict[s].centroid for s in flrg.RHS]) def train(self, data, sets):
return ret self.sets = sets
def forecast(self,data): for s in self.sets: self.setsDict[s.name] = s
l = 1
tmpdata = FuzzySet.fuzzySeries(data, self.sets)
ndata = np.array(data) flrs = FLR.generateRecurrentFLRs(tmpdata)
self.flrgs = self.generateFLRG(flrs)
l = len(ndata)
def getMidpoints(self, flrg):
ret = [] ret = np.array([self.setsDict[s].centroid for s in flrg.RHS])
return ret
for k in np.arange(0,l):
def forecast(self, data):
mv = common.fuzzyInstance(ndata[k], self.sets) l = 1
actual = self.sets[ np.argwhere( mv == max(mv) )[0,0] ] ndata = np.array(data)
if actual.name not in self.flrgs: l = len(ndata)
ret.append(actual.centroid)
else: ret = []
flrg = self.flrgs[actual.name]
mp = self.getMidpoints(flrg) for k in np.arange(0, l):
ret.append( mp.dot( flrg.weights() )) mv = FuzzySet.fuzzyInstance(ndata[k], self.sets)
return ret actual = self.sets[np.argwhere(mv == max(mv))[0, 0]]
if actual.name not in self.flrgs:
ret.append(actual.centroid)
else:
flrg = self.flrgs[actual.name]
mp = self.getMidpoints(flrg)
ret.append(mp.dot(flrg.weights()))
return ret

View File

@ -2,7 +2,7 @@ import numpy as np
import math import math
import random as rnd import random as rnd
import functools,operator import functools,operator
from pyFTS import * from pyFTS.common import FuzzySet,Membership
def distancia(x,y): def distancia(x,y):
if isinstance(x, list): if isinstance(x, list):
@ -86,6 +86,6 @@ def CMeansPartitionerTrimf(data,npart,names = None,prefix = "A"):
centroides = list(set(centroides)) centroides = list(set(centroides))
centroides.sort() centroides.sort()
for c in np.arange(1,len(centroides)-1): for c in np.arange(1,len(centroides)-1):
sets.append(common.FuzzySet(prefix+str(c),common.trimf,[round(centroides[c-1],3), round(centroides[c],3), round(centroides[c+1],3)], round(centroides[c],3) ) ) sets.append(FuzzySet(prefix+str(c),Membership.trimf,[round(centroides[c-1],3), round(centroides[c],3), round(centroides[c+1],3)], round(centroides[c],3) ) )
return sets return sets

View File

@ -2,7 +2,7 @@ import numpy as np
import math import math
import random as rnd import random as rnd
import functools,operator import functools,operator
from pyFTS import * from pyFTS.common import FuzzySet,Membership
#import CMeans #import CMeans
@ -108,6 +108,6 @@ def FCMPartitionerTrimf(data,npart,names = None,prefix = "A"):
centroides = list(set(centroides)) centroides = list(set(centroides))
centroides.sort() centroides.sort()
for c in np.arange(1,len(centroides)-1): for c in np.arange(1,len(centroides)-1):
sets.append(common.FuzzySet(prefix+str(c),common.trimf,[round(centroides[c-1],3), round(centroides[c],3), round(centroides[c+1],3)], round(centroides[c],3) ) ) sets.append(FuzzySet(prefix+str(c),Membership.trimf,[round(centroides[c-1],3), round(centroides[c],3), round(centroides[c+1],3)], round(centroides[c],3) ) )
return sets return sets

View File

@ -2,7 +2,7 @@ import numpy as np
import math import math
import random as rnd import random as rnd
import functools,operator import functools,operator
from pyFTS import * from pyFTS.common import FuzzySet,Membership
#print(common.__dict__) #print(common.__dict__)
@ -16,7 +16,7 @@ def GridPartitionerTrimf(data,npart,names = None,prefix = "A"):
partlen = math.ceil(dlen / npart) partlen = math.ceil(dlen / npart)
partition = math.ceil(dmin) partition = math.ceil(dmin)
for c in range(npart): for c in range(npart):
sets.append(common.FuzzySet(prefix+str(c),common.trimf,[round(partition-partlen,3), partition, partition+partlen], partition ) ) sets.append(FuzzySet(prefix+str(c),Membership.trimf,[round(partition-partlen,3), partition, partition+partlen], partition ) )
partition = partition + partlen partition = partition + partlen
return sets return sets

564
pifts.py
View File

@ -1,291 +1,297 @@
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import math import math
from pyFTS import * from pyFTS.common import FuzzySet,FLR
import hofts, ifts, tree
class ProbabilisticFLRG(hofts.HighOrderFLRG): class ProbabilisticFLRG(hofts.HighOrderFLRG):
def __init__(self,order): def __init__(self, order):
super(ProbabilisticFLRG, self).__init__(order) super(ProbabilisticFLRG, self).__init__(order)
self.RHS = {} self.RHS = {}
self.frequencyCount = 0 self.frequencyCount = 0
def appendRHS(self,c): def appendRHS(self, c):
self.frequencyCount = self.frequencyCount + 1 self.frequencyCount = self.frequencyCount + 1
if c.name in self.RHS: if c.name in self.RHS:
self.RHS[c.name] = self.RHS[c.name] + 1 self.RHS[c.name] = self.RHS[c.name] + 1
else: else:
self.RHS[c.name] = 1 self.RHS[c.name] = 1
def getProbability(self,c): def getProbability(self, c):
return self.RHS[c] / self.frequencyCount return self.RHS[c] / self.frequencyCount
def __str__(self): def __str__(self):
tmp2 = "" tmp2 = ""
for c in sorted(self.RHS): for c in sorted(self.RHS):
if len(tmp2) > 0: if len(tmp2) > 0:
tmp2 = tmp2 + ", " tmp2 = tmp2 + ", "
tmp2 = tmp2 + c + "(" + str(round(self.RHS[c]/self.frequencyCount,3)) + ")" tmp2 = tmp2 + c + "(" + str(round(self.RHS[c] / self.frequencyCount, 3)) + ")"
return self.strLHS() + " -> " + tmp2 return self.strLHS() + " -> " + tmp2
class ProbabilisticIntervalFTS(ifts.IntervalFTS): class ProbabilisticIntervalFTS(ifts.IntervalFTS):
def __init__(self,name): def __init__(self, name):
super(ProbabilisticIntervalFTS, self).__init__("PIFTS") super(ProbabilisticIntervalFTS, self).__init__("PIFTS")
self.shortname = "PIFTS " + name self.shortname = "PIFTS " + name
self.name = "Probabilistic Interval FTS" self.name = "Probabilistic Interval FTS"
self.detail = "Silva, P.; Guimarães, F.; Sadaei, H." self.detail = "Silva, P.; Guimarães, F.; Sadaei, H."
self.flrgs = {} self.flrgs = {}
self.globalFrequency = 0 self.globalFrequency = 0
self.isInterval = True self.isInterval = True
self.isDensity = True self.isDensity = True
def generateFLRG(self, flrs):
flrgs = {}
l = len(flrs)
for k in np.arange(self.order +1, l):
flrg = ProbabilisticFLRG(self.order)
for kk in np.arange(k - self.order, k):
flrg.appendLHS( flrs[kk].LHS )
if flrg.strLHS() in flrgs:
flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
else:
flrgs[flrg.strLHS()] = flrg;
flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
self.globalFrequency = self.globalFrequency + 1
return (flrgs)
def getProbability(self, flrg):
if flrg.strLHS() in self.flrgs:
return self.flrgs[ flrg.strLHS() ].frequencyCount / self.globalFrequency
else:
return 1.0 / self.globalFrequency
def getUpper(self,flrg):
if flrg.strLHS() in self.flrgs:
tmp = self.flrgs[ flrg.strLHS() ]
ret = sum(np.array([ tmp.getProbability(s) * self.setsDict[s].upper for s in tmp.RHS]))
else:
ret = sum(np.array([ 0.33 * s.upper for s in flrg.LHS]))
return ret
def getLower(self,flrg):
if flrg.strLHS() in self.flrgs:
tmp = self.flrgs[ flrg.strLHS() ]
ret = sum(np.array([ tmp.getProbability(s) * self.setsDict[s].lower for s in tmp.RHS]))
else:
ret = sum(np.array([ 0.33 * s.lower for s in flrg.LHS]))
return ret
def forecast(self,data):
ndata = np.array(data)
l = len(ndata) def generateFLRG(self, flrs):
flrgs = {}
ret = [] l = len(flrs)
for k in np.arange(self.order + 1, l):
for k in np.arange(self.order-1,l): flrg = ProbabilisticFLRG(self.order)
#print(k)
affected_flrgs = []
affected_flrgs_memberships = []
norms = []
up = []
lo = []
# Find the sets which membership > 0 for each lag
count = 0
lags = {}
if self.order > 1:
subset = ndata[k-(self.order-1) : k+1 ]
for instance in subset:
mb = common.fuzzyInstance(instance, self.sets)
tmp = np.argwhere( mb )
idx = np.ravel(tmp) #flatten the array
if idx.size == 0: # the element is out of the bounds of the Universe of Discourse
if math.ceil(instance) <= self.sets[0].lower:
idx = [0]
elif math.ceil(instance) >= self.sets[-1].upper:
idx = [len(self.sets)-1]
else:
raise Exception( instance )
lags[count] = idx for kk in np.arange(k - self.order, k):
count = count + 1 flrg.appendLHS(flrs[kk].LHS)
# Build the tree with all possible paths
root = tree.FLRGTreeNode(None)
self.buildTree(root,lags,0)
# Trace the possible paths and build the PFLRG's
for p in root.paths():
path = list(reversed(list(filter(None.__ne__, p))))
flrg = hofts.HighOrderFLRG(self.order)
for kk in path: flrg.appendLHS(self.sets[ kk ])
assert len(flrg.LHS) == subset.size, str(subset) + " -> " + str([s.name for s in flrg.LHS])
##
affected_flrgs.append( flrg )
# Find the general membership of FLRG
affected_flrgs_memberships.append(min(self.getSequenceMembership(subset, flrg.LHS)))
else: if flrg.strLHS() in flrgs:
flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
mv = common.fuzzyInstance(ndata[k],self.sets) # get all membership values else:
tmp = np.argwhere( mv ) # get the indices of values > 0 flrgs[flrg.strLHS()] = flrg;
idx = np.ravel(tmp) # flatten the array flrgs[flrg.strLHS()].appendRHS(flrs[k].RHS)
if idx.size == 0: # the element is out of the bounds of the Universe of Discourse
if math.ceil(ndata[k]) <= self.sets[0].lower:
idx = [0]
elif math.ceil(ndata[k]) >= self.sets[-1].upper:
idx = [len(self.sets)-1]
else:
raise Exception( ndata[k] )
for kk in idx: self.globalFrequency = self.globalFrequency + 1
flrg = hofts.HighOrderFLRG(self.order) return (flrgs)
flrg.appendLHS(self.sets[ kk ])
affected_flrgs.append( flrg )
affected_flrgs_memberships.append(mv[kk])
count = 0
for flrg in affected_flrgs:
# achar o os bounds de cada FLRG, ponderados pela probabilidade e pertinência
norm = self.getProbability(flrg) * affected_flrgs_memberships[count]
if norm == 0:
norm = self.getProbability(flrg) # * 0.001
up.append( norm * self.getUpper(flrg) )
lo.append( norm * self.getLower(flrg) )
norms.append(norm)
count = count + 1
# gerar o intervalo
norm = sum(norms)
if norm == 0:
ret.append( [ 0, 0 ] )
else:
ret.append( [ sum(lo)/norm, sum(up)/norm ] )
return ret
def forecastAhead(self,data,steps):
ret = [[data[k],data[k]] for k in np.arange(len(data)-self.order,len(data))]
for k in np.arange(self.order-1,steps): def getProbability(self, flrg):
if flrg.strLHS() in self.flrgs:
if ret[-1][0] <= self.sets[0].lower and ret[-1][1] >= self.sets[-1].upper: return self.flrgs[flrg.strLHS()].frequencyCount / self.globalFrequency
ret.append(ret[-1]) else:
else: return 1.0 / self.globalFrequency
lower = self.forecast( [ret[x][0] for x in np.arange(k-self.order,k)] )
upper = self.forecast( [ret[x][1] for x in np.arange(k-self.order,k)] ) def getUpper(self, flrg):
if flrg.strLHS() in self.flrgs:
ret.append([np.min(lower),np.max(upper)]) tmp = self.flrgs[flrg.strLHS()]
ret = sum(np.array([tmp.getProbability(s) * self.setsDict[s].upper for s in tmp.RHS]))
return ret else:
ret = sum(np.array([0.33 * s.upper for s in flrg.LHS]))
def getGridClean(self,resolution): return ret
grid = {}
for sbin in np.arange(self.sets[0].lower,self.sets[-1].upper,resolution): def getLower(self, flrg):
grid[sbin] = 0 if flrg.strLHS() in self.flrgs:
tmp = self.flrgs[flrg.strLHS()]
return grid ret = sum(np.array([tmp.getProbability(s) * self.setsDict[s].lower for s in tmp.RHS]))
else:
def gridCount(self, grid, resolution, interval): ret = sum(np.array([0.33 * s.lower for s in flrg.LHS]))
for sbin in sorted(grid): return ret
if sbin >= interval[0] and (sbin + resolution) <= interval[1]:
grid[sbin] = grid[sbin] + 1 def forecast(self, data):
return grid
ndata = np.array(data)
def forecastDistributionAhead2(self,data,steps,resolution):
l = len(ndata)
ret = []
ret = []
intervals = self.forecastAhead(data,steps)
for k in np.arange(self.order - 1, l):
for k in np.arange(self.order,steps):
# print(k)
grid = self.getGridClean(resolution)
grid = self.gridCount(grid,resolution, intervals[k]) affected_flrgs = []
affected_flrgs_memberships = []
lags = {} norms = []
cc = 0 up = []
for x in np.arange(k-self.order,k): lo = []
tmp = []
for qt in np.arange(0,100,5): # Find the sets which membership > 0 for each lag
tmp.append(intervals[x][0] + qt*(intervals[x][1]-intervals[x][0])/100) count = 0
tmp.append(intervals[x][1] - qt*(intervals[x][1]-intervals[x][0])/100) lags = {}
tmp.append(intervals[x][0] + (intervals[x][1]-intervals[x][0])/2) if self.order > 1:
subset = ndata[k - (self.order - 1): k + 1]
lags[cc] = tmp
for instance in subset:
cc = cc + 1 mb = FuzzySet.fuzzyInstance(instance, self.sets)
# Build the tree with all possible paths tmp = np.argwhere(mb)
idx = np.ravel(tmp) # flatten the array
root = tree.FLRGTreeNode(None)
if idx.size == 0: # the element is out of the bounds of the Universe of Discourse
self.buildTree(root,lags,0) if math.ceil(instance) <= self.sets[0].lower:
idx = [0]
# Trace the possible paths and build the PFLRG's elif math.ceil(instance) >= self.sets[-1].upper:
idx = [len(self.sets) - 1]
for p in root.paths(): else:
path = list(reversed(list(filter(None.__ne__, p)))) raise Exception(instance)
subset = [kk for kk in path] lags[count] = idx
count = count + 1
qtle = self.forecast(subset)
grid = self.gridCount(grid,resolution, np.ravel(qtle)) # Build the tree with all possible paths
tmp = np.array([ grid[k] for k in sorted(grid) ]) root = tree.FLRGTreeNode(None)
ret.append( tmp/sum(tmp) )
self.buildTree(root, lags, 0)
grid = self.getGridClean(resolution)
df = pd.DataFrame(ret, columns=sorted(grid)) # Trace the possible paths and build the PFLRG's
return df
for p in root.paths():
def forecastDistributionAhead(self,data,steps,resolution): path = list(reversed(list(filter(None.__ne__, p))))
flrg = hofts.HighOrderFLRG(self.order)
ret = [] for kk in path: flrg.appendLHS(self.sets[kk])
intervals = self.forecastAhead(data,steps) assert len(flrg.LHS) == subset.size, str(subset) + " -> " + str([s.name for s in flrg.LHS])
for k in np.arange(self.order,steps): ##
affected_flrgs.append(flrg)
grid = self.getGridClean(resolution)
grid = self.gridCount(grid,resolution, intervals[k]) # Find the general membership of FLRG
affected_flrgs_memberships.append(min(self.getSequenceMembership(subset, flrg.LHS)))
for qt in np.arange(1,50,2):
#print(qt) else:
qtle_lower = self.forecast([intervals[x][0] + qt*(intervals[x][1]-intervals[x][0])/100 for x in np.arange(k-self.order,k)] )
grid = self.gridCount(grid,resolution, np.ravel(qtle_lower)) mv = FuzzySet.fuzzyInstance(ndata[k], self.sets) # get all membership values
qtle_upper = self.forecast([intervals[x][1] - qt*(intervals[x][1]-intervals[x][0])/100 for x in np.arange(k-self.order,k)] ) tmp = np.argwhere(mv) # get the indices of values > 0
grid = self.gridCount(grid,resolution, np.ravel(qtle_upper)) idx = np.ravel(tmp) # flatten the array
qtle_mid = self.forecast([intervals[x][0] + (intervals[x][1]-intervals[x][0])/2 for x in np.arange(k-self.order,k)] )
grid = self.gridCount(grid,resolution, np.ravel(qtle_mid)) if idx.size == 0: # the element is out of the bounds of the Universe of Discourse
if math.ceil(ndata[k]) <= self.sets[0].lower:
tmp = np.array([ grid[k] for k in sorted(grid) ]) idx = [0]
elif math.ceil(ndata[k]) >= self.sets[-1].upper:
ret.append( tmp/sum(tmp) ) idx = [len(self.sets) - 1]
else:
grid = self.getGridClean(resolution) raise Exception(ndata[k])
df = pd.DataFrame(ret, columns=sorted(grid))
return df for kk in idx:
flrg = hofts.HighOrderFLRG(self.order)
def __str__(self): flrg.appendLHS(self.sets[kk])
tmp = self.name + ":\n" affected_flrgs.append(flrg)
for r in sorted(self.flrgs): affected_flrgs_memberships.append(mv[kk])
p = round(self.flrgs[r].frequencyCount / self.globalFrequency,3)
tmp = tmp + "(" + str(p) + ") " + str(self.flrgs[r]) + "\n" count = 0
return tmp for flrg in affected_flrgs:
# achar o os bounds de cada FLRG, ponderados pela probabilidade e pertinência
norm = self.getProbability(flrg) * affected_flrgs_memberships[count]
if norm == 0:
norm = self.getProbability(flrg) # * 0.001
up.append(norm * self.getUpper(flrg))
lo.append(norm * self.getLower(flrg))
norms.append(norm)
count = count + 1
# gerar o intervalo
norm = sum(norms)
if norm == 0:
ret.append([0, 0])
else:
ret.append([sum(lo) / norm, sum(up) / norm])
return ret
def forecastAhead(self, data, steps):
ret = [[data[k], data[k]] for k in np.arange(len(data) - self.order, len(data))]
for k in np.arange(self.order - 1, steps):
if ret[-1][0] <= self.sets[0].lower and ret[-1][1] >= self.sets[-1].upper:
ret.append(ret[-1])
else:
lower = self.forecast([ret[x][0] for x in np.arange(k - self.order, k)])
upper = self.forecast([ret[x][1] for x in np.arange(k - self.order, k)])
ret.append([np.min(lower), np.max(upper)])
return ret
def getGridClean(self, resolution):
grid = {}
for sbin in np.arange(self.sets[0].lower, self.sets[-1].upper, resolution):
grid[sbin] = 0
return grid
def gridCount(self, grid, resolution, interval):
for sbin in sorted(grid):
if sbin >= interval[0] and (sbin + resolution) <= interval[1]:
grid[sbin] = grid[sbin] + 1
return grid
def forecastDistributionAhead2(self, data, steps, resolution):
ret = []
intervals = self.forecastAhead(data, steps)
for k in np.arange(self.order, steps):
grid = self.getGridClean(resolution)
grid = self.gridCount(grid, resolution, intervals[k])
lags = {}
cc = 0
for x in np.arange(k - self.order, k):
tmp = []
for qt in np.arange(0, 100, 5):
tmp.append(intervals[x][0] + qt * (intervals[x][1] - intervals[x][0]) / 100)
tmp.append(intervals[x][1] - qt * (intervals[x][1] - intervals[x][0]) / 100)
tmp.append(intervals[x][0] + (intervals[x][1] - intervals[x][0]) / 2)
lags[cc] = tmp
cc = cc + 1
# Build the tree with all possible paths
root = tree.FLRGTreeNode(None)
self.buildTree(root, lags, 0)
# Trace the possible paths and build the PFLRG's
for p in root.paths():
path = list(reversed(list(filter(None.__ne__, p))))
subset = [kk for kk in path]
qtle = self.forecast(subset)
grid = self.gridCount(grid, resolution, np.ravel(qtle))
tmp = np.array([grid[k] for k in sorted(grid)])
ret.append(tmp / sum(tmp))
grid = self.getGridClean(resolution)
df = pd.DataFrame(ret, columns=sorted(grid))
return df
def forecastDistributionAhead(self, data, steps, resolution):
ret = []
intervals = self.forecastAhead(data, steps)
for k in np.arange(self.order, steps):
grid = self.getGridClean(resolution)
grid = self.gridCount(grid, resolution, intervals[k])
for qt in np.arange(1, 50, 2):
# print(qt)
qtle_lower = self.forecast([intervals[x][0] + qt * (intervals[x][1] - intervals[x][0]) / 100 for x in
np.arange(k - self.order, k)])
grid = self.gridCount(grid, resolution, np.ravel(qtle_lower))
qtle_upper = self.forecast([intervals[x][1] - qt * (intervals[x][1] - intervals[x][0]) / 100 for x in
np.arange(k - self.order, k)])
grid = self.gridCount(grid, resolution, np.ravel(qtle_upper))
qtle_mid = self.forecast(
[intervals[x][0] + (intervals[x][1] - intervals[x][0]) / 2 for x in np.arange(k - self.order, k)])
grid = self.gridCount(grid, resolution, np.ravel(qtle_mid))
tmp = np.array([grid[k] for k in sorted(grid)])
ret.append(tmp / sum(tmp))
grid = self.getGridClean(resolution)
df = pd.DataFrame(ret, columns=sorted(grid))
return df
def __str__(self):
tmp = self.name + ":\n"
for r in sorted(self.flrgs):
p = round(self.flrgs[r].frequencyCount / self.globalFrequency, 3)
tmp = tmp + "(" + str(p) + ") " + str(self.flrgs[r]) + "\n"
return tmp

149
sadaei.py
View File

@ -1,81 +1,82 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet,FLR
import fts
class ExponentialyWeightedFLRG: class ExponentialyWeightedFLRG:
def __init__(self,LHS,c): def __init__(self, LHS, c):
self.LHS = LHS self.LHS = LHS
self.RHS = [] self.RHS = []
self.count = 0.0 self.count = 0.0
self.c = c self.c = c
def append(self, c):
self.RHS.append(c)
self.count = self.count + 1.0
def weights(self):
wei = [self.c ** k for k in np.arange(0.0, self.count, 1.0)]
tot = sum(wei)
return np.iarray([k / tot for k in wei])
def __str__(self):
tmp = self.LHS.name + " -> "
tmp2 = ""
cc = 0
wei = [self.c ** k for k in np.arange(0.0, self.count, 1.0)]
tot = sum(wei)
for c in sorted(self.RHS, key=lambda s: s.name):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c.name + "(" + str(wei[cc] / tot) + ")"
cc = cc + 1
return tmp + tmp2
def append(self,c):
self.RHS.append(c)
self.count = self.count + 1.0
def weights(self):
wei = [ self.c**k for k in np.arange(0.0,self.count,1.0)]
tot = sum( wei )
return np.array([ k/tot for k in wei ])
def __str__(self):
tmp = self.LHS.name + " -> "
tmp2 = ""
cc = 0
wei = [ self.c**k for k in np.arange(0.0,self.count,1.0)]
tot = sum( wei )
for c in sorted(self.RHS, key=lambda s: s.name):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c.name + "(" + str(wei[cc]/tot) + ")"
cc = cc + 1
return tmp + tmp2
class ExponentialyWeightedFTS(fts.FTS): class ExponentialyWeightedFTS(fts.FTS):
def __init__(self,name): def __init__(self, name):
super(ExponentialyWeightedFTS, self).__init__(1,"EWFTS") super(ExponentialyWeightedFTS, self).__init__(1, "EWFTS")
self.name = "Exponentialy Weighted FTS" self.name = "Exponentialy Weighted FTS"
self.detail = "Sadaei" self.detail = "Sadaei"
self.c = 1 self.c = 1
def generateFLRG(self, flrs, c):
flrgs = {}
for flr in flrs:
if flr.LHS.name in flrgs:
flrgs[flr.LHS.name].append(flr.RHS)
else:
flrgs[flr.LHS.name] = ExponentialyWeightedFLRG(flr.LHS, c);
flrgs[flr.LHS.name].append(flr.RHS)
return (flrgs)
def train(self, data, sets, c): def generateFLRG(self, flrs, c):
self.c = c flrgs = {}
self.sets = sets for flr in flrs:
tmpdata = common.fuzzySeries(data,sets) if flr.LHS.name in flrgs:
flrs = common.generateRecurrentFLRs(tmpdata) flrgs[flr.LHS.name].append(flr.RHS)
self.flrgs = self.generateFLRG(flrs,c) else:
flrgs[flr.LHS.name] = ExponentialyWeightedFLRG(flr.LHS, c);
def forecast(self,data): flrgs[flr.LHS.name].append(flr.RHS)
l = 1 return (flrgs)
ndata = np.array(data) def train(self, data, sets, c):
self.c = c
l = len(ndata) self.sets = sets
tmpdata = FuzzySet.fuzzySeries(data, sets)
ret = [] flrs = FLR.generateRecurrentFLRs(tmpdata)
self.flrgs = self.generateFLRG(flrs, c)
for k in np.arange(0,l):
def forecast(self, data):
mv = common.fuzzyInstance(ndata[k], self.sets) l = 1
actual = self.sets[ np.argwhere( mv == max(mv) )[0,0] ] ndata = np.array(data)
if actual.name not in self.flrgs: l = len(ndata)
ret.append(actual.centroid)
else: ret = []
flrg = self.flrgs[actual.name]
mp = self.getMidpoints(flrg) for k in np.arange(0, l):
ret.append( mp.dot( flrg.weights() )) mv = FuzzySet.fuzzyInstance(ndata[k], self.sets)
return ret actual = self.sets[np.argwhere(mv == max(mv))[0, 0]]
if actual.name not in self.flrgs:
ret.append(actual.centroid)
else:
flrg = self.flrgs[actual.name]
mp = self.getMidpoints(flrg)
ret.append(mp.dot(flrg.weights()))
return ret

123
sfts.py
View File

@ -1,68 +1,69 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet,FLR
import fts
class SeasonalFLRG(fts.FTS): class SeasonalFLRG(fts.FTS):
def __init__(self,seasonality): def __init__(self, seasonality):
self.LHS = seasonality self.LHS = seasonality
self.RHS = [] self.RHS = []
def append(self,c): def append(self, c):
self.RHS.append(c) self.RHS.append(c)
def __str__(self):
tmp = str(self.LHS) + " -> "
tmp2 = ""
for c in sorted(self.RHS, key=lambda s: s.name):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c.name
return tmp + tmp2
def __str__(self):
tmp = str(self.LHS) + " -> "
tmp2 = ""
for c in sorted(self.RHS, key=lambda s: s.name):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c.name
return tmp + tmp2
class SeasonalFTS(fts.FTS): class SeasonalFTS(fts.FTS):
def __init__(self,name): def __init__(self, name):
super(SeasonalFTS, self).__init__(1,"SFTS") super(SeasonalFTS, self).__init__(1, "SFTS")
self.name = "Seasonal FTS" self.name = "Seasonal FTS"
self.detail = "Chen" self.detail = "Chen"
self.seasonality = 1 self.seasonality = 1
self.isSeasonal = True self.isSeasonal = True
def generateFLRG(self, flrs):
def generateFLRG(self, flrs): flrgs = []
flrgs = [] season = 1
season = 1 for flr in flrs:
for flr in flrs: if len(flrgs) < self.seasonality:
if len(flrgs) < self.seasonality: flrgs.append(SeasonalFLRG(season))
flrgs.append(SeasonalFLRG(season))
flrgs[season].append(flr.RHS)
flrgs[season].append(flr.RHS)
season = (season + 1) % (self.seasonality + 1)
season = (season + 1) % (self.seasonality + 1)
if season == 0: season = 1
if season == 0: season = 1
return (flrgs)
return (flrgs)
def train(self, data, sets, seasonality):
def train(self, data, sets, seasonality): self.sets = sets
self.sets = sets self.seasonality = seasonality
self.seasonality = seasonality tmpdata = FuzzySet.fuzzySeries(data, sets)
tmpdata = common.fuzzySeries(data,sets) flrs = FLR.generateRecurrentFLRs(tmpdata)
flrs = common.generateRecurrentFLRs(tmpdata) self.flrgs = self.generateFLRG(flrs)
self.flrgs = self.generateFLRG(flrs)
def forecast(self, data):
def forecast(self,data):
ndata = np.array(data)
ndata = np.array(data)
l = len(ndata)
l = len(ndata)
ret = []
ret = []
for k in np.arange(1, l):
for k in np.arange(1,l): flrg = self.flrgs[data[k]]
flrg = self.flrgs[ data[k] ]
mp = self.getMidpoints(flrg)
mp = self.getMidpoints(flrg)
ret.append(sum(mp) / len(mp))
ret.append(sum(mp)/len(mp))
return ret
return ret

81
tree.py
View File

@ -4,48 +4,49 @@ import numpy as np
class FLRGTreeNode: class FLRGTreeNode:
def __init__(self, value):
def __init__(self,value): self.isRoot = False
self.isRoot = False self.children = []
self.children = [] self.value = value
self.value = value
def appendChild(self, child):
def appendChild(self,child): self.children.append(child)
self.children.append(child)
def getChildren(self):
def getChildren(self): for child in self.children:
for child in self.children: yield child
yield child
def paths(self, acc=[]):
def paths(self, acc=[]): if len(self.children) == 0:
if len(self.children) == 0: yield [self.value] + acc
yield [self.value]+acc
for child in self.children:
for leaf_path in child.paths([self.value] + acc): # these two
yield leaf_path
def getStr(self, k):
if self.isRoot:
tmp = str(self.value)
else:
tmp = "\\" + ("-" * k) + str(self.value)
for child in self.getChildren():
tmp = tmp + "\n" + child.getStr(k + 1)
return tmp
def __str__(self):
return self.getStr(0)
for child in self.children:
for leaf_path in child.paths([self.value]+acc): # these two
yield leaf_path
def getStr(self,k):
if self.isRoot:
tmp = str(self.value)
else:
tmp = "\\" + ("-" * k) + str(self.value)
for child in self.getChildren():
tmp = tmp + "\n" + child.getStr(k + 1)
return tmp
def __str__(self):
return self.getStr(0)
class FLRGTree: class FLRGTree:
def __init__(self): def __init__(self):
self.root = FLRGTreeNode(None) self.root = FLRGTreeNode(None)
def flat(dados): def flat(dados):
for inst in dados: for inst in dados:
if isinstance(inst, (list, tuple)): if isinstance(inst, (list, tuple)):
x = flat(inst) x = flat(inst)
for k in x: for k in x:
yield k yield k
else: else:
yield inst yield inst

137
yu.py
View File

@ -1,77 +1,78 @@
import numpy as np import numpy as np
from pyFTS import * from pyFTS.common import FuzzySet,FLR
import fts
class WeightedFLRG(fts.FTS): class WeightedFLRG(fts.FTS):
def __init__(self,LHS): def __init__(self, LHS):
self.LHS = LHS self.LHS = LHS
self.RHS = [] self.RHS = []
self.count = 1.0 self.count = 1.0
def append(self,c): def append(self, c):
self.RHS.append(c) self.RHS.append(c)
self.count = self.count + 1.0 self.count = self.count + 1.0
def weights(self):
tot = sum(np.arange(1.0, self.count, 1.0))
return np.array([k / tot for k in np.arange(1.0, self.count, 1.0)])
def __str__(self):
tmp = self.LHS.name + " -> "
tmp2 = ""
cc = 1.0
tot = sum(np.arange(1.0, self.count, 1.0))
for c in sorted(self.RHS, key=lambda s: s.name):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c.name + "(" + str(round(cc / tot, 3)) + ")"
cc = cc + 1.0
return tmp + tmp2
def weights(self):
tot = sum( np.arange(1.0,self.count,1.0) )
return np.array([ k/tot for k in np.arange(1.0,self.count,1.0) ])
def __str__(self):
tmp = self.LHS.name + " -> "
tmp2 = ""
cc = 1.0
tot = sum( np.arange(1.0,self.count,1.0) )
for c in sorted(self.RHS, key=lambda s: s.name):
if len(tmp2) > 0:
tmp2 = tmp2 + ","
tmp2 = tmp2 + c.name + "(" + str(round(cc/tot,3)) + ")"
cc = cc + 1.0
return tmp + tmp2
class WeightedFTS(fts.FTS): class WeightedFTS(fts.FTS):
def __init__(self,name): def __init__(self, name):
super(WeightedFTS, self).__init__(1,"WFTS") super(WeightedFTS, self).__init__(1, "WFTS")
self.name = "Weighted FTS" self.name = "Weighted FTS"
self.detail = "Yu" self.detail = "Yu"
def generateFLRG(self, flrs):
def generateFLRG(self, flrs): flrgs = {}
flrgs = {} for flr in flrs:
for flr in flrs: if flr.LHS.name in flrgs:
if flr.LHS.name in flrgs: flrgs[flr.LHS.name].append(flr.RHS)
flrgs[flr.LHS.name].append(flr.RHS) else:
else: flrgs[flr.LHS.name] = WeightedFLRG(flr.LHS);
flrgs[flr.LHS.name] = WeightedFLRG(flr.LHS); flrgs[flr.LHS.name].append(flr.RHS)
flrgs[flr.LHS.name].append(flr.RHS) return (flrgs)
return (flrgs)
def train(self, data, sets): def train(self, data, sets):
self.sets = sets self.sets = sets
tmpdata = common.fuzzySeries(data,sets) tmpdata = FuzzySet.fuzzySeries(data, sets)
flrs = common.generateRecurrentFLRs(tmpdata) flrs = FLR.generateRecurrentFLRs(tmpdata)
self.flrgs = self.generateFLRG(flrs) self.flrgs = self.generateFLRG(flrs)
def forecast(self,data): def forecast(self, data):
l = 1 l = 1
ndata = np.array(data) ndata = np.array(data)
l = len(ndata) l = len(ndata)
ret = [] ret = []
for k in np.arange(0,l): for k in np.arange(0, l):
mv = common.fuzzyInstance(ndata[k], self.sets) mv = FuzzySet.fuzzyInstance(ndata[k], self.sets)
actual = self.sets[ np.argwhere( mv == max(mv) )[0,0] ] actual = self.sets[np.argwhere(mv == max(mv))[0, 0]]
if actual.name not in self.flrgs: if actual.name not in self.flrgs:
ret.append(actual.centroid) ret.append(actual.centroid)
else: else:
flrg = self.flrgs[actual.name] flrg = self.flrgs[actual.name]
mp = self.getMidpoints(flrg) mp = self.getMidpoints(flrg)
ret.append( mp.dot( flrg.weights() )) ret.append(mp.dot(flrg.weights()))
return ret return ret