Esempio n. 1
0
def main():
    for i in range(111, 112):
        numberOfRepets = 800000
        learningRate = 5
        inputNodes = 6
        hiddenNodes = 13
        outputNodes = 2
        print(
            "numOfCycles:\tLearningRate:\tinputNodes:\thiddenNodes:\toutputNodes:"
        )
        print("-->", numberOfRepets, "\t-->", learningRate, "\t\t--> 6\t\t-->",
              hiddenNodes, "\t\t--> 2")

        weightsIH, biasH, weightsHO, biasO = f.setting(inputNodes, hiddenNodes,
                                                       outputNodes,
                                                       numberOfRepets,
                                                       learningRate)

        inputArray, expectedArray = f.dataAccessing()
        testinput = inputArray[i, :]
        print("\n\n\ttestinput:\t\t\texpectedArray:")
        print(testinput, "\t", expectedArray[i, :])
        print("\n\n\n")
        f.predict(testinput, weightsIH, biasH, weightsHO, biasO)
        print("\n\n\n\n\n\n\n\n\n")

    input("press any key to finish the program")
Esempio n. 2
0
def check_spam(sender, data, pred =[]):
    with window("Simple SMS Spam Filter"):
        if pred == []:
            #runs only once - the the button is first clicked
            #and pred[-1] widget doesn't exist
            add_spacing(count=12)
            add_separator()
            add_spacing(count=12)
            #collect input, pre-process and get prediction
            input_value = get_value("Input")
            input_value = pre_process(input_value)
            pred_text, text_colour = predict(input_value)
            #store prediction inside the pred list
            pred.append(pred_text)
            #display prediction to user
            add_text(pred[-1], color=text_colour)
        else:
            #hide prediction widget
            hide_item(pred[-1])
            #collect the current user input and evaluate it
            input_value = get_value("Input")
            input_value = pre_process(input_value)
            pred_text, text_colour = predict(input_value)
            #store prediction inside the pred list
            pred.append(pred_text)
            add_text(pred[-1], color=text_colour)
Esempio n. 3
0
    def predict(self):
        self.user_id = int(self.lineEdit.text())
        self.topk = int(self.comboBox.currentText())

        data = f.predict(self.user_id,self.topk)

        self.showRes.setText(str(data))
Esempio n. 4
0
File: main.py Progetto: Vitvicky/cpl
def test(net, dataloader, all_prototypes, gamma):
    logger = logging.getLogger(__name__)

    distance_sum = 0.0

    correct = 0

    for i, (feature, label) in enumerate(dataloader):
        feature, label = feature.to(net.device), int(label)

        # extract abstract feature through CNN.
        feature = net(feature).view(1, -1)

        predicted_label, probability, min_distance = functions.predict(
            feature, all_prototypes, gamma)

        if label == predicted_label:
            correct += 1

        distance_sum += min_distance

        logger.debug(
            "%5d: Label: %d, Prediction: %d, Probability: %7.4f, Distance: %7.4f, Accuracy: %7.4f",
            i + 1, label, predicted_label, probability, min_distance,
            correct / (i + 1))

    return correct / len(dataloader), distance_sum / len(dataloader)
Esempio n. 5
0
def main():
    start_time = time()

    in_arg = get_input_args()

    device = set_device(in_arg.gpu)

    prob, classes = func.predict(in_arg.image_dir, in_arg.checkpoint, device,
                                 in_arg.top_k)
    names = []
    try:
        with open(in_arg.category_names, 'r') as f:
            cat_to_name = json.load(f)
        for clas in classes:
            names.append(cat_to_name[str(clas)])
    except:
        pass

    if len(names) != 0:
        for i in range(len(classes)):
            print("Classes: ", classes[i], names[i], " Probabilty: ", prob[i])
    elif not names:
        if len(names) == 0:
            for i in range(len(classes)):
                print("Classes: ", classes[i], " Probabilty: ", prob[i])
