def load_solubility_data(self): """Loads solubility data from example.csv""" if os.path.exists(self.data_dir): shutil.rmtree(self.data_dir) featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] task_type = "regression" input_file = os.path.join(self.current_dir, "../../models/tests/example.csv") featurizer = DataLoader( tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") return featurizer.featurize(input_file, self.data_dir)
def test_samples_move(self): """Test that featurized samples can be moved and reloaded.""" verbosity = "high" data_dir = os.path.join(self.base_dir, "data") moved_data_dir = os.path.join(self.base_dir, "moved_data") dataset_file = os.path.join( self.current_dir, "example.csv") featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] loader = DataLoader(tasks=tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) featurized_dataset = loader.featurize( dataset_file, data_dir) n_dataset = len(featurized_dataset) # Now perform move shutil.move(data_dir, moved_data_dir) moved_featurized_dataset = Dataset( data_dir=moved_data_dir, reload=True) assert len(moved_featurized_dataset) == n_dataset
def test_drop(self): """Test on dataset where RDKit fails on some strings.""" # Set some global variables up top reload = True verbosity = "high" len_full = 25 current_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = os.path.join(self.base_dir, "dataset") model_dir = os.path.join(self.base_dir, "model") print("About to load emols dataset.") dataset_file = os.path.join(current_dir, "mini_emols.csv") # Featurize emols dataset print("About to featurize datasets.") featurizer = CircularFingerprint(size=1024) emols_tasks = ['activity'] loader = DataLoader(tasks=emols_tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) dataset = loader.featurize(dataset_file, data_dir, debug=True, logging=False) X, y, w, ids = (dataset.X, dataset.y, dataset.w, dataset.ids) print("ids.shape, X.shape, y.shape, w.shape") print(ids.shape, X.shape, y.shape, w.shape) assert len(X) == len(y) == len(w) == len(ids)
def test_singletask_rf_ECFP_regression_sharded_API(self): """Test of singletask RF ECFP regression API: sharded edition.""" splittype = "scaffold" compound_featurizers = [CircularFingerprint(size=1024)] complex_featurizers = [] input_transforms = [] output_transforms = ["normalize"] model_params = {} task_types = {"label": "regression"} input_file = "../../../datasets/pdbbind_core_df.pkl.gz" train_dataset, test_dataset = self._featurize_train_test_split( splittype, compound_featurizers, complex_featurizers, input_transforms, output_transforms, input_file, task_types.keys(), shard_size=50) # We set shard size above to force the creation of multiple shards of the data. # pdbbind_core has ~200 examples. model_params["data_shape"] = train_dataset.get_data_shape() from sklearn.ensemble import RandomForestRegressor model = SklearnModel(task_types, model_params, model_instance=RandomForestRegressor()) self._create_model(train_dataset, test_dataset, model)
def test_move_load(self): """Test that datasets can be moved and loaded.""" verbosity = "high" current_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = os.path.join(self.base_dir, "data") moved_data_dir = os.path.join(self.base_dir, "moved_data") dataset_file = os.path.join(current_dir, "../../models/tests/example.csv") featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] loader = DataLoader(tasks=tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) dataset = loader.featurize(dataset_file, data_dir) X, y, w, ids = (dataset.X, dataset.y, dataset.w, dataset.ids) shutil.move(data_dir, moved_data_dir) moved_dataset = DiskDataset(moved_data_dir, reload=True) X_moved, y_moved, w_moved, ids_moved = (moved_dataset.X, moved_dataset.y, moved_dataset.w, moved_dataset.ids) np.testing.assert_allclose(X, X_moved) np.testing.assert_allclose(y, y_moved) np.testing.assert_allclose(w, w_moved) np.testing.assert_array_equal(ids, ids_moved)
def test_reshard_shuffle(self): """Test that datasets can be merged.""" verbosity = "high" current_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = os.path.join(self.base_dir, "dataset") dataset_file = os.path.join(current_dir, "../../models/tests/example.csv") featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] loader = DataLoader(tasks=tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) dataset = loader.featurize(dataset_file, data_dir, shard_size=2) X_orig, y_orig, w_orig, orig_ids = dataset.to_numpy() orig_len = len(dataset) dataset.reshard_shuffle(reshard_size=1) X_new, y_new, w_new, new_ids = dataset.to_numpy() assert len(dataset) == orig_len # The shuffling should have switched up the ordering assert not np.array_equal(orig_ids, new_ids) # But all the same entries should still be present assert sorted(orig_ids) == sorted(new_ids) # All the data should have same shape assert X_orig.shape == X_new.shape assert y_orig.shape == y_new.shape assert w_orig.shape == w_new.shape
def random_test_train_valid_test_split(self): """Test of singletask RF ECFP regression API.""" input_transforms = [] output_transforms = ["normalize"] model_params = {} tasks = ["log-solubility"] task_type = "regression" task_types = {task: task_type for task in tasks} input_file = os.path.join(self.current_dir, "example.csv") featurizer = CircularFingerprint(size=1024) input_file = os.path.join(self.current_dir, input_file) loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) # Splits featurized samples into train/test splitter = RandomSplitter() train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split( dataset, self.train_dir, self.valid_dir, self.test_dir) assert len(train_dataset) == 8 assert len(valid_dataset) == 1 assert len(test_dataset) == 1
def test_subset(self): """Tests that subsetting of datasets works.""" verbosity = "high" current_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = os.path.join(self.base_dir, "dataset") subset_dir = os.path.join(self.base_dir, "subset") dataset_file = os.path.join(current_dir, "../../models/tests/example.csv") featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] loader = DataLoader(tasks=tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) dataset = loader.featurize(dataset_file, data_dir, shard_size=2) shard_nums = [1, 2] orig_ids = dataset.ids _, _, _, ids_1 = dataset.get_shard(1) _, _, _, ids_2 = dataset.get_shard(2) subset = dataset.subset(subset_dir, shard_nums) after_ids = dataset.ids assert len(subset) == 4 assert sorted(subset.ids) == sorted(np.concatenate([ids_1, ids_2])) assert list(orig_ids) == list(after_ids)
def load_pdbbind(pdbbind_dir, base_dir, reload=True): """Load PDBBind datasets. Does not do train/test split""" # Set some global variables up top reload = True verbosity = "high" model = "logistic" regen = False # Create some directories for analysis # The base_dir holds the results of all analysis if not reload: if os.path.exists(base_dir): shutil.rmtree(base_dir) if not os.path.exists(base_dir): os.makedirs(base_dir) current_dir = os.path.dirname(os.path.realpath(__file__)) #Make directories to store the raw and featurized datasets. data_dir = os.path.join(base_dir, "dataset") # Load PDBBind dataset labels_file = os.path.join(pdbbind_dir, "INDEX_core_data.2013") pdb_subdirs = os.path.join(pdbbind_dir, "website-core-set") tasks = ["-logKd/Ki"] print("About to load contents.") contents_df = load_pdbbind_labels(labels_file) ids = contents_df["PDB code"].values y = np.array([float(val) for val in contents_df["-logKd/Ki"].values]) # Define featurizers grid_featurizer = GridFeaturizer(voxel_width=16.0, feature_types="voxel_combined", voxel_feature_types=[ "ecfp", "splif", "hbond", "pi_stack", "cation_pi", "salt_bridge" ], ecfp_power=9, splif_power=9, parallel=True, flatten=True) compound_featurizers = [CircularFingerprint(size=1024)] complex_featurizers = [grid_featurizer] # Featurize Dataset features = [] for pdb_code in ids: pdb_subdir = os.path.join(pdb_subdirs, pdb_code) computed_feature = compute_pdbbind_feature(compound_featurizers, complex_featurizers, pdb_subdir, pdb_code) if len(computed_feature) == 0: computed_feature = np.zeros(1024) features.append(computed_feature) X = np.vstack(features) w = np.ones_like(y) dataset = Dataset.from_numpy(data_dir, X, y, w, ids) transformers = [] return tasks, dataset, transformers
def test_multitask_tf_mlp_ECFP_classification_hyperparam_opt(self): """Straightforward test of Tensorflow multitask deepchem classification API.""" splittype = "scaffold" task_type = "classification" input_file = os.path.join(self.current_dir, "multitask_example.csv") tasks = ["task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16"] task_types = {task: task_type for task in tasks} featurizer = CircularFingerprint(size=1024) loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split( dataset, self.train_dir, self.valid_dir, self.test_dir) transformers = [] metric = Metric(metrics.matthews_corrcoef, np.mean, mode="classification") params_dict = {"activation": ["relu"], "momentum": [.9], "batch_size": [50], "init": ["glorot_uniform"], "data_shape": [train_dataset.get_data_shape()], "learning_rate": [1e-3], "decay": [1e-6], "nb_hidden": [1000], "nb_epoch": [1], "nesterov": [False], "dropouts": [(.5,)], "nb_layers": [1], "batchnorm": [False], "layer_sizes": [(1000,)], "weight_init_stddevs": [(.1,)], "bias_init_consts": [(1.,)], "num_classes": [2], "penalty": [0.], "optimizer": ["sgd"], "num_classification_tasks": [len(task_types)] } def model_builder(tasks, task_types, params_dict, logdir, verbosity=None): return TensorflowModel( tasks, task_types, params_dict, logdir, tf_class=TensorflowMultiTaskClassifier, verbosity=verbosity) optimizer = HyperparamOpt(model_builder, tasks, task_types, verbosity="low") best_model, best_hyperparams, all_results = optimizer.hyperparam_search( params_dict, train_dataset, valid_dataset, transformers, metric, logdir=None)
def test_singletask_sklearn_rf_ECFP_regression_API(self): """Test of singletask RF ECFP regression API.""" splittype = "scaffold" featurizer = CircularFingerprint(size=1024) model_params = {} tasks = ["log-solubility"] task_type = "regression" task_types = {task: task_type for task in tasks} input_file = os.path.join(self.current_dir, "example.csv") loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, test_dataset = splitter.train_test_split( dataset, self.train_dir, self.test_dir) input_transformers = [] output_transformers = [ NormalizationTransformer(transform_y=True, dataset=train_dataset) ] transformers = input_transformers + output_transformers model_params["data_shape"] = train_dataset.get_data_shape() regression_metrics = [ Metric(metrics.r2_score), Metric(metrics.mean_squared_error), Metric(metrics.mean_absolute_error) ] model = SklearnModel(tasks, task_types, model_params, self.model_dir, mode="regression", model_instance=RandomForestRegressor()) # Fit trained model model.fit(train_dataset) model.save() # Eval model on train evaluator = Evaluator(model, train_dataset, transformers, verbosity=True) _ = evaluator.compute_model_performance(regression_metrics) # Eval model on test evaluator = Evaluator(model, test_dataset, transformers, verbosity=True) _ = evaluator.compute_model_performance(regression_metrics)
def load_muv(base_dir, reload=True): """Load MUV datasets. Does not do train/test split""" # Set some global variables up top reload = True verbosity = "high" model = "logistic" regen = False # Create some directories for analysis # The base_dir holds the results of all analysis if not reload: if os.path.exists(base_dir): shutil.rmtree(base_dir) if not os.path.exists(base_dir): os.makedirs(base_dir) current_dir = os.path.dirname(os.path.realpath(__file__)) #Make directories to store the raw and featurized datasets. data_dir = os.path.join(base_dir, "dataset") # Load MUV dataset print("About to load MUV dataset.") dataset_file = os.path.join( current_dir, "../../datasets/muv.csv.gz") dataset = load_from_disk(dataset_file) print("Columns of dataset: %s" % str(dataset.columns.values)) print("Number of examples in dataset: %s" % str(dataset.shape[0])) # Featurize MUV dataset print("About to featurize MUV dataset.") featurizer = CircularFingerprint(size=1024) all_MUV_tasks = sorted(['MUV-692', 'MUV-689', 'MUV-846', 'MUV-859', 'MUV-644', 'MUV-548', 'MUV-852', 'MUV-600', 'MUV-810', 'MUV-712', 'MUV-737', 'MUV-858', 'MUV-713', 'MUV-733', 'MUV-652', 'MUV-466', 'MUV-832']) loader = DataLoader(tasks=all_MUV_tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) if not reload or not os.path.exists(data_dir): dataset = loader.featurize(dataset_file, data_dir) regen = True else: dataset = Dataset(data_dir, reload=True) # Initialize transformers transformers = [ BalancingTransformer(transform_w=True, dataset=dataset)] if regen: print("About to transform data") for transformer in transformers: transformer.transform(dataset) return all_MUV_tasks, dataset, transformers
def load_tox21(base_dir, reload=True): """Load Tox21 datasets. Does not do train/test split""" # Set some global variables up top reload = True verbosity = "high" model = "logistic" # Create some directories for analysis # The base_dir holds the results of all analysis if not reload: if os.path.exists(base_dir): shutil.rmtree(base_dir) if not os.path.exists(base_dir): os.makedirs(base_dir) current_dir = os.path.dirname(os.path.realpath(__file__)) #Make directories to store the raw and featurized datasets. samples_dir = os.path.join(base_dir, "samples") data_dir = os.path.join(base_dir, "dataset") # Load Tox21 dataset print("About to load Tox21 dataset.") dataset_file = os.path.join( current_dir, "../../datasets/tox21.csv.gz") dataset = load_from_disk(dataset_file) print("Columns of dataset: %s" % str(dataset.columns.values)) print("Number of examples in dataset: %s" % str(dataset.shape[0])) # Featurize Tox21 dataset print("About to featurize Tox21 dataset.") featurizer = CircularFingerprint(size=1024) all_tox21_tasks = ['NR-AR', 'NR-AR-LBD', 'NR-AhR', 'NR-Aromatase', 'NR-ER', 'NR-ER-LBD', 'NR-PPAR-gamma', 'SR-ARE', 'SR-ATAD5', 'SR-HSE', 'SR-MMP', 'SR-p53'] if not reload or not os.path.exists(data_dir): loader = DataLoader(tasks=all_tox21_tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) dataset = loader.featurize( dataset_file, data_dir, shard_size=8192) else: dataset = Dataset(data_dir, all_tox21_tasks, reload=True) # Initialize transformers transformers = [ BalancingTransformer(transform_w=True, dataset=dataset)] if not reload: print("About to transform data") for transformer in transformers: transformer.transform(dataset) return all_tox21_tasks, dataset, transformers
def load_classification_data(self): """Loads classification data from example.csv""" if os.path.exists(self.data_dir): shutil.rmtree(self.data_dir) featurizer = CircularFingerprint(size=1024) tasks = ["outcome"] task_type = "classification" input_file = os.path.join( self.current_dir, "../../models/tests/example_classification.csv") loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") return loader.featurize(input_file, self.data_dir)
def _run_muv_experiment(self, dataset_file, reload=False, verbosity=None): """Loads or reloads a small version of MUV dataset.""" # Load MUV dataset raw_dataset = load_from_disk(dataset_file) print("Number of examples in dataset: %s" % str(raw_dataset.shape[0])) print("About to featurize compounds") featurizer = CircularFingerprint(size=1024) MUV_tasks = [ 'MUV-692', 'MUV-689', 'MUV-846', 'MUV-859', 'MUV-644', 'MUV-548', 'MUV-852', 'MUV-600', 'MUV-810', 'MUV-712', 'MUV-737', 'MUV-858', 'MUV-713', 'MUV-733', 'MUV-652', 'MUV-466', 'MUV-832' ] loader = DataLoader(tasks=MUV_tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) dataset = loader.featurize(dataset_file, self.data_dir) assert len(dataset) == len(raw_dataset) print("About to split compounds into train/valid/test") splitter = ScaffoldSplitter(verbosity=verbosity) frac_train, frac_valid, frac_test = .8, .1, .1 train_dataset, valid_dataset, test_dataset = \ splitter.train_valid_test_split( dataset, self.train_dir, self.valid_dir, self.test_dir, log_every_n=1000, frac_train=frac_train, frac_test=frac_test, frac_valid=frac_valid) # Do an approximate comparison since splits are sometimes slightly off from # the exact fraction. assert relative_difference(len(train_dataset), frac_train * len(dataset)) < 1e-3 assert relative_difference(len(valid_dataset), frac_valid * len(dataset)) < 1e-3 assert relative_difference(len(test_dataset), frac_test * len(dataset)) < 1e-3 # TODO(rbharath): Transformers don't play nice with reload! Namely, # reloading will cause the transform to be reapplied. This is undesirable in # almost all cases. Need to understand a method to fix this. transformers = [ BalancingTransformer(transform_w=True, dataset=train_dataset) ] print("Transforming datasets") for dataset in [train_dataset, valid_dataset, test_dataset]: for transformer in transformers: transformer.transform(dataset) return (len(train_dataset), len(valid_dataset), len(test_dataset))
def test_log_solubility_dataset(self): """Test of loading for simple log-solubility dataset.""" current_dir = os.path.dirname(os.path.realpath(__file__)) input_file = "../../models/tests/example.csv" input_file = os.path.join(current_dir, input_file) tasks = ["log-solubility"] smiles_field = "smiles" loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=CircularFingerprint(size=1024), verbosity="low") dataset = loader.featurize(input_file, self.data_dir) assert len(dataset) == 10
def load_sparse_multitask_dataset(self): """Load sparse tox multitask data, sample dataset.""" if os.path.exists(self.data_dir): shutil.rmtree(self.data_dir) featurizer = CircularFingerprint(size=1024) tasks = ["task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9"] input_file = os.path.join( self.current_dir, "../../models/tests/sparse_multitask_example.csv") loader = DataLoader( tasks=tasks, smiles_field="smiles", featurizer=featurizer, verbosity="low") return loader.featurize(input_file, self.data_dir)
def load_multitask_data(self): """Load example multitask data.""" if os.path.exists(self.data_dir): shutil.rmtree(self.data_dir) featurizer = CircularFingerprint(size=1024) tasks = ["task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16"] input_file = os.path.join( self.current_dir, "../../models/tests/multitask_example.csv") loader = DataLoader( tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") return loader.featurize(input_file, self.data_dir)
def test_multitask_order(self): """Test that order of tasks in multitask datasets is preserved.""" from deepchem.models.keras_models.fcnet import MultiTaskDNN splittype = "scaffold" output_transformers = [] input_transformers = [] task_type = "classification" # TODO(rbharath): There should be some automatic check to ensure that all # required model_params are specified. model_params = { "nb_hidden": 10, "activation": "relu", "dropout": .5, "learning_rate": .01, "momentum": .9, "nesterov": False, "decay": 1e-4, "batch_size": 5, "nb_epoch": 2, "init": "glorot_uniform", "nb_layers": 1, "batchnorm": False } input_file = os.path.join(self.current_dir, "multitask_example.csv") tasks = [ "task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16" ] task_types = {task: task_type for task in tasks} featurizer = CircularFingerprint(size=1024) loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, test_dataset = splitter.train_test_split( dataset, self.train_dir, self.test_dir) assert train_dataset.get_task_names() == tasks assert test_dataset.get_task_names() == tasks
def test_singletask_tf_mlp_ECFP_classification_API(self): """Straightforward test of Tensorflow singletask deepchem classification API.""" n_features = 1024 featurizer = CircularFingerprint(size=n_features) tasks = ["outcome"] input_file = os.path.join(self.current_dir, "example_classification.csv") loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, test_dataset = splitter.train_test_split( dataset, self.train_dir, self.test_dir) transformers = [ NormalizationTransformer(transform_y=True, dataset=train_dataset)] for dataset in [train_dataset, test_dataset]: for transformer in transformers: transformer.transform(dataset) classification_metrics = [Metric(metrics.roc_auc_score), Metric(metrics.matthews_corrcoef), Metric(metrics.recall_score), Metric(metrics.accuracy_score)] tensorflow_model = TensorflowMultiTaskClassifier( len(tasks), n_features, self.model_dir) model = TensorflowModel(tensorflow_model, self.model_dir) # Fit trained model model.fit(train_dataset) model.save() # Eval model on train evaluator = Evaluator(model, train_dataset, transformers, verbosity=True) _ = evaluator.compute_model_performance(classification_metrics) # Eval model on test evaluator = Evaluator(model, test_dataset, transformers, verbosity=True) _ = evaluator.compute_model_performance(classification_metrics)
def test_multitask_keras_mlp_ECFP_classification_API(self): """Straightforward test of Keras multitask deepchem classification API.""" g = tf.Graph() sess = tf.Session(graph=g) K.set_session(sess) with g.as_default(): task_type = "classification" input_file = os.path.join(self.current_dir, "multitask_example.csv") tasks = ["task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16"] n_features = 1024 featurizer = CircularFingerprint(size=n_features) loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, test_dataset = splitter.train_test_split( dataset, self.train_dir, self.test_dir) transformers = [] classification_metrics = [Metric(metrics.roc_auc_score), Metric(metrics.matthews_corrcoef), Metric(metrics.recall_score), Metric(metrics.accuracy_score)] keras_model = MultiTaskDNN(len(tasks), n_features, "classification", dropout=0.) model = KerasModel(keras_model, self.model_dir) # Fit trained model model.fit(train_dataset) model.save() # Eval model on train evaluator = Evaluator(model, train_dataset, transformers, verbosity=True) _ = evaluator.compute_model_performance(classification_metrics) # Eval model on test evaluator = Evaluator(model, test_dataset, transformers, verbosity=True) _ = evaluator.compute_model_performance(classification_metrics)
def test_multitask_keras_mlp_ECFP_classification_hyperparam_opt(self): """Straightforward test of Keras multitask deepchem classification API.""" task_type = "classification" input_file = os.path.join(self.current_dir, "multitask_example.csv") tasks = [ "task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16" ] n_features = 1024 featurizer = CircularFingerprint(size=n_features) loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split( dataset, self.train_dir, self.valid_dir, self.test_dir) transformers = [] metric = Metric(metrics.matthews_corrcoef, np.mean, mode="classification") params_dict = {"n_hidden": [5, 10]} def model_builder(model_params, model_dir): keras_model = MultiTaskDNN(len(tasks), n_features, task_type, dropout=0., **model_params) return KerasModel(keras_model, model_dir) optimizer = HyperparamOpt(model_builder, verbosity="low") best_model, best_hyperparams, all_results = optimizer.hyperparam_search( params_dict, train_dataset, valid_dataset, transformers, metric, logdir=None)
def test_singletask_rf_ECFP_regression_API(self): """Test of singletask RF ECFP regression API.""" splittype = "scaffold" compound_featurizers = [CircularFingerprint(size=1024)] complex_featurizers = [] input_transforms = [] output_transforms = ["normalize"] model_params = {} task_types = {"log-solubility": "regression"} input_file = "example.csv" train_dataset, test_dataset = self._featurize_train_test_split( splittype, compound_featurizers, complex_featurizers, input_transforms, output_transforms, input_file, task_types.keys()) model_params["data_shape"] = train_dataset.get_data_shape() from sklearn.ensemble import RandomForestRegressor model = SklearnModel(task_types, model_params, model_instance=RandomForestRegressor()) self._create_model(train_dataset, test_dataset, model)
def test_multitask_mlp_ECFP_classification_API(self): """Straightforward test of multitask deepchem classification API.""" splittype = "scaffold" output_transforms = [] input_transforms = [] task_type = "classification" # TODO(rbharath): There should be some automatic check to ensure that all # required model_params are specified. model_params = { "nb_hidden": 10, "activation": "relu", "dropout": .5, "learning_rate": .01, "momentum": .9, "nesterov": False, "decay": 1e-4, "batch_size": 5, "nb_epoch": 2, "init": "glorot_uniform", "nb_layers": 1, "batchnorm": False } input_file = os.path.join(self.current_dir, "multitask_example.csv") tasks = [ "task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16" ] task_types = {task: task_type for task in tasks} compound_featurizers = [CircularFingerprint(size=1024)] complex_featurizers = [] train_dataset, test_dataset = self._featurize_train_test_split( splittype, compound_featurizers, complex_featurizers, input_transforms, output_transforms, input_file, task_types.keys()) model_params["data_shape"] = train_dataset.get_data_shape() model = MultiTaskDNN(task_types, model_params) self._create_model(train_dataset, test_dataset, model)
def test_multitask_keras_mlp_ECFP_classification_hyperparam_opt(self): """Straightforward test of Keras multitask deepchem classification API.""" task_type = "classification" input_file = os.path.join(self.current_dir, "multitask_example.csv") tasks = ["task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16"] task_types = {task: task_type for task in tasks} featurizer = CircularFingerprint(size=1024) loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split( dataset, self.train_dir, self.valid_dir, self.test_dir) transformers = [] metric = Metric(metrics.matthews_corrcoef, np.mean, mode="classification") params_dict= {"nb_hidden": [5, 10], "activation": ["relu"], "dropout": [.5], "learning_rate": [.01], "momentum": [.9], "nesterov": [False], "decay": [1e-4], "batch_size": [5], "nb_epoch": [2], "init": ["glorot_uniform"], "nb_layers": [1], "batchnorm": [False], "data_shape": [train_dataset.get_data_shape()]} optimizer = HyperparamOpt(MultiTaskDNN, tasks, task_types, verbosity="low") best_model, best_hyperparams, all_results = optimizer.hyperparam_search( params_dict, train_dataset, valid_dataset, transformers, metric, logdir=None)
def _featurize_train_valid_test_split(self, splittype, input_file, tasks, frac_train, frac_valid, frac_test): # Featurize input compound_featurizers = [CircularFingerprint(size=1024)] complex_featurizers = [] featurizers = compound_featurizers + complex_featurizers input_file = os.path.join(self.current_dir, input_file) featurizer = DataFeaturizer(tasks=tasks, smiles_field=self.smiles_field, compound_featurizers=compound_featurizers, complex_featurizers=complex_featurizers, verbose=True) #Featurizes samples and transforms them into NumPy arrays suitable for ML. #returns an instance of class FeaturizedSamples() samples = featurizer.featurize(input_file, self.feature_dir, self.samples_dir) # Splits featurized samples into train/test if frac_valid > 0: train_samples, valid_samples, test_samples = samples.train_valid_test_split( splittype, train_dir=self.train_dir, valid_dir=self.valid_dir, test_dir=self.test_dir, frac_train=frac_train, frac_valid=frac_valid, frac_test=frac_test) return train_samples, valid_samples, test_samples else: train_samples, test_samples = samples.train_test_split( splittype, train_dir=self.train_dir, test_dir=self.test_dir, frac_train=frac_train) return train_samples, test_samples
def test_multitask_order(self): """Test that order of tasks in multitask datasets is preserved.""" input_file = os.path.join(self.current_dir, "multitask_example.csv") tasks = [ "task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16" ] featurizer = CircularFingerprint(size=1024) loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, test_dataset = splitter.train_test_split( dataset, self.train_dir, self.test_dir) assert train_dataset.get_task_names() == tasks assert test_dataset.get_task_names() == tasks
def test_singletask_sklearn_rf_ECFP_regression_hyperparam_opt(self): """Test of hyperparam_opt with singletask RF ECFP regression API.""" featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] input_file = os.path.join(self.current_dir, "example.csv") loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split( dataset, self.train_dir, self.valid_dir, self.test_dir) transformers = [ NormalizationTransformer(transform_y=True, dataset=train_dataset) ] for dataset in [train_dataset, test_dataset]: for transformer in transformers: transformer.transform(dataset) params_dict = {"n_estimators": [10, 100]} metric = Metric(metrics.r2_score) def rf_model_builder(model_params, model_dir): sklearn_model = RandomForestRegressor(**model_params) return SklearnModel(sklearn_model, model_dir) optimizer = HyperparamOpt(rf_model_builder, verbosity="low") best_model, best_hyperparams, all_results = optimizer.hyperparam_search( params_dict, train_dataset, valid_dataset, transformers, metric, logdir=None)
def test_merge(self): """Test that datasets can be merged.""" verbosity = "high" current_dir = os.path.dirname(os.path.realpath(__file__)) first_data_dir = os.path.join(self.base_dir, "first_dataset") second_data_dir = os.path.join(self.base_dir, "second_dataset") merged_data_dir = os.path.join(self.base_dir, "merged_data") dataset_file = os.path.join(current_dir, "../../models/tests/example.csv") featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] loader = DataLoader(tasks=tasks, smiles_field="smiles", featurizer=featurizer, verbosity=verbosity) first_dataset = loader.featurize(dataset_file, first_data_dir) second_dataset = loader.featurize(dataset_file, second_data_dir) merged_dataset = DiskDataset.merge(merged_data_dir, [first_dataset, second_dataset]) assert len(merged_dataset) == len(first_dataset) + len(second_dataset)
def test_singletask_sklearn_rf_ECFP_regression_hyperparam_opt(self): """Test of hyperparam_opt with singletask RF ECFP regression API.""" splittype = "scaffold" featurizer = CircularFingerprint(size=1024) tasks = ["log-solubility"] task_type = "regression" task_types = {task: task_type for task in tasks} input_file = os.path.join(self.current_dir, "example.csv") loader = DataLoader(tasks=tasks, smiles_field=self.smiles_field, featurizer=featurizer, verbosity="low") dataset = loader.featurize(input_file, self.data_dir) splitter = ScaffoldSplitter() train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split( dataset, self.train_dir, self.valid_dir, self.test_dir) input_transformers = [] output_transformers = [ NormalizationTransformer(transform_y=True, dataset=train_dataset)] transformers = input_transformers + output_transformers for dataset in [train_dataset, test_dataset]: for transformer in transformers: transformer.transform(dataset) params_dict = { "n_estimators": [10, 100], "max_features": ["auto"], "data_shape": train_dataset.get_data_shape() } metric = Metric(metrics.r2_score) optimizer = HyperparamOpt(rf_model_builder, tasks, task_types, verbosity="low") best_model, best_hyperparams, all_results = optimizer.hyperparam_search( params_dict, train_dataset, valid_dataset, output_transformers, metric, logdir=None)