def main():
    # start model
    model = predict.build_model()

    # results array
    results = list()

    for stage in _STAGES:
        # per ogni paziente
        for patient in os.listdir('Matrices/' + stage):

            print(stage, patient, '...')

            # path matrice paziente
            patient_path = 'Matrices/{}/{}'.format(stage, patient)

            # leggo la matrice
            original_adj = np.genfromtxt(patient_path, delimiter=' ')
            original_adj = original_adj + original_adj.T
            np.fill_diagonal(original_adj, 0)

            # predizione
            data, label = predict.prediction(model, original_adj)
            c1_value, c2_value, c3_value, c4_value = data[0]

            # salvo ad indice 0
            results.append((stage, patient, 0, c1_value, c2_value, c3_value,
                            c4_value, label))

            # leggo gli archi importanti (ordine per importanza decrescente)
            important_edges = list()
            with open('ImportantEdges/' + stage + '/' +
                      patient) as impedges_file:
                important_edges = impedges_file.read().rstrip().split(' ')
                important_edges = [
                    list(map(int, x.split(','))) for x in important_edges
                ]

            # per ogni arco importante in i = 1..300
            for n_edge in range(0, 300):
                # azzero questo arco nella matrice
                x, y = important_edges[n_edge][0] - 1, important_edges[n_edge][
                    1] - 1
                original_adj[x][y] = 0
                original_adj[y][x] = 0

                # predizione
                data, label = predict.prediction(model, original_adj)
                c1_value, c2_value, c3_value, c4_value = data[0]

                # salvo ad indice i
                results.append((stage, patient, n_edge + 1, c1_value, c2_value,
                                c3_value, c4_value, label))

    # appendo al csv
    with open('results_brutefor.csv', 'w') as f_out:
        w_to_csv = csv.writer(f_out, delimiter=';')
        w_to_csv.writerow(_HEADER_CSV)
        for row in results:
            w_to_csv.writerow(row)
Пример #2
0
def detect(video_path, cascade_loc='haarcascade_frontalface_alt_tree.xml'):
    face_casc = cv.CascadeClassifier(cascade_loc)
    videCapture = cv.VideoCapture(video_path)

    if videCapture.isOpened() == False:
        print("error")
        return
    counter = 1
    while (videCapture.isOpened()):
        ret, frame = videCapture.read()
        faces = face_casc.detectMultiScale(frame, 1.3, 2)
        if ret == True:
            for (x, y, w, h) in faces:
                cv.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
                test_img = crop_from_video_as_obj(frame, (x, y, x + w, y + h))
                prediction(test_img)
            cv.imshow('test', frame)
        else:
            break
        if cv.waitKey(1) & 0xFF == ord('q'):
            break
        cv.imshow('test', frame)

    videCapture.release()
    cv.destroyAllWindows()
Пример #3
0
def upload_file():
        # for i in request.__dict__:
        #     print(i)
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            predict.prediction()
            copyfile("main.html", "templates/main.html")
    return render_template("index.html")
Пример #4
0
def main():
    # get nearest neighbor count
    if len(sys.argv) < 2:
        print("Please enter number of nearest neighbor:")
        no_of_nearest_neighbor = input()
    else:
        no_of_nearest_neighbor = sys.argv[1]

    # load dataset
    print(
        "Please put the dataset in data folder(named test.txt and train.txt)")
    train_set, test_set = load_dataset()

    print("Length of test set is %d and length of train set is %d" %
          (len(train_set), len(test_set)))

    # predictions
    p = prediction(train_set, test_set)
    print(
        "Select option- 1: Get Accuracy from test set, 2: Get Sentimental Analysis"
    )
    option = int(input())
    if (option == 1):
        print(p.get_accuracy(no_of_nearest_neighbor))
    else:
        if (option == 2):
            print('Input string to get sentiments:')
            input_data = input()
            print(p.get_sentiments(input_data, no_of_nearest_neighbor))
        else:
            print("Invalid option")
Пример #5
0
def workOnTrajectory():
    # To store my output
    blankFrame = np.zeros(shape=[rect_end, rect_end, 3], dtype=np.uint8)
    blankFrame.fill(255)

    draw_trajectory(blankFrame, traverse_point)

    #dimension of the image to crop
    l = min(traverse_point, key=lambda t: t[0])[0]
    r = max(traverse_point, key=lambda t: t[0])[0]
    u = min(traverse_point, key=lambda t: t[1])[1]
    d = max(traverse_point, key=lambda t: t[1])[1]

    l = l - 10 if l - 10 >= 0 else 0
    r = r + 10 if r + 10 <= rect_end else rect_end
    u = u - 10 if u - 10 >= 0 else 0
    d = d + 10 if d + 10 <= rect_end else rect_end

    blankFrame = blankFrame[u:d, l:r]  #crop image

    trajectory = resizeTrajectoryFrame(blankFrame)

    global predicted
    predicted = prediction(trajectory)
    assign()  #assign values to expression