def main():
    #Set up argument parser for console input
    parser = argparse.ArgumentParser(description='Predict category of flower')
    parser.add_argument('image_path', help='path of image to be analyzed')
    parser.add_argument(
        'checkpoint_dir',
        help=
        'directory containing /checkpoint.pth with pre-trained model to be used for prediction'
    )
    parser.add_argument('--top_k',
                        help='number of top K most likely classes',
                        default=1,
                        type=int)
    parser.add_argument('--category_names', help='Select JSON file')
    parser.add_argument('--gpu', help='Enable GPU', action='store_true')

    args = parser.parse_args()

    #Load pre-trained model from checkpoint
    loaded_model, optimizer, criterion, epochs = fu.load_checkpoint(
        args.checkpoint_dir + '/checkpoint.pth')

    #Set mode
    device = torch.device(
        'cuda' if torch.cuda.is_available() and args.gpu == True else 'cpu')
    print('Device is: ', device)

    #Inference calculation
    probs, classes = fu.predict(args.image_path, loaded_model, args.top_k,
                                device, args.category_names)
    print(probs)
    print(classes)
Esempio n. 7
0
def train(features: np.ndarray, targets: np.ndarray, theta0: float,
          theta1: float, learning_rate: float) -> Tuple[float, float]:
    """Train the weights with given features and targets, returns updated weights."""
    predictions = predict(theta0, theta1, features)
    errors = error(predictions, targets)
    delta0 = learning_rate * (1 / errors.shape[0]) * np.sum(errors)
    delta1 = learning_rate * (1 / errors.shape[0]) * np.sum(errors * features)
    return (theta0 - delta0, theta1 - delta1)
Esempio n. 8
0
async def predict_api(file: UploadFile = File(...)):
    extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")
    if not extension:
        return "Image must be jpg or png format!"
    image = read_imagefile(await file.read())
    prediction = predict(image)

    return prediction
Esempio n. 9
0
def main():
    mil = askMileage()
    if (mil is None):
        print("Alright I warned you. Bye.")
        return ("None")

    try:
        theta = readTheta()
        pred = predict(mil, theta)
        print("This very powerful algorithm predicts the price to be around " +
              str(round(pred)) + " of whatever money that is.")
    except TypeError:
        print(
            "Yeah no I haven't been trained before so I'm gonna try to guess: how about "
            + str(np.random.randint(-99999999, 99999999)) + "?")
        print("Seriously tho, run python train.py first.")
        return (None)
    predict(mil, theta)
Esempio n. 10
0
def classify(image):
    num_px = 64

    my_image = scipy.misc.imresize(image, size=(num_px, num_px))
    my_image = my_image.reshape((1, num_px * num_px * 3)).T

    prediction = predict(data["w"], data["b"], my_image)

    return np.squeeze(prediction) == 1
Esempio n. 11
0
def Algorithm(inputData, outputData, outputList, parameters, param):

    train_x = inputData[:, 0:4000]
    train_y = outputData[:, 0:4000]
    test_x = inputData[:, 4000:4600]
    test_y = outputData[:, 4000:4600]
    test_y_List = outputList

    if (param == True):
        startTime = time.time()
        parameters = L_layer_model(train_x,
                                   train_y,
                                   layers_dims,
                                   num_iterations=10000,
                                   print_cost=True)
        endTime = time.time()
    t1 = time.time()
    pred_test, cost = functions.predict(test_x, test_y, parameters)
    t2 = time.time()
    avgError = functions.averageError(pred_test, test_y)
    outList.append(pred_test[0])
    outList.append(test_y[0])
    outList.append([cost])
    outList.append([avgError])
    if (param == True):
        outList.append([endTime - startTime])
    outList.append([t2 - t1])

    costList = []
    averageErrorList = []

    for j in range(0, np.shape(test_y_List)[0]):
        pred_test, cost = functions.predict(test_x, test_y_List[j][:,
                                                                   4000:4600],
                                            parameters)
        test_x = np.concatenate((test_x[1:6, :], pred_test, test_x[6:, :]), 0)
        costList.append(cost)
        averageError = functions.averageError(pred_test,
                                              test_y_List[j][:, 4000:4600])
        averageErrorList.append(averageError)

    outList.append(costList)
    outList.append(averageErrorList)
