Exemplo n.º 1
0
    def create(
        country_id,
        measure_type,
        measure_value,
        measure_date
    ):
        """ Create a new measure """
        measure = Measure(
            country_id,
            measure_type,
            measure_value,
            measure_date
        )

        return measure.save()
Exemplo n.º 2
0
def handle_measure():
    """
    Trae lista de medida (GET) y agrega una medida (POST)
    """

    # POST request
    if request.method == 'POST':
        body = request.get_json()

        if body is None:
            raise APIException("You need to specify the request body as a json object", status_code=400)
        if 'name' not in body:
            raise APIException('You need to specify the name', status_code=400)
        if 'unit' not in body:
            raise APIException('You need to specify the unit', status_code=400)
        if 'symbol' not in body:
            raise APIException('You need to specify the symbol', status_code=400)

        measure1 = Measure(name=body['name'], unit=body['unit'], symbol=body['symbol'])
        db.session.add(measure1)
        db.session.commit()
        return "ok", 200

    # GET request
    if request.method == 'GET':
        all_measures = Measure.query.all()
        all_measures = list(map(lambda x: x.serialize(), all_measures))
        return jsonify(all_measures), 200

    return "Invalid Method", 404
Exemplo n.º 3
0
def LSTM(X_train_seq, X_test_seq, y_train, y_test):
    max_words = 10000
    max_len = 200
    lstm_model = Sequential()
    lstm_model.add(Embedding(max_words, 50, input_length=max_len))
    lstm_model.add(LSTM_lib(128, dropout=0.25, recurrent_dropout=0.25))
    lstm_model.add(Dense(1, activation='sigmoid'))
    lstm_model.compile(loss='binary_crossentropy',
                       optimizer='adam',
                       metrics=['accuracy'])

    print('Train model')
    lstm_model.fit(X_train_seq,
                   y_train,
                   batch_size=32,
                   epochs=3,
                   validation_data=(X_test_seq, y_test))
    y_pred = lstm_model.predict_classes(X_test_seq)
    lstm_model.save('51_acc_language_model.h5')
    acc_score = accuracy_score(y_test, y_pred)
    precision, recall, fscore, support = score(y_test,
                                               y_pred,
                                               average='weighted')
    target_names = ['Non-Spam', 'Spam']
    print(classification_report(y_test, y_pred, target_names=target_names))
    return Measure.Measure(acc_score, precision, recall, fscore)
Exemplo n.º 4
0
    def GET(self, name):
        """Get Measures with descriptions"""
        results = Measure.get_all()
        data = results_to_measures(results, True)

        if not data:
            raise Error(NORESULT)
        return data
Exemplo n.º 5
0
def save_measure_in_db(session, data, point):
    objects = []
    value = data.pop(0)

    my_ssid = Ssid(value[0])
    my_bssid = Bssid(value[1])
    my_measure = Measure(value[2])
    my_channel = Channel(value[3])
    my_security = Security(value[4])
    my_point = Point(point)

    entry = session.query(Ssid).filter(Ssid.ssid_value.like(value[0])).first()
    if entry is None:
        my_ssid.measure.append(my_measure)
        objects.append(my_ssid)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Bssid).filter(Bssid.bssid_value.like(
        value[1])).first()
    if entry is None:
        my_bssid.measure.append(my_measure)
        objects.append(my_bssid)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Channel).filter(Channel.channel_number.like(
        value[3])).first()
    if entry is None:
        my_channel.measure.append(my_measure)
        objects.append(my_channel)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Security).filter(
        Security.security_type.like(value[4])).first()
    if entry is None:
        my_security.measure.append(my_measure)
        objects.append(my_security)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Point).filter(Point.x_location == point.x).filter(
        Point.y_location == point.y).first()
    if entry is None:
        my_point.measure.append(my_measure)
        objects.append(my_point)
    else:
        entry.measure.append(my_measure)

    objects.append(my_measure)

    session.add_all(objects)
    session.commit()
    if len(data) != 0:
        save_measure_in_db(session, data, point)
    else:
        return
Exemplo n.º 6
0
def postSensor(id):
    sensor = Sensor.query.get(id)
    data = request.json
    if sensor:
        data['sensor_id'] = id
        data['update_on'] = datetime.now()
        m = Measure(**data)
        db.session.add(m)
        db.session.commit()
    else:
        abort(404)

    return json.dumps({"result": "OK"})
Exemplo n.º 7
0
def fill_measures():
    """
    Llena con medidas (POST)
    """

    # POST request
    if request.method == 'POST':
        for i in range(3):
            measures1 = Measure(name="medida"+str(i+1), unit="unidad"+str(i+1), symbol="símbolo"+str(i+1))
            db.session.add(measures1)
        db.session.commit()
        return "ok", 200

    return "Invalid Method", 404
Exemplo n.º 8
0
def KNN(X_train, X_test, y_train, y_test):
    KNN = KNeighborsClassifier(n_neighbors=1)
    KNN.fit(X_train, y_train)
    y_knc = KNN.predict(X_test)
    print('KNeighbors Accuracy_score: ', accuracy_score(y_test, y_knc))
    print('KNeighbors confusion_matrix:/n', confusion_matrix(y_test, y_knc))
    print(classification_report(y_test, KNN.predict(X_test)))
    joblib.dump(KNN, 'KNN.pkl')
    precision, recall, fscore, support = score(y_test,
                                               y_knc,
                                               average='weighted')
    acc_score = accuracy_score(y_test, y_knc)
    # print('Decision Tree Accuracy: ', accuracy_score(y_test, y_dtc))
    # print('Precision : {}'.format(precision))
    # print('Recall    : {}'.format(recall))
    # print('F-score   : {}'.format(fscore))
    # print('Support   : {}'.format(support))
    return Measure.Measure(acc_score, precision, recall, fscore)
