當前位置: 首頁>>代碼示例>>Python>>正文


Python creator.Individual方法代碼示例

本文整理匯總了Python中deap.creator.Individual方法的典型用法代碼示例。如果您正苦於以下問題:Python creator.Individual方法的具體用法?Python creator.Individual怎麽用?Python creator.Individual使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在deap.creator的用法示例。


在下文中一共展示了creator.Individual方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_score_2

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_score_2():
    """Assert that the TPOTClassifier score function outputs a known score for a fixed pipeline."""
    tpot_obj = TPOTClassifier(random_state=34)
    tpot_obj._fit_init()
    known_score = 0.977777777778  # Assumes use of the TPOT accuracy function

    # Create a pipeline with a known score
    pipeline_string = (
        'KNeighborsClassifier('
        'input_matrix, '
        'KNeighborsClassifier__n_neighbors=10, '
        'KNeighborsClassifier__p=1, '
        'KNeighborsClassifier__weights=uniform'
        ')'
    )
    tpot_obj._optimized_pipeline = creator.Individual.from_string(pipeline_string, tpot_obj._pset)
    tpot_obj.fitted_pipeline_ = tpot_obj._toolbox.compile(expr=tpot_obj._optimized_pipeline)
    tpot_obj.fitted_pipeline_.fit(training_features, training_target)
    # Get score from TPOT
    score = tpot_obj.score(testing_features, testing_target)

    assert np.allclose(known_score, score) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:24,代碼來源:tpot_tests.py

示例2: test_predict_2

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_predict_2():
    """Assert that the TPOT predict function returns a numpy matrix of shape (num_testing_rows,)."""
    tpot_obj = TPOTClassifier()
    tpot_obj._fit_init()
    pipeline_string = (
        'DecisionTreeClassifier('
        'input_matrix, '
        'DecisionTreeClassifier__criterion=gini, '
        'DecisionTreeClassifier__max_depth=8, '
        'DecisionTreeClassifier__min_samples_leaf=5, '
        'DecisionTreeClassifier__min_samples_split=5'
        ')'
    )
    tpot_obj._optimized_pipeline = creator.Individual.from_string(pipeline_string, tpot_obj._pset)
    tpot_obj.fitted_pipeline_ = tpot_obj._toolbox.compile(expr=tpot_obj._optimized_pipeline)
    tpot_obj.fitted_pipeline_.fit(training_features, training_target)
    result = tpot_obj.predict(testing_features)

    assert result.shape == (testing_features.shape[0],) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:21,代碼來源:tpot_tests.py

示例3: test_predict_3

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_predict_3():
    """Assert that the TPOT predict function works on dataset with nan"""
    tpot_obj = TPOTClassifier()
    tpot_obj._fit_init()

    pipeline_string = (
        'DecisionTreeClassifier('
        'input_matrix, '
        'DecisionTreeClassifier__criterion=gini, '
        'DecisionTreeClassifier__max_depth=8, '
        'DecisionTreeClassifier__min_samples_leaf=5, '
        'DecisionTreeClassifier__min_samples_split=5'
        ')'
    )
    tpot_obj._optimized_pipeline = creator.Individual.from_string(pipeline_string, tpot_obj._pset)
    tpot_obj.fitted_pipeline_ = tpot_obj._toolbox.compile(expr=tpot_obj._optimized_pipeline)
    tpot_obj.fitted_pipeline_.fit(training_features, training_target)
    result = tpot_obj.predict(features_with_nan)

    assert result.shape == (features_with_nan.shape[0],) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:22,代碼來源:tpot_tests.py