Esempio n. 12
0
def check_spam(sender, data, pred=[]):
    with window("Simple SMS Spam Filter"):
        if pred == []:
            add_spacing(count=12)
            add_separator
            add_spacing(count=12)
            input_value = get_value("Input")
            input_value = pre_process(input_value)
            pred_text, text_colour = predict(input_value)

            pred.append(pred_text)
            add_text(pred[-1], color=text_colour)
        else:
            hide_item(pred[-1])
            input_value = get_value("Input")
            input_value = pre_process(input_value)
            pred_text, text_colour = predict(input_value)

            pred.append(pred_text)
            add_text(pred[-1], color=text_colour)
Esempio n. 13
0
def main():
    # user inputs from command line
    in_arg = get_input_args()
    # load model checkpoint
    model_checkpoint = load_checkpoint(in_arg.checkpoint)
    # load and process unseen image data
    new_image = process_image(in_arg.image_path)
    # predict on unseen image data
    probs, classes = predict(new_image, model_checkpoint, in_arg.topk,
                             in_arg.gpu)
    # get labels
    get_labels(probs, classes, model_checkpoint)
def predict():
    if request.method == 'POST':
        name = request.form["s"]
        audio = request.files['file']
        audio.save(secure_filename("prediction.wav"))
        return render_template('predict.html',
                               prediction=functions.predict(
                                   "prediction.wav", str(name)),
                               n=name)
    else:
        name = request.args.get("s")
        return render_template('predict.html', s=name, prediction="")
Esempio n. 15
0
def check():
    try:
        url = request.args.get("url")
        if url == "":
            raise Exception("Wrong url")

        val = process(url)

        return {"status": str(predict(val))}, 200

    except Exception as e:
        return {"status": -2}, 500
Esempio n. 16
0
def CostList(parameters):
    costList = []
    averageErrorList = []
    for i in range(0 + predictionData.p, 136 - predictionData.p):
        X, Y, Y_List = predictionData.DataSet(predictionData.postMile[i])
        pred_test, cost = functions.predict(X[:, 4000:4600], Y[:, 4000:4600],
                                            parameters)
        averageError = functions.averageError(pred_test, Y[:, 4000:4600])
        costList.append(cost)
        averageErrorList.append(averageError)

    outList.append(costList)
    outList.append(averageErrorList)
Esempio n. 17
0
def test(images, labels):
    try:
        all_theta = np.fromfile(theta_filename, sep='\n').reshape((classifiers_number, features_number + 1))
        # Adding fake feature
        images = np.concatenate((np.ones((images.shape[0], 1)), images), axis=1)
        predictions = predict(all_theta, images)
        correct_predictions = sum(map(int, (labels == predictions).reshape(labels.shape[0])))
        print '*** Testing results ***'
        print 'Total digits: %d' % images.shape[0]
        print 'Correctly predicted: %d' % correct_predictions
        print 'Percentage: %.2f%%' % (correct_predictions * 100. / images.shape[0])
    except (IOError, ValueError) as e:
        print 'Failed to read parameters from "%s". Error: %s' % (theta_filename, str(e))
        print 'File does not exists or corrupted. Run "train" command to recover it'
