예제 #1
0
파일: races.py 프로젝트: Dan-Mead/DnD
    def add_race_modifiers(self, char):

        char.info.Race = self.race_name
        char.stats.size.Race = self.size
        char.stats.speed.Race = self.speed
        char.proficiencies.languages.Race = self.languages

        for trait in vars(self).keys():
            if trait == 'attributes':
                for attr in self.attributes:
                    char.attributes[attr[0]]['race'] = attr[1]

            elif trait == 'skills':
                for skill in self.skills:
                    char.skills[skill].prof += [self.race_name]

            elif trait == 'feats':
                from feats import get_feat
                for feat in self.feats:
                    new_feat = get_feat(feat, self.race_name)
                    char.feats[feat] = new_feat
                    char.feats[feat].initial_effects(char)

            elif trait == 'features':
                from features import get_feature
                for feature in self.features:
                    new_feature = get_feature(feature)
                    char.features[self.race_name][feature] = new_feature
                    new_feature.initial_effects(char)

            elif trait not in ['race_name', 'size', 'speed', 'languages']:
                raise Exception(f"{trait} included which hasn't been added.")
예제 #2
0
def predict(train_data,
            train_labels,
            test_path,
            labels,
            result_path,
            n_estimators,
            random_state,
            fixed_size=DEF_SIZE):
    clf = RandomForestClassifier(n_estimators=n_estimators,
                                 random_state=random_state,
                                 n_jobs=-1)

    clf.fit(train_data, train_labels)

    # loop through the test images
    for ind, file in enumerate(glob.glob(test_path + "/*.*")):
        # read the image
        image = cv2.imread(file)
        # ресайзим все к одному размеру
        image = cv2.resize(image, fixed_size)

        # get feature
        global_feature = get_feature(image)

        # predict label of test image
        prediction = clf.predict(global_feature.reshape(1, -1))[0]

        # display the output image
        display(image, labels[prediction], f'{result_path}/{ind}.png')
 def predict(self, fs, signal):
     """
     return a label (name)
     """
     try:
         feat = get_feature(fs, signal)
     except Exception as e:
         print (e)
     return self.gmmset.predict_one(feat)
예제 #4
0
 def verify(self, fs, signal, personid):
     """
     return a label (name)
     """
     try:
         feat = get_feature(fs, signal)
     except Exception as e:
         print(e)
     return self.gmmset.verify(feat, personid)
예제 #5
0
파일: classes.py 프로젝트: Dan-Mead/DnD
    def add_class_features(self, char):

        if not hasattr(char, 'classes'):

            char.classes = Dict()

            origin = 'origin: ' + self.class_name

            for trait in vars(self).keys():

                if trait == 'saves':
                    for save in self.saves:
                        char.saving_throws[save].prof += [origin]

                elif trait == 'skills':
                    for skill in self.skills:
                        char.skills[skill].prof += [origin]

                elif trait == 'prof_weapons':
                    char.proficiencies.weapons[origin] = self.prof_weapons
                elif trait == 'prof_armor':
                    char.proficiencies.armor[origin] = self.prof_armor
                elif trait == 'prof_tools':
                    char.proficiencies.tools[origin] = self.prof_tools

                elif trait == 'equipment':
                    self.equipment = f.choose_weapons(self.equipment)
                    for item in self.equipment:
                        if item[0] in char.equipment:
                            char.equipment[item[0]].add_number(item[1])
                        else:
                            char.equipment.update(
                                {item[0]: get_item(item[0], item[1])})

                elif trait not in [
                        'class_name', 'hit_dice', 'hit_points', 'levels'
                ]:
                    raise Exception(
                        f"{trait} included which haven't been added.")

            char.classes[self.class_name] = character_class(
                1, self.hit_dice, self.hit_points, True)
        else:
            char.classes[self.class_name] = character_class(
                1, self.hit_dice, self.hit_points, False)

        for feature in self.levels[1]:
            new_feature = get_feature(feature)
            char.features[f"Class: {self.class_name}"][feature] = new_feature
            new_feature.initial_effects(char)