示例4: test_predict_proba

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_predict_proba():
    """Assert that the TPOT predict_proba function returns a numpy matrix of shape (num_testing_rows, num_testing_target)."""
    tpot_obj = TPOTClassifier()
    tpot_obj._fit_init()

    pipeline_string = (
        'DecisionTreeClassifier('
        'input_matrix, '
        'DecisionTreeClassifier__criterion=gini, '
        'DecisionTreeClassifier__max_depth=8, '
        'DecisionTreeClassifier__min_samples_leaf=5, '
        'DecisionTreeClassifier__min_samples_split=5)'
    )
    tpot_obj._optimized_pipeline = creator.Individual.from_string(pipeline_string, tpot_obj._pset)
    tpot_obj.fitted_pipeline_ = tpot_obj._toolbox.compile(expr=tpot_obj._optimized_pipeline)
    tpot_obj.fitted_pipeline_.fit(training_features, training_target)

    result = tpot_obj.predict_proba(testing_features)
    num_labels = np.amax(testing_target) + 1

    assert result.shape == (testing_features.shape[0], num_labels) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:23,代碼來源:tpot_tests.py

示例5: test_predict_proba_2

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_predict_proba_2():
    """Assert that the TPOT predict_proba function returns a numpy matrix filled with probabilities (float)."""
    tpot_obj = TPOTClassifier()
    tpot_obj._fit_init()
    pipeline_string = (
        'DecisionTreeClassifier('
        'input_matrix, '
        'DecisionTreeClassifier__criterion=gini, '
        'DecisionTreeClassifier__max_depth=8, '
        'DecisionTreeClassifier__min_samples_leaf=5, '
        'DecisionTreeClassifier__min_samples_split=5)'
    )
    tpot_obj._optimized_pipeline = creator.Individual.from_string(pipeline_string, tpot_obj._pset)
    tpot_obj.fitted_pipeline_ = tpot_obj._toolbox.compile(expr=tpot_obj._optimized_pipeline)
    tpot_obj.fitted_pipeline_.fit(training_features, training_target)

    result = tpot_obj.predict_proba(testing_features)
    rows, columns = result.shape

    for i in range(rows):
        for j in range(columns):
            float_range(result[i][j]) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:24,代碼來源:tpot_tests.py

示例6: test_fit_4

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_fit_4():
    """Assert that the TPOT fit function provides an optimized pipeline with max_time_mins of 2 second."""
    tpot_obj = TPOTClassifier(
        random_state=42,
        population_size=2,
        generations=None,
        verbosity=0,
        max_time_mins=2/60.,
        config_dict='TPOT light'
    )
    tpot_obj._fit_init()
    assert tpot_obj.generations == 1000000

    # reset generations to 20 just in case that the failed test may take too much time
    tpot_obj.generations = 20

    tpot_obj.fit(training_features, training_target)
    assert tpot_obj._pop == []
    assert isinstance(tpot_obj._optimized_pipeline, creator.Individual)
    assert not (tpot_obj._start_datetime is None) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:22,代碼來源:tpot_tests.py

示例7: test_fit_5

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_fit_5():
    """Assert that the TPOT fit function provides an optimized pipeline with max_time_mins of 2 second with warm_start=True."""
    tpot_obj = TPOTClassifier(
        random_state=42,
        population_size=2,
        generations=None,
        verbosity=0,
        max_time_mins=3/60.,
        config_dict='TPOT light',
        warm_start=True
    )
    tpot_obj._fit_init()
    assert tpot_obj.generations == 1000000

    # reset generations to 20 just in case that the failed test may take too much time
    tpot_obj.generations = 20

    tpot_obj.fit(training_features, training_target)
    assert tpot_obj._pop != []
    assert isinstance(tpot_obj._optimized_pipeline, creator.Individual)
    assert not (tpot_obj._start_datetime is None)
    # rerun it
    tpot_obj.fit(training_features, training_target)
    assert tpot_obj._pop != [] 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:26,代碼來源:tpot_tests.py