Пример #6
0
def print():
    """Result page of webapp

    Args:
        Null

    Returns:
        flask-obj: rendered html page

    """
    user1 = request.form['OverallQual']
    user2 = request.form['GrLivArea']
    user3 = request.form['GarageCars']
    user4 = request.form['YearBuilt']
    user5 = request.form['FullBath']

    # logging
    #logger.info('Got user input.')

    # predict house price using model.prediction
    housepred= prediction(user1,user2,user3,user4,user5)

    # logging
    logger.info('Successfully predict price for user input.')
    return render_template('result.html', result=housepred)
Пример #7
0
def some_func(bot, update):
    pass
    if not update.effective_message.text:
        update.effective_message.reply_text(
            text="Cannot handle given format, getting aware now")
    else:
        msg = update.effective_message.text
        update.effective_message.reply_text(text=prediction(msg))
Пример #8
0
    def displayResults(self):

        path = os.path.join("portrait", "*")
        list_images = glob.glob(resource_path(path))
        print(list_images)
        latest_img = max(list_images, key=os.path.getctime)
        try:
            age_deteced, gender_detected = prediction(latest_img)
            age_deteced = [math.floor(k * 100) for k in age_deteced]
            for k in range(len(gender_detected)):
                gen = gender_detected[k]
                if gen < 0.5:
                    gen = math.floor((1 - gen) * 100)
                else:
                    gen = math.floor(gen * 100)
                gender_detected[k] = gen

            img_dir = os.path.join('detection', 'images', 'detected', '*')
            list_of_files = glob.glob(resource_path(img_dir))
            latest_file = max(list_of_files, key=os.path.getctime)

            if latest_file.endswith(".png"):
                img = cv2.imread(latest_file)
                self.displayImage(img)
            if self.language == 0:

                self.resultLabel.setText(
                    f" L'IA prédit à {gender_detected} % de confiance votre genre \net à {age_deteced} % de confiance votre age "
                )

            elif self.language == 1:

                self.resultLabel.setText(
                    f" The IA predicts your gender with {gender_detected} % of confidence\nand your age with {age_deteced} % of confidence "
                )

            elif self.language == 2:

                self.resultLabel.setText(
                    f" The IA predicts your gender with {gender_detected} % of confidence\nand your age with {age_deteced} % of confidence "
                )

            elif self.language == 3:

                self.resultLabel.setText(
                    f" The IA predicts your gender with {gender_detected} % of confidence\nand your age with {age_deteced} % of confidence "
                )

            else:

                self.resultLabel.setText(
                    f" The IA predicts your gender with {gender_detected} % of confidence\nand your age with {age_deteced} % of confidence "
                )
            self.framekeep.show()
        except Exception:
            self.facedetec = 1
            os.remove(latest_img)
Пример #9
0
    def predict(self, X_test, Y_test=[]):
        # (self.X_train, X_test) = norm.preprocess(self.X_train, X_test,1)
        result = []
        # (self.X_train, X_test) = norm.preprocess(self.X_train, X_test)
        # g, nbrs = nBuilding.networkBuildKnn(
        #     self.X_train, self.Y_train, self.knn, self.ePercentile, labels=True
        # )
        # nBuilding.getProperty(g)
        # draw.drawGraph(g,title="Graph Iris Dataset k="+str(self.knn)+" e="+str(self.ePercentile)+ " b=10 α=0.0" )
        # draw.drawGraph(g,title="" )
        g = self.graph
        results = []
        for index, instance in enumerate(X_test):
            # CHECK INDEX LNNET WAS REMOVED + index
            indexNode = g.graph["lnNet"]
            if len(Y_test) == 0:
                nBuilding.quipusInsertByInstance(g, self.nbrsGroup, instance)
            else:
                nBuilding.quipusInsertByInstance(g, self.nbrsGroup, instance,
                                                 Y_test[index])
            # draw.drawGraph(g,"New Dark Node Inserted")
            tmpResults = predict.prediction(g, self.bnn, self.alpha)
            results.append(tmpResults)
            maxIndex = np.argmax(tmpResults)
            newLabel = g.graph["classNames"][maxIndex]
            result.append(newLabel)
            # g.remove_node(str(indexNode))
            g.nodes[str(indexNode)]["label"] = newLabel
            nn = list(nx.neighbors(g, str(indexNode)))
            for node in nn:
                if g.nodes[str(node)]["label"] != newLabel:
                    g.remove_edge(str(node), str(indexNode))
            # draw.drawGraph(g,"Final Node")
            for edge in g.edges:
                g.edges[edge]["color"] = "#9db4c0"
            g.graph["index"] += 1
        # draw.drawGraph(g,title="")

        if len(Y_test) != 0:
            # print("RESULT:", np.array(result))
            # print("Y_TEST:", np.array(Y_test))
            acc = 0
            err = []
            err.append(g.graph["classNames"])
            for index, element in enumerate(result):
                if element == Y_test[index]:
                    acc += 1
                else:
                    err.append([element, Y_test[index], results[index]])
            acc /= len(X_test)

            # print("ERRORS: ", err)
            print("Accuracy ", round(acc, 2), "%")
        return result