예제 #6
0
def task_predict(input_files, input_model):
    # 把输入的多个模型目录字符串分离为目录列表
    input_models = [os.path.expanduser(k) for k in input_model.strip().split()]
    # 把各个目录下的模型列表解压出来组合成一个迭代器
    models = itertools.chain(*(glob.glob(m) for m in input_models))
    # 生成并加载包括所有模型文件的列表
    models = [ModelInterface.load(m) for m in models]
    # 定义统计准确率的变量
    right = 0
    wrong = 0
    num = 0
    # 对每个预测音频文件提取特征并与每个模型匹配得到TOP结果
    for f in glob.glob(os.path.expanduser(input_files)):
        fs, signal = read_wav(f)
        print(f)
        feat = get_feature(fs, signal)
        predict_result = []
        # 每个音频文件分别匹配每个模型组并得出分数放到总列表
        for model in models:
            #print(model)
            #m = ModelInterface.load(model)
            results = model.predict(feat)
            for result in results:
                predict_result.append(result)
        #print("predict_result:",predict_result)
        # 对预测结果按分数作高到底排序
        predict_result = sorted(predict_result,
                                key=operator.itemgetter(1),
                                reverse=True)
        #print("sort_predict_result:", predict_result)
        # 微信语音数据集的label格式
        label = os.path.basename(f).split('_')[0]  #[6:11]
        #label=os.path.basename(f).split('(')[0]#[6:11]
        # AISHELL数据集的label格式
        #label=os.path.basename(f)[6:11]
        predict = predict_result[0][0]
        #print('Top:',predict_result[:10])
        # 统计准确率
        if label in predict:
            right += 1
            print('label:', label, '  predict:', predict, '  right')
        else:
            wrong += 1
            print('label:', label, '  predict:', predict, '  wrong')
        num += 1
    print('All:', num, '  right:', right, '  wrong:', wrong, '  acc:',
          right / num)
예제 #7
0
def init_h5py(train_path: str,
              train_labels: list[str],
              h5_data_file: str,
              h5_labels_file: str,
              fixed_img_size=DEF_SIZE):
    global_features = []
    labels = []

    # loop over the training data sub-folders
    for training_name in train_labels:
        current_dir = os.path.join(train_path, training_name)

        images = [
            f for f in os.listdir(current_dir)
            if os.path.isfile(os.path.join(current_dir, f))
            and f.endswith(".jpg") or f.endswith(".png")
        ]

        for file in images:
            file_path = os.path.join(current_dir, file)

            # read the image and resize it to a fixed-size
            image = cv2.imread(file_path)
            image = cv2.resize(image, fixed_img_size)

            global_feature = get_feature(image)

            # update the list of labels and feature vectors
            labels.append(training_name)
            global_features.append(global_feature)

        print(f"[STATUS] processed folder: {training_name}")

    le = LabelEncoder()
    target = le.fit_transform(labels)

    # save the feature vector using HDF5
    h5f_data = h5py.File(h5_data_file, 'w')
    h5f_data.create_dataset('dataset_1', data=np.array(global_features))

    h5f_label = h5py.File(h5_labels_file, 'w')
    h5f_label.create_dataset('dataset_1', data=np.array(target))

    h5f_data.close()
    h5f_label.close()

    print("[STATUS] end of training..")
 def enroll(self, name, fs, signal):
     feat = get_feature(fs, signal)
     self.features[name].extend(feat)
예제 #9
0
def task_predict(input_files, input_model):
    # 把输入的多个模型目录字符串分离为目录列表
    input_models = [os.path.expanduser(k) for k in input_model.strip().split()]
    # 把各个目录下的模型列表解压出来组合成一个迭代器
    models = itertools.chain(*(glob.glob(m) for m in input_models))
    # 生成并加载包括所有模型文件(skgmm.GMMSet object)的列表
    models = [ModelInterface.load(m) for m in models]
    if len(models) == 0:
        print("No model file found in %s" % input_model)
        sys.exit(1)
    # 定义统计准确率的变量
    right = 0
    right1 = 0
    wrong = 0
    wrong1 = 0
    num = 0
    # 对每个预测音频文件提取特征并与每个模型匹配得到TOP结果
    for f in glob.glob(os.path.expanduser(input_files)):
        fs, signal = read_wav(f)
        print(f)
        feat = get_feature(fs, signal)
        predict_result = []
        # 每个音频文件分别匹配每个模型组并得出分数放到总列表
        for model in models:
            #print(model)
            #m = ModelInterface.load(model)
            results = model.predict_proba(feat)
            print(results)
            #print(results)
            for result in results:
                predict_result.append(result)
        #print("predict_result:",predict_result)
        # 对预测结果按分数作高到底排序
        predict_result = sorted(predict_result,
                                key=operator.itemgetter(1),
                                reverse=True)
        #print("sort_predict_result:", predict_result)
        # 微信语音数据集的label格式
        label = os.path.basename(f).split('_')[0]  #[6:11]
        #label=os.path.basename(f).split('(')[0]#[6:11]
        # AISHELL数据集的label格式
        # label=os.path.basename(f)[6:11]
        predict = predict_result[0][0]
        predict_score = predict_result[0][1]
        # #print('Top:',predict_result[:10])
        # 统计top1准确率
        if label in predict:
            right1 += 1
            print('label:', label, '  predict:', predict, '  score:',
                  predict_score, ' top1 right')
        else:
            wrong1 += 1
            print('label:', label, '  predict:', predict, '  score:',
                  predict_score, ' top1 wrong')
        # 统计Top10准确率
        predicts = []
        predict_scores = []
        for pre in predict_result[:10]:
            predicts.append(pre[0])
            predict_scores.append(pre[1])
        if label in predicts:
            right += 1
            print('label:', label, '  predicts:', predicts, '  scores:',
                  predict_scores, ' top10 Right')
        else:
            wrong += 1
            print('label:', label, '  predicts:', predicts, '  scores:',
                  predict_scores, ' top10 Wrong')
        num += 1
    print('top1:', num, '  right:', right1, '  wrong:', wrong1, ' top1 acc:',
          right1 / num)
    print('top10:', num, '  right:', right, '  wrong:', wrong, ' top10 acc:',
          right / num)
 def enroll(self, name, fs, signal):
     feat = get_feature(fs, signal)
     #print("feat:",feat)
     #print(len(feat))
     self.features[name].extend(feat)