Esempio n. 18
0
def model(X_train,
          Y_train,
          X_test,
          Y_test,
          iterations=2500,
          learning_rate=0.005):
    w = np.zeros((X_train.shape[0], 1))
    b = 0

    parameters, grads, costs = functions.optimize(w,
                                                  b,
                                                  X_train,
                                                  Y_train,
                                                  iterations=iterations,
                                                  learning_rate=learning_rate)

    w = parameters["w"]
    b = parameters["b"]

    Y_prediction_test = functions.predict(w, b, X_test)
    Y_prediction_train = functions.predict(w, b, X_train)

    train_accuracy = 100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100
    logging.info(f"train accuracy: {train_accuracy} %")

    test_accuracy = 100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100
    logging.info(f"test accuracy: {test_accuracy} %")

    return {
        "costs": costs,
        "Y_prediction_test": Y_prediction_test,
        "Y_prediction_train": Y_prediction_train,
        "w": w,
        "b": b,
        "learning_rate": learning_rate,
        "iterations": iterations
    }
Esempio n. 19
0
def main():
    model = uf.loadModel(checp)
    with open(cat_name, 'r') as json_file:
        cat_to_name = json.load(json_file)

    pts = uf.predict(image, model, top_k, gpu)
    labels = [cat_to_name[str(index + 1)] for index in np.array(pts[1][0])]
    probability = np.array(pts[0][0])
    i = 0
    while i < top_k:
        print("{} with a probability of {:.3f}".format(labels[i],
                                                       probability[i]))
        i += 1

    print("Done Predicting!")
Esempio n. 20
0
def main():

    # Get CLI arguments
    args = get_input_args()

    # Build model from checkpoint
    model = functions.load_checkpoint(args.checkpoint)

    # Get probabilities, labels and flower name from prediction function
    top_probs, top_labels, top_flowers = functions.predict(
        args.image_path, model, args.category_name, args.gpu, args.top_k)

    # Print result
    for i in zip(top_probs, top_labels, top_flowers):
        print(i)
Esempio n. 21
0
def main() -> None:
    """Executes the program."""
    kilometrage = input("Kilometrage: ")
    try:
        kilometrage = int(kilometrage)
    except:
        print("Cannot cast '{}' to float.".format(kilometrage))
        exit(1)
    theta0, theta1 = get_weights()
    prediction = predict(theta0, theta1, kilometrage)
    print("Estimated price for {}kms: {:.4f}$".format(kilometrage, prediction))
    if (theta0 == 0 and theta1 == 0):
        print(
            "Note: it seems that the model is not trained yet. Run train.py to set weights."
        )
Esempio n. 22
0
def prediction_made(text):
    #It should be a button that send us back to prediction
    df = pd.DataFrame()
    df = get_10tweets(current_user.username)

    info_user = prepare_prediction(current_user.username, text)
    FC_pred, RT_pred = predict(info_user)

    RT_mean = df["RT_l10"][0]
    FAV_mean = df["FC_l10"][0]

    rt_bool = RT_mean >= RT_mean
    fv_bool = FAV_mean >= FAV_mean
    if rt_bool:
        RT_text = 'Great job!'
    else:
        RT_text = ''
    if fv_bool:
        FAV_text = 'Great job!'
    else:
        FAV_text = ''

    has = ''
    for m in re.finditer(r"#\w+", text):
        w = m.group(0)
        w = w.strip('#')
        has += w
        has += ','
    has = has[:-1]
    no_has = ''
    for m in re.finditer(r"\s\w+", text):
        w = m.group(0)
        no_has += w

    # text = request.args.get('text')
    # some response showing the number of RT/FAVS
    return render_template('prediction/aftermath.html',
                           RT=RT_mean,
                           FAV=FAV_mean,
                           text=text,
                           RTaa=RT_text,
                           FAVaa=FAV_text,
                           rt_bool=rt_bool,
                           fv_bool=fv_bool,
                           FC_pred=FC_pred,
                           RT_pred=RT_pred,
                           has=has,
                           nohas=no_has)
def predict_review(trie):
    review_typed = ''
    while True:
        next_chars = stdin.readline().rstrip('\r\n')
        if len(next_chars) == 0:
            return
        review_typed += next_chars
        preds = f.predict(review_typed, trie)
        try:
            print('{}{}{}{}{}'.format(preds[0], sep, preds[1], sep, preds[2]))
            stdout.flush()
        except Exception:
            print(
                ' {} {} '.format(sep, sep)
            )  # in the event that anything weird happens, pass three blank predictions
            stdout.flush()