示例8: test_memory

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_memory():
    """Assert that the TPOT fit function runs normally with memory=\'auto\'."""
    tpot_obj = TPOTClassifier(
        random_state=42,
        population_size=1,
        offspring_size=2,
        generations=1,
        config_dict='TPOT light',
        memory='auto',
        verbosity=0
    )
    tpot_obj.fit(training_features, training_target)

    assert isinstance(tpot_obj._optimized_pipeline, creator.Individual)
    assert not (tpot_obj._start_datetime is None)
    assert tpot_obj.memory is not None
    assert tpot_obj._memory is None
    assert tpot_obj._cachedir is not None
    assert not os.path.isdir(tpot_obj._cachedir) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:21,代碼來源:tpot_tests.py

示例9: test_update_top_pipeline

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_update_top_pipeline():
    """Assert that the TPOT _update_top_pipeline updated an optimized pipeline."""
    tpot_obj = TPOTClassifier(
        random_state=42,
        population_size=1,
        offspring_size=2,
        generations=1,
        verbosity=0,
        config_dict='TPOT light'
    )
    tpot_obj.fit(training_features, training_target)
    tpot_obj._optimized_pipeline = None
    tpot_obj.fitted_pipeline_ = None
    tpot_obj._update_top_pipeline()

    assert isinstance(tpot_obj._optimized_pipeline, creator.Individual) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:18,代碼來源:tpot_tests.py

示例10: test_evaluated_individuals_

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def test_evaluated_individuals_():
    """Assert that evaluated_individuals_ stores current pipelines and their CV scores."""
    tpot_obj = TPOTClassifier(
        random_state=42,
        population_size=2,
        offspring_size=4,
        generations=1,
        verbosity=0,
        config_dict='TPOT light'
    )
    tpot_obj.fit(training_features, training_target)
    assert isinstance(tpot_obj.evaluated_individuals_, dict)
    for pipeline_string in sorted(tpot_obj.evaluated_individuals_.keys()):
        deap_pipeline = creator.Individual.from_string(pipeline_string, tpot_obj._pset)
        sklearn_pipeline = tpot_obj._toolbox.compile(expr=deap_pipeline)
        operator_count = tpot_obj._operator_count(deap_pipeline)

        try:
            cv_scores = model_selection.cross_val_score(sklearn_pipeline, training_features, training_target, cv=5, scoring='accuracy', verbose=0)
            mean_cv_scores = np.mean(cv_scores)
        except Exception:
            mean_cv_scores = -float('inf')
        assert np.allclose(tpot_obj.evaluated_individuals_[pipeline_string]['internal_cv_score'], mean_cv_scores)
        assert np.allclose(tpot_obj.evaluated_individuals_[pipeline_string]['operator_count'], operator_count) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:26,代碼來源:tpot_tests.py

示例11: _setup_toolbox

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def _setup_toolbox(self):
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            creator.create('FitnessMulti', base.Fitness, weights=(-1.0, 1.0))
            creator.create('Individual', gp.PrimitiveTree, fitness=creator.FitnessMulti, statistics=dict)

        self._toolbox = base.Toolbox()
        self._toolbox.register('expr', self._gen_grow_safe, pset=self._pset, min_=self._min, max_=self._max)
        self._toolbox.register('individual', tools.initIterate, creator.Individual, self._toolbox.expr)
        self._toolbox.register('population', tools.initRepeat, list, self._toolbox.individual)
        self._toolbox.register('compile', self._compile_to_sklearn)
        self._toolbox.register('select', tools.selNSGA2)
        self._toolbox.register('mate', self._mate_operator)
        if self.tree_structure:
            self._toolbox.register('expr_mut', self._gen_grow_safe, min_=self._min, max_=self._max + 1)
        else:
            self._toolbox.register('expr_mut', self._gen_grow_safe, min_=self._min, max_=self._max)
        self._toolbox.register('mutate', self._random_mutation_operator) 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:20,代碼來源:base.py

