예제 #1
0
파일: nilm.py 프로젝트: SoapClancy/Load
def energies_paper_train_nilm_models_for_ampds2_dataset(top_n: int = 3):
    """
    只从ampds2_dataset中的training_set中选取top_n个(默认3个)appliance。分别是HPE, FRE and CDE。
    这里是符合nilmtk标准的算法。
    torch的算法单独处理
    :return:
    """
    # 准备训练数据
    training_set, test_set, _ = get_training_set_and_test_set_for_ampds2_dataset(
    )
    top_n_train_elec = training_set.select_using_appliances(
        original_name=['HPE', 'FRE', 'CDE'])
    # 模型save的路径
    models_path = Path('../../../Data/Results/Energies_paper/Ampds2')
    models_path.mkdir(parents=True, exist_ok=True)
    # 训练所有模型
    models = {'CO': CombinatorialOptimisation(), 'FHMM': FHMM()}
    sample_period = 60  # 都是down sample到60s
    for this_model_name, this_model in models.items():
        this_model_file = models_path / (this_model_name + '.pkl')
        if try_to_find_file(this_model_file):
            this_model.import_model(this_model_file)
        else:
            print("*" * 20)
            print(this_model_name)
            print("*" * 20)
            start = time.time()
            this_model.train(top_n_train_elec, sample_period=sample_period)
            this_model.export_model(this_model_file)
            end = time.time()
            print("Runtime =", end - start, "seconds.")
예제 #2
0
    def test_fhmm_correctness(self):
        elec = self.dataset.buildings[1].elec
        fhmm = FHMM()
        fhmm.train(elec)
        mains = elec.mains()
        output = HDFDataStore('output.h5', 'w')
        fhmm.disaggregate(mains, output, sample_period=1)

        for meter in range(2, 4):
            df1 = output.store.get('/building1/elec/meter{}'.format(meter))
            df2 = self.dataset.store.store.get(
                '/building1/elec/meter{}'.format(meter))

            self.assertEqual((df1 == df2).sum().values[0], len(df1.index))
            self.assertEqual(len(df1.index), len(df2.index))
        output.close()
        remove("output.h5")
print("....")
train = DataSet('C:/Users/20552/Desktop/HMM/HMM/NMLTK/iawe.h5')
test = DataSet('C:/Users/20552/Desktop/HMM/HMM/NMLTK/iawe.h5')
test_use = DataSet('C:/Users/20552/Desktop/HMM/HMM/NMLTK/iawe.h5')
building = 1
train.set_window(end="2013-07-13")
test.set_window(start="2013-07-13")
test_use.set_window(start="2013-07-13")
train_elec = train.buildings[1].elec
test_elec = test.buildings[1].elec
#test_use_elec = test_use.buildings[1].elec
print(test_elec)
#top_5_train_elec = train_elec.submeters().select_top_k(k=10)
top_5_train_elec = train_elec.submeters().select_top_k(k=5)

classifiers = {'CO':CombinatorialOptimisation(), 'FHMM':FHMM()}
classifiers = {'FHMM':FHMM()}
predictions = {}
sample_period = 5
for clf_name, clf in classifiers.items():
    print("*"*20)
    print(clf_name)
    print("*" *20)
    clf.train(top_5_train_elec, sample_period=sample_period)
    for i in range(50):
        ep=1-i*0.02
        #test_elec = laplace(test_elec,ep)
        temp=[]
        temp_1=[]
        for j in range(5):
            gt, predictions[clf_name] = predict(clf, test_elec,5, train.metadata['timezone'],ep)
예제 #4
0
    gt_overall = gt_overall.loc[common_index_local]
    pred_overall = pred_overall.loc[common_index_local]
    appliance_labels = [m for m in gt_overall.columns.values]
    gt_overall.columns = appliance_labels
    pred_overall.columns = appliance_labels
    
    return gt_overall, pred_overall

# Since the methods use randomized initialization, let's fix a seed here
# to make this notebook reproducible
import numpy.random
numpy.random.seed(42)
sample_period = 120 
predictions = []
gts = []
fhmm = FHMM()
for building in range(5):
    print('*' * 20 )
    print('Casa : {}'.format(building))
    print('Usando o metodo FHHM...')
    print('*' * 20 )
    fhmm.train(top_5_train_elec[building], sample_period=sample_period)
    gt, prediction = predict(fhmm, test_elec[building], sample_period, train.metadata['timezone'])
    gts.append(gt)
    predictions.append(prediction)

for i in range(5):
    appliance_labels = [m.label() for m in gts[i].columns.values]
    gts[i].columns = appliance_labels
    predictions[i].columns = appliance_labels
예제 #5
0
        thread_processamento.start()

        for b in buffer:
            response.write(b.encode())

        self.wfile.write(response.getvalue())


print("[OK] Carregando base de dados da casa: " + str(HOUSE))
buffer = []
train = DataSet('banco_unifei_casa_2.h5')
#Enumera todas as casas
buildings = [i for i in range(3)]
#Vetor que guarda os dados de todas as casas
train_elec = [None for i in range(3)]
for building in buildings:
    train_elec[building] = train.buildings[building + 1].elec

print("[OK] Treinamento inicializado...")
numpy.random.seed(42)
sample_period = 120
predictions = []
gts = []
fhmm = FHMM()
fhmm.train(train_elec[0], sample_period=sample_period)

print("[OK] Processo de desagregacao iniciado...")
httpd = HTTPServer((SERVER_IP, PORT), SimpleHTTPRequestHandler)
print("[OK] Servidor HTTP Estabelecido com sucesso")
httpd.serve_forever()