Exemplo n.º 9
0
def Naive_Bayes(X_train, X_test, y_train, y_test):
    clf = MultinomialNB()
    clf.fit(X_train, y_train)
    y_mnb = clf.predict(X_test)
    cm = confusion_matrix(y_mnb, y_test)
    print(cm)
    print('Naive Bayes Accuracy: ', accuracy_score(y_test, y_mnb))
    # #in ra độ chính xác của các label
    print(classification_report(y_test, clf.predict(X_test)))
    joblib.dump(clf, 'NB.pkl')
    precision, recall, fscore, support = score(y_test,
                                               y_mnb,
                                               average='weighted')
    acc_score = accuracy_score(y_test, y_mnb)
    # print('Decision Tree Accuracy: ', accuracy_score(y_test, y_dtc))
    # print('Precision : {}'.format(precision))
    # print('Recall    : {}'.format(recall))
    # print('F-score   : {}'.format(fscore))
    # print('Support   : {}'.format(support))
    return Measure.Measure(acc_score, precision, recall, fscore)
Exemplo n.º 10
0
def SVM(X_train, X_test, y_train, y_test):
    SVM = svm.SVC(kernel='linear')  # Linear Kernel
    # Train the model using the training sets
    SVM.fit(X_train, y_train)
    # Predict the response for test dataset
    y_pred = SVM.predict(X_test)
    cm = confusion_matrix(y_pred, y_test)
    print(cm)
    print('svm  Accuracy: ', accuracy_score(y_test, y_pred))
    # #in ra độ chính xác của các label
    print(classification_report(y_test, SVM.predict(X_test)))
    joblib.dump(SVM, 'SVM.pkl')
    precision, recall, fscore, support = score(y_test,
                                               y_pred,
                                               average='weighted')
    acc_score = accuracy_score(y_test, y_pred)
    # print('Decision Tree Accuracy: ', accuracy_score(y_test, y_dtc))
    # print('Precision : {}'.format(precision))
    # print('Recall    : {}'.format(recall))
    # print('F-score   : {}'.format(fscore))
    # print('Support   : {}'.format(support))
    return Measure.Measure(acc_score, precision, recall, fscore)
Exemplo n.º 11
0
def DecisionTree(X_train, X_test, y_train, y_test):
    # huấn luyện mô hình bằng tập train và test
    dtc = DecisionTreeClassifier(min_samples_split=7, random_state=None)
    dtc.fit(X_train, y_train)
    # dự đoán cho tập dữ liệu test
    y_dtc = dtc.predict(X_test)
    cm = confusion_matrix(y_dtc, y_test)
    print(cm)
    print('Decision Tree Accuracy: ', accuracy_score(y_test, y_dtc))
    # in ra độ chính xác của các label
    print(classification_report(y_test, dtc.predict(X_test)))
    joblib.dump(dtc, 'DecisionTree.pkl')
    precision, recall, fscore, support = score(y_test,
                                               y_dtc,
                                               average='weighted')
    acc_score = accuracy_score(y_test, y_dtc)
    # print('Decision Tree Accuracy: ', accuracy_score(y_test, y_dtc))
    # print('Precision : {}'.format(precision))
    # print('Recall    : {}'.format(recall))
    # print('F-score   : {}'.format(fscore))
    # print('Support   : {}'.format(support))
    return Measure.Measure(acc_score, precision, recall, fscore)
Exemplo n.º 12
0
def index(request):
    if request.method == 'POST':
        measure = Measure()
        measure.ch1 = request.POST['ch1']
        measure.ch2 = request.POST['ch2']
        measure.ch3 = request.POST['ch3']
        measure.ch4 = request.POST['ch4']
        measure.ch5 = request.POST['ch5']
        measure.ch6 = request.POST['ch6']
        measure.ch7 = request.POST['ch7']
        measure.ch8 = request.POST['ch8']
        measure.ch9 = request.POST['ch9']
        measure.ch10 = request.POST['ch10']
        measure.ch11 = request.POST['ch11']
        measure.ch12 = request.POST['ch12']
        measure.therm = request.POST['therm']
        measure.temp = request.POST['temp']
        measure.excv = request.POST['excv']
        measure.batt = request.POST['batt']
        measure.time = request.POST['time']
        measure.date = request.POST['date']
        measure.save()
    list = Measure.objects
    listOfMeasure = []
    for m in list:
        listOfMeasure.append(m)
    context = {
        'listOfMeasure': listOfMeasure,
    }
    return render(request, 'crud/index.html', context)
Exemplo n.º 13
0
def load(request):
    import os
    fh = open(os.path.join(FILE_LOAD_DIR, 'L4286F08.txt'), "r")
    fh.readline()
    p = fh.readline()
    while p != '':
        p = p.split('\t')
        p[-1] = p[-1].split('\n')[0]
        measure = Measure()
        measure.ch1 = p[0]
        measure.ch2 = p[1]
        measure.ch3 = p[2]
        measure.ch4 = p[3]
        measure.ch5 = p[4]
        measure.ch6 = p[5]
        measure.ch7 = p[6]
        measure.ch8 = p[7]
        measure.ch9 = p[8]
        measure.ch10 = p[9]
        measure.ch11 = p[10]
        measure.ch12 = p[11]
        measure.therm = p[12]
        measure.temp = p[13]
        measure.excv = p[14]
        measure.batt = p[15]
        measure.time = p[16]
        measure.date = p[17]
        measure.save()
        p = fh.readline()
    return HttpResponseRedirect(reverse('crud:index'))