当前位置: 首页>>代码示例>>Python>>正文


Python ensemble.RandomForestRegressor方法代码示例

本文整理汇总了Python中sklearn.ensemble.RandomForestRegressor方法的典型用法代码示例。如果您正苦于以下问题:Python ensemble.RandomForestRegressor方法的具体用法?Python ensemble.RandomForestRegressor怎么用?Python ensemble.RandomForestRegressor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sklearn.ensemble的用法示例。


在下文中一共展示了ensemble.RandomForestRegressor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def __init__(self, model_type='classifier', feature_type='fingerprints',
                 n_estimators=100, n_ensemble=5):
        super(RandomForestQSAR, self).__init__()
        self.n_estimators = n_estimators
        self.n_ensemble = n_ensemble
        self.model = []
        self.model_type = model_type
        if self.model_type == 'classifier':
            for i in range(n_ensemble):
                self.model.append(RFC(n_estimators=n_estimators))
        elif self.model_type == 'regressor':
            for i in range(n_ensemble):
                self.model.append(RFR(n_estimators=n_estimators))
        else:
            raise ValueError('invalid value for argument')
        self.feature_type = feature_type
        if self.feature_type == 'descriptors':
            self.calc = Calculator(descriptors, ignore_3D=True)
            self.desc_mean = [0]*self.n_ensemble 
开发者ID:Mariewelt,项目名称:OpenChem,代码行数:21,代码来源:vanilla_model.py

示例2: test_sklearn_regression_overfit

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def test_sklearn_regression_overfit(self):
    """Test that sklearn models can overfit simple regression datasets."""
    n_samples = 10
    n_features = 3
    n_tasks = 1

    # Generate dummy dataset
    np.random.seed(123)
    ids = np.arange(n_samples)
    X = np.random.rand(n_samples, n_features)
    y = np.random.rand(n_samples, n_tasks)
    w = np.ones((n_samples, n_tasks))
    dataset = dc.data.NumpyDataset(X, y, w, ids)

    regression_metric = dc.metrics.Metric(dc.metrics.r2_score)
    sklearn_model = RandomForestRegressor()
    model = dc.models.SklearnModel(sklearn_model)

    # Fit trained model
    model.fit(dataset)
    model.save()

    # Eval model on train
    scores = model.evaluate(dataset, [regression_metric])
    assert scores[regression_metric.name] > .7 
开发者ID:deepchem,项目名称:deepchem,代码行数:27,代码来源:test_overfit.py

示例3: get_regressor_fitted

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def get_regressor_fitted(file_path,
                         X_train,
                         X_test,
                         y_train,
                         y_test):
    if os.path.exists(file_path):
        try:
            regressor_fitted = load_sklearn_model(file_path)
        except EOFError as e:
            print(file_path)
            raise e
    else:
        regressor = RandomForestRegressor(n_estimators=50,
                                          criterion="mse",
                                          max_features="auto",
                                          n_jobs=get_threads_number())

        regressor_fitted = regressor.fit(X_train, y_train)

        store_sklearn_model(file_path, regressor_fitted)
    return regressor_fitted 
开发者ID:MKLab-ITI,项目名称:news-popularity-prediction,代码行数:23,代码来源:ranking.py

示例4: Train

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def Train(data, treecount, tezh, yanzhgdata):
    model = RF(n_estimators=treecount, max_features=tezh)
    model.fit(data[:, :-1], data[:, -1])
    # 给出训练数据的预测值
    train_out = model.predict(data[:, :-1])
    # 计算MSE
    train_mse = mse(data[:, -1], train_out)

    # 给出验证数据的预测值
    add_yan = model.predict(yanzhgdata[:, :-1])
    # 计算MSE
    add_mse = mse(yanzhgdata[:, -1], add_yan)
    print(train_mse, add_mse)
    return train_mse, add_mse

# 最终确定组合的函数 
开发者ID:Anfany,项目名称:Machine-Learning-for-Beginner-by-Python3,代码行数:18,代码来源:pm25_RF_Regression.py

示例5: build_ensemble

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def build_ensemble(**kwargs):
    """Generate ensemble."""

    ens = SuperLearner(**kwargs)
    prep = {'Standard Scaling': [StandardScaler()],
            'Min Max Scaling': [MinMaxScaler()],
            'No Preprocessing': []}

    est = {'Standard Scaling':
               [ElasticNet(), Lasso(), KNeighborsRegressor()],
           'Min Max Scaling':
               [SVR()],
           'No Preprocessing':
               [RandomForestRegressor(random_state=SEED),
                GradientBoostingRegressor()]}

    ens.add(est, prep)

    ens.add(GradientBoostingRegressor(), meta=True)

    return ens 
