示例#1
0
 def welcome(self, msg, balance):
     """Print out welcome message"""
     check_balance(balance)
     print('\n●●●●● Welcome to【{}】●●●●●'.format(self.name))
     print('Your current balance is ${:.2f}'.format(balance))
     print(
         '(You can go back to main menu by typing "quit", or exit the program by typing "exit".)'
     )
示例#2
0
def basic_segment_classifier(dir, out_model):
    """
    Train audio models
    :param dir: directory which contains
        audio organized in folders of classes
    :param output_model: path to save the output model
    :return: None
    """
    basic_features_params = config['basic_features_params']
    feature_extractor = AudioFeatureExtraction(basic_features_params)
    features, labels, class_mapping = feature_extractor.transform(dir)

    is_imbalanced = check_balance(labels)
    clf = train_basic_segment_classifier(features, labels, is_imbalanced, config, seed)

    model_dict = {}
    model_dict['classifier_type'] = 'basic'
    model_dict['class_mapping'] = class_mapping
    model_dict['classifier'] = clf
    model_dict['basic_features_params'] = basic_features_params

    out_folder = config['out_folder']
    if out_model is None:
        save_model(model_dict,out_folder, name="basic_classifier")
    else:
        save_model(model_dict,out_folder, out_model=out_model)
    return None
def test_multiple_line_string():
    string = """
    ((
    sdfd
      sdf ))

    """
    assert (check_balance(string) == True)
示例#4
0
def basic_segment_classifier(data, feature_extractor, pretrained, out_model):
    """
    Reads the config file and trains a classifier. It stores a model_dict
    containing the following information:
        - classifier: the output classifier
        - classifier_type: the type of the output classifier (i.e basic)
        - classifier_classnames: the name of the classes
        - embedding_model: path to the used embeddings model
        - embeddings_limit: possible limit on embeddings vectors

    :param data: csv file with one column transcriptions (text samples)
                   and one column labels
    :param feature_extractor: an initialized TextFeatureExtraction object 
    :param pretrained: the path of embeddings model
    :param out_model: name of the output model
    :return None
    """

    np.random.seed(seed)

    print('--> Loading Dataset...')
    transcriptions, labels, classnames = load_text_dataset(
        data, config['hop_samples'])

    is_imbalanced = check_balance(labels)

    # extract features based on pretrained fasttext model

    if pretrained == "bert":
        use_cuda = torch.cuda.is_available()
        device = torch.device("cuda:0" if use_cuda else "cpu")
        bert = BertModel.from_pretrained('bert-base-cased', output_hidden_states=True)
        total_features, _, max_len = bert_embeddings(transcriptions, labels, bert, device=device)
    else:
        total_features, labels = feature_extractor.transform(transcriptions,labels)

    clf = train_basic_segment_classifier(
        total_features, labels, is_imbalanced, config, seed)

    model_dict = {}
    model_dict['classifier_type'] = 'basic'
    model_dict['classifier'] = clf
    model_dict['classifier_classnames'] = classnames
    model_dict['embedding_model'] = pretrained
    if pretrained != "bert":
        model_dict['embeddings_limit'] = feature_extractor.embeddings_limit
    else:
        model_dict['max_len'] = max_len
    out_folder = config['out_folder']
    if out_model is None:
        save_model(model_dict,out_folder, name="basic_classifier")
    else:
        save_model(model_dict,out_folder, out_model=out_model)

    return None
示例#5
0
def main():
    # User's money
    money = 100.00

    # All the games available
    games = {1:'Flip a Coin!', 2:'Cho-Han', 3:'Poker Game', 4:'Mini Roulette'}

    # Welcome message
    print('\n★☆★☆★☆ Welcome to Games of Chance ★☆★☆★☆')
    print('You have $100 to start!')
    print('(You can exit the program at any time by entering "exit".)')

    while True:
        check_balance(money)

        # Print out main menu
        print('【Main Menu】')
        print('Your current balance is ${:.2f}'.format(money))
        print('(You can exit the program at any time by entering "exit".)')
        print('The current available games are:')
        for index in games:
            print('   {}. {}'.format(index, games[index]))

        # Prompt the user to select a game
        inpt = input('Please make your selection by entering the index of the game: ')
        selection = validate_input(inpt, 'game', num_games=len(games))
        if selection == 'quit': return

        # Execute the selected game
        if games[selection] == 'Flip a Coin!':
            cf = CoinFlip()
            money = cf.execute(money)
        elif games[selection] == 'Cho-Han':
            chohan = ChoHan()
            money = chohan.execute(money)
        elif games[selection] == 'Poker Game':
            poker = PlayCards()
            money = poker.execute(money)
        elif games[selection] == 'Mini Roulette':
            roulette = Roulette()
            money = roulette.execute(money)
