本文整理汇总了Python中sklearn.linear_model.ElasticNet方法的典型用法代码示例。如果您正苦于以下问题:Python linear_model.ElasticNet方法的具体用法?Python linear_model.ElasticNet怎么用?Python linear_model.ElasticNet使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.linear_model
的用法示例。
在下文中一共展示了linear_model.ElasticNet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_ensemble
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [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
示例2: test_n_clusters
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_n_clusters():
# Test that n_clusters param works properly
X, y = make_blobs(n_samples=100, centers=10)
brc1 = Birch(n_clusters=10)
brc1.fit(X)
assert_greater(len(brc1.subcluster_centers_), 10)
assert_equal(len(np.unique(brc1.labels_)), 10)
# Test that n_clusters = Agglomerative Clustering gives
# the same results.
gc = AgglomerativeClustering(n_clusters=10)
brc2 = Birch(n_clusters=gc)
brc2.fit(X)
assert_array_equal(brc1.subcluster_labels_, brc2.subcluster_labels_)
assert_array_equal(brc1.labels_, brc2.labels_)
# Test that the wrong global clustering step raises an Error.
clf = ElasticNet()
brc3 = Birch(n_clusters=clf)
assert_raises(ValueError, brc3.fit, X)
# Test that a small number of clusters raises a warning.
brc4 = Birch(threshold=10000.)
assert_warns(ConvergenceWarning, brc4.fit, X)
示例3: getModels
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def getModels():
result = []
result.append("LinearRegression")
result.append("BayesianRidge")
result.append("ARDRegression")
result.append("ElasticNet")
result.append("HuberRegressor")
result.append("Lasso")
result.append("LassoLars")
result.append("Rigid")
result.append("SGDRegressor")
result.append("SVR")
result.append("MLPClassifier")
result.append("KNeighborsClassifier")
result.append("SVC")
result.append("GaussianProcessClassifier")
result.append("DecisionTreeClassifier")
result.append("RandomForestClassifier")
result.append("AdaBoostClassifier")
result.append("GaussianNB")
result.append("LogisticRegression")
result.append("QuadraticDiscriminantAnalysis")
return result
示例4: test_model_elastic_net_regressor
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_model_elastic_net_regressor(self):
model, X = fit_regression_model(linear_model.ElasticNet())
model_onnx = convert_sklearn(
model,
"scikit-learn elastic-net regression",
[("input", FloatTensorType([None, X.shape[1]]))],
)
self.assertIsNotNone(model_onnx)
dump_data_and_model(
X,
model,
model_onnx,
basename="SklearnElasticNet-Dec4",
allow_failure="StrictVersion("
"onnxruntime.__version__)"
"<= StrictVersion('0.2.1')",
)
示例5: test_model_elastic_net_regressor_bool
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_model_elastic_net_regressor_bool(self):
model, X = fit_regression_model(
linear_model.ElasticNet(), is_bool=True)
model_onnx = convert_sklearn(
model, "elastic net regression",
[("input", BooleanTensorType([None, X.shape[1]]))])
self.assertIsNotNone(model_onnx)
dump_data_and_model(
X,
model,
model_onnx,
basename="SklearnElasticNetRegressorBool",
allow_failure="StrictVersion("
"onnxruntime.__version__)"
"<= StrictVersion('0.2.1')",
)
示例6: test_n_clusters
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_n_clusters():
# Test that n_clusters param works properly
X, y = make_blobs(n_samples=100, centers=10)
brc1 = Birch(n_clusters=10)
brc1.fit(X)
assert_greater(len(brc1.subcluster_centers_), 10)
assert_equal(len(np.unique(brc1.labels_)), 10)
# Test that n_clusters = Agglomerative Clustering gives
# the same results.
gc = AgglomerativeClustering(n_clusters=10)
brc2 = Birch(n_clusters=gc)
brc2.fit(X)
assert_array_equal(brc1.subcluster_labels_, brc2.subcluster_labels_)
assert_array_equal(brc1.labels_, brc2.labels_)
# Test that the wrong global clustering step raises an Error.
clf = ElasticNet()
brc3 = Birch(n_clusters=clf)
assert_raises(ValueError, brc3.fit, X)
# Test that a small number of clusters raises a warning.
brc4 = Birch(threshold=10000.)
assert_warns(UserWarning, brc4.fit, X)
示例7: get_regression_coefs
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def get_regression_coefs(self, category, clf=ElasticNet()):
''' Computes regression score of tdfidf transformed features
Parameters
----------
category : str
category name to score
clf : sklearn regressor
Returns
-------
coefficient array
'''
self._fit_tfidf_model(category, clf)
return clf.coef_
示例8: build_ensemble
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def build_ensemble(**kwargs):
"""Generate ensemble."""
ens = SuperLearner(**kwargs)
est = [ElasticNet(copy_X=False),
Lasso(copy_X=False)]
ens.add(est)
ens.add(KNeighborsRegressor())
return ens
示例9: test_elasticnet_convergence
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_elasticnet_convergence(klass):
# Check that the SGD output is consistent with coordinate descent
n_samples, n_features = 1000, 5
rng = np.random.RandomState(0)
X = rng.randn(n_samples, n_features)
# ground_truth linear model that generate y from X and to which the
# models should converge if the regularizer would be set to 0.0
ground_truth_coef = rng.randn(n_features)
y = np.dot(X, ground_truth_coef)
# XXX: alpha = 0.1 seems to cause convergence problems
for alpha in [0.01, 0.001]:
for l1_ratio in [0.5, 0.8, 1.0]:
cd = linear_model.ElasticNet(alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=False)
cd.fit(X, y)
sgd = klass(penalty='elasticnet', max_iter=50,
alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=False)
sgd.fit(X, y)
err_msg = ("cd and sgd did not converge to comparable "
"results for alpha=%f and l1_ratio=%f"
% (alpha, l1_ratio))
assert_almost_equal(cd.coef_, sgd.coef_, decimal=2,
err_msg=err_msg)
示例10: test_compare_sklearn
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_compare_sklearn(solver):
"""Test results against sklearn."""
def rmse(a, b):
return np.sqrt(np.mean((a - b) ** 2))
X, Y, coef_ = make_regression(
n_samples=1000, n_features=1000,
noise=0.1, n_informative=10, coef=True,
random_state=42)
alpha = 0.1
l1_ratio = 0.5
clf = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, tol=1e-5)
clf.fit(X, Y)
glm = GLM(distr='gaussian', alpha=l1_ratio, reg_lambda=alpha,
solver=solver, tol=1e-5, max_iter=70)
glm.fit(X, Y)
y_sk = clf.predict(X)
y_pg = glm.predict(X)
assert abs(rmse(Y, y_sk) - rmse(Y, y_pg)) < 1.0
glm = GLM(distr='gaussian', alpha=l1_ratio, reg_lambda=alpha,
solver=solver, tol=1e-5, max_iter=5, fit_intercept=False)
glm.fit(X, Y)
assert glm.beta0_ == 0.
glm.predict(X)
示例11: learn_model
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def learn_model(self, x, y, clf, lam = None):
if (lam is None and self.initlam != -1):
lam = self.initlam
if (clf is not None):
if (lam is not None):
clf = linear_model.ElasticNetCV(max_iter = 10000)
clf.fit(x, y)
lam = clf.alpha_
clf = linear_model.ElasticNet(alpha = lam, \
max_iter = 10000, \
warm_start = True)
clf.fit(x, y)
return clf, lam
示例12: __init__
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def __init__(self, options):
self.handle_options(options)
out_params = convert_params(
options.get('params', {}),
bools=['fit_intercept', 'normalize'],
floats=['alpha', 'l1_ratio'],
)
if 'l1_ratio' in out_params:
if out_params['l1_ratio'] < 0 or out_params['l1_ratio'] > 1:
raise RuntimeError('l1_ratio must be >= 0 and <= 1')
self.estimator = _ElasticNet(**out_params)
示例13: test_ElasticNet
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_ElasticNet(self):
ElasticNetAlgo.register_codecs()
self.regressor_util(ElasticNet)
示例14: ensure_many_models
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def ensure_many_models(self):
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.linear_model import ElasticNet, RANSACRegressor, HuberRegressor, PassiveAggressiveRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR, LinearSVR
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings('ignore', category=ConvergenceWarning)
data = self.create_uninformative_ox_dataset()
for propensity_learner in [GradientBoostingClassifier(n_estimators=10),
RandomForestClassifier(n_estimators=100),
MLPClassifier(hidden_layer_sizes=(5,)),
KNeighborsClassifier(n_neighbors=20)]:
weight_model = IPW(propensity_learner)
propensity_learner_name = str(propensity_learner).split("(", maxsplit=1)[0]
for outcome_learner in [GradientBoostingRegressor(n_estimators=10), RandomForestRegressor(n_estimators=10),
MLPRegressor(hidden_layer_sizes=(5,)),
ElasticNet(), RANSACRegressor(), HuberRegressor(), PassiveAggressiveRegressor(),
KNeighborsRegressor(), SVR(), LinearSVR()]:
outcome_learner_name = str(outcome_learner).split("(", maxsplit=1)[0]
outcome_model = Standardization(outcome_learner)
with self.subTest("Test fit & predict using {} & {}".format(propensity_learner_name,
outcome_learner_name)):
model = self.estimator.__class__(outcome_model, weight_model)
model.fit(data["X"], data["a"], data["y"], refit_weight_model=False)
model.estimate_individual_outcome(data["X"], data["a"])
self.assertTrue(True) # Fit did not crash
示例15: test_lm
# 需要导入模块: from sklearn import linear_model [as 别名]
# 或者: from sklearn.linear_model import ElasticNet [as 别名]
def test_lm(self):
_checkLM(ElasticNet())
_checkLM(LinearRegression())
_checkLM(SGDRegressor())