开发者ID:flennerhag,项目名称:mlens,代码行数:23,代码来源:friedman_scores.py

示例6: regression_rf

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def regression_rf(x,y):
    '''
        Estimate a random forest regressor
    '''
    # create the regressor object
    random_forest = en.RandomForestRegressor(
        min_samples_split=80, random_state=666, 
        max_depth=5, n_estimators=10)

    # estimate the model
    random_forest.fit(x,y)

    # return the object
    return random_forest

# the file name of the dataset 
开发者ID:drabastomek,项目名称:practicalDataAnalysisCookbook,代码行数:18,代码来源:regression_randomForest.py

示例7: test_single_condition

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def test_single_condition():
    estimator = ensemble.RandomForestRegressor(n_estimators=2, random_state=1)

    estimator.fit([[1], [2]], [1, 2])

    assembler = assemblers.RandomForestModelAssembler(estimator)
    actual = assembler.assemble()

    expected = ast.BinNumExpr(
        ast.BinNumExpr(
            ast.NumVal(1.0),
            ast.IfExpr(
                ast.CompExpr(
                    ast.FeatureRef(0),
                    ast.NumVal(1.5),
                    ast.CompOpType.LTE),
                ast.NumVal(1.0),
                ast.NumVal(2.0)),
            ast.BinNumOpType.ADD),
        ast.NumVal(0.5),
        ast.BinNumOpType.MUL)

    assert utils.cmp_exprs(actual, expected) 
开发者ID:BayesWitnesses,项目名称:m2cgen,代码行数:25,代码来源:test_ensemble.py

示例8: generate_regression_data_and_models

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def generate_regression_data_and_models():
    df = pd.DataFrame()
    for _ in range(1000):
        a = np.random.normal(0, 1)
        b = np.random.normal(0, 3)
        c = np.random.normal(12, 4)
        target = a + b + c
        df = df.append({
            "A": a,
            "B": b,
            "C": c,
            "target": target
        }, ignore_index=True)

    reg1 = tree.DecisionTreeRegressor()
    reg2 = ensemble.RandomForestRegressor()
    column_names = ["A", "B", "C"]
    target_name = "target"
    X = df[column_names]
    reg1.fit(X, df[target_name])
    reg2.fit(X, df[target_name])
    return df, column_names, target_name, reg1, reg2 
开发者ID:EricSchles,项目名称:drifter_ml,代码行数:24,代码来源:test_regression_tests.py

示例9: fit

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def fit(self, X, y):
        """
        Fit a Random Forest model to data `X` and targets `y`.

        Parameters
        ----------
        X : array-like
            Input values.
        y: array-like
            Target values.
        """
        self.X = X
        self.y = y
        self.n = self.X.shape[0]
        self.model = RandomForestRegressor(**self.params)
        self.model.fit(X, y) 
开发者ID:josejimenezluna,项目名称:pyGPGO,代码行数:18,代码来源:RandomForest.py

示例10: test_regression

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def test_regression(self):
        training_pt = gpd.read_file(ms.meuse)
        training = self.stack_meuse.extract_vector(gdf=training_pt)
        training["zinc"] = training_pt["zinc"]
        training["cadmium"] = training_pt["cadmium"]
        training["copper"] = training_pt["copper"]
        training["lead"] = training_pt["lead"]
        training = training.dropna()

        # single target regression
        regr = RandomForestRegressor(n_estimators=50)
        X = training.loc[:, self.stack_meuse.names]
        y = training["zinc"]
        regr.fit(X, y)

        single_regr = self.stack_meuse.predict(regr)
        self.assertIsInstance(single_regr, Raster)
        self.assertEqual(single_regr.count, 1)

        # multi-target regression
        y = training.loc[:, ["zinc", "cadmium", "copper", "lead"]]
        regr.fit(X, y)
        multi_regr = self.stack_meuse.predict(regr)
        self.assertIsInstance(multi_regr, Raster)
        self.assertEqual(multi_regr.count, 4) 
开发者ID:stevenpawley,项目名称:Pyspatialml,代码行数:27,代码来源:test_prediction.py