示例#6
0
def recording_level_classifier(inputs_path, model_name, features_given=False):
    '''
    Train recording level classifier using audio and text features
    :param inputs_path: the directory where samples are divided into
    class-folders
    :param model_name: the name of the model that we are gonna train
    :param features_given: True if extracted features are given as input, instead of wav files
    :return: None. The classifier will be saved at the directory
    which is declared at the config.yaml file and with the input name.
    '''
    basic_features_params = config

    if features_given:
        feature_loader = RecordingLevelFeatureLoading(basic_features_params)
        fused_features, feature_list, fused_names, readys_features, \
        readys_list, readys_names, pyaudio_features, pyaudio_list, \
        pyaudio_names, labels, class_mapping, class_names, filenames = feature_loader.transform(inputs_path)
    else:
        feature_extractor = RecordingLevelFeatureExtraction(
            basic_features_params)
        fused_features, feature_list, fused_names, readys_features, \
        readys_list, readys_names, pyaudio_features, pyaudio_list, \
        pyaudio_names, labels, class_mapping, class_names, filenames = feature_extractor.transform(inputs_path)

    is_imbalanced = check_balance(labels)
    if basic_features_params['audio_features'] == "late_fused":
        filename = "readys_report.html"
        plot_feature_histograms(readys_list, readys_names, class_names,
                                filename)
        filename = "pyaudio_report.html"
        plot_feature_histograms(pyaudio_list, pyaudio_names, class_names,
                                filename)
        clf_readys, clf_pyaudio = train_late_fusion(readys_features,
                                                    pyaudio_features, labels,
                                                    is_imbalanced, config,
                                                    filenames, seed)
        model_dict = {}
        model_dict['classifier_type'] = config['late_fusion'][
            'classifier_pyaudio']
        model_dict['class_mapping'] = class_mapping
        model_dict['classifier'] = clf_pyaudio
        model_dict['features_type'] = config['features_type']
        model_dict['reference_text'] = config['reference_text']
        model_dict['text_segmentation_params'] = config[
            'text_segmentation_params']
        model_dict['audio_features'] = config['audio_features']
        model_dict['pyaudio_params'] = config['pyaudio_params']
        model_dict['pyaudio_num_features'] = config['pyaudio_num_features']
        model_dict['raudio_num_features_discard'] = config[
            'raudio_num_features_discard']
        model_dict['gender'] = config['gender']
        out_folder = config['out_folder']
        if model_name is None:
            save_model(model_dict, out_folder, name="basic_classifier_LLA")
        else:
            save_model(model_dict, out_folder, out_model=model_name + "_LLA")
        model_dict['classifier_type'] = config['late_fusion'][
            'classifier_raudio']
        model_dict['classifier'] = clf_readys
        if model_name is None:
            save_model(model_dict, out_folder, name="basic_classifier_MA")
        else:
            save_model(model_dict, out_folder, out_model=model_name + "_MA")
    else:
        filename = "report.html"
        plot_feature_histograms(feature_list, fused_names, class_names,
                                filename)
        clf = train_recording_level_classifier(fused_features, labels,
                                               is_imbalanced, config,
                                               filenames, seed)
        model_dict = {}
        model_dict['classifier_type'] = config['classifier_type']
        model_dict['class_mapping'] = class_mapping
        model_dict['classifier'] = clf
        model_dict['features_type'] = config['features_type']
        model_dict['reference_text'] = config['reference_text']
        model_dict['text_segmentation_params'] = config[
            'text_segmentation_params']
        model_dict['audio_features'] = config['audio_features']
        model_dict['pyaudio_params'] = config['pyaudio_params']
        model_dict['pyaudio_num_features'] = config['pyaudio_num_features']
        model_dict['raudio_num_features_discard'] = config[
            'raudio_num_features_discard']
        model_dict['gender'] = config['gender']
        out_folder = config['out_folder']
        if model_name is None:
            save_model(model_dict, out_folder, name="basic_classifier")
        else:
            save_model(model_dict, out_folder, out_model=model_name)

    return None
def test_empty_string():
    string = " "
    assert (check_balance(string) == True)
def test_multiple_par_unmatch_within():
    string = "{ [} ]"
    assert (check_balance(string) == False)
def test_multiple_par_match():
    string = "(123 {sdfds [23]})"
    assert (check_balance(string) == True)
def test_unmatched_string_error():
    string = ")"
    assert (check_balance(string) == False)
def test_unmatched_string():
    string = "(((sdfsdfsd sdfds))"
    assert (check_balance(string) == False)
def test_matched_string():
    string = " (((1 df dfdr)))"
    assert (check_balance(string) == True)