예제 #11
0
 def enroll(self, name, fs, signal):
     print("enroll "+name)
     feat = get_feature(fs, signal)
     self.features[name].extend(feat)
def task_predict(input_files, input_model):
    # 把输入的多个模型目录字符串分离为目录列表
    input_models = [os.path.expanduser(k) for k in input_model.strip().split()]
    # 把各个目录下的模型列表解压出来组合成一个迭代器
    models = itertools.chain(*(glob.glob(m) for m in input_models))
    # 生成并加载包括所有模型文件(skgmm.GMMSet object)的列表
    models = [ModelInterface.load(m) for m in models]
    if len(models) == 0:
        print("No model file found in %s" % input_model)
        sys.exit(1)
    # 定义统计准确率的变量
    right = 0
    right1 = 0
    wrong = 0
    wrong1 = 0
    num = 0
    # 对每个预测音频文件提取特征并与每个模型匹配得到TOP结果
    for f in glob.glob(os.path.expanduser(input_files)):
        start_time = time.time()
        fs, signal = read_wav(f)
        print(f)
        feat = get_feature(fs, signal)
        #print("Get feature ", time.time() - start_time, " seconds")
        predict_result = []
        f_models = [(feat, m) for m in models]
        #print(models)
        # 每个音频文件分别匹配每个模型组并得出分数放到总列表
        # for model in models:
        #     #start_time1 = time.time()
        #     #print(model)
        #     # 模型文件是一个元组:(label,gmm)
        #     score = model[1].score(feat)
        #     label=model[0]
        #     result=(label,score)
        #     #print(results)
        #     predict_result.append(result)
        #print("Get one score ", time.time() - start_time1, " seconds")
        pool = ThreadPool(2)
        predict_result = pool.map(get_score, f_models)
        pool.close()
        pool.join()
        #print(results)
        #print("Get score ", time.time() - start_time, " seconds")
        proba = GMMSet.softmax([i[1] for i in predict_result])
        predict_result = [(predict_result[i][0], proba[i])
                          for i in range(len(proba))]
        #print("predict_result:",predict_result)
        # 对预测结果按分数作高到底排序
        predict_result = sorted(predict_result,
                                key=operator.itemgetter(1),
                                reverse=True)
        #print("sort_predict_result:", predict_result)
        # 微信语音数据集的label格式
        label = os.path.basename(f).split('_')[0]  #[6:11]
        #label=os.path.basename(f).split('(')[0]#[6:11]
        # AISHELL数据集的label格式
        # label=os.path.basename(f)[6:11]
        predict = predict_result[0][0]
        predict_score = predict_result[0][1]
        print("Predict ", time.time() - start_time, " seconds")
        # #print('Top:',predict_result[:10])
        # 统计top1准确率
        if label in predict:
            right1 += 1
            print('label:', label, '  predict:', predict, '  score:',
                  predict_score, ' top1 right')
        else:
            wrong1 += 1
            print('label:', label, '  predict:', predict, '  score:',
                  predict_score, ' top1 wrong')
        # 统计Top10准确率
        predicts = []
        predict_scores = []
        for pre in predict_result[:10]:
            predicts.append(pre[0])
            predict_scores.append(pre[1])
        if label in predicts:
            right += 1
            print('label:', label, '  predicts:', predicts, '  scores:',
                  predict_scores, ' top10 Right')
        else:
            wrong += 1
            print('label:', label, '  predicts:', predicts, '  scores:',
                  predict_scores, ' top10 Wrong')
        num += 1
    print('top1:', num, '  right:', right1, '  wrong:', wrong1, ' top1 acc:',
          right1 / num)
    print('top10:', num, '  right:', right, '  wrong:', wrong, ' top10 acc:',
          right / num)