Best Python code snippet using autotest_python
models.py
Source:models.py
...13from imblearn.pipeline import make_pipeline as make_pipeline_imb14from .factory import register_model15from ._models import sk_model_factory, nn_model_factory, cv_factory, gcv_factory16from ..helpers.utils import decorate_class17@decorate_class(staticmethod)18@decorate_class(register_model(sk_model_factory))19class SkLearnModels():20 def xgboost():21 return XGBClassifier()22 def randomforest():23 return RandomForestClassifier()24 def ridge():25 return make_pipeline(StandardScaler(), RidgeClassifier())26 def lr():27 return make_pipeline(StandardScaler(), LogisticRegression())28 def dummy():29 return DummyClassifier()30 def catboost():31 return CatBoostClassifier()32 def lightgbm():33 return LGBMClassifier()34 def rf_xgboost():35 return make_pipeline(36 SelectFromModel(RandomForestClassifier(random_state=17)),37 XGBClassifier()38 )39 def rf_lr():40 return make_pipeline(41 SelectFromModel(RandomForestClassifier(random_state=17)),42 LogisticRegression()43 )44 def columnestimator():45 return ColumnEstimator()46 def smote_randomforest():47 return make_pipeline_imb(48 SMOTE(), RandomForestClassifier()49 )50 def smote_xgboost():51 return make_pipeline_imb(52 SMOTE(), XGBClassifier()53 )54 def smote_ridge():55 return make_pipeline_imb(56 SMOTE(), StandardScaler(), RidgeClassifier()57 )58 59 def smote_lr():60 return make_pipeline_imb(61 SMOTE(), StandardScaler(), LogisticRegression()62 )63 def smote_catboost():64 return make_pipeline_imb(65 SMOTE(), CatBoostClassifier()66 )67 68 def smote_lightgbm():69 return make_pipeline_imb(70 SMOTE(), LGBMClassifier(),71 )72from tensorflow.keras.models import Sequential73from tensorflow.keras import layers as L74@decorate_class(staticmethod)75@decorate_class(register_model(nn_model_factory))76class KerasModels:77 def perceptron(input_shape: tuple, n_classes: int=3, units_array: list=[10], 78 optimizer: str='adam') -> Sequential:79 model = Sequential([80 L.Input(shape=input_shape),81 *(L.Dense(units=units, activation='relu') for units in units_array),82 L.Dense(units=n_classes, activation='softmax') 83 ])84 model.compile(loss='categorical_crossentropy', optimizer=optimizer)85 return model86 def lstm(input_shape, n_classes, units_array, optimizer, ):87 88 model = Sequential([89 L.Input(shape=input_shape),90 *(L.LSTM(i, return_sequences=True, ) 91 for i in units_array['rnn'][:-1]),92 L.LSTM(units_array['rnn'][-1]),93 *(L.Dense(units=units, activation='relu') 94 for units in units_array['dense']),95 L.Dense(n_classes, activation='softmax')96 ], )97 98 model.compile(loss='categorical_crossentropy', optimizer=optimizer)99 return model100 def gru(input_shape, n_classes, units_array, optimizer, ):101 102 model = Sequential([103 L.Input(shape=input_shape),104 *(L.GRU(i, return_sequences=True, ) 105 for i in units_array['rnn'][:-1]),106 L.GRU(units_array['rnn'][-1]),107 *(L.Dense(units=units, activation='relu') 108 for units in units_array['dense']),109 L.Dense(n_classes, activation='softmax')110 ], )111 112 model.compile(loss='categorical_crossentropy', optimizer=optimizer)113 return model114 115 def bi_lstm(input_shape, n_classes, units_array, optimizer, ):116 117 model = Sequential([118 L.Input(shape=input_shape),119 *(L.Bidirectional(L.LSTM(i, return_sequences=True, ))120 for i in units_array['rnn'][:-1]),121 L.Bidirectional(L.LSTM(units_array['rnn'][-1])),122 *(L.Dense(units=units, activation='relu') 123 for units in units_array['dense']),124 L.Dense(n_classes, activation='softmax')125 ], )126 127 model.compile(loss='categorical_crossentropy', optimizer=optimizer)128 return model129 def bi_gru(input_shape, n_classes, units_array, optimizer, ):130 131 model = Sequential([132 L.Input(shape=input_shape),133 *(L.Bidirectional(L.GRU(i, return_sequences=True, ))134 for i in units_array['rnn'][:-1]),135 L.Bidirectional(L.GRU(units_array['rnn'][-1])),136 *(L.Dense(units=units, activation='relu') 137 for units in units_array['dense']),138 L.Dense(n_classes, activation='softmax')139 ], )140 141 model.compile(loss='categorical_crossentropy', optimizer=optimizer)142 return model143from sklearn.model_selection import StratifiedKFold, TimeSeriesSplit144@decorate_class(staticmethod)145@decorate_class(register_model(cv_factory))146class CV:147 def skf(**kwargs):148 return StratifiedKFold(**kwargs)149 150 def tss(**kwargs):151 return TimeSeriesSplit(**kwargs)152from sklearn.model_selection import GridSearchCV, RandomizedSearchCV153@decorate_class(staticmethod)154@decorate_class(register_model(gcv_factory))155class GCV:156 def gcv(**kwargs):157 return GridSearchCV(**kwargs)158 159 def rscv(**kwargs):160 if 'param_grid' in kwargs:161 kwargs['param_distributions'] = kwargs['param_grid']162 kwargs.pop('param_grid')163 ...
decorators.py
Source:decorators.py
...7 """8 Custom decorator for mocking the course_catalog_api_client property of siteconfiguration9 to return a new instance of EdxRestApiClient with a dummy jwt value.10 """11 def decorate_class(klass):12 for attr in dir(klass):13 # Decorate only callable unit tests.14 if not attr.startswith('test_'):15 continue16 attr_value = getattr(klass, attr)17 if not hasattr(attr_value, "__call__"):18 continue19 setattr(klass, attr, decorate_callable(attr_value))20 return klass21 def decorate_callable(test):22 @functools.wraps(test)23 def wrapper(*args, **kw):24 with mock.patch(25 'ecommerce.core.models.SiteConfiguration.course_catalog_api_client',26 mock.PropertyMock(return_value=EdxRestApiClient(27 settings.COURSE_CATALOG_API_URL,28 jwt='auth-token'29 ))30 ):31 return test(*args, **kw)32 return wrapper33 if isinstance(test, type):34 return decorate_class(test)35 return decorate_callable(test)36def mock_enterprise_api_client(test):37 """38 Custom decorator for mocking the property "enterprise_api_client" of39 siteconfiguration to construct a new instance of EdxRestApiClient with a40 dummy jwt value.41 """42 def decorate_class(klass):43 for attr in dir(klass):44 # Decorate only callable unit tests.45 if not attr.startswith('test_'):46 continue47 attr_value = getattr(klass, attr)48 if not hasattr(attr_value, '__call__'):49 continue50 setattr(klass, attr, decorate_callable(attr_value))51 return klass52 def decorate_callable(test):53 @functools.wraps(test)54 def wrapper(*args, **kw):55 with mock.patch(56 'ecommerce.core.models.SiteConfiguration.enterprise_api_client',57 mock.PropertyMock(58 return_value=EdxRestApiClient(59 settings.ENTERPRISE_API_URL,60 jwt='auth-token'61 )62 )63 ):64 return test(*args, **kw)65 return wrapper66 if isinstance(test, type):67 return decorate_class(test)...
__init__.py
Source:__init__.py
...16 return callable(x)17 if mode == "function":18 wrapped_func = decorate_function(orig_func, func_name_str)19 elif mode == "class":20 wrapped_func = decorate_class(orig_func, func_name_str)21 else:22 if is_class(orig_func):23 wrapped_func = decorate_class(orig_func, func_name_str)24 elif is_callable(orig_func):25 wrapped_func = decorate_function(orig_func, func_name_str)26 else:27 wrapped_func = orig_func28 setattr(module_obj, func_name, wrapped_func)29with open(__file__.replace("__init__.py", "torch.txt"), "r") as f1:30 lines = f1.readlines()31 skipped = ["enable_grad", "get_default_dtype", "load", "tensor", "no_grad", "jit"]32 for l in lines:33 l = l.strip()34 if l not in skipped:35 hijack(torch, l, mode="function")36with open(__file__.replace("__init__.py", "torch.nn.txt"), "r") as f2:37 lines = f2.readlines()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!