Пример #10
0
def review_c(card):
    print("Write: " + card.bot)
    get_img()
    # os.system('clear')
    answer = predict.prediction()
    if (answer==card.top):
        os.system('clear')
        print('CORRECT!')
        return 5
    else:
        return 1
Пример #11
0
def step():
    rawim = get_captcha()
    im = Image.open(io.BytesIO(rawim))
    ans = prediction(gen_images(im))
    succ = check_captcha(ans)

    serial = '%d-%d' % (1000 * time.time(), random.random() * 1000)
    with open(
            'bootstrap_img_%s/%s=%s.gif' %
        ('succ' if succ else 'fail', ans, serial), 'wb') as f:
        f.write(rawim)

    return succ, ans
Пример #12
0
def predict_tfidf():
    """
    1) predict end point to accept label from user and load model based on the label , eg football
    2) train end point which accept columns
    3) upload end point for train.csv
    4) predict end point to accept files and folders.
    5) replicate this for other classifiers and models.
    :return:
    """
    data = json.loads(request.data.decode('utf8'))
    preds = []
    for val in data['articles']:
        preds.append(prediction(val))
    return json.dumps({'label' : preds})
Пример #13
0
def predict():

    if request.method == 'GET':
        return render_template("index.html")

    if request.method == 'POST':

        if 'imageUpload' not in request.files:
            #flash('No file part')
            return redirect(request.url)

        file = request.files['imageUpload']

        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':

            #print("YES")
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)

            for files in os.listdir('static/temp/'):
                os.remove('static/temp/' + files)

            new_filename = "temp" + str(time.time()) + '.jpg'

            file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))

            print("Loaded the Image Successfully")

            itching = int(request.form['itching'])
            discharge = int(request.form['discharge'])
            pain_blur = int(request.form['pain_blur'])

            print("Got the Form Successfully")

            pink_eye = prediction(new_filename, itching, discharge, pain_blur)

            print("result is successfully predicted: ", pink_eye)

            result = json.dumps({
                'result': pink_eye[0],
                'disease': pink_eye[1]
            })

            return (result)
Пример #14
0
def test_predict():
    """Test predict.py for array length and data type."""
    # Create a row of data and run prediction
    user1 = '10'
    user2 = '200'
    user3 = '3'
    user4 = '2010'
    user5 = '3'
    result = prediction(user1, user2, user3, user4, user5)

    # Check type of output
    assert isinstance(result, str)
    # Check prediction result
    assert result == "$120,384.98"


