本文整理汇总了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
示例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
示例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
示例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
# 最终确定组合的函数
示例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
示例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
示例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)
示例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
示例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)
示例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)
示例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)
示例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)
示例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))
示例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)
示例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)