Esempio n. 24
0
def main():

    train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset(
    )

    m_train = train_set_x_orig.shape[0]  ##### m=n (DUNNO WHY BUT IT IS) 209
    m_test = test_set_x_orig.shape[0]  ##### same for this one 50
    num_px = train_set_x_orig.shape[2]  ##### 64 (cuz image is 64x64)

    train_set_x_flatten = train_set_x_orig.reshape(
        train_set_x_orig.shape[0],
        -1).T  ### at this point we need to turn X to make it vertical
    test_set_x_flatten = test_set_x_orig.reshape(
        test_set_x_orig.shape[0],
        -1).T  ### and make it from (209,64,64,3) into (12288,209)

    train_set_x = train_set_x_flatten / 255.  #### now every pixel is nomore 0-255, it's 0-1 (make's a little sense here, but useful when input is various
    test_set_x = test_set_x_flatten / 255.

    d = F.model(train_set_x,
                train_set_y,
                test_set_x,
                test_set_y,
                num_iterations=2000,
                learning_rate=0.005,
                print_cost=False)

    F.analysis([0.01, 0.001], train_set_x, train_set_y, test_set_x, test_set_y)
    ##################

    #############EXAMPLE

    my_image = "123.jpg"  # change this to the name of your image file
    ## END CODE HERE ##

    # We preprocess the image to fit your algorithm.
    fname = "images/" + my_image
    image = np.array(ndimage.imread(fname, flatten=False))
    my_image = scipy.misc.imresize(image, size=(num_px, num_px)).reshape(
        (1, num_px * num_px * 3)).T
    my_predicted_image = F.predict(d["w"], d["b"], my_image)

    plt.imshow(image)
    print("y = " + str(np.squeeze(my_predicted_image)) +
          ", your algorithm predicts a \"" +
          classes[int(np.squeeze(my_predicted_image)), ].decode("utf-8") +
          "\" picture.")
Esempio n. 25
0
def main():
    #Args
    args1 = arg_parser_test()
    #Load the model
    model=load_model(args1.checkpoint)  
    #label 
    with open(args1.cat_name_dir,'r') as json_file:
        cat_to_name = json.load(json_file)
    #Prediction
    probabilities = predict(args1.image_path, model, args1.top_k)
    labels = [cat_to_name[str(index + 1)] for index in np.array(probabilities[1][0])]
    probability = np.array(probabilities[0][0])
    i=0
    while i < args1.top_k:
        print("{} with a probability of {}".format(labels[i], probability[i]))
        i += 1
    print("Predictiion is done !")
Esempio n. 26
0
def main():
    #print("hello world") for luck

    in_arg = predict_input_args()

    print("   image =", in_arg.image_dir, "\n   model checkpoint =",
          in_arg.load_dir, "\n   top k =", in_arg.top_k, "\n   device =",
          in_arg.device, "\n   json =", in_arg.json)

    model, optimizer = load_model(in_arg.load_dir, in_arg.device)

    probs, classes, labels = predict(in_arg.image_dir, model, in_arg.json,
                                     in_arg.top_k, in_arg.device)

    results = dict(zip(labels, probs))
    print("-" * 40)
    for x in results:
        print("   {:20s}   {:.2f}%".format(x.title(), results[x] * 100))
Esempio n. 27
0
def main():
    in_arg = get_input_args()
    images_data = data_loaders(in_arg.data_dir)
    if in_arg.gpu is True:
        if torch.cuda.is_available():
            device = torch.device('cuda')
        else:
            device = torch.device('cpu')
            print("Using CPU since GPU is not available")
    model = load_checkpoint(in_arg.checkpoint)
    cat_to_name = cat_names(in_arg.cat_name)
    probs, classes = predict(in_arg.image, model, device, in_arg.top_k)
    #df = dict(sorted(zip(names, probs)))
    names = [cat_to_name[name] for name in classes]
    print(probs, [cat_to_name[name] for name in classes])
    p = probs.index(max(probs))
    print('Predicted flower in image is {} with a probability of {}'.format(
        names[p], probs[p]))
