def make_predictions(year, features, sex): import predict PREDICTIVE_INDICES = [0, 25, 43, 65] print 'make_predictions(year=%d)' % year X, y, keys = getXy_by_features(year, features, sex) X = X[:,PREDICTIVE_INDICES] keys = [keys[i] for i in PREDICTIVE_INDICES] predict.classify('sex=%s_year=%d' % (sex,year), X, y, keys)
def uploadPC(): print("in upload") app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: print(request.files) d = Response("Error", status=201, mimetype='application/json') return d file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': d = Response("No filename", status=201, mimetype='application/json') return d if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) category, confidence = pred.classify(filename, response=False) print(category, confidence) confidence = '%.2f' % (confidence * 100) if category == "malignant": return render_template("malignant.html", confidence=confidence) else: return render_template("benign.html", confidence=confidence)
def sentiment_classification(): """Run definition quality classification given text. --- parameters: - name: body in: body schema: id: text required: - text properties: text: type: string description: the required text for POST method required: true definitions: SentimentResponse: Project: properties: status: type: string ml-result: type: object responses: 40x: description: Client error 200: description: Text Classification Response examples: [ { "status": "success", "category": "good" }, { "status": "error", "message": "Exception caught" }, ] """ json_request = request.get_json() if not json_request: return Response("No json provided.", status=400) text = json_request['text'] if text is None: return Response("No text provided.", status=400) else: label = classify(text) return flask.jsonify({"status": "success", "label": label})
def upload(): app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: d = Response("Error", status=201, mimetype='application/json') return d file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': d = Response("No filename", status=201, mimetype='application/json') return d if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return pred.classify(filename) return render_template("index.html")
def run_classification(self, image_path): label = predict.classify(image_path) return label
def _predict(): text = request.json["text"] labels = classify(text) return jsonify(labels)
def main(alert_mode: bool, sound: bool, save_image: bool) -> None: if sound: if not Path(SOUND_ROOT_PATH).exists(): raise OheyaObeyaError( '音源フォルダが見つかりません。(再配布不可の音源を使用しているため、GitHub上に音源ファイルは置いていません。使用する場合は、自身で用意してください)' ) pygame.mixer.init() # 実際には以下のサイトから素材を借りた # 効果音ラボ: https://soundeffect-lab.info/sound/button/ # PANICPUMPKIN: http://pansound.com/panicpumpkin/index.html # ※ 再配布不可なのでGitHub上には音源ファイルはuploadしていない # 使用する際は指定のパスに適当な音源を配置すること pygame.mixer.music.load(str(Path(SOUND_ROOT_PATH) / 'start.mp3')) pygame.mixer.music.play(1) camera_id = check_expected_camera_id() messy_flag = False messy_count = 0 not_messy_count = 0 cap = cv2.VideoCapture(camera_id) pygame.init() pygame.display.set_caption("OheyaObeya Classification Demo") screen = pygame.display.set_mode() status_font = pygame.font.Font(None, 100) status_color = { 'messy': (255, 0, 0), 'so-so': (255, 165, 0), 'clean': (181, 255, 20) } sub_font = pygame.font.Font(None, 60) if save_image: for label_name in ['messy', 'so-so', 'clean']: dir_path = Path(DST_IMAGE_PATH) / label_name dir_path.mkdir(parents=True, exist_ok=True) while True: # Capture ret, image = cap.read() path = Path('now.jpg') cv2.imwrite(str(path), image) # Predict result_dict = classify(path) display_prediction_result(result_dict) result = result_dict['prediction'] # 保存モードがONの場合は、日時_推測結果.jpgで画像を保存する if save_image: file_name = datetime.now().strftime( "%Y%m%d_%H%M%S_{}.jpg".format(result)) path = Path(DST_IMAGE_PATH) / result / file_name cv2.imwrite(str(path), image) # TODO: 連続した回数ではなく、過去n回分のm%分で判断させる if result == 'messy': messy_count += 1 not_messy_count = 0 logger.debug('messy_count = {}'.format(messy_count)) else: not_messy_count += 1 messy_count = 0 logger.debug('not_messy_count = {}'.format(not_messy_count)) # スクリーンを初期化 screen.fill([0, 0, 0]) # スクリーンにカメラの映像を表示する frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = frame[:, ::-1] frame = np.rot90(frame) # frame = frame[:, ::-1] # 上下を逆にする frame = pygame.surfarray.make_surface(frame) screen.blit(frame, (0, 0)) # スクリーンに判定結果を表示する status_text = status_font.render(result, True, status_color[result]) screen.blit(status_text, [20, 20]) # スクリーンにmessyの確率を表示する messy_prob = [ x['probability'] for x in result_dict['predictions'] if x['label'] == 'messy' ][0] messy_prob_text = sub_font.render('{:.2f}'.format(messy_prob), True, (255, 0, 0)) screen.blit(messy_prob_text, [20, 100]) if messy_flag and alert_mode: # スクリーンに警報の文字を表示する messy_alarm = '!!! Obeya Alarm!!!' messy_alarm_text = sub_font.render(messy_alarm, True, (255, 0, 0)) screen.blit(messy_alarm_text, [20, 150]) # 警報中は、messyじゃない状態が続いたら緑のバーが伸びていく not_messy_bar = '{}: {}'.format(not_messy_count, '*' * not_messy_count) not_messy_bar_text = sub_font.render(not_messy_bar, True, (181, 255, 20)) screen.blit(not_messy_bar_text, [150, 100]) else: # messyの状態が続いたら赤いバーが伸びていく messy_bar = '{}: {}'.format(messy_count, '*' * messy_count) messy_bar_text = sub_font.render(messy_bar, True, (255, 0, 0)) screen.blit(messy_bar_text, [150, 100]) pygame.display.update() # 汚部屋警報のON/OFFが切り替わったか判定 if messy_count > 10 and not messy_flag and alert_mode: messy_flag = True alert_obeya(on=True, sound=sound) elif not_messy_count > 10 and messy_flag: messy_flag = False alert_obeya(on=False, sound=sound) for event in pygame.event.get(): pass cap.release()
from sklearn.naive_bayes import MultinomialNB from predict import classify # Making final predictions with Multinomial NB multi_NB = MultinomialNB(alpha=0.25) # Calling classify function from predict module classify(multi_NB)