#test_predict()
def upload_file():
    if request.method == 'POST':
        import time
        start_time = time.time()
        file = request.files['file']

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)

            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(file_path)
            license_number = predict.prediction(file_path)

            print(license_number)
            print(file_path)
            filename = my_random_string(6) + filename

            os.rename(file_path,
                      os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print("--- %s seconds ---" % str(time.time() - start_time))
            return render_template('template.html',
                                   label=license_number,
                                   imagesource='../uploads/' + filename)
Пример #16
0
def upload_file():
    if request.method == 'POST':
        # Check if the post request has the file part
        if 'file' not in request.files:
            return '<html><body><p>No image sent</p></body></html>'
        file = request.files['file']

        # If user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            return '<html><body><p>Empty image sent</p></body></html>'
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            index = prediction(UPLOAD_FOLDER + filename).flatten().argmax()
            masks_dict = {
                0: '3M Blue',
                1: '3M Grey',
                2: 'Draeger Black',
                3: 'Draeger Grey'
            }
            return masks_dict[index]
    return "<html><body><p>404</p></body></html>"
Пример #17
0
def predict():
    JScontent = request.json
    img = JScontent["image"]
    response = prediction(img)
    return response
Пример #18
0
def predict():
    import predict
    if predict.prediction():
        return render_template("dog.html")
    return render_template("cat.html")
Пример #19
0
train = pd.read_csv("./bike-sharing-demand/train.csv")
test = pd.read_csv("./bike-sharing-demand/test.csv")

train_date = extract_date(train)
test_date = extract_date(test)

train = mod_data(train)
test = mod_data(test)

std_cols = ['temp', 'atemp', 'humidity', 'windspeed']
pred_cols = [
    'season', 'holiday', 'workingday', 'weather', 'temp', 'atemp', 'humidity',
    'windspeed', 'year', 'month', 'day', 'hour'
]
target = ['count']

if train_param['norm']:
    train = min_max_normalize(train, std_cols, -1, 1)
    test = min_max_normalize(test, std_cols, -1, 1)

X_train = np.asarray(train[pred_cols])
y_train = np.asarray(train[target])
X_train = np.expand_dims(X_train, axis=0)
y_train = np.expand_dims(y_train, axis=0)

X_test = np.asarray(test[pred_cols])
X_test = np.expand_dims(X_test, axis=0)
history, model = train_stateful_model(X_train, y_train)

prediction(test_date, X_test, model)
Пример #20
0
i=1
while True:
    ret, img= cap.read()
    #gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    #blurring the image
    
    blur=cv2.GaussianBlur(img,(15,15),0)
    
    #Applying threshold
    #th2 = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            #cv2.THRESH_BINARY,11,2)
    
    fgmask=fgbg.apply(blur)
    Colored_Mask = cv2.bitwise_and(img, img, mask=fgmask)
    nzCount = cv2.countNonZero(fgmask)
    if nzCount >= 5000 and nzCount<307200:
        cv2.imwrite(filename="screens/"+str(i)+"alpha.png", img=img)
        pred_image_only(model, img)
        i+=1
    
    cv2.imshow('image', img)
    cv2.imshow('thresh', Colored_Mask)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()
prediction(model)  
 def predict(self):
     pred.prediction(self.root, self.train[0])
Пример #22
0
def upload_file():
    if request.method == 'POST':  # POST 방식으로 전달된 경우
        f = request.files['upload_image'].read()
        # # 파일 객체 혹은 파일 스트림을 가져오고, html 파일에서 넘겨지는 값의 이름을 file1으로 했기 때문에 file1임.
        # 업로드된 파일을 특정 폴더에저장하고,

        # convert string data to numpy array
        npimg = numpy.fromstring(f, dtype=numpy.uint8)
        # convert numpy array to image
        img = cv2.imdecode(npimg, cv2.IMREAD_COLOR)

        import face_detection
        import predict
        global detector
        face_extract = face_detection.input_image(detector, img)
        print("얼굴추출 완료")
        if len(face_extract) == 0:
            print("얼굴인식 못했음")
            return render_template('fail_back.html')
        else:
            # cv2.imshow('original', face_extract)
            # cv2.waitKey(0)
            #
            # cv2.imwrite('face_test.jpg', face_extract)
            #
            #
            # img = Image.fromarray(face_extract)
            # print("fromarray")
            # #BGR - > RGB 블루끼 없애줌
            # b, g, r = img.split()
            # img = Image.merge("RGB", (r, g, b))
            # # img.save("temp.jpeg")
            #
            # # create file-object in memory
            # file_object = io.BytesIO()
            #
            # img.save(file_object, 'JPEG')
            #
            # # move to beginning of file so `send_file()` it will read from start
            # file_object.seek(0)

            global model
            result, k = predict.prediction(face_extract, model)

            iu_percent = round(float(k[0][0] * 100), 3)
            suzy_percent = round(float(k[0][1]) * 100, 3)

            # return send_file(file_object, mimetype='image/jpeg')
            if iu_percent > suzy_percent:
                return render_template('result.html',
                                       image_file="image/result_iu.jpg",
                                       not_similler="수지",
                                       not_similler_percent=suzy_percent,
                                       similler="아이유",
                                       similler_percent=iu_percent)
            else:
                return render_template('result.html',
                                       image_file="image/result_suzy.jpg",
                                       not_similler="아이유",
                                       not_similler_percent=iu_percent,
                                       similler="수지",
                                       similler_percent=suzy_percent)
    else:
        return render_template('fail_back.html')
Пример #23
0
            'path': args.features_dir,
            'model_path': args.model_dir,
            'batch_size': args.batch_size,
            'epochs': args.epochs,
            'learning_rate': args.learning_rate,
            'n_cnn_filters': [int(x) for x in args.n_filters.split('-')],
            'n_cnn_kernels': [int(x) for x in args.n_kernels.split('-')],
            'n_fc_units': [int(x) for x in args.n_fc_units.split('-')],
            'n_classes': args.n_classes,
            'train_val_ratio': args.train_val_ratio,
            'baseline_val_loss': args.baseline_val_loss,
        }

        train_model(params)

        print('model training complete')

    elif mode == 'prediction':

        params = {
            'test_data': args.test_speech_dir,
            'model_path': os.path.join(args.model_dir, 'vad_model.pt'),
            'smoothing': args.smoothing,
            'visualize': args.visualize,
            'parallel': args.parallel,
            'fig_path': args.fig_path
        }

        prediction(params)

        print('prediction complete')