Esempio n. 28
0
def hello():
    c = 0
    target_parameter = None
    for key in request.args.keys():
        if key == 'target':
            target_parameter = request.args[key]

    ret_res = {}
    for key in request.files.keys():
        print(key)
        request.files["{}".format(key)].save(image_vault)
        arr, cand = pp_nd_ss(image_vault)
        predictions = predict(model, arr)
        res = max_predict(predictions,
                          cand,
                          label_encoder,
                          target_parameter,
                          api=True)
        ret_res[c] = res
        c = c + 1

    return jsonify(ret_res)
def main():
    args = parser_fun_test()

    with open(args.cat_to_name, 'r') as f:
        cat_to_name = json.load(f)

    # load the model
    loaded = torch.load("trained_model.pth")
    model = load_model(loaded)

    # prediction
    probabilities = predict(args.image_path, model, args.top_k, 'gpu')
    labels = [
        cat_to_name[str(index + 1)] for index in np.array(probabilities[1][0])
    ]
    probability = np.array(probabilities[0][0])

    i = 0
    while i < args.top_k:
        print("{} with a probability of {:.5f}".format(labels[i],
                                                       probability[i]))
        i += 1
    print("Predictiion is done !")
Esempio n. 30
0
def main():
    parser = argparse.ArgumentParser(
        description='This program predicts a flower name from an image')
    parser.add_argument('image_path', type=str, help='Image path')
    parser.add_argument('checkpoint', type=str, help='Checkpoint')
    parser.add_argument('--top_k',
                        type=int,
                        default='1',
                        help='Top k probablities')
    parser.add_argument('--category_names',
                        type=str,
                        default='cat_to_name.json',
                        help='Mappings of indices and class names')
    parser.add_argument('--gpu',
                        action='store_true',
                        help='Use GPU',
                        default=False)

    args = parser.parse_args()
    device = torch.device("cuda:0" if torch.cuda.is_available() else 'cpu'
                          ) if args.gpu else 'cpu'

    with open(args.category_names, 'r') as f:
        cat_to_name = json.load(f)

        model_load, optimizer_load, scheduler_load, epoch = load_checkpoint(
            device, args.checkpoint)

        probs, classes, flowers = predict(model_load,
                                          process_image(args.image_path),
                                          cat_to_name, args.top_k)

        print("Predictions for {}: {}".format(args.image_path, flowers))

        probs = np.array(probs)[0]
        print("Probablities: {}".format(probs))
Esempio n. 31
0
plt.title('Terrain patch')
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.set_zlabel(r'$z$')
fig.colorbar(surf, shrink=0.35, aspect=10)
plt.show()
plt.show()

#Fit OLS, Ridge or Lasso, predict training data
x1 = x.ravel()
y1 = y.ravel()
z1 = patch.ravel()

degrees = 5
beta = OLS(x1, y1, z1, degrees)  #Change to Lasso or Ridge
z_ = predict(x1, y1, beta, degrees)
'''
Test dependency of lambda on the ridge and lasso regression

lds = np.linspace(0,1,10)
degree = 5

error = np.zeros(10)
R2 = np.zeros(10)

for i, ld in enumerate(lds):

    beta = Ridge(x1, y1, z1, degree, ld)
    z_ = predict(x1, y1, beta, degree)
    error[i] = np.mean( (z_ - z1)**2 )
    R2[i] = 1 - np.sum( (z_ - z1)**2 )/np.sum( (z1- np.mean(z1))**2 )
Esempio n. 32
0
 def predict(self, vehicle):
     '''
     Display predicted range of vehicle
     '''
     print('Prediction for {0}: {1:.2f} miles'.format(vehicle['reg_no'], FN.predict(vehicle)))