示例11: fit

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def fit(self, losses, configs=None):

        if configs is None:
            configs = [[]]*len(times)

        # convert learning curves into X and y data

        X = []
        y = []

        for l,c in zip(losses, configs):
            l = self.apply_differencing(l)

            for i in range(self.order, len(l)):
                X.append(np.hstack([l[i-self.order:i], c]))
                y.append(l[i])

        self.X = np.array(X)
        self.y = np.array(y)


        self.rfr = rfr().fit(self.X,self.y) 
开发者ID:automl,项目名称:HpBandSter,代码行数:24,代码来源:arif.py

示例12: extend_partial

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def extend_partial(self, obs_losses, num_steps, config=None):
        # TODO: add variance predictions
        if config is None:
            config = []

        d_losses = self.apply_differencing(obs_losses)


        for t in range(num_steps):
            x = np.hstack([d_losses[-self.order:], config])
            y = self.rfr.predict([x])
            d_losses = np.hstack([d_losses, y])


        prediction = self.invert_differencing( obs_losses, d_losses[-num_steps:])

        return(prediction) 
开发者ID:automl,项目名称:HpBandSter,代码行数:19,代码来源:arif.py

示例13: test_random_forest_regressor

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def test_random_forest_regressor(self):
        for dtype in self.number_data_type.keys():
            scikit_model = RandomForestRegressor(random_state=1)
            data = self.scikit_data["data"].astype(dtype)
            target = self.scikit_data["target"].astype(dtype)
            scikit_model, spec = self._sklearn_setup(scikit_model, dtype, data, target)
            test_data = data[0].reshape(1, -1)
            self._check_tree_model(spec, "multiArrayType", "doubleType", 1)
            coreml_model = create_model(spec)
            try:
                self.assertEqual(
                    scikit_model.predict(test_data)[0].dtype,
                    type(coreml_model.predict({"data": test_data})["target"]),
                )
                self.assertAlmostEqual(
                    scikit_model.predict(test_data)[0],
                    coreml_model.predict({"data": test_data})["target"],
                    msg="{} != {} for Dtype: {}".format(
                        scikit_model.predict(test_data)[0],
                        coreml_model.predict({"data": test_data})["target"],
                        dtype,
                    ),
                )
            except RuntimeError:
                print("{} not supported. ".format(dtype)) 
开发者ID:apple,项目名称:coremltools,代码行数:27,代码来源:test_io_types.py

示例14: _train_convert_evaluate_assert

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def _train_convert_evaluate_assert(self, **scikit_params):
        """
        Train a scikit-learn model, convert it and then evaluate it with CoreML
        """
        scikit_model = RandomForestRegressor(random_state=1, **scikit_params)
        scikit_model.fit(self.X, self.target)

        # Convert the model
        spec = skl_converter.convert(scikit_model, self.feature_names, self.output_name)

        if _is_macos() and _macos_version() >= (10, 13):
            # Get predictions
            df = pd.DataFrame(self.X, columns=self.feature_names)
            df["prediction"] = scikit_model.predict(self.X)

            # Evaluate it
            metrics = evaluate_regressor(spec, df, verbose=False)
            self._check_metrics(metrics, scikit_params) 
开发者ID:apple,项目名称:coremltools,代码行数:20,代码来源:test_random_forest_regression_numeric.py

示例15: test_smoke_regression_methods

# 需要导入模块: from sklearn import ensemble [as 别名]
# 或者: from sklearn.ensemble import RandomForestRegressor [as 别名]
def test_smoke_regression_methods(regression_test_data, n_jobs):
    """Construct, fit, and predict on realistic problem.
    """
    xtrain = regression_test_data['x']
    ytrain = regression_test_data['y']

    rng = np.random.RandomState(17)
    est_list = [('lr', LinearRegression()),
                ('rf', RandomForestRegressor(random_state=rng,
                                             n_estimators=10)),
                ('nnls', NonNegativeLinearRegression())]
    sm = StackedRegressor(est_list, n_jobs=n_jobs)
    sm.fit(xtrain, ytrain)
    sm.predict(xtrain)
    sm.score(xtrain, ytrain)

    with pytest.raises(AttributeError):
        sm.predict_proba(xtrain) 
开发者ID:civisanalytics,项目名称:civisml-extensions,代码行数:20,代码来源:test_stacking.py


注:本文中的sklearn.ensemble.RandomForestRegressor方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。