Пример #24
0
def run(video_path):
    image_url_list = split_video_into_images(video_path)
    return prediction(image_url_list)
Пример #25
0
 def get_network_results(self):
     print('recording...\n')
     wavFile = sd.rec(self.analyzer['seconds'] * self.analyzer['fs'], samplerate=self.analyzer['fs'], channels=1, dtype='int16')
     sd.wait()
     cmd = prediction(wavFile, self.model, self.analyzer['fs'])
     self.assign(cmd)
Пример #26
0
def result():
    """Result page of webapp
    Args:
        Null
    Returns:
        flask-obj: rendered html page
    """

    try:
        #sets user input of form equal to following variables
        logger.info("At results page.")
        user1 = request.form['city']
        user2 = request.form['bedrooms']
        user3 = request.form['bathrooms']
        user4 = request.form['floors']
        user5 = request.form['waterfront']
        user6 = request.form['condition']
        user7 = request.form['sqft_basement']
        user8 = request.form['yr_built']
        user9 = request.form['yr_renovated']
        user10 = request.form['lot_log']

        with open(path1, "rb") as f:
            models = pickle.load(f)

        logger.info('Got user input.')
        user_input1 = User(city=user1,
                           bedrooms=user2,
                           bathrooms=user3,
                           floors=user4,
                           waterfront=user5,
                           condition=user6,
                           sqft_basement=user7,
                           yr_built=user8,
                           yr_renovated=user9,
                           lot_log=user10)
        db.session.add(user_input1)
        db.session.commit()
        logger.info(
            "User input committed to database: %s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
            user1, user2, user3, user4, user5, user6, user7, user8, user9,
            user10)

        # predict house price using model.prediction
        housepred = prediction(models, user1, user2, user3, user4, user5,
                               user6, user7, user8, user9, user10)
        attribute_and_change, price_changes = dec_price(
            models, user1, user2, user3, user4, user5, user6, user7, user8,
            user9, user10)
        try:
            attribute = attribute_and_change[0]
            change = attribute_and_change[1]
            low_price = int(np.exp(min(price_changes)[0]))
            price = '${:0,.0f}'.format(low_price)
            if price == housepred:
                attribute = 0
                change = 0
                price = 0
            logger.info(
                "Sucessfully found if there was an attribute that could lower price."
            )
        except:
            attribute = 0
            change = 0
            price = 0
            logger.warning("Could not find attribute change and lower price.")

        return render_template('result.html',
                               result=housepred,
                               result2=attribute,
                               result3=change,
                               result4=price)

    except:
        logger.warning("Not able to predict, error page returned.")
        return render_template('error.html')
Пример #27
0
		blood_pressure = sensor(i)['blood_pressure_high']
		blood_oxygen = sensor(i)['blood_oxygen']
		# check if there is any alert triggered
		alert = event.check(timer(0,0,i))
		# default state is normal
		signal = "NORMAL"
		if len(event.alert) != 0:
			signal = event.alert[0]

		print("-------Current State-------")
		print("Time: ", i)
		print("Pulse: ",pulse)
		print("Blood Pressure: ",blood_pressure)
		print("Blood Oxygen: ",blood_oxygen)
		print("Alert Status: ",signal)

		
		print("------- Prediction -------")
		# make prediction based on data in database
		print("Prediction of future parameters :")
		prediction(i)

	#example of pulling a GUI Interface
	signal = "NORMAL"
	pulse = 87
	blood_pressure = 120
	blood_oxygen = 96
	health_monitor.monitor(signal,pulse,blood_pressure,blood_oxygen)