def create_model(X_train, X_test, y_train, y_test, model_type): # function contains three different models for predictions from model import model model = model(model_type) # argument has to be provided among Linear, Lasso, Ridge (Case Sensitive). model.fit(X_train, y_train) predictions = model.predict(X_test) print('Making predictions and calculating errors...') error = y_test.values.reshape(3000, 1) - predictions mae = mean_absolute_error(y_test, predictions) rmse = np.sqrt(mean_squared_error(y_test, predictions)) coefficients = model.coef_ intercept = model.intercept_ errors = pd.DataFrame({'Y': y_test, 'Predictions': predictions}) plt.figure(figsize = (8,8)) sns.set_style('darkgrid') sns.lmplot(x = 'Predictions', y = 'Y', data = errors) plt.figure(figsize = (8,8)) sns.set_style('darkgrid') sns.distplot(error) print('\n') print('The mean absolute error of model is:' + str(mean_absolute_error(y_test, predictions))) print('The root mean squared error of model is:' + str(np.sqrt(mean_squared_error(y_test, predictions)))) print('\n') return predictions, error, coefficients, intercept, mae, rmse, model
def predict(): data = request.get_json() image = data['image'] prediction = model.predict(image) prediction = str(prediction).strip('[]') print("Prediction", prediction) return jsonify(prediction)
def do_upload(): final = list() batchList = list() athleteList = list() print(request.body.read()) row = request.POST['uploaded_file'].file.getvalue().split('\n') for i in range(1, len(row)): data = row[i].split(',') print "DATA ", data batch = list() for i in range(1, len(data), 2): if data[i] is not '': batch.append([data[i], date_Covert(data[i + 1])]) for i in range(len(data), 64): batch.append([0, 0]) batchList.append(batch) athleteList.append(data[0]) print "BATCH IS ", batch res, RMSE = model.predict(batch, len(data) / 2) for i in res: final.append(i) obj = json.loads(model.predict_helper(final, RMSE)) obj["times"] = [] obj["athletes"] = [] obj["times"].append(batchList) obj["athletes"].append(athleteList) return obj
def neural_network(X_train, X_test, y_train, y_test, epoch, batch): # a seprate neural network. from neural_model import neural_model model = neural_model() print('Training Neural Network...') model.fit(x = X_train, y = y_train.values, validation_data = (X_test, y_test.values), epochs = epoch, batch_size = batch) print('\n') print('Neural Network trained!') loss = pd.DataFrame(model.history.history) sns.set_style('darkgrid') plt.figure(figsize = (8,8)) loss.plot() print('Making predictions...') predictions= model.predict(X_test) error = y_test.values.reshape(3000, 1) - predictions mae = mean_absolute_error(y_test, predictions) rmse = np.sqrt(mean_squared_error(y_test, predictions)) sns.set_style('darkgrid') plt.figure(figsize = (8,8)) sns.distplot(error, kde = True) weights = model.weights print('\n') print('The mean absolute error of model is:' + str(mean_absolute_error(y_test, predictions))) print('The root mean squared error of model is:' + str(np.sqrt(mean_squared_error(y_test, predictions)))) return predictions, error, weights, mae, rmse, model
def update(self, dt): if self.screen._screen_manager.current == 'camera': try: _, frame = self.capture.read() buf = cv2.flip(frame, 0).tostring() texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr") texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte") self.screen.image_camera.texture = texture facecasc = cv2.CascadeClassifier( 'haarcascade_frontalface_default.xml') gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = facecasc.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y - 50), (x + w, y + h + 10), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] cropped_img = np.expand_dims( np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0) prediction = model.predict(cropped_img) maxindex = int(np.argmax(prediction)) cv2.putText(frame, emotion_dict[maxindex], (x + 20, y - 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2, cv2.LINE_AA) self.tmp_emotion = emotion_dict[maxindex] except: pass
def predict(test_sample, model, scaler): #n = 10 #test_sample = test_sample.drop('priceUSD', axis = 1).iloc[n] #test_sample = scaler.transform(test_sample.values.reshape(-1,8)) # for rnd while using example from test sample test_sample = scaler.transform(test_sample.reshape(-1, 8)) output = model.predict(test_sample)[0][0] #print('The original price of car is:' + str(data['priceUSD'].iloc[n])) print('The expected price of car is: ' + str(output))
def analyzeFile(soundscape, test_function): ncnt = 0 # Store analysis here analysis = {} # Keep track of timestamps pred_start = 0 # Set species list accordingly setSpeciesList(cfg.DEPLOYMENT_LOCATION[0], cfg.DEPLOYMENT_LOCATION[1], cfg.DEPLOYMENT_WEEK) # Get specs for file spec_batch = [] for spec in audio.specsFromFile(soundscape, rate=cfg.SAMPLE_RATE, seconds=cfg.SPEC_LENGTH, overlap=cfg.SPEC_OVERLAP, minlen=cfg.SPEC_MINLEN, fmin=cfg.SPEC_FMIN, fmax=cfg.SPEC_FMAX, win_len=cfg.WIN_LEN, spec_type=cfg.SPEC_TYPE, magnitude_scale=cfg.MAGNITUDE_SCALE, bandpass=True, shape=(cfg.IM_SIZE[1], cfg.IM_SIZE[0]), offset=0, duration=None): # Prepare as input spec = model.prepareInput(spec) # Add to batch if len(spec_batch) > 0: spec_batch = np.vstack((spec_batch, spec)) else: spec_batch = spec # Do we have enough specs for a prediction? if len(spec_batch) >= cfg.SPECS_PER_PREDICTION: # Make prediction p, _ = model.predict(spec_batch, test_function) # Calculate next timestamp pred_end = pred_start + cfg.SPEC_LENGTH + ( (len(spec_batch) - 1) * (cfg.SPEC_LENGTH - cfg.SPEC_OVERLAP)) # Store prediction analysis[getTimestamp(pred_start, pred_end)] = p # Advance to next timestamp pred_start = pred_end - cfg.SPEC_OVERLAP spec_batch = [] return analysis
def plot(Z, Y): fig = plt.figure() ax = fig.add_subplot(111) Y = model.predict(X) ax.scatter(X, Z, c='r') ax.scatter(X, Y, c='b') plt.show()
def classify(model, image): """ Fingertip detection """ image = np.asarray(image) image = image.astype('float32') image = image / 255.0 image = np.expand_dims(image, axis=0) position = model.predict(image) position = position[0] return position
def test_threed_target(self): X, Z, Z_corrupt, fct = setup_spiral_set(100000) model = online.regression.LinReg(dim_in=X.shape[1], dim_out=Z.shape[1], dim_basis=3, basis_fcts=fct) self._fit(model, X, Z) Y = model.predict(X) plot3d(Z[:100], Y[:100])
def hello_world(): if request.method == 'POST': e = int(request.form['experience']) t = int(request.form['test_score']) i = int(request.form['interview_score']) data = np.array([[e, t, i]]) output = str(round(model.predict(data)[0], 2)) return render_template('result.html', result=output) else: return render_template('index.html')
async def predict_get(data: Feature_type= Depends()): # input nel corpo try: data = pd.DataFrame(data) data = data.T data.rename(columns=data.iloc[0], inplace = True) data= data.iloc[1:] predictions = model.predict(data) return {'prediction': predictions[0]} except: return {"prediction": "there was an error"}
async def predict_put(data: Feature_type): try: data = pd.DataFrame(data) data = data.T data.rename(columns=data.iloc[0], inplace = True) data= data.iloc[1:] predictions = model.predict(data) return {"prediction": predictions[0]} except: return {"prediction": "there was an error"}
def classify(image): img = image.resize((32, 32)) img = np.asarray(img) img = np.expand_dims(img, axis=0) img = img / 255.0 prediction = model.predict(img) prediction = prediction[0] max_index = np.argmax(prediction) class_name = classes_name.get(max_index) return class_name
def classify(image): global model image = np.asarray(image) image = image.astype('float32') image = image / 255.0 image = np.expand_dims(image, axis=0) with graph.as_default(): position = model.predict(image) position = position[0] return position
def test_threed_target(self): X, Z, Z_corrupt, fct = setup_spiral_set(100000) model = online.regression.LinReg( dim_in=X.shape[1], dim_out=Z.shape[1], dim_basis=3, basis_fcts=fct ) self._fit(model, X, Z) Y = model.predict(X) plot3d(Z[:100], Y[:100])
def test_model(): features = np.array([12]).reshape(-1, 1) try: predicted_value = model.predict(features) except: predicted_value = None real_value = 191392.543992269 diff = abs(predicted_value - real_value) assert diff < 1e-6
def predict_images(img): img = img_to_array(img) img = img.reshape(1, 100, 100, 3) img = img.astype('float32') img = img - [123.68, 116.779, 103.939] result = model.predict(img) return result
def root(): if request.form.get("context", "") and request.form.get("question", ""): context = request.form.get("context") question = request.form.get("question") answer = model.predict(context, question) print(answer["answer"]) return jsonify({"message": dict(question=question, answer=answer["answer"])}), 200 else: return jsonify({"message": "something went wrong"}), 400
def generate(model, vectorizer, seed, length=100, diversity=0.5): seed_vector = vectorizer.vectorize(seed) # Feed in seed string print("Seed:", seed, end=' ' if vectorizer.word_tokens else '') model.reset_states() preds = None for char_index in np.nditer(seed_vector): preds = model.predict(np.array([[char_index]]), verbose=0) sampled_indices = [] # np.array([], dtype=np.int32) # Sample the model one token at a time for _ in range(length): char_index = 0 if preds is not None: char_index = sample_preds(preds[0][0], diversity) sampled_indices.append( char_index) # = np.append(sampled_indices, char_index) preds = model.predict(np.array([[char_index]]), verbose=0) sample = vectorizer.unvectorize(sampled_indices) return sample
def attempt_predict(): global predict_status, predict_error, predict_result try: predict_status = 'In Progress...' from model.model import predict predict_result = predict('1.png') predict_status = 'Successful' predict_error = '' except: predict_status = 'failed' predict_result = '' predict_error = traceback.format_exc()
def test_eeg_emg(self): X, Z = setup_emg_eeg_dataset() print 'after ste creation {}'.format(Z.shape) idendity = lambda X: X model = online.regression.LinReg(dim_in=X.shape[1], dim_out=Z.shape[1], dim_basis=X.shape[1], basis_fcts=idendity) print 'Shape X {}, Shape Z: {}'.format(X.shape, Z.shape) self._fit(model, X, Z, batchsize=10, alpha=0.1) Y = model.predict(X) display.predict_report(X, Y, Z, True)
def predict(): response.headers['Content-type'] = 'application/json' data = request.json x = list() length = len(data['values']) for i in data['values']: x.append(i) for i in range(length, 32): x.append([0, 0]) x, RMSE = model.predict(x, length) return model.predict_helper(x, RMSE)
def index(): if request.args: context = request.args["context"] question = request.args["question"] answer = model.predict(context, question) print(answer["answer"]) return flask.render_template('index.html', question=question, answer=answer["answer"], content=context) else: return flask.render_template('index.html')
def attempt_predict(): global predict_status, predict_error, predict_result try: predict_status = 'In Progress...' from model.model import predict predict_result = predict('COCO_val2014_000000581394.jpg') # predict_result = predict('COCO_val2014_000000488977.jpg') predict_status = 'Successful' predict_error = '' except: predict_status = 'failed' predict_result = '' predict_error = traceback.format_exc()
def test_eeg_emg(self): X, Z = setup_emg_eeg_dataset() print 'after ste creation {}'.format(Z.shape) idendity = lambda X: X model = online.regression.LinReg( dim_in=X.shape[1], dim_out=Z.shape[1], dim_basis=X.shape[1], basis_fcts=idendity ) print 'Shape X {}, Shape Z: {}'.format(X.shape, Z.shape) self._fit(model, X, Z, batchsize=10, alpha=0.1) Y = model.predict(X) display.predict_report(X, Y, Z, True)
def test_predict_multiple_images(): """ Test prediction on multiple images. Ensure that the classes returned are valid and that the results are consistent across all images. """ for image_file_index in range(1, 6): image_file = str(image_file_index) + '.png' prediction_result = predict(image_file) assert len( prediction_result.keys()) == 2 # Ensure correct size dict returned assert 'classes' in prediction_result and 'result' in prediction_result # Ensure fields present for result_key in prediction_result['result'].keys( ): # Ensure all values accounted for in class list assert result_key in prediction_result['classes']
def predict(original_image): model.load_weights("models/_mini_XCEPTION.87-0.65.hdf5") highlighted_face_image, faces = find_face(original_image) nfaces = len(faces) prediction = None predicted_emotion = None if len(faces) > 0: for [x, y, w, h] in faces: image = original_image[y:y+h,x:x+w] image = preprocess_live_image(image) image = [[image]] prediction = model.predict(image) maximum = max(prediction) predicted_emotion = emotion_list[prediction.argmax()] cv2.putText(highlighted_face_image, predicted_emotion, (x,y-20), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,0,255), 10) return image_extraction(highlighted_face_image, faces, nfaces, prediction, predicted_emotion,original_image)
def test_predict_multiple_images(): """ Test prediction on multiple images. Ensure that the classes returned are valid and that the results are consistent across all images. """ for image_file_name in os.listdir('images/'): # image_file = 'images/' + image_file_name prediction_result = predict(image_file_name) assert len( prediction_result.keys()) == 2 # Ensure correct size dict returned assert 'classes' in prediction_result and 'result' in prediction_result # Ensure fields present for result_key in prediction_result['result'].keys( ): # Ensure all values accounted for in class list assert result_key in prediction_result['classes']
def test(image_path, snapshot_path, transform=False): img = Image.open( image_path) # WARNING : this image is well centered and square img = img.resize(model.inputs[0].shape) imarr = np.array(img).astype(np.float32) imarr = imarr.transpose((2, 0, 1)) imarr = np.expand_dims(imarr, axis=0) model.load_weights(snapshot_path) out = model.predict(imarr) best_index = np.argmax(out, axis=1)[0] print best_index
def fun(): lis1 = [] a1 = pregnancies.get() a2 = glucose.get() a3 = bloodPressure.get() a4 = skinThickness.get() a5 = insulin.get() a6 = bmi.get() a7 = diabetesPedigreeFunction.get() a8 = age.get() lis1.append(a1) lis1.append(a2) lis1.append(a3) lis1.append(a4) lis1.append(a5) lis1.append(a6) lis1.append(a7) lis1.append(a8) ind = [ 'Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age' ] test_x1 = pd.DataFrame(lis1, index=ind) test_x1 = scaler.transform(np.array(test_x1).reshape(1, 8)) prediction = model.predict(test_x1) print(prediction) if prediction == 0: cv.create_text(750, 550, text='NEGATIVE', font=('arial', 14, 'bold'), fill='blue', anchor='nw', tags=('label')) else: cv.create_text(750, 550, text='POSITIVE', font=('arial', 14, 'bold'), fill='green', anchor='nw', tags=('label'))
def create_and_train_model(train_X, train_y, test_X, test_y, epoch, batch): from model import model print('Training model ..') model = model() # Training the model on 90% of the dataset (train data) model.fit(x=train_X, y=train_y.values, validation_data=(test_X, test_y.values), epochs=epoch, batch_size=batch) loss = pd.DataFrame(model.history.history) loss.plot() # Predicting the output (prieUSD) for test set. preds = model.predict(test_X) return preds, model print('Training completed.')