示例12: clean_pipeline_string

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def clean_pipeline_string(self, individual):
        """Provide a string of the individual without the parameter prefixes.

        Parameters
        ----------
        individual: individual
            Individual which should be represented by a pretty string

        Returns
        -------
        A string like str(individual), but with parameter prefixes removed.

        """
        dirty_string = str(individual)
        # There are many parameter prefixes in the pipeline strings, used solely for
        # making the terminal name unique, eg. LinearSVC__.
        parameter_prefixes = [(m.start(), m.end()) for m in re.finditer(', [\w]+__', dirty_string)]
        # We handle them in reverse so we do not mess up indices
        pretty = dirty_string
        for (start, end) in reversed(parameter_prefixes):
            pretty = pretty[:start + 2] + pretty[end:]

        return pretty 
開發者ID:EpistasisLab,項目名稱:tpot,代碼行數:25,代碼來源:base.py

示例13: main

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def main():
    numpy.random.seed()

    # The CMA-ES One Plus Lambda algorithm takes a initialized parent as argument
    parent = creator.Individual((numpy.random.rand() * 5) - 1 for _ in range(N))
    parent.fitness.values = toolbox.evaluate(parent)
    
    strategy = cma.StrategyOnePlusLambda(parent, sigma=5.0, lambda_=10)
    toolbox.register("generate", strategy.generate, ind_init=creator.Individual)
    toolbox.register("update", strategy.update)

    hof = tools.HallOfFame(1)    
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)
   
    algorithms.eaGenerateUpdate(toolbox, ngen=200, halloffame=hof, stats=stats) 
開發者ID:DEAP,項目名稱:deap,代碼行數:21,代碼來源:cma_1+l_minfct.py

示例14: main

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def main():
    # The cma module uses the numpy random number generator
    numpy.random.seed(128)

    # The CMA-ES algorithm takes a population of one individual as argument
    # The centroid is set to a vector of 5.0 see http://www.lri.fr/~hansen/cmaes_inmatlab.html
    # for more details about the rastrigin and other tests for CMA-ES    
    strategy = cma.Strategy(centroid=[5.0]*N, sigma=5.0, lambda_=20*N)
    toolbox.register("generate", strategy.generate, creator.Individual)
    toolbox.register("update", strategy.update)

    hof = tools.HallOfFame(1)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)
    #logger = tools.EvolutionLogger(stats.functions.keys())
   
    # The CMA-ES algorithm converge with good probability with those settings
    algorithms.eaGenerateUpdate(toolbox, ngen=250, stats=stats, halloffame=hof)
    
    # print "Best individual is %s, %s" % (hof[0], hof[0].fitness.values)
    return hof[0].fitness.values[0] 
開發者ID:DEAP,項目名稱:deap,代碼行數:26,代碼來源:cma_minfct.py

示例15: main

# 需要導入模塊: from deap import creator [as 別名]
# 或者: from deap.creator import Individual [as 別名]
def main():
    N, LAMBDA = 30, 1000
    MU = int(LAMBDA/4)
    strategy = EMNA(centroid=[5.0]*N, sigma=5.0, mu=MU, lambda_=LAMBDA)
    
    toolbox = base.Toolbox()
    toolbox.register("evaluate", benchmarks.sphere)
    toolbox.register("generate", strategy.generate, creator.Individual)
    toolbox.register("update", strategy.update)
    
    # Numpy equality function (operators.eq) between two arrays returns the
    # equality element wise, which raises an exception in the if similar()
    # check of the hall of fame. Using a different equality function like
    # numpy.array_equal or numpy.allclose solve this issue.
    hof = tools.HallOfFame(1, similar=numpy.array_equal)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)
    
    algorithms.eaGenerateUpdate(toolbox, ngen=150, stats=stats, halloffame=hof)
    
    return hof[0].fitness.values[0] 
開發者ID:DEAP,項目名稱:deap,代碼行數:26,代碼來源:emna.py


注:本文中的deap.creator.Individual方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。