repo_name
stringlengths
6
103
path
stringlengths
5
191
copies
stringlengths
1
4
size
stringlengths
4
6
content
stringlengths
986
970k
license
stringclasses
15 values
glouppe/scikit-learn
sklearn/utils/tests/test_shortest_path.py
292
2841
from collections import defaultdict import numpy as np from numpy.testing import assert_array_almost_equal from sklearn.utils.graph import (graph_shortest_path, single_source_shortest_path_length) def floyd_warshall_slow(graph, directed=False): N = graph.shape[0] #set nonzero entries to infinity graph[np.where(graph == 0)] = np.inf #set diagonal to zero graph.flat[::N + 1] = 0 if not directed: graph = np.minimum(graph, graph.T) for k in range(N): for i in range(N): for j in range(N): graph[i, j] = min(graph[i, j], graph[i, k] + graph[k, j]) graph[np.where(np.isinf(graph))] = 0 return graph def generate_graph(N=20): #sparse grid of distances rng = np.random.RandomState(0) dist_matrix = rng.random_sample((N, N)) #make symmetric: distances are not direction-dependent dist_matrix = dist_matrix + dist_matrix.T #make graph sparse i = (rng.randint(N, size=N * N // 2), rng.randint(N, size=N * N // 2)) dist_matrix[i] = 0 #set diagonal to zero dist_matrix.flat[::N + 1] = 0 return dist_matrix def test_floyd_warshall(): dist_matrix = generate_graph(20) for directed in (True, False): graph_FW = graph_shortest_path(dist_matrix, directed, 'FW') graph_py = floyd_warshall_slow(dist_matrix.copy(), directed) assert_array_almost_equal(graph_FW, graph_py) def test_dijkstra(): dist_matrix = generate_graph(20) for directed in (True, False): graph_D = graph_shortest_path(dist_matrix, directed, 'D') graph_py = floyd_warshall_slow(dist_matrix.copy(), directed) assert_array_almost_equal(graph_D, graph_py) def test_shortest_path(): dist_matrix = generate_graph(20) # We compare path length and not costs (-> set distances to 0 or 1) dist_matrix[dist_matrix != 0] = 1 for directed in (True, False): if not directed: dist_matrix = np.minimum(dist_matrix, dist_matrix.T) graph_py = floyd_warshall_slow(dist_matrix.copy(), directed) for i in range(dist_matrix.shape[0]): # Non-reachable nodes have distance 0 in graph_py dist_dict = defaultdict(int) dist_dict.update(single_source_shortest_path_length(dist_matrix, i)) for j in range(graph_py[i].shape[0]): assert_array_almost_equal(dist_dict[j], graph_py[i, j]) def test_dijkstra_bug_fix(): X = np.array([[0., 0., 4.], [1., 0., 2.], [0., 5., 0.]]) dist_FW = graph_shortest_path(X, directed=False, method='FW') dist_D = graph_shortest_path(X, directed=False, method='D') assert_array_almost_equal(dist_D, dist_FW)
bsd-3-clause
bytedance/fedlearner
test/trainer/test_horizontal_nn_trainer.py
1
18484
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 import unittest import threading import os import time import logging import json from datetime import datetime, timedelta from multiprocessing import Process import tensorflow.compat.v1 as tf from tensorflow.compat.v1 import gfile from queue import PriorityQueue import enum from tensorflow.core.example.feature_pb2 import FloatList, Features, Feature, \ Int64List, BytesList from tensorflow.core.example.example_pb2 import Example import numpy as np from fedlearner.data_join import ( data_block_manager, common, raw_data_manifest_manager ) from fedlearner.common import ( db_client, common_pb2 as common_pb, data_join_service_pb2 as dj_pb ) from fedlearner.data_join.data_block_manager import DataBlockBuilder from fedlearner.data_join.raw_data_iter_impl.tf_record_iter import TfExampleItem import fedlearner.trainer as flt from graph_def.horizontal_leader import main as lm from graph_def.horizontal_follower import main as fm debug_mode = False local_mnist_path = "./mnist.npz" output_path = "./output" total_worker_num = 1 child_env = os.environ.copy() child_env["KVSTORE_USE_MOCK"] = "on" child_env["KVSTORE_MOCK_DISK_SYNC"] = "on" os.environ = child_env class _Task(object): def __init__(self, name, weight, target, args=None, kwargs=None, daemon=None, force_quit=False): self.name = name self.weight = 0 - weight self._target = target self._args = args self._kwargs = kwargs self.force_quit = force_quit self._daemon = True self._lock = threading.Lock() self._task = None self._stop = False self._start_new() def _start_new(self): if self._task is not None and self._task.is_alive(): logging.info(" %s is alive, no need to start new" % self.name) return self._task = Process(target=self._target, name=self.name, args=self._args, kwargs=self._kwargs, daemon=self._daemon) self._task.start() logging.info("Task starts %s" % self.name) time.sleep(10) def __gt__(self, o): return self.weight > o.weight def kill(self, force = False): with self._lock: logging.info("Kill task %s", self.name) if self._task is None or not self._task.is_alive(): return if force or self.force_quit: self._task.terminate() elif self._task.is_alive(): raise ValueError("can not kill by force") def start(self): logging.info("begin to start") with self._lock: if self._stop: return if self._task.is_alive(): logging.info(" %s is alive, no need to start" % self.name) return self._start_new() time.sleep(2) def is_alive(self): with self._lock: if self._task is None: return True return self._task.is_alive() class _Signal(enum.Enum): KILL = 1 RUN = 2 class _Event(object): def __init__(self, name, action, timeout): self.name = name self.action = action self.timeout = timeout self._start_time = time.time() self._trigged = False def handle(self, task): if self._trigged: return if self.timeout + self._start_time > time.time(): return logging.info("handle event: %s=%s", task.name, self.action) self._trigged = True if self.action == _Signal.KILL: task.kill(True) elif self.action == _Signal.RUN: task.start() else: raise ValueError("unknown event %d" % self.action) class _TaskScheduler(object): def __init__(self, timeout): self._task_queue = PriorityQueue() self._task_done = {} self._start_time = time.time() self._event_queue = [] self._task_killed = {} self._keepalive = [] self._timeout = timeout def submit(self, task): self._keepalive.append(task.name) self._task_queue.put(task) def recv(self, ev): self._event_queue.append(ev) def _handle_events(self, name, task): for e in self._event_queue: if e.name == name: e.handle(task) def bye(self): while not self._task_queue.empty(): task = self._task_queue.get() if task.is_alive(): task.kill(True) def run(self): while not self._task_queue.empty(): task = [] done = {} while not self._task_queue.empty(): next_task = self._task_queue.get() logging.info("handle queue: %s", next_task.name) if not next_task.is_alive(): done[next_task.name] = next_task continue self._handle_events(next_task.name, next_task) if next_task.is_alive(): task.append(next_task) else: done[next_task.name] = next_task for t in task: self._task_queue.put(t) for k, v in done.items(): if k in self._keepalive: if v._task.exitcode != 0: v.start() self._task_queue.put(v) continue self._task_done[k] = v time.sleep(1) if self._timeout + self._start_time < time.time(): logging.info("stop!!!!!") return def make_ckpt_dir(role, remote="local", rank=None): if rank is None: rank = "N" ckpt_path = "{}/{}_ckpt_{}_{}".format(output_path, remote, role, rank) exp_path = "{}/saved_model".format(ckpt_path) if gfile.Exists(ckpt_path): gfile.DeleteRecursively(ckpt_path) return ckpt_path, exp_path def run_ps(port, env=None): if env is not None: os.environ = env addr = "0.0.0.0:{}".format(port) cluster_spec = tf.train.ClusterSpec({'local': {0: addr}}) server = tf.train.Server(cluster_spec, job_name="local", task_index=0) server.join() def run_lm(args, env=None): if env is not None: os.environ = env lm(args) def run_fm(args, env=None): if env is not None: os.environ = env fm(args) class TestHorizontalNNTraining(unittest.TestCase): def _create_data_block(self, data_source, partition_id, x, y, N): data_block_metas = [] dbm = data_block_manager.DataBlockManager(data_source, partition_id) self.assertEqual(dbm.get_dumped_data_block_count(), 0) self.assertEqual(dbm.get_lastest_data_block_meta(), None) print(data_source.data_source_meta.name, data_source.output_base_dir, x.shape) chunk_size = x.shape[0] // N leader_index = 0 follower_index = N * chunk_size * 10 event_time = datetime.strptime('20210101', '%Y%m%d') delta = timedelta(minutes=1) for i in range(N): builder = DataBlockBuilder( common.data_source_data_block_dir(data_source), data_source.data_source_meta.name, partition_id, i, dj_pb.WriterOptions(output_writer="TF_RECORD", compressed_type="GZIP"), None ) builder.set_data_block_manager(dbm) for j in range(chunk_size): feat = {} idx = i * chunk_size + j exam_id = '{}'.format(idx).encode() feat['example_id'] = Feature( bytes_list=BytesList(value=[exam_id])) evt_time =int(event_time.strftime('%Y%m%d%H%M%S')) feat['event_time'] = Feature( int64_list = Int64List(value=[evt_time]) ) feat['x'] = Feature(float_list=FloatList(value=list(x[idx]))) if y is not None: feat['y'] = Feature(int64_list=Int64List(value=[y[idx]])) feat['leader_index'] = Feature( int64_list = Int64List(value=[leader_index]) ) feat['follower_index'] = Feature( int64_list = Int64List(value=[follower_index]) ) example = Example(features=Features(feature=feat)) builder.append_item(TfExampleItem(example.SerializeToString()), leader_index, follower_index) leader_index += 1 follower_index += 1 event_time += delta data_block_metas.append(builder.finish_data_block()) self.max_index = follower_index return data_block_metas def _gen_ds_meta(self, role, index, data_source_name): data_source = common_pb.DataSource() data_source.data_source_meta.name = data_source_name data_source.data_source_meta.partition_num = 1 data_source.data_source_meta.start_time = 0 data_source.data_source_meta.end_time = 100000 data_source.output_base_dir = "{}/{}_{}_{}/data_source/".format( output_path, data_source.data_source_meta.name, role, index) data_source.role = role return data_source def setUp(self): self.sche = _TaskScheduler(250) self.app_id = "test_trainer_v1" if debug_mode: (x, y), _ = tf.keras.datasets.mnist.load_data(local_mnist_path) else: (x, y), _ = tf.keras.datasets.mnist.load_data() x = x.reshape(x.shape[0], -1).astype(np.float32) / 255.0 y = y.astype(np.int64) num_parts = 3 num_sample = x.shape[0] chunk_size = (num_sample // 2) + 1 xs = [x[:chunk_size], x[chunk_size:num_sample], x[:chunk_size]] ys = [y[:chunk_size], y[chunk_size:num_sample], y[:chunk_size]] self.kv_store = [None, None, None] self._local_data_source = "test-liuqi-mnist-local" data_source = [self._gen_ds_meta(common_pb.FLRole.Leader, 0, "test-liuqi-mnist-v1"), self._gen_ds_meta(common_pb.FLRole.Leader, 1, self._local_data_source), self._gen_ds_meta(common_pb.FLRole.Follower, 0, "test-liuqi-mnist-v1")] self._etcd_base_dirs = ["fedlearner0", "fedlearner0", "fedlearner2"] for role in range(num_parts): os.environ['ETCD_BASE_DIR'] = self._etcd_base_dirs[role] self.kv_store[role] = db_client.DBClient("etcd", True) self.data_source = data_source for role in range(num_parts): common.commit_data_source(self.kv_store[role], data_source[role]) if gfile.Exists(data_source[role].output_base_dir): gfile.DeleteRecursively(data_source[role].output_base_dir) manifest_manager = raw_data_manifest_manager.RawDataManifestManager( self.kv_store[role], data_source[role] ) partition_num = data_source[role].data_source_meta.partition_num #num_data_blocks = 100 if role == 1 else 2 num_data_blocks = 100 if role == 1 else 20 for i in range(partition_num): self._create_data_block(data_source[role], i, xs[role], ys[role], num_data_blocks) #x[role], y if role == 0 else None) manifest_manager._finish_partition('join_example_rep', dj_pb.JoinExampleState.UnJoined, dj_pb.JoinExampleState.Joined, -1, i) #@unittest.skip("demonstrating skipping") def test_remote_cluster(self): parser = flt.trainer_worker.create_argument_parser() parser.add_argument('--local-worker', action='store_true', help='is local worker') num_worker = 2 leader_master_address = "0.0.0.0:4051" leader_cluster_spec = { "clusterSpec": { "Master": ["0.0.0.0:4050"], "PS": ["0.0.0.0:4060"], "Worker": ["0.0.0.0:4070", "0.0.0.0:4071", "0.0.0.0:4080", "0.0.0.0:5081"] } } leader_cluster_spec_str = json.dumps(leader_cluster_spec) follower_master_address = "0.0.0.0:5051" follower_cluster_spec = { "clusterSpec": { "Master": ["0.0.0.0:5050"], "PS": ["0.0.0.0:5060"], "Worker": ["0.0.0.0:5070", "0.0.0.0:5071"] } } follower_cluster_spec_str = json.dumps(follower_cluster_spec) self.sche.bye() # launch leader/follower master ckpt_path, exp_path = make_ckpt_dir("leader", "remote") args = parser.parse_args(( "--master", "--application-id", self.app_id, "--master-addr", leader_master_address, "--data-source", self.data_source[0].data_source_meta.name, "--local-data-source", self.data_source[1].data_source_meta.name, "--cluster-spec", leader_cluster_spec_str, "--checkpoint-path", ckpt_path, "--export-path", exp_path, "--shuffle-in-day", 'true', )) child_env['ETCD_BASE_DIR'] = self._etcd_base_dirs[0] tml = _Task(name="RunLeaderMaster", target=run_lm, args=(args,), weight=1, force_quit=True, kwargs={'env' : child_env}, daemon=True) self.sche.submit(tml) ckpt_path, exp_path = make_ckpt_dir("follower", "remote") args = parser.parse_args(( "--master", "--application-id", self.app_id, "--master-addr", follower_master_address, "--data-source", self.data_source[2].data_source_meta.name, "--cluster-spec", follower_cluster_spec_str, "--checkpoint-path", ckpt_path, "--export-path", exp_path, )) child_env['ETCD_BASE_DIR'] = self._etcd_base_dirs[2] tml = _Task(name="RunFollowerMaster", target=run_fm, args=(args,), weight=1, force_quit=True, kwargs={'env' : child_env}, daemon=True) self.sche.submit(tml) # launch leader/follower PS for i, addr in enumerate(leader_cluster_spec["clusterSpec"]["PS"]): psl = _Task(name="RunLeaderPS_%d"%i, target=run_ps, args=(addr, ), weight=1, force_quit=True, kwargs={'env' : child_env}, daemon=True) self.sche.submit(psl) for i, addr in enumerate(follower_cluster_spec["clusterSpec"]["PS"]): psl = _Task(name="RunFollowerPS_%d"%i, target=run_ps, args=(addr, ), weight=1, force_quit=True, kwargs={'env' : child_env}, daemon=True) self.sche.submit(psl) # launch leader/follower worker for i in range(num_worker): _, leader_worker_port = \ leader_cluster_spec["clusterSpec"]["Worker"][i].split(':') leader_worker_port = int(leader_worker_port) + 10000 _, follower_worker_port = \ follower_cluster_spec["clusterSpec"]["Worker"][i].split(':') follower_worker_port = int(follower_worker_port) + 10000 # leader worker args = parser.parse_args(( "--worker", "--application-id", self.app_id, "--master-addr", leader_master_address, "--local-addr", "0.0.0.0:%d"%leader_worker_port, "--peer-addr", "0.0.0.0:%d"%follower_worker_port, "--cluster-spec", leader_cluster_spec_str, "--worker-rank", str(i), )) ftm = _Task(name="RunLeaderWorker_%d"%i, target=run_lm, args=(args, ), weight=1, force_quit=True, kwargs={'env' : child_env}, daemon=True) self.sche.submit(ftm) # follower worker args = parser.parse_args(( "--worker", "--application-id", self.app_id, "--master-addr", follower_master_address, "--local-addr", "0.0.0.0:%d"%follower_worker_port, "--peer-addr", "0.0.0.0:%d"%leader_worker_port, "--cluster-spec", follower_cluster_spec_str, "--worker-rank", str(i), )) ftm = _Task(name="RunLeaderWorker_%d"%i, target=run_fm, args=(args, ), weight=1, force_quit=True, kwargs={'env' : child_env}, daemon=True) self.sche.submit(ftm) # leader local worker local_worker_rank = i + num_worker args = parser.parse_args(( "--worker", "--local-worker", "--application-id", self.app_id, "--master-addr", leader_master_address, "--cluster-spec", leader_cluster_spec_str, "--worker-rank", str(local_worker_rank), )) ftm = _Task(name="RunLeaderWorker_%d"%local_worker_rank, target=run_lm, args=(args, ), weight=1, force_quit=True, kwargs={'env' : child_env}, daemon=True) self.sche.submit(ftm) self.sche.run() def tearDown(self): self.sche.bye() if not debug_mode and gfile.Exists(output_path): gfile.DeleteRecursively(output_path) if __name__ == '__main__': unittest.main()
apache-2.0
DwangoMediaVillage/pqkmeans
pqkmeans/encoder/encoder_base.py
2
1627
import numpy import sklearn import typing class EncoderBase(sklearn.base.BaseEstimator): def fit_generator(self, x_train): # type: (typing.Iterable[typing.Iterator[float]]) -> None raise NotImplementedError() def transform_generator(self, x_test): # type: (typing.Iterable[typing.Iterator[float]]) -> Any raise NotImplementedError() def inverse_transform_generator(self, x_test): # type: (typing.Iterable[typing.Iterator[Any]]) -> Any raise NotImplementedError() def fit(self, x_train): # type: (numpy.array) -> None assert len(x_train.shape) == 2 self.fit_generator(iter(x_train)) def transform(self, x_test): # type: (numpy.array) -> Any assert len(x_test.shape) == 2 return numpy.array(list(self.transform_generator(x_test))) def inverse_transform(self, x_test): # type: (numpy.array) -> Any assert len(x_test.shape) == 2 return numpy.array(list(self.inverse_transform_generator(x_test))) def _buffered_process(self, x_input, process, buffer_size=10000): # type: (typing.Iterable[typing.Iterator[Any]], Any, int) -> Any buffer = [] for input_vector in x_input: buffer.append(input_vector) if len(buffer) == buffer_size: encoded = process(buffer) for encoded_vec in encoded: yield encoded_vec buffer = [] if len(buffer) > 0: # rest encoded = process(buffer) for encoded_vec in encoded: yield encoded_vec
mit
LohithBlaze/scikit-learn
sklearn/feature_extraction/tests/test_dict_vectorizer.py
274
3790
# Authors: Lars Buitinck <L.J.Buitinck@uva.nl> # Dan Blanchard <dblanchard@ets.org> # License: BSD 3 clause from random import Random import numpy as np import scipy.sparse as sp from numpy.testing import assert_array_equal from sklearn.utils.testing import (assert_equal, assert_in, assert_false, assert_true) from sklearn.feature_extraction import DictVectorizer from sklearn.feature_selection import SelectKBest, chi2 def test_dictvectorizer(): D = [{"foo": 1, "bar": 3}, {"bar": 4, "baz": 2}, {"bar": 1, "quux": 1, "quuux": 2}] for sparse in (True, False): for dtype in (int, np.float32, np.int16): for sort in (True, False): for iterable in (True, False): v = DictVectorizer(sparse=sparse, dtype=dtype, sort=sort) X = v.fit_transform(iter(D) if iterable else D) assert_equal(sp.issparse(X), sparse) assert_equal(X.shape, (3, 5)) assert_equal(X.sum(), 14) assert_equal(v.inverse_transform(X), D) if sparse: # CSR matrices can't be compared for equality assert_array_equal(X.A, v.transform(iter(D) if iterable else D).A) else: assert_array_equal(X, v.transform(iter(D) if iterable else D)) if sort: assert_equal(v.feature_names_, sorted(v.feature_names_)) def test_feature_selection(): # make two feature dicts with two useful features and a bunch of useless # ones, in terms of chi2 d1 = dict([("useless%d" % i, 10) for i in range(20)], useful1=1, useful2=20) d2 = dict([("useless%d" % i, 10) for i in range(20)], useful1=20, useful2=1) for indices in (True, False): v = DictVectorizer().fit([d1, d2]) X = v.transform([d1, d2]) sel = SelectKBest(chi2, k=2).fit(X, [0, 1]) v.restrict(sel.get_support(indices=indices), indices=indices) assert_equal(v.get_feature_names(), ["useful1", "useful2"]) def test_one_of_k(): D_in = [{"version": "1", "ham": 2}, {"version": "2", "spam": .3}, {"version=3": True, "spam": -1}] v = DictVectorizer() X = v.fit_transform(D_in) assert_equal(X.shape, (3, 5)) D_out = v.inverse_transform(X) assert_equal(D_out[0], {"version=1": 1, "ham": 2}) names = v.get_feature_names() assert_true("version=2" in names) assert_false("version" in names) def test_unseen_or_no_features(): D = [{"camelot": 0, "spamalot": 1}] for sparse in [True, False]: v = DictVectorizer(sparse=sparse).fit(D) X = v.transform({"push the pram a lot": 2}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) X = v.transform({}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) try: v.transform([]) except ValueError as e: assert_in("empty", str(e)) def test_deterministic_vocabulary(): # Generate equal dictionaries with different memory layouts items = [("%03d" % i, i) for i in range(1000)] rng = Random(42) d_sorted = dict(items) rng.shuffle(items) d_shuffled = dict(items) # check that the memory layout does not impact the resulting vocabulary v_1 = DictVectorizer().fit([d_sorted]) v_2 = DictVectorizer().fit([d_shuffled]) assert_equal(v_1.vocabulary_, v_2.vocabulary_)
bsd-3-clause
jzt5132/scikit-learn
sklearn/feature_extraction/tests/test_dict_vectorizer.py
274
3790
# Authors: Lars Buitinck <L.J.Buitinck@uva.nl> # Dan Blanchard <dblanchard@ets.org> # License: BSD 3 clause from random import Random import numpy as np import scipy.sparse as sp from numpy.testing import assert_array_equal from sklearn.utils.testing import (assert_equal, assert_in, assert_false, assert_true) from sklearn.feature_extraction import DictVectorizer from sklearn.feature_selection import SelectKBest, chi2 def test_dictvectorizer(): D = [{"foo": 1, "bar": 3}, {"bar": 4, "baz": 2}, {"bar": 1, "quux": 1, "quuux": 2}] for sparse in (True, False): for dtype in (int, np.float32, np.int16): for sort in (True, False): for iterable in (True, False): v = DictVectorizer(sparse=sparse, dtype=dtype, sort=sort) X = v.fit_transform(iter(D) if iterable else D) assert_equal(sp.issparse(X), sparse) assert_equal(X.shape, (3, 5)) assert_equal(X.sum(), 14) assert_equal(v.inverse_transform(X), D) if sparse: # CSR matrices can't be compared for equality assert_array_equal(X.A, v.transform(iter(D) if iterable else D).A) else: assert_array_equal(X, v.transform(iter(D) if iterable else D)) if sort: assert_equal(v.feature_names_, sorted(v.feature_names_)) def test_feature_selection(): # make two feature dicts with two useful features and a bunch of useless # ones, in terms of chi2 d1 = dict([("useless%d" % i, 10) for i in range(20)], useful1=1, useful2=20) d2 = dict([("useless%d" % i, 10) for i in range(20)], useful1=20, useful2=1) for indices in (True, False): v = DictVectorizer().fit([d1, d2]) X = v.transform([d1, d2]) sel = SelectKBest(chi2, k=2).fit(X, [0, 1]) v.restrict(sel.get_support(indices=indices), indices=indices) assert_equal(v.get_feature_names(), ["useful1", "useful2"]) def test_one_of_k(): D_in = [{"version": "1", "ham": 2}, {"version": "2", "spam": .3}, {"version=3": True, "spam": -1}] v = DictVectorizer() X = v.fit_transform(D_in) assert_equal(X.shape, (3, 5)) D_out = v.inverse_transform(X) assert_equal(D_out[0], {"version=1": 1, "ham": 2}) names = v.get_feature_names() assert_true("version=2" in names) assert_false("version" in names) def test_unseen_or_no_features(): D = [{"camelot": 0, "spamalot": 1}] for sparse in [True, False]: v = DictVectorizer(sparse=sparse).fit(D) X = v.transform({"push the pram a lot": 2}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) X = v.transform({}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) try: v.transform([]) except ValueError as e: assert_in("empty", str(e)) def test_deterministic_vocabulary(): # Generate equal dictionaries with different memory layouts items = [("%03d" % i, i) for i in range(1000)] rng = Random(42) d_sorted = dict(items) rng.shuffle(items) d_shuffled = dict(items) # check that the memory layout does not impact the resulting vocabulary v_1 = DictVectorizer().fit([d_sorted]) v_2 = DictVectorizer().fit([d_shuffled]) assert_equal(v_1.vocabulary_, v_2.vocabulary_)
bsd-3-clause
lilleswing/deepchem
contrib/one_shot_models/examples/muv_attn_one_fold.py
8
2521
""" Train low-data attn models on MUV. Test last fold only. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from datasets import load_muv_convmol # Number of folds for split K = 4 # Depth of attention module max_depth = 3 # number positive/negative ligands n_pos = 1 n_neg = 1 # Set batch sizes for network test_batch_size = 128 support_batch_size = n_pos + n_neg nb_epochs = 1 n_train_trials = 2000 n_eval_trials = 20 learning_rate = 1e-4 log_every_n_samples = 50 # Number of features on conv-mols n_feat = 75 muv_tasks, dataset, transformers = load_muv_convmol() # Define metric metric = dc.metrics.Metric(dc.metrics.roc_auc_score, mode="classification") task_splitter = dc.splits.TaskSplitter() fold_datasets = task_splitter.k_fold_split(dataset, K) train_folds = fold_datasets[:-1] train_dataset = dc.splits.merge_fold_datasets(train_folds) test_dataset = fold_datasets[-1] # Train support model on train support_model = dc.nn.SequentialSupportGraph(n_feat) # Add layers support_model.add(dc.nn.GraphConv(64, n_feat, activation='relu')) support_model.add(dc.nn.GraphPool()) support_model.add(dc.nn.GraphConv(128, 64, activation='relu')) support_model.add(dc.nn.GraphPool()) support_model.add(dc.nn.GraphConv(64, 128, activation='relu')) support_model.add(dc.nn.GraphPool()) support_model.add(dc.nn.Dense(128, 64, activation='tanh')) support_model.add_test(dc.nn.GraphGather(test_batch_size, activation='tanh')) support_model.add_support( dc.nn.GraphGather(support_batch_size, activation='tanh')) # Apply an attention lstm layer support_model.join( dc.nn.AttnLSTMEmbedding(test_batch_size, support_batch_size, 128, max_depth)) model = dc.models.SupportGraphClassifier( support_model, test_batch_size=test_batch_size, support_batch_size=support_batch_size, learning_rate=learning_rate) model.fit( train_dataset, nb_epochs=nb_epochs, n_episodes_per_epoch=n_train_trials, n_pos=n_pos, n_neg=n_neg, log_every_n_samples=log_every_n_samples) mean_scores, std_scores = model.evaluate( test_dataset, metric, n_pos, n_neg, n_trials=n_eval_trials) print("Mean Scores on evaluation dataset") print(mean_scores) print("Standard Deviations on evaluation dataset") print(std_scores) print("Median of Mean Scores") print(np.median(np.array(mean_scores.values())))
mit
ethen8181/machine-learning
projects/kaggle_rossman_store_sales/gbt_module/model.py
1
5582
import numpy as np from sklearn.base import BaseEstimator from sklearn.model_selection import RandomizedSearchCV, PredefinedSplit __all__ = ['GBTPipeline'] class GBTPipeline(BaseEstimator): """ Gradient Boosted Tree Pipeline set up to do train/validation split and hyperparameter search. """ def __init__(self, input_cols, cat_cols, label_col, weights_col, model_task, model_id, model_type, model_parameters, model_hyper_parameters, search_parameters): self.input_cols = input_cols self.cat_cols = cat_cols self.label_col = label_col self.weights_col = weights_col self.model_id = model_id self.model_type = model_type self.model_task = model_task self.model_parameters = model_parameters self.model_hyper_parameters = model_hyper_parameters self.search_parameters = search_parameters def fit(self, data, val_fold, fit_params=None): """ Fit the pipeline to the input data. Parameters ---------- data : pd.DataFrame Input training data. The data will be split into train/validation set by providing the val_fold (validation fold) parameter. val_fold : 1d ndarray The validation fold used for the `PredefinedSplit <https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.PredefinedSplit.html>`_ fit_params : dict Any additional parameters that are passed to the fit method of the model. e.g. `LGBMClassifier.fit <https://lightgbm.readthedocs.io/en/latest/Python-API.html#lightgbm.LGBMClassifier.fit>`_ Returns ------- self """ data_features = data[self.input_cols] label = data[self.label_col] sample_weights = data[self.weights_col] if self.weights_col is not None else None self.fit_params_ = self._create_default_fit_params(data_features, label, val_fold, sample_weights) if fit_params is not None: self.fit_params_.update(fit_params) model = self._get_model() cv = PredefinedSplit(val_fold) model_tuned = RandomizedSearchCV( estimator=model, param_distributions=self.model_hyper_parameters, cv=cv, **self.search_parameters ).fit(data_features, label, **self.fit_params_) self.model_tuned_ = model_tuned return self def _get_model(self): if self.model_task == 'classification' and self.model_type == 'lgb': from lightgbm import LGBMClassifier model = LGBMClassifier(**self.model_parameters) elif self.model_task == 'regression' and self.model_type == 'lgb': from lightgbm import LGBMRegressor model = LGBMRegressor(**self.model_parameters) else: raise ValueError("model_task should be regression/classification") return model def _create_default_fit_params(self, data, label, val_fold, sample_weights): mask = val_fold != -1 data_train = data[~mask] data_val = data[mask] label_train = label[~mask] label_val = label[mask] fit_params = { 'eval_set': [(data_train, label_train), (data_val, label_val)], 'feature_name': self.input_cols, 'categorical_feature': self.cat_cols } if sample_weights is not None: fit_params['sample_weights'] = sample_weights return fit_params def predict(self, data): """ Prediction estimates from the best model. Parameters ---------- data : pd.DataFrame Data that contains the same input_cols and cat_cols as the data that was used to fit the model. Returns ------- prediction : ndarray """ best = self.model_tuned_.best_estimator_ return best.predict(data, num_iteration=best.best_iteration_) def get_feature_importance(self, threshold=1e-3): """ Sort the feature importance based on decreasing order of the normalized gain. Parameters ---------- threshold : float, default 1e-3 Features that have a normalized gain smaller than the specified ``threshold`` will not be returned. """ booster = self.model_tuned_.best_estimator_.booster_ importance = booster.feature_importance(importance_type='gain') importance /= importance.sum() feature_name = np.array(booster.feature_name()) mask = importance > threshold importance = importance[mask] feature_name = feature_name[mask] idx = np.argsort(importance)[::-1] return list(zip(feature_name[idx], np.round(importance[idx], 4))) def save(self, path=None): import os from joblib import dump model_checkpoint = self.model_id + '.pkl' if path is None else path # create the directory if it's not the current directory and it doesn't exist already model_dir = os.path.split(model_checkpoint)[0] if model_dir.strip() and not os.path.isdir(model_dir): os.makedirs(model_dir, exist_ok=True) dump(self, model_checkpoint) return model_checkpoint @classmethod def load(cls, path): from joblib import load loaded_model = load(path) return loaded_model
mit
glouppe/scikit-learn
sklearn/utils/testing.py
13
27118
"""Testing utilities.""" # Copyright (c) 2011, 2012 # Authors: Pietro Berkes, # Andreas Muller # Mathieu Blondel # Olivier Grisel # Arnaud Joly # Denis Engemann # Giorgio Patrini # License: BSD 3 clause import os import inspect import pkgutil import warnings import sys import re import platform import struct import scipy as sp import scipy.io from functools import wraps from operator import itemgetter try: # Python 2 from urllib2 import urlopen from urllib2 import HTTPError except ImportError: # Python 3+ from urllib.request import urlopen from urllib.error import HTTPError import tempfile import shutil import os.path as op import atexit # WindowsError only exist on Windows try: WindowsError except NameError: WindowsError = None import sklearn from sklearn.base import BaseEstimator from sklearn.externals import joblib # Conveniently import all assertions in one place. from nose.tools import assert_equal from nose.tools import assert_not_equal from nose.tools import assert_true from nose.tools import assert_false from nose.tools import assert_raises from nose.tools import raises from nose import SkipTest from nose import with_setup from numpy.testing import assert_almost_equal from numpy.testing import assert_array_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_less from numpy.testing import assert_approx_equal import numpy as np from sklearn.base import (ClassifierMixin, RegressorMixin, TransformerMixin, ClusterMixin) from sklearn.cluster import DBSCAN __all__ = ["assert_equal", "assert_not_equal", "assert_raises", "assert_raises_regexp", "raises", "with_setup", "assert_true", "assert_false", "assert_almost_equal", "assert_array_equal", "assert_array_almost_equal", "assert_array_less", "assert_less", "assert_less_equal", "assert_greater", "assert_greater_equal", "assert_approx_equal"] try: from nose.tools import assert_in, assert_not_in except ImportError: # Nose < 1.0.0 def assert_in(x, container): assert_true(x in container, msg="%r in %r" % (x, container)) def assert_not_in(x, container): assert_false(x in container, msg="%r in %r" % (x, container)) try: from nose.tools import assert_raises_regex except ImportError: # for Python 2 def assert_raises_regex(expected_exception, expected_regexp, callable_obj=None, *args, **kwargs): """Helper function to check for message patterns in exceptions""" not_raised = False try: callable_obj(*args, **kwargs) not_raised = True except expected_exception as e: error_message = str(e) if not re.compile(expected_regexp).search(error_message): raise AssertionError("Error message should match pattern " "%r. %r does not." % (expected_regexp, error_message)) if not_raised: raise AssertionError("%s not raised by %s" % (expected_exception.__name__, callable_obj.__name__)) # assert_raises_regexp is deprecated in Python 3.4 in favor of # assert_raises_regex but lets keep the bacward compat in scikit-learn with # the old name for now assert_raises_regexp = assert_raises_regex def _assert_less(a, b, msg=None): message = "%r is not lower than %r" % (a, b) if msg is not None: message += ": " + msg assert a < b, message def _assert_greater(a, b, msg=None): message = "%r is not greater than %r" % (a, b) if msg is not None: message += ": " + msg assert a > b, message def assert_less_equal(a, b, msg=None): message = "%r is not lower than or equal to %r" % (a, b) if msg is not None: message += ": " + msg assert a <= b, message def assert_greater_equal(a, b, msg=None): message = "%r is not greater than or equal to %r" % (a, b) if msg is not None: message += ": " + msg assert a >= b, message def assert_warns(warning_class, func, *args, **kw): """Test that a certain warning occurs. Parameters ---------- warning_class : the warning class The class to test for, e.g. UserWarning. func : callable Calable object to trigger warnings. *args : the positional arguments to `func`. **kw : the keyword arguments to `func` Returns ------- result : the return value of `func` """ # very important to avoid uncontrolled state propagation clean_warning_registry() with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. result = func(*args, **kw) if hasattr(np, 'VisibleDeprecationWarning'): # Filter out numpy-specific warnings in numpy >= 1.9 w = [e for e in w if e.category is not np.VisibleDeprecationWarning] # Verify some things if not len(w) > 0: raise AssertionError("No warning raised when calling %s" % func.__name__) found = any(warning.category is warning_class for warning in w) if not found: raise AssertionError("%s did not give warning: %s( is %s)" % (func.__name__, warning_class, w)) return result def assert_warns_message(warning_class, message, func, *args, **kw): # very important to avoid uncontrolled state propagation """Test that a certain warning occurs and with a certain message. Parameters ---------- warning_class : the warning class The class to test for, e.g. UserWarning. message : str | callable The entire message or a substring to test for. If callable, it takes a string as argument and will trigger an assertion error if it returns `False`. func : callable Calable object to trigger warnings. *args : the positional arguments to `func`. **kw : the keyword arguments to `func`. Returns ------- result : the return value of `func` """ clean_warning_registry() with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") if hasattr(np, 'VisibleDeprecationWarning'): # Let's not catch the numpy internal DeprecationWarnings warnings.simplefilter('ignore', np.VisibleDeprecationWarning) # Trigger a warning. result = func(*args, **kw) # Verify some things if not len(w) > 0: raise AssertionError("No warning raised when calling %s" % func.__name__) found = [issubclass(warning.category, warning_class) for warning in w] if not any(found): raise AssertionError("No warning raised for %s with class " "%s" % (func.__name__, warning_class)) message_found = False # Checks the message of all warnings belong to warning_class for index in [i for i, x in enumerate(found) if x]: # substring will match, the entire message with typo won't msg = w[index].message # For Python 3 compatibility msg = str(msg.args[0] if hasattr(msg, 'args') else msg) if callable(message): # add support for certain tests check_in_message = message else: check_in_message = lambda msg: message in msg if check_in_message(msg): message_found = True break if not message_found: raise AssertionError("Did not receive the message you expected " "('%s') for <%s>, got: '%s'" % (message, func.__name__, msg)) return result # To remove when we support numpy 1.7 def assert_no_warnings(func, *args, **kw): # XXX: once we may depend on python >= 2.6, this can be replaced by the # warnings module context manager. # very important to avoid uncontrolled state propagation clean_warning_registry() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') result = func(*args, **kw) if hasattr(np, 'VisibleDeprecationWarning'): # Filter out numpy-specific warnings in numpy >= 1.9 w = [e for e in w if e.category is not np.VisibleDeprecationWarning] if len(w) > 0: raise AssertionError("Got warnings when calling %s: %s" % (func.__name__, w)) return result def ignore_warnings(obj=None): """ Context manager and decorator to ignore warnings Note. Using this (in both variants) will clear all warnings from all python modules loaded. In case you need to test cross-module-warning-logging this is not your tool of choice. Examples -------- >>> with ignore_warnings(): ... warnings.warn('buhuhuhu') >>> def nasty_warn(): ... warnings.warn('buhuhuhu') ... print(42) >>> ignore_warnings(nasty_warn)() 42 """ if callable(obj): return _ignore_warnings(obj) else: return _IgnoreWarnings() def _ignore_warnings(fn): """Decorator to catch and hide warnings without visual nesting""" @wraps(fn) def wrapper(*args, **kwargs): # very important to avoid uncontrolled state propagation clean_warning_registry() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') return fn(*args, **kwargs) w[:] = [] return wrapper class _IgnoreWarnings(object): """Improved and simplified Python warnings context manager Copied from Python 2.7.5 and modified as required. """ def __init__(self): """ Parameters ========== category : warning class The category to filter. Defaults to Warning. If None, all categories will be muted. """ self._record = True self._module = sys.modules['warnings'] self._entered = False self.log = [] def __repr__(self): args = [] if self._record: args.append("record=True") if self._module is not sys.modules['warnings']: args.append("module=%r" % self._module) name = type(self).__name__ return "%s(%s)" % (name, ", ".join(args)) def __enter__(self): clean_warning_registry() # be safe and not propagate state + chaos warnings.simplefilter('always') if self._entered: raise RuntimeError("Cannot enter %r twice" % self) self._entered = True self._filters = self._module.filters self._module.filters = self._filters[:] self._showwarning = self._module.showwarning if self._record: self.log = [] def showwarning(*args, **kwargs): self.log.append(warnings.WarningMessage(*args, **kwargs)) self._module.showwarning = showwarning return self.log else: return None def __exit__(self, *exc_info): if not self._entered: raise RuntimeError("Cannot exit %r without entering first" % self) self._module.filters = self._filters self._module.showwarning = self._showwarning self.log[:] = [] clean_warning_registry() # be safe and not propagate state + chaos try: from nose.tools import assert_less except ImportError: assert_less = _assert_less try: from nose.tools import assert_greater except ImportError: assert_greater = _assert_greater def _assert_allclose(actual, desired, rtol=1e-7, atol=0, err_msg='', verbose=True): actual, desired = np.asanyarray(actual), np.asanyarray(desired) if np.allclose(actual, desired, rtol=rtol, atol=atol): return msg = ('Array not equal to tolerance rtol=%g, atol=%g: ' 'actual %s, desired %s') % (rtol, atol, actual, desired) raise AssertionError(msg) if hasattr(np.testing, 'assert_allclose'): assert_allclose = np.testing.assert_allclose else: assert_allclose = _assert_allclose def assert_raise_message(exceptions, message, function, *args, **kwargs): """Helper function to test error messages in exceptions Parameters ---------- exceptions : exception or tuple of exception Name of the estimator func : callable Calable object to raise error *args : the positional arguments to `func`. **kw : the keyword arguments to `func` """ try: function(*args, **kwargs) except exceptions as e: error_message = str(e) if message not in error_message: raise AssertionError("Error message does not include the expected" " string: %r. Observed error message: %r" % (message, error_message)) else: # concatenate exception names if isinstance(exceptions, tuple): names = " or ".join(e.__name__ for e in exceptions) else: names = exceptions.__name__ raise AssertionError("%s not raised by %s" % (names, function.__name__)) def fake_mldata(columns_dict, dataname, matfile, ordering=None): """Create a fake mldata data set. Parameters ---------- columns_dict : dict, keys=str, values=ndarray Contains data as columns_dict[column_name] = array of data. dataname : string Name of data set. matfile : string or file object The file name string or the file-like object of the output file. ordering : list, default None List of column_names, determines the ordering in the data set. Notes ----- This function transposes all arrays, while fetch_mldata only transposes 'data', keep that into account in the tests. """ datasets = dict(columns_dict) # transpose all variables for name in datasets: datasets[name] = datasets[name].T if ordering is None: ordering = sorted(list(datasets.keys())) # NOTE: setting up this array is tricky, because of the way Matlab # re-packages 1D arrays datasets['mldata_descr_ordering'] = sp.empty((1, len(ordering)), dtype='object') for i, name in enumerate(ordering): datasets['mldata_descr_ordering'][0, i] = name scipy.io.savemat(matfile, datasets, oned_as='column') class mock_mldata_urlopen(object): def __init__(self, mock_datasets): """Object that mocks the urlopen function to fake requests to mldata. `mock_datasets` is a dictionary of {dataset_name: data_dict}, or {dataset_name: (data_dict, ordering). `data_dict` itself is a dictionary of {column_name: data_array}, and `ordering` is a list of column_names to determine the ordering in the data set (see `fake_mldata` for details). When requesting a dataset with a name that is in mock_datasets, this object creates a fake dataset in a StringIO object and returns it. Otherwise, it raises an HTTPError. """ self.mock_datasets = mock_datasets def __call__(self, urlname): dataset_name = urlname.split('/')[-1] if dataset_name in self.mock_datasets: resource_name = '_' + dataset_name from io import BytesIO matfile = BytesIO() dataset = self.mock_datasets[dataset_name] ordering = None if isinstance(dataset, tuple): dataset, ordering = dataset fake_mldata(dataset, resource_name, matfile, ordering) matfile.seek(0) return matfile else: raise HTTPError(urlname, 404, dataset_name + " is not available", [], None) def install_mldata_mock(mock_datasets): # Lazy import to avoid mutually recursive imports from sklearn import datasets datasets.mldata.urlopen = mock_mldata_urlopen(mock_datasets) def uninstall_mldata_mock(): # Lazy import to avoid mutually recursive imports from sklearn import datasets datasets.mldata.urlopen = urlopen # Meta estimators need another estimator to be instantiated. META_ESTIMATORS = ["OneVsOneClassifier", "OutputCodeClassifier", "OneVsRestClassifier", "RFE", "RFECV", "BaseEnsemble"] # estimators that there is no way to default-construct sensibly OTHER = ["Pipeline", "FeatureUnion", "GridSearchCV", "RandomizedSearchCV", "SelectFromModel"] # some trange ones DONT_TEST = ['SparseCoder', 'EllipticEnvelope', 'DictVectorizer', 'LabelBinarizer', 'LabelEncoder', 'MultiLabelBinarizer', 'TfidfTransformer', 'TfidfVectorizer', 'IsotonicRegression', 'OneHotEncoder', 'RandomTreesEmbedding', 'FeatureHasher', 'DummyClassifier', 'DummyRegressor', 'TruncatedSVD', 'PolynomialFeatures', 'GaussianRandomProjectionHash', 'HashingVectorizer', 'CheckingClassifier', 'PatchExtractor', 'CountVectorizer', # GradientBoosting base estimators, maybe should # exclude them in another way 'ZeroEstimator', 'ScaledLogOddsEstimator', 'QuantileEstimator', 'MeanEstimator', 'LogOddsEstimator', 'PriorProbabilityEstimator', '_SigmoidCalibration', 'VotingClassifier'] def all_estimators(include_meta_estimators=False, include_other=False, type_filter=None, include_dont_test=False): """Get a list of all estimators from sklearn. This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included. By default meta_estimators such as GridSearchCV are also not included. Parameters ---------- include_meta_estimators : boolean, default=False Whether to include meta-estimators that can be constructed using an estimator as their first argument. These are currently BaseEnsemble, OneVsOneClassifier, OutputCodeClassifier, OneVsRestClassifier, RFE, RFECV. include_other : boolean, default=False Wether to include meta-estimators that are somehow special and can not be default-constructed sensibly. These are currently Pipeline, FeatureUnion and GridSearchCV include_dont_test : boolean, default=False Whether to include "special" label estimator or test processors. type_filter : string, list of string, or None, default=None Which kind of estimators should be returned. If None, no filter is applied and all estimators are returned. Possible values are 'classifier', 'regressor', 'cluster' and 'transformer' to get estimators only of these specific types, or a list of these to get the estimators that fit at least one of the types. Returns ------- estimators : list of tuples List of (name, class), where ``name`` is the class name as string and ``class`` is the actuall type of the class. """ def is_abstract(c): if not(hasattr(c, '__abstractmethods__')): return False if not len(c.__abstractmethods__): return False return True all_classes = [] # get parent folder path = sklearn.__path__ for importer, modname, ispkg in pkgutil.walk_packages( path=path, prefix='sklearn.', onerror=lambda x: None): if (".tests." in modname): continue module = __import__(modname, fromlist="dummy") classes = inspect.getmembers(module, inspect.isclass) all_classes.extend(classes) all_classes = set(all_classes) estimators = [c for c in all_classes if (issubclass(c[1], BaseEstimator) and c[0] != 'BaseEstimator')] # get rid of abstract base classes estimators = [c for c in estimators if not is_abstract(c[1])] if not include_dont_test: estimators = [c for c in estimators if not c[0] in DONT_TEST] if not include_other: estimators = [c for c in estimators if not c[0] in OTHER] # possibly get rid of meta estimators if not include_meta_estimators: estimators = [c for c in estimators if not c[0] in META_ESTIMATORS] if type_filter is not None: if not isinstance(type_filter, list): type_filter = [type_filter] else: type_filter = list(type_filter) # copy filtered_estimators = [] filters = {'classifier': ClassifierMixin, 'regressor': RegressorMixin, 'transformer': TransformerMixin, 'cluster': ClusterMixin} for name, mixin in filters.items(): if name in type_filter: type_filter.remove(name) filtered_estimators.extend([est for est in estimators if issubclass(est[1], mixin)]) estimators = filtered_estimators if type_filter: raise ValueError("Parameter type_filter must be 'classifier', " "'regressor', 'transformer', 'cluster' or None, got" " %s." % repr(type_filter)) # drop duplicates, sort for reproducibility # itemgetter is used to ensure the sort does not extend to the 2nd item of # the tuple return sorted(set(estimators), key=itemgetter(0)) def set_random_state(estimator, random_state=0): """Set random state of an estimator if it has the `random_state` param. Classes for whom random_state is deprecated are ignored. Currently DBSCAN is one such class. """ if isinstance(estimator, DBSCAN): return if "random_state" in estimator.get_params(): estimator.set_params(random_state=random_state) def if_matplotlib(func): """Test decorator that skips test if matplotlib not installed. """ @wraps(func) def run_test(*args, **kwargs): try: import matplotlib matplotlib.use('Agg', warn=False) # this fails if no $DISPLAY specified import matplotlib.pyplot as plt plt.figure() except ImportError: raise SkipTest('Matplotlib not available.') else: return func(*args, **kwargs) return run_test def skip_if_32bit(func): """Test decorator that skips tests on 32bit platforms.""" @wraps(func) def run_test(*args, **kwargs): bits = 8 * struct.calcsize("P") if bits == 32: raise SkipTest('Test skipped on 32bit platforms.') else: return func(*args, **kwargs) return run_test def if_not_mac_os(versions=('10.7', '10.8', '10.9'), message='Multi-process bug in Mac OS X >= 10.7 ' '(see issue #636)'): """Test decorator that skips test if OS is Mac OS X and its major version is one of ``versions``. """ warnings.warn("if_not_mac_os is deprecated in 0.17 and will be removed" " in 0.19: use the safer and more generic" " if_safe_multiprocessing_with_blas instead", DeprecationWarning) mac_version, _, _ = platform.mac_ver() skip = '.'.join(mac_version.split('.')[:2]) in versions def decorator(func): if skip: @wraps(func) def func(*args, **kwargs): raise SkipTest(message) return func return decorator def if_safe_multiprocessing_with_blas(func): """Decorator for tests involving both BLAS calls and multiprocessing Under POSIX (e.g. Linux or OSX), using multiprocessing in conjunction with some implementation of BLAS (or other libraries that manage an internal posix thread pool) can cause a crash or a freeze of the Python process. In practice all known packaged distributions (from Linux distros or Anaconda) of BLAS under Linux seems to be safe. So we this problem seems to only impact OSX users. This wrapper makes it possible to skip tests that can possibly cause this crash under OS X with. Under Python 3.4+ it is possible to use the `forkserver` start method for multiprocessing to avoid this issue. However it can cause pickling errors on interactively defined functions. It therefore not enabled by default. """ @wraps(func) def run_test(*args, **kwargs): if sys.platform == 'darwin': raise SkipTest( "Possible multi-process bug with some BLAS") return func(*args, **kwargs) return run_test def clean_warning_registry(): """Safe way to reset warnings """ warnings.resetwarnings() reg = "__warningregistry__" for mod_name, mod in list(sys.modules.items()): if 'six.moves' in mod_name: continue if hasattr(mod, reg): getattr(mod, reg).clear() def check_skip_network(): if int(os.environ.get('SKLEARN_SKIP_NETWORK_TESTS', 0)): raise SkipTest("Text tutorial requires large dataset download") def check_skip_travis(): """Skip test if being run on Travis.""" if os.environ.get('TRAVIS') == "true": raise SkipTest("This test needs to be skipped on Travis") def _delete_folder(folder_path, warn=False): """Utility function to cleanup a temporary folder if still existing. Copy from joblib.pool (for independance)""" try: if os.path.exists(folder_path): # This can fail under windows, # but will succeed when called by atexit shutil.rmtree(folder_path) except WindowsError: if warn: warnings.warn("Could not delete temporary folder %s" % folder_path) class TempMemmap(object): def __init__(self, data, mmap_mode='r'): self.temp_folder = tempfile.mkdtemp(prefix='sklearn_testing_') self.mmap_mode = mmap_mode self.data = data def __enter__(self): fpath = op.join(self.temp_folder, 'data.pkl') joblib.dump(self.data, fpath) data_read_only = joblib.load(fpath, mmap_mode=self.mmap_mode) atexit.register(lambda: _delete_folder(self.temp_folder, warn=True)) return data_read_only def __exit__(self, exc_type, exc_val, exc_tb): _delete_folder(self.temp_folder) with_network = with_setup(check_skip_network) with_travis = with_setup(check_skip_travis)
bsd-3-clause
glouppe/scikit-learn
examples/covariance/plot_robust_vs_empirical_covariance.py
71
6451
r""" ======================================= Robust vs Empirical covariance estimate ======================================= The usual covariance maximum likelihood estimate is very sensitive to the presence of outliers in the data set. In such a case, it would be better to use a robust estimator of covariance to guarantee that the estimation is resistant to "erroneous" observations in the data set. Minimum Covariance Determinant Estimator ---------------------------------------- The Minimum Covariance Determinant estimator is a robust, high-breakdown point (i.e. it can be used to estimate the covariance matrix of highly contaminated datasets, up to :math:`\frac{n_\text{samples} - n_\text{features}-1}{2}` outliers) estimator of covariance. The idea is to find :math:`\frac{n_\text{samples} + n_\text{features}+1}{2}` observations whose empirical covariance has the smallest determinant, yielding a "pure" subset of observations from which to compute standards estimates of location and covariance. After a correction step aiming at compensating the fact that the estimates were learned from only a portion of the initial data, we end up with robust estimates of the data set location and covariance. The Minimum Covariance Determinant estimator (MCD) has been introduced by P.J.Rousseuw in [1]_. Evaluation ---------- In this example, we compare the estimation errors that are made when using various types of location and covariance estimates on contaminated Gaussian distributed data sets: - The mean and the empirical covariance of the full dataset, which break down as soon as there are outliers in the data set - The robust MCD, that has a low error provided :math:`n_\text{samples} > 5n_\text{features}` - The mean and the empirical covariance of the observations that are known to be good ones. This can be considered as a "perfect" MCD estimation, so one can trust our implementation by comparing to this case. References ---------- .. [1] P. J. Rousseeuw. Least median of squares regression. Journal of American Statistical Ass., 79:871, 1984. .. [2] Johanna Hardin, David M Rocke. The distribution of robust distances. Journal of Computational and Graphical Statistics. December 1, 2005, 14(4): 928-946. .. [3] Zoubir A., Koivunen V., Chakhchoukh Y. and Muma M. (2012). Robust estimation in signal processing: A tutorial-style treatment of fundamental concepts. IEEE Signal Processing Magazine 29(4), 61-80. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt import matplotlib.font_manager from sklearn.covariance import EmpiricalCovariance, MinCovDet # example settings n_samples = 80 n_features = 5 repeat = 10 range_n_outliers = np.concatenate( (np.linspace(0, n_samples / 8, 5), np.linspace(n_samples / 8, n_samples / 2, 5)[1:-1])) # definition of arrays to store results err_loc_mcd = np.zeros((range_n_outliers.size, repeat)) err_cov_mcd = np.zeros((range_n_outliers.size, repeat)) err_loc_emp_full = np.zeros((range_n_outliers.size, repeat)) err_cov_emp_full = np.zeros((range_n_outliers.size, repeat)) err_loc_emp_pure = np.zeros((range_n_outliers.size, repeat)) err_cov_emp_pure = np.zeros((range_n_outliers.size, repeat)) # computation for i, n_outliers in enumerate(range_n_outliers): for j in range(repeat): rng = np.random.RandomState(i * j) # generate data X = rng.randn(n_samples, n_features) # add some outliers outliers_index = rng.permutation(n_samples)[:n_outliers] outliers_offset = 10. * \ (np.random.randint(2, size=(n_outliers, n_features)) - 0.5) X[outliers_index] += outliers_offset inliers_mask = np.ones(n_samples).astype(bool) inliers_mask[outliers_index] = False # fit a Minimum Covariance Determinant (MCD) robust estimator to data mcd = MinCovDet().fit(X) # compare raw robust estimates with the true location and covariance err_loc_mcd[i, j] = np.sum(mcd.location_ ** 2) err_cov_mcd[i, j] = mcd.error_norm(np.eye(n_features)) # compare estimators learned from the full data set with true # parameters err_loc_emp_full[i, j] = np.sum(X.mean(0) ** 2) err_cov_emp_full[i, j] = EmpiricalCovariance().fit(X).error_norm( np.eye(n_features)) # compare with an empirical covariance learned from a pure data set # (i.e. "perfect" mcd) pure_X = X[inliers_mask] pure_location = pure_X.mean(0) pure_emp_cov = EmpiricalCovariance().fit(pure_X) err_loc_emp_pure[i, j] = np.sum(pure_location ** 2) err_cov_emp_pure[i, j] = pure_emp_cov.error_norm(np.eye(n_features)) # Display results font_prop = matplotlib.font_manager.FontProperties(size=11) plt.subplot(2, 1, 1) lw = 2 plt.errorbar(range_n_outliers, err_loc_mcd.mean(1), yerr=err_loc_mcd.std(1) / np.sqrt(repeat), label="Robust location", lw=lw, color='m') plt.errorbar(range_n_outliers, err_loc_emp_full.mean(1), yerr=err_loc_emp_full.std(1) / np.sqrt(repeat), label="Full data set mean", lw=lw, color='green') plt.errorbar(range_n_outliers, err_loc_emp_pure.mean(1), yerr=err_loc_emp_pure.std(1) / np.sqrt(repeat), label="Pure data set mean", lw=lw, color='black') plt.title("Influence of outliers on the location estimation") plt.ylabel(r"Error ($||\mu - \hat{\mu}||_2^2$)") plt.legend(loc="upper left", prop=font_prop) plt.subplot(2, 1, 2) x_size = range_n_outliers.size plt.errorbar(range_n_outliers, err_cov_mcd.mean(1), yerr=err_cov_mcd.std(1), label="Robust covariance (mcd)", color='m') plt.errorbar(range_n_outliers[:(x_size / 5 + 1)], err_cov_emp_full.mean(1)[:(x_size / 5 + 1)], yerr=err_cov_emp_full.std(1)[:(x_size / 5 + 1)], label="Full data set empirical covariance", color='green') plt.plot(range_n_outliers[(x_size / 5):(x_size / 2 - 1)], err_cov_emp_full.mean(1)[(x_size / 5):(x_size / 2 - 1)], color='green', ls='--') plt.errorbar(range_n_outliers, err_cov_emp_pure.mean(1), yerr=err_cov_emp_pure.std(1), label="Pure data set empirical covariance", color='black') plt.title("Influence of outliers on the covariance estimation") plt.xlabel("Amount of contamination (%)") plt.ylabel("RMSE") plt.legend(loc="upper center", prop=font_prop) plt.show()
bsd-3-clause
LohithBlaze/scikit-learn
sklearn/ensemble/__init__.py
216
1307
""" The :mod:`sklearn.ensemble` module includes ensemble-based methods for classification and regression. """ from .base import BaseEnsemble from .forest import RandomForestClassifier from .forest import RandomForestRegressor from .forest import RandomTreesEmbedding from .forest import ExtraTreesClassifier from .forest import ExtraTreesRegressor from .bagging import BaggingClassifier from .bagging import BaggingRegressor from .weight_boosting import AdaBoostClassifier from .weight_boosting import AdaBoostRegressor from .gradient_boosting import GradientBoostingClassifier from .gradient_boosting import GradientBoostingRegressor from .voting_classifier import VotingClassifier from . import bagging from . import forest from . import weight_boosting from . import gradient_boosting from . import partial_dependence __all__ = ["BaseEnsemble", "RandomForestClassifier", "RandomForestRegressor", "RandomTreesEmbedding", "ExtraTreesClassifier", "ExtraTreesRegressor", "BaggingClassifier", "BaggingRegressor", "GradientBoostingClassifier", "GradientBoostingRegressor", "AdaBoostClassifier", "AdaBoostRegressor", "VotingClassifier", "bagging", "forest", "gradient_boosting", "partial_dependence", "weight_boosting"]
bsd-3-clause
glouppe/scikit-learn
examples/model_selection/plot_validation_curve.py
135
1931
""" ========================== Plotting Validation Curves ========================== In this plot you can see the training scores and validation scores of an SVM for different values of the kernel parameter gamma. For very low values of gamma, you can see that both the training score and the validation score are low. This is called underfitting. Medium values of gamma will result in high values for both scores, i.e. the classifier is performing fairly well. If gamma is too high, the classifier will overfit, which means that the training score is good but the validation score is poor. """ print(__doc__) import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_digits from sklearn.svm import SVC from sklearn.model_selection import validation_curve digits = load_digits() X, y = digits.data, digits.target param_range = np.logspace(-6, -1, 5) train_scores, test_scores = validation_curve( SVC(), X, y, param_name="gamma", param_range=param_range, cv=10, scoring="accuracy", n_jobs=1) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.title("Validation Curve with SVM") plt.xlabel("$\gamma$") plt.ylabel("Score") plt.ylim(0.0, 1.1) lw = 2 plt.semilogx(param_range, train_scores_mean, label="Training score", color="darkorange", lw=lw) plt.fill_between(param_range, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.2, color="darkorange", lw=lw) plt.semilogx(param_range, test_scores_mean, label="Cross-validation score", color="navy", lw=lw) plt.fill_between(param_range, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.2, color="navy", lw=lw) plt.legend(loc="best") plt.show()
bsd-3-clause
luo66/scikit-learn
examples/neighbors/plot_digits_kde_sampling.py
250
2022
""" ========================= Kernel Density Estimation ========================= This example shows how kernel density estimation (KDE), a powerful non-parametric density estimation technique, can be used to learn a generative model for a dataset. With this generative model in place, new samples can be drawn. These new samples reflect the underlying model of the data. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.neighbors import KernelDensity from sklearn.decomposition import PCA from sklearn.grid_search import GridSearchCV # load the data digits = load_digits() data = digits.data # project the 64-dimensional data to a lower dimension pca = PCA(n_components=15, whiten=False) data = pca.fit_transform(digits.data) # use grid search cross-validation to optimize the bandwidth params = {'bandwidth': np.logspace(-1, 1, 20)} grid = GridSearchCV(KernelDensity(), params) grid.fit(data) print("best bandwidth: {0}".format(grid.best_estimator_.bandwidth)) # use the best estimator to compute the kernel density estimate kde = grid.best_estimator_ # sample 44 new points from the data new_data = kde.sample(44, random_state=0) new_data = pca.inverse_transform(new_data) # turn data into a 4x11 grid new_data = new_data.reshape((4, 11, -1)) real_data = digits.data[:44].reshape((4, 11, -1)) # plot real digits and resampled digits fig, ax = plt.subplots(9, 11, subplot_kw=dict(xticks=[], yticks=[])) for j in range(11): ax[4, j].set_visible(False) for i in range(4): im = ax[i, j].imshow(real_data[i, j].reshape((8, 8)), cmap=plt.cm.binary, interpolation='nearest') im.set_clim(0, 16) im = ax[i + 5, j].imshow(new_data[i, j].reshape((8, 8)), cmap=plt.cm.binary, interpolation='nearest') im.set_clim(0, 16) ax[0, 5].set_title('Selection from the input data') ax[5, 5].set_title('"New" digits drawn from the kernel density model') plt.show()
bsd-3-clause
fx2003/tensorflow-study
TensorFlow实战/models/attention_ocr/python/datasets/fsns_test.py
15
3374
# Copyright 2017 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for FSNS datasets module.""" import collections import os import tensorflow as tf from tensorflow.contrib import slim import fsns import unittest_utils FLAGS = tf.flags.FLAGS def get_test_split(): config = fsns.DEFAULT_CONFIG.copy() config['splits'] = {'test': {'size': 50, 'pattern': 'fsns-00000-of-00001'}} return fsns.get_split('test', dataset_dir(), config) def dataset_dir(): return os.path.join(os.path.dirname(__file__), 'testdata/fsns') class FsnsTest(tf.test.TestCase): def test_decodes_example_proto(self): expected_label = range(37) expected_image, encoded = unittest_utils.create_random_image( 'PNG', shape=(150, 600, 3)) serialized = unittest_utils.create_serialized_example({ 'image/encoded': [encoded], 'image/format': ['PNG'], 'image/class': expected_label, 'image/unpadded_class': range(10), 'image/text': ['Raw text'], 'image/orig_width': [150], 'image/width': [600] }) decoder = fsns.get_split('train', dataset_dir()).decoder with self.test_session() as sess: data_tuple = collections.namedtuple('DecodedData', decoder.list_items()) data = sess.run(data_tuple(*decoder.decode(serialized))) self.assertAllEqual(expected_image, data.image) self.assertAllEqual(expected_label, data.label) self.assertEqual(['Raw text'], data.text) self.assertEqual([1], data.num_of_views) def test_label_has_shape_defined(self): serialized = 'fake' decoder = fsns.get_split('train', dataset_dir()).decoder [label_tf] = decoder.decode(serialized, ['label']) self.assertEqual(label_tf.get_shape().dims[0], 37) def test_dataset_tuple_has_all_extra_attributes(self): dataset = fsns.get_split('train', dataset_dir()) self.assertTrue(dataset.charset) self.assertTrue(dataset.num_char_classes) self.assertTrue(dataset.num_of_views) self.assertTrue(dataset.max_sequence_length) self.assertTrue(dataset.null_code) def test_can_use_the_test_data(self): batch_size = 1 dataset = get_test_split() provider = slim.dataset_data_provider.DatasetDataProvider( dataset, shuffle=True, common_queue_capacity=2 * batch_size, common_queue_min=batch_size) image_tf, label_tf = provider.get(['image', 'label']) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) with slim.queues.QueueRunners(sess): image_np, label_np = sess.run([image_tf, label_tf]) self.assertEqual((150, 600, 3), image_np.shape) self.assertEqual((37, ), label_np.shape) if __name__ == '__main__': tf.test.main()
mit
automl/auto-sklearn
test/test_pipeline/components/feature_preprocessing/test_select_rates_classification.py
1
4623
import numpy as np import scipy.sparse import sklearn.preprocessing from autosklearn.pipeline.components.feature_preprocessing.select_rates_classification import ( # noqa: E501 SelectClassificationRates, ) from autosklearn.pipeline.util import _test_preprocessing, get_dataset import unittest class SelectClassificationRatesComponentTest(unittest.TestCase): def test_default_configuration(self): transformation, original = _test_preprocessing(SelectClassificationRates) self.assertEqual(transformation.shape[0], original.shape[0]) self.assertEqual(transformation.shape[1], 3) self.assertFalse((transformation == 0).all()) transformation, original = _test_preprocessing( SelectClassificationRates, make_sparse=True ) self.assertTrue(scipy.sparse.issparse(transformation)) self.assertEqual(transformation.shape[0], original.shape[0]) self.assertEqual(transformation.shape[1], int(original.shape[1] / 2)) # Custom preprocessing test to check if clipping to zero works X_train, Y_train, X_test, Y_test = get_dataset(dataset="digits") original_X_train = X_train.copy() ss = sklearn.preprocessing.StandardScaler() X_train = ss.fit_transform(X_train) configuration_space = ( SelectClassificationRates.get_hyperparameter_search_space() ) default = configuration_space.get_default_configuration() preprocessor = SelectClassificationRates( random_state=1, **{ hp_name: default[hp_name] for hp_name in default if default[hp_name] is not None }, ) transformer = preprocessor.fit(X_train, Y_train) transformation, original = transformer.transform(X_train), original_X_train self.assertEqual(transformation.shape[0], original.shape[0]) # I don't know why it's 52 here and not 32 which would be half of the # number of features. Seems to be related to a runtime warning raised # by sklearn self.assertEqual(transformation.shape[1], 52) def test_preprocessing_dtype(self): # Dense # np.float32 X_train, Y_train, X_test, Y_test = get_dataset("iris") self.assertEqual(X_train.dtype, np.float32) configuration_space = ( SelectClassificationRates.get_hyperparameter_search_space() ) default = configuration_space.get_default_configuration() preprocessor = SelectClassificationRates( random_state=1, **{hp_name: default[hp_name] for hp_name in default} ) preprocessor.fit(X_train, Y_train) Xt = preprocessor.transform(X_train) self.assertEqual(Xt.dtype, np.float32) # np.float64 X_train, Y_train, X_test, Y_test = get_dataset("iris") X_train = X_train.astype(np.float64) configuration_space = ( SelectClassificationRates.get_hyperparameter_search_space() ) default = configuration_space.get_default_configuration() preprocessor = SelectClassificationRates( random_state=1, **{hp_name: default[hp_name] for hp_name in default} ) preprocessor.fit(X_train, Y_train) Xt = preprocessor.transform(X_train) self.assertEqual(Xt.dtype, np.float64) # Sparse # np.float32 X_train, Y_train, X_test, Y_test = get_dataset("iris", make_sparse=True) self.assertEqual(X_train.dtype, np.float32) configuration_space = ( SelectClassificationRates.get_hyperparameter_search_space() ) default = configuration_space.get_default_configuration() preprocessor = SelectClassificationRates( random_state=1, **{hp_name: default[hp_name] for hp_name in default} ) preprocessor.fit(X_train, Y_train) Xt = preprocessor.transform(X_train) self.assertEqual(Xt.dtype, np.float32) # np.float64 X_train, Y_train, X_test, Y_test = get_dataset("iris", make_sparse=True) X_train = X_train.astype(np.float64) configuration_space = ( SelectClassificationRates.get_hyperparameter_search_space() ) default = configuration_space.get_default_configuration() preprocessor = SelectClassificationRates( random_state=1, **{hp_name: default[hp_name] for hp_name in default} ) preprocessor.fit(X_train, Y_train) Xt = preprocessor.transform(X_train) self.assertEqual(Xt.dtype, np.float64)
bsd-3-clause
sgenoud/scikit-learn
benchmarks/bench_lasso.py
6
3368
""" Benchmarks of Lasso vs LassoLars First, we fix a training set and increase the number of samples. Then we plot the computation time as function of the number of samples. In the second benchmark, we increase the number of dimensions of the training set. Then we plot the computation time as function of the number of dimensions. In both cases, only 10% of the features are informative. """ import gc from time import time import numpy as np from sklearn.datasets.samples_generator import make_regression def compute_bench(alpha, n_samples, n_features, precompute): lasso_results = [] lars_lasso_results = [] n_test_samples = 0 it = 0 for ns in n_samples: for nf in n_features: it += 1 print '==================' print 'Iteration %s of %s' % (it, max(len(n_samples), len(n_features))) print '==================' n_informative = nf // 10 X, Y, coef_ = make_regression(n_samples=ns, n_features=nf, n_informative=n_informative, noise=0.1, coef=True) X /= np.sqrt(np.sum(X ** 2, axis=0)) # Normalize data gc.collect() print "- benching Lasso" clf = Lasso(alpha=alpha, fit_intercept=False, precompute=precompute) tstart = time() clf.fit(X, Y) lasso_results.append(time() - tstart) gc.collect() print "- benching LassoLars" clf = LassoLars(alpha=alpha, fit_intercept=False, normalize=False, precompute=precompute) tstart = time() clf.fit(X, Y) lars_lasso_results.append(time() - tstart) return lasso_results, lars_lasso_results if __name__ == '__main__': from sklearn.linear_model import Lasso, LassoLars import pylab as pl alpha = 0.01 # regularization parameter n_features = 10 list_n_samples = np.linspace(100, 1000000, 5).astype(np.int) lasso_results, lars_lasso_results = compute_bench(alpha, list_n_samples, [n_features], precompute=True) pl.clf() pl.subplot(211) pl.plot(list_n_samples, lasso_results, 'b-', label='Lasso (with precomputed Gram matrix)') pl.plot(list_n_samples, lars_lasso_results, 'r-', label='LassoLars (with precomputed Gram matrix)') pl.title('Lasso benchmark (%d features - alpha=%s)' % (n_features, alpha)) pl.legend(loc='upper left') pl.xlabel('number of samples') pl.ylabel('time (in seconds)') pl.axis('tight') n_samples = 2000 list_n_features = np.linspace(500, 3000, 5).astype(np.int) lasso_results, lars_lasso_results = compute_bench(alpha, [n_samples], list_n_features, precompute=False) pl.subplot(212) pl.plot(list_n_features, lasso_results, 'b-', label='Lasso') pl.plot(list_n_features, lars_lasso_results, 'r-', label='LassoLars') pl.title('Lasso benchmark (%d samples - alpha=%s)' % (n_samples, alpha)) pl.legend(loc='upper left') pl.xlabel('number of features') pl.ylabel('time (in seconds)') pl.axis('tight') pl.show()
bsd-3-clause
MohammedWasim/scikit-learn
sklearn/tests/test_naive_bayes.py
70
17509
import pickle from io import BytesIO import numpy as np import scipy.sparse from sklearn.datasets import load_digits, load_iris from sklearn.cross_validation import cross_val_score, train_test_split from sklearn.externals.six.moves import zip from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_greater from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB # Data is just 6 separable points in the plane X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) y = np.array([1, 1, 1, 2, 2, 2]) # A bit more random tests rng = np.random.RandomState(0) X1 = rng.normal(size=(10, 3)) y1 = (rng.normal(size=(10)) > 0).astype(np.int) # Data is 6 random integer points in a 100 dimensional space classified to # three classes. X2 = rng.randint(5, size=(6, 100)) y2 = np.array([1, 1, 2, 2, 3, 3]) def test_gnb(): # Gaussian Naive Bayes classification. # This checks that GaussianNB implements fit and predict and returns # correct values for a simple toy dataset. clf = GaussianNB() y_pred = clf.fit(X, y).predict(X) assert_array_equal(y_pred, y) y_pred_proba = clf.predict_proba(X) y_pred_log_proba = clf.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8) # Test whether label mismatch between target y and classes raises # an Error # FIXME Remove this test once the more general partial_fit tests are merged assert_raises(ValueError, GaussianNB().partial_fit, X, y, classes=[0, 1]) def test_gnb_prior(): # Test whether class priors are properly set. clf = GaussianNB().fit(X, y) assert_array_almost_equal(np.array([3, 3]) / 6.0, clf.class_prior_, 8) clf.fit(X1, y1) # Check that the class priors sum to 1 assert_array_almost_equal(clf.class_prior_.sum(), 1) def test_gnb_sample_weight(): """Test whether sample weights are properly used in GNB. """ # Sample weights all being 1 should not change results sw = np.ones(6) clf = GaussianNB().fit(X, y) clf_sw = GaussianNB().fit(X, y, sw) assert_array_almost_equal(clf.theta_, clf_sw.theta_) assert_array_almost_equal(clf.sigma_, clf_sw.sigma_) # Fitting twice with half sample-weights should result # in same result as fitting once with full weights sw = rng.rand(y.shape[0]) clf1 = GaussianNB().fit(X, y, sample_weight=sw) clf2 = GaussianNB().partial_fit(X, y, classes=[1, 2], sample_weight=sw / 2) clf2.partial_fit(X, y, sample_weight=sw / 2) assert_array_almost_equal(clf1.theta_, clf2.theta_) assert_array_almost_equal(clf1.sigma_, clf2.sigma_) # Check that duplicate entries and correspondingly increased sample # weights yield the same result ind = rng.randint(0, X.shape[0], 20) sample_weight = np.bincount(ind, minlength=X.shape[0]) clf_dupl = GaussianNB().fit(X[ind], y[ind]) clf_sw = GaussianNB().fit(X, y, sample_weight) assert_array_almost_equal(clf_dupl.theta_, clf_sw.theta_) assert_array_almost_equal(clf_dupl.sigma_, clf_sw.sigma_) def test_discrete_prior(): # Test whether class priors are properly set. for cls in [BernoulliNB, MultinomialNB]: clf = cls().fit(X2, y2) assert_array_almost_equal(np.log(np.array([2, 2, 2]) / 6.0), clf.class_log_prior_, 8) def test_mnnb(): # Test Multinomial Naive Bayes classification. # This checks that MultinomialNB implements fit and predict and returns # correct values for a simple toy dataset. for X in [X2, scipy.sparse.csr_matrix(X2)]: # Check the ability to predict the learning set. clf = MultinomialNB() assert_raises(ValueError, clf.fit, -X, y2) y_pred = clf.fit(X, y2).predict(X) assert_array_equal(y_pred, y2) # Verify that np.log(clf.predict_proba(X)) gives the same results as # clf.predict_log_proba(X) y_pred_proba = clf.predict_proba(X) y_pred_log_proba = clf.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8) # Check that incremental fitting yields the same results clf2 = MultinomialNB() clf2.partial_fit(X[:2], y2[:2], classes=np.unique(y2)) clf2.partial_fit(X[2:5], y2[2:5]) clf2.partial_fit(X[5:], y2[5:]) y_pred2 = clf2.predict(X) assert_array_equal(y_pred2, y2) y_pred_proba2 = clf2.predict_proba(X) y_pred_log_proba2 = clf2.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba2), y_pred_log_proba2, 8) assert_array_almost_equal(y_pred_proba2, y_pred_proba) assert_array_almost_equal(y_pred_log_proba2, y_pred_log_proba) # Partial fit on the whole data at once should be the same as fit too clf3 = MultinomialNB() clf3.partial_fit(X, y2, classes=np.unique(y2)) y_pred3 = clf3.predict(X) assert_array_equal(y_pred3, y2) y_pred_proba3 = clf3.predict_proba(X) y_pred_log_proba3 = clf3.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba3), y_pred_log_proba3, 8) assert_array_almost_equal(y_pred_proba3, y_pred_proba) assert_array_almost_equal(y_pred_log_proba3, y_pred_log_proba) def check_partial_fit(cls): clf1 = cls() clf1.fit([[0, 1], [1, 0]], [0, 1]) clf2 = cls() clf2.partial_fit([[0, 1], [1, 0]], [0, 1], classes=[0, 1]) assert_array_equal(clf1.class_count_, clf2.class_count_) assert_array_equal(clf1.feature_count_, clf2.feature_count_) clf3 = cls() clf3.partial_fit([[0, 1]], [0], classes=[0, 1]) clf3.partial_fit([[1, 0]], [1]) assert_array_equal(clf1.class_count_, clf3.class_count_) assert_array_equal(clf1.feature_count_, clf3.feature_count_) def test_discretenb_partial_fit(): for cls in [MultinomialNB, BernoulliNB]: yield check_partial_fit, cls def test_gnb_partial_fit(): clf = GaussianNB().fit(X, y) clf_pf = GaussianNB().partial_fit(X, y, np.unique(y)) assert_array_almost_equal(clf.theta_, clf_pf.theta_) assert_array_almost_equal(clf.sigma_, clf_pf.sigma_) assert_array_almost_equal(clf.class_prior_, clf_pf.class_prior_) clf_pf2 = GaussianNB().partial_fit(X[0::2, :], y[0::2], np.unique(y)) clf_pf2.partial_fit(X[1::2], y[1::2]) assert_array_almost_equal(clf.theta_, clf_pf2.theta_) assert_array_almost_equal(clf.sigma_, clf_pf2.sigma_) assert_array_almost_equal(clf.class_prior_, clf_pf2.class_prior_) def test_discretenb_pickle(): # Test picklability of discrete naive Bayes classifiers for cls in [BernoulliNB, MultinomialNB, GaussianNB]: clf = cls().fit(X2, y2) y_pred = clf.predict(X2) store = BytesIO() pickle.dump(clf, store) clf = pickle.load(BytesIO(store.getvalue())) assert_array_equal(y_pred, clf.predict(X2)) if cls is not GaussianNB: # TODO re-enable me when partial_fit is implemented for GaussianNB # Test pickling of estimator trained with partial_fit clf2 = cls().partial_fit(X2[:3], y2[:3], classes=np.unique(y2)) clf2.partial_fit(X2[3:], y2[3:]) store = BytesIO() pickle.dump(clf2, store) clf2 = pickle.load(BytesIO(store.getvalue())) assert_array_equal(y_pred, clf2.predict(X2)) def test_input_check_fit(): # Test input checks for the fit method for cls in [BernoulliNB, MultinomialNB, GaussianNB]: # check shape consistency for number of samples at fit time assert_raises(ValueError, cls().fit, X2, y2[:-1]) # check shape consistency for number of input features at predict time clf = cls().fit(X2, y2) assert_raises(ValueError, clf.predict, X2[:, :-1]) def test_input_check_partial_fit(): for cls in [BernoulliNB, MultinomialNB]: # check shape consistency assert_raises(ValueError, cls().partial_fit, X2, y2[:-1], classes=np.unique(y2)) # classes is required for first call to partial fit assert_raises(ValueError, cls().partial_fit, X2, y2) # check consistency of consecutive classes values clf = cls() clf.partial_fit(X2, y2, classes=np.unique(y2)) assert_raises(ValueError, clf.partial_fit, X2, y2, classes=np.arange(42)) # check consistency of input shape for partial_fit assert_raises(ValueError, clf.partial_fit, X2[:, :-1], y2) # check consistency of input shape for predict assert_raises(ValueError, clf.predict, X2[:, :-1]) def test_discretenb_predict_proba(): # Test discrete NB classes' probability scores # The 100s below distinguish Bernoulli from multinomial. # FIXME: write a test to show this. X_bernoulli = [[1, 100, 0], [0, 1, 0], [0, 100, 1]] X_multinomial = [[0, 1], [1, 3], [4, 0]] # test binary case (1-d output) y = [0, 0, 2] # 2 is regression test for binary case, 02e673 for cls, X in zip([BernoulliNB, MultinomialNB], [X_bernoulli, X_multinomial]): clf = cls().fit(X, y) assert_equal(clf.predict(X[-1:]), 2) assert_equal(clf.predict_proba([X[0]]).shape, (1, 2)) assert_array_almost_equal(clf.predict_proba(X[:2]).sum(axis=1), np.array([1., 1.]), 6) # test multiclass case (2-d output, must sum to one) y = [0, 1, 2] for cls, X in zip([BernoulliNB, MultinomialNB], [X_bernoulli, X_multinomial]): clf = cls().fit(X, y) assert_equal(clf.predict_proba(X[0:1]).shape, (1, 3)) assert_equal(clf.predict_proba(X[:2]).shape, (2, 3)) assert_almost_equal(np.sum(clf.predict_proba([X[1]])), 1) assert_almost_equal(np.sum(clf.predict_proba([X[-1]])), 1) assert_almost_equal(np.sum(np.exp(clf.class_log_prior_)), 1) assert_almost_equal(np.sum(np.exp(clf.intercept_)), 1) def test_discretenb_uniform_prior(): # Test whether discrete NB classes fit a uniform prior # when fit_prior=False and class_prior=None for cls in [BernoulliNB, MultinomialNB]: clf = cls() clf.set_params(fit_prior=False) clf.fit([[0], [0], [1]], [0, 0, 1]) prior = np.exp(clf.class_log_prior_) assert_array_equal(prior, np.array([.5, .5])) def test_discretenb_provide_prior(): # Test whether discrete NB classes use provided prior for cls in [BernoulliNB, MultinomialNB]: clf = cls(class_prior=[0.5, 0.5]) clf.fit([[0], [0], [1]], [0, 0, 1]) prior = np.exp(clf.class_log_prior_) assert_array_equal(prior, np.array([.5, .5])) # Inconsistent number of classes with prior assert_raises(ValueError, clf.fit, [[0], [1], [2]], [0, 1, 2]) assert_raises(ValueError, clf.partial_fit, [[0], [1]], [0, 1], classes=[0, 1, 1]) def test_discretenb_provide_prior_with_partial_fit(): # Test whether discrete NB classes use provided prior # when using partial_fit iris = load_iris() iris_data1, iris_data2, iris_target1, iris_target2 = train_test_split( iris.data, iris.target, test_size=0.4, random_state=415) for cls in [BernoulliNB, MultinomialNB]: for prior in [None, [0.3, 0.3, 0.4]]: clf_full = cls(class_prior=prior) clf_full.fit(iris.data, iris.target) clf_partial = cls(class_prior=prior) clf_partial.partial_fit(iris_data1, iris_target1, classes=[0, 1, 2]) clf_partial.partial_fit(iris_data2, iris_target2) assert_array_almost_equal(clf_full.class_log_prior_, clf_partial.class_log_prior_) def test_sample_weight_multiclass(): for cls in [BernoulliNB, MultinomialNB]: # check shape consistency for number of samples at fit time yield check_sample_weight_multiclass, cls def check_sample_weight_multiclass(cls): X = [ [0, 0, 1], [0, 1, 1], [0, 1, 1], [1, 0, 0], ] y = [0, 0, 1, 2] sample_weight = np.array([1, 1, 2, 2], dtype=np.float) sample_weight /= sample_weight.sum() clf = cls().fit(X, y, sample_weight=sample_weight) assert_array_equal(clf.predict(X), [0, 1, 1, 2]) # Check sample weight using the partial_fit method clf = cls() clf.partial_fit(X[:2], y[:2], classes=[0, 1, 2], sample_weight=sample_weight[:2]) clf.partial_fit(X[2:3], y[2:3], sample_weight=sample_weight[2:3]) clf.partial_fit(X[3:], y[3:], sample_weight=sample_weight[3:]) assert_array_equal(clf.predict(X), [0, 1, 1, 2]) def test_sample_weight_mnb(): clf = MultinomialNB() clf.fit([[1, 2], [1, 2], [1, 0]], [0, 0, 1], sample_weight=[1, 1, 4]) assert_array_equal(clf.predict([[1, 0]]), [1]) positive_prior = np.exp(clf.intercept_[0]) assert_array_almost_equal([1 - positive_prior, positive_prior], [1 / 3., 2 / 3.]) def test_coef_intercept_shape(): # coef_ and intercept_ should have shapes as in other linear models. # Non-regression test for issue #2127. X = [[1, 0, 0], [1, 1, 1]] y = [1, 2] # binary classification for clf in [MultinomialNB(), BernoulliNB()]: clf.fit(X, y) assert_equal(clf.coef_.shape, (1, 3)) assert_equal(clf.intercept_.shape, (1,)) def test_check_accuracy_on_digits(): # Non regression test to make sure that any further refactoring / optim # of the NB models do not harm the performance on a slightly non-linearly # separable dataset digits = load_digits() X, y = digits.data, digits.target binary_3v8 = np.logical_or(digits.target == 3, digits.target == 8) X_3v8, y_3v8 = X[binary_3v8], y[binary_3v8] # Multinomial NB scores = cross_val_score(MultinomialNB(alpha=10), X, y, cv=10) assert_greater(scores.mean(), 0.86) scores = cross_val_score(MultinomialNB(alpha=10), X_3v8, y_3v8, cv=10) assert_greater(scores.mean(), 0.94) # Bernoulli NB scores = cross_val_score(BernoulliNB(alpha=10), X > 4, y, cv=10) assert_greater(scores.mean(), 0.83) scores = cross_val_score(BernoulliNB(alpha=10), X_3v8 > 4, y_3v8, cv=10) assert_greater(scores.mean(), 0.92) # Gaussian NB scores = cross_val_score(GaussianNB(), X, y, cv=10) assert_greater(scores.mean(), 0.77) scores = cross_val_score(GaussianNB(), X_3v8, y_3v8, cv=10) assert_greater(scores.mean(), 0.86) def test_feature_log_prob_bnb(): # Test for issue #4268. # Tests that the feature log prob value computed by BernoulliNB when # alpha=1.0 is equal to the expression given in Manning, Raghavan, # and Schuetze's "Introduction to Information Retrieval" book: # http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html X = np.array([[0, 0, 0], [1, 1, 0], [0, 1, 0], [1, 0, 1], [0, 1, 0]]) Y = np.array([0, 0, 1, 2, 2]) # Fit Bernoulli NB w/ alpha = 1.0 clf = BernoulliNB(alpha=1.0) clf.fit(X, Y) # Manually form the (log) numerator and denominator that # constitute P(feature presence | class) num = np.log(clf.feature_count_ + 1.0) denom = np.tile(np.log(clf.class_count_ + 2.0), (X.shape[1], 1)).T # Check manual estimate matches assert_array_equal(clf.feature_log_prob_, (num - denom)) def test_bnb(): # Tests that BernoulliNB when alpha=1.0 gives the same values as # those given for the toy example in Manning, Raghavan, and # Schuetze's "Introduction to Information Retrieval" book: # http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html # Training data points are: # Chinese Beijing Chinese (class: China) # Chinese Chinese Shanghai (class: China) # Chinese Macao (class: China) # Tokyo Japan Chinese (class: Japan) # Features are Beijing, Chinese, Japan, Macao, Shanghai, and Tokyo X = np.array([[1, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1]]) # Classes are China (0), Japan (1) Y = np.array([0, 0, 0, 1]) # Fit BernoulliBN w/ alpha = 1.0 clf = BernoulliNB(alpha=1.0) clf.fit(X, Y) # Check the class prior is correct class_prior = np.array([0.75, 0.25]) assert_array_almost_equal(np.exp(clf.class_log_prior_), class_prior) # Check the feature probabilities are correct feature_prob = np.array([[0.4, 0.8, 0.2, 0.4, 0.4, 0.2], [1/3.0, 2/3.0, 2/3.0, 1/3.0, 1/3.0, 2/3.0]]) assert_array_almost_equal(np.exp(clf.feature_log_prob_), feature_prob) # Testing data point is: # Chinese Chinese Chinese Tokyo Japan X_test = np.array([[0, 1, 1, 0, 0, 1]]) # Check the predictive probabilities are correct unnorm_predict_proba = np.array([[0.005183999999999999, 0.02194787379972565]]) predict_proba = unnorm_predict_proba / np.sum(unnorm_predict_proba) assert_array_almost_equal(clf.predict_proba(X_test), predict_proba)
bsd-3-clause
sgenoud/scikit-learn
sklearn/feature_selection/tests/test_rfe.py
1
1626
""" Testing Recursive feature elimination """ import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_true from sklearn.feature_selection.rfe import RFE, RFECV from sklearn.datasets import load_iris from sklearn.metrics import zero_one from sklearn.svm import SVC from sklearn.utils import check_random_state def test_rfe(): generator = check_random_state(0) iris = load_iris() X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] y = iris.target clf = SVC(kernel="linear") rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1) rfe.fit(X, y) X_r = rfe.transform(X) assert_true(X_r.shape == iris.data.shape) assert_array_almost_equal(X_r[:10], iris.data[:10]) assert_array_almost_equal(rfe.predict(X), clf.predict(iris.data)) assert_true(rfe.score(X, y) == clf.score(iris.data, iris.target)) def test_rfecv(): generator = check_random_state(0) iris = load_iris() X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] y = iris.target # Test using the score function rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=3) rfecv.fit(X, y) X_r = rfecv.transform(X) assert_true(X_r.shape == iris.data.shape) assert_array_almost_equal(X_r[:10], iris.data[:10]) # Test using a customized loss function rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=3, loss_func=zero_one) rfecv.fit(X, y) X_r = rfecv.transform(X) assert_true(X_r.shape == iris.data.shape) assert_array_almost_equal(X_r[:10], iris.data[:10])
bsd-3-clause
manipopopo/tensorflow
tensorflow/contrib/learn/python/learn/datasets/base_test.py
132
3072
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.python.platform import test mock = test.mock _TIMEOUT = IOError(110, "timeout") class BaseTest(test.TestCase): """Test load csv functions.""" def testUrlretrieveRetriesOnIOError(self): with mock.patch.object(base, "time") as mock_time: with mock.patch.object(base, "urllib") as mock_urllib: mock_urllib.request.urlretrieve.side_effect = [ _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, None ] base.urlretrieve_with_retry("http://dummy.com", "/tmp/dummy") # Assert full backoff was tried actual_list = [arg[0][0] for arg in mock_time.sleep.call_args_list] expected_list = [1, 2, 4, 8, 16] for actual, expected in zip(actual_list, expected_list): self.assertLessEqual(abs(actual - expected), 0.25 * expected) self.assertEquals(len(actual_list), len(expected_list)) def testUrlretrieveRaisesAfterRetriesAreExhausted(self): with mock.patch.object(base, "time") as mock_time: with mock.patch.object(base, "urllib") as mock_urllib: mock_urllib.request.urlretrieve.side_effect = [ _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, ] with self.assertRaises(IOError): base.urlretrieve_with_retry("http://dummy.com", "/tmp/dummy") # Assert full backoff was tried actual_list = [arg[0][0] for arg in mock_time.sleep.call_args_list] expected_list = [1, 2, 4, 8, 16] for actual, expected in zip(actual_list, expected_list): self.assertLessEqual(abs(actual - expected), 0.25 * expected) self.assertEquals(len(actual_list), len(expected_list)) def testUrlretrieveRaisesOnNonRetriableErrorWithoutRetry(self): with mock.patch.object(base, "time") as mock_time: with mock.patch.object(base, "urllib") as mock_urllib: mock_urllib.request.urlretrieve.side_effect = [ IOError(2, "No such file or directory"), ] with self.assertRaises(IOError): base.urlretrieve_with_retry("http://dummy.com", "/tmp/dummy") # Assert no retries self.assertFalse(mock_time.called) if __name__ == "__main__": test.main()
apache-2.0
lukeiwanski/tensorflow
tensorflow/contrib/learn/python/learn/datasets/base_test.py
132
3072
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.python.platform import test mock = test.mock _TIMEOUT = IOError(110, "timeout") class BaseTest(test.TestCase): """Test load csv functions.""" def testUrlretrieveRetriesOnIOError(self): with mock.patch.object(base, "time") as mock_time: with mock.patch.object(base, "urllib") as mock_urllib: mock_urllib.request.urlretrieve.side_effect = [ _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, None ] base.urlretrieve_with_retry("http://dummy.com", "/tmp/dummy") # Assert full backoff was tried actual_list = [arg[0][0] for arg in mock_time.sleep.call_args_list] expected_list = [1, 2, 4, 8, 16] for actual, expected in zip(actual_list, expected_list): self.assertLessEqual(abs(actual - expected), 0.25 * expected) self.assertEquals(len(actual_list), len(expected_list)) def testUrlretrieveRaisesAfterRetriesAreExhausted(self): with mock.patch.object(base, "time") as mock_time: with mock.patch.object(base, "urllib") as mock_urllib: mock_urllib.request.urlretrieve.side_effect = [ _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, _TIMEOUT, ] with self.assertRaises(IOError): base.urlretrieve_with_retry("http://dummy.com", "/tmp/dummy") # Assert full backoff was tried actual_list = [arg[0][0] for arg in mock_time.sleep.call_args_list] expected_list = [1, 2, 4, 8, 16] for actual, expected in zip(actual_list, expected_list): self.assertLessEqual(abs(actual - expected), 0.25 * expected) self.assertEquals(len(actual_list), len(expected_list)) def testUrlretrieveRaisesOnNonRetriableErrorWithoutRetry(self): with mock.patch.object(base, "time") as mock_time: with mock.patch.object(base, "urllib") as mock_urllib: mock_urllib.request.urlretrieve.side_effect = [ IOError(2, "No such file or directory"), ] with self.assertRaises(IOError): base.urlretrieve_with_retry("http://dummy.com", "/tmp/dummy") # Assert no retries self.assertFalse(mock_time.called) if __name__ == "__main__": test.main()
apache-2.0
CCI-Tools/cate-core
cate/ops/correlation.py
1
14291
# The MIT License (MIT) # Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ Description =========== Correlation operations Functions ========= """ import numpy as np import pandas as pd import xarray as xr # If CTRL-C is pressed on console on Windows, we get # forrtl: error (200): program aborting due to control-C event # Setting FOR_DISABLE_CONSOLE_CTRL_HANDLER=1 should actually avoid this, # see https://stackoverflow.com/questions/15457786/ctrl-c-crashes-python-after-importing-scipy-stats # import os # os.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = '1' # Unfortunately, if the above is uncommented cate-webapi doesn't handle CTRL-C anymore even though # a SIGINT handler is registered. from scipy.stats import pearsonr from scipy.special import betainc from cate.core.op import op, op_input, op_return from cate.core.types import VarName, DatasetLike, ValidationError from cate.util.monitor import Monitor from cate.ops.normalize import adjust_spatial_attrs @op(tags=['utility', 'correlation']) @op_input('ds_x', data_type=DatasetLike) @op_input('ds_y', data_type=DatasetLike) @op_input('var_x', value_set_source='ds_x', data_type=VarName) @op_input('var_y', value_set_source='ds_y', data_type=VarName) def pearson_correlation_scalar(ds_x: DatasetLike.TYPE, ds_y: DatasetLike.TYPE, var_x: VarName.TYPE, var_y: VarName.TYPE, monitor: Monitor = Monitor.NONE) -> pd.DataFrame: """ Do product moment `Pearson's correlation <http://www.statsoft.com/Textbook/Statistics-Glossary/P/button/p#Pearson%20Correlation>`_ analysis. Performs a simple correlation analysis on two data variables and returns a correlation coefficient and the corresponding p_value. Positive correlation implies that as x grows, so does y. Negative correlation implies that as x increases, y decreases. For more information how to interpret the results, see `here <http://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/how-to/correlation/interpret-the-results/>`_, and `here <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.pearsonr.html>`_. :param ds_x: The 'x' dataset :param ds_y: The 'y' dataset :param var_x: Dataset variable to use for correlation analysis in the 'variable' dataset :param var_y: Dataset variable to use for correlation analysis in the 'dependent' dataset :param monitor: a progress monitor. :return: Data frame {'corr_coef': correlation coefficient, 'p_value': probability value} """ ds_x = DatasetLike.convert(ds_x) ds_y = DatasetLike.convert(ds_y) var_x = VarName.convert(var_x) var_y = VarName.convert(var_y) array_y = ds_y[var_y] array_x = ds_x[var_x] if (array_x.dims != array_y.dims): raise ValidationError('Both datasets should feature the same' ' dimensionality. Currently provided ds_x[var_x] ' f'has {array_x.dims}, provided ds_y[var_y]' f' has {array_y.dims}') for dim in array_x.dims: if len(array_x[dim]) != len(array_y[dim]): raise ValidationError('All dimensions of both provided data variables' f' must be the same length. Currently {dim} of ds_x[var_x]' f' has {len(array_x[dim])} values, while' f' {dim} of ds_y[var_y] has {len(array_y[dim])} values.' ' You may want to try to coregister the datasets beforehand.') n_vals = 1 for dim in array_x.dims: n_vals = n_vals * len(array_x[dim]) if n_vals < 3: raise ValidationError('There should be no less than 3 values in both data variables' f' to perform the correlation. Currently there are {n_vals} values') with monitor.observing("Calculate Pearson correlation"): cc, pv = pearsonr(array_x.stack(z=array_x.dims), array_y.stack(z=array_y.dims)) return pd.DataFrame({'corr_coef': [cc], 'p_value': [pv]}) @op(tags=['utility', 'correlation'], version='1.0') @op_input('ds_x', data_type=DatasetLike) @op_input('ds_y', data_type=DatasetLike) @op_input('var_x', value_set_source='ds_x', data_type=VarName) @op_input('var_y', value_set_source='ds_y', data_type=VarName) @op_return(add_history=True) def pearson_correlation(ds_x: DatasetLike.TYPE, ds_y: DatasetLike.TYPE, var_x: VarName.TYPE, var_y: VarName.TYPE, monitor: Monitor = Monitor.NONE) -> xr.Dataset: """ Do product moment `Pearson's correlation <http://www.statsoft.com/Textbook/Statistics-Glossary/P/button/p#Pearson%20Correlation>`_ analysis. Perform Pearson correlation on two datasets and produce a lon/lat map of correlation coefficients and the correspoding p_values. In case two 3D lon/lat/time datasets are provided, pixel by pixel correlation will be performed. It is also possible two pro Perform Pearson correlation analysis on two time/lat/lon datasets and produce a lat/lon map of correlation coefficients and p_values of underlying timeseries in the provided datasets. The lat/lon definition of both datasets has to be the same. The length of the time dimension should be equal, but not neccessarily have the same definition. E.g., it is possible to correlate different times of the same area. There are 'x' and 'y' datasets. Positive correlations imply that as x grows, so does y. Negative correlations imply that as x increases, y decreases. For more information how to interpret the results, see `here <http://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/how-to/correlation/interpret-the-results/>`_, and `here <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.pearsonr.html>`_. :param ds_x: The 'x' dataset :param ds_y: The 'y' dataset :param var_x: Dataset variable to use for correlation analysis in the 'variable' dataset :param var_y: Dataset variable to use for correlation analysis in the 'dependent' dataset :param monitor: a progress monitor. :return: a dataset containing a map of correlation coefficients and p_values """ ds_x = DatasetLike.convert(ds_x) ds_y = DatasetLike.convert(ds_y) var_x = VarName.convert(var_x) var_y = VarName.convert(var_y) array_y = ds_y[var_y] array_x = ds_x[var_x] # Further validate inputs if array_x.dims == array_y.dims: if len(array_x.dims) != 3 or len(array_y.dims) != 3: raise ValidationError('A correlation coefficient map can only be produced' ' if both provided datasets are 3D datasets with' ' lon/lat/time dimensionality, or if a combination' ' of a 3D lon/lat/time dataset and a 1D timeseries' ' is provided.') if array_x.values.shape != array_y.values.shape: raise ValidationError(f'The provided variables {var_x} and {var_y} do not have the' ' same shape, Pearson correlation can not be' ' performed. Please review operation' ' documentation') if (not ds_x['lat'].equals(ds_y['lat']) or not ds_x['lon'].equals(ds_y['lon'])): raise ValidationError('When performing a pixel by pixel correlation the' ' datasets have to have the same lat/lon' ' definition. Consider running coregistration' ' first') elif (((len(array_x.dims) == 3) and (len(array_y.dims) != 1)) or ((len(array_x.dims) == 1) and (len(array_y.dims) != 3)) or ((len(array_x.dims) != 3) and (len(array_y.dims) == 1)) or ((len(array_x.dims) != 1) and (len(array_y.dims) == 3))): raise ValidationError('A correlation coefficient map can only be produced' ' if both provided datasets are 3D datasets with' ' lon/lat/time dimensionality, or if a combination' ' of a 3D lon/lat/time dataset and a 1D timeseries' ' is provided.') if len(array_x['time']) != len(array_y['time']): raise ValidationError('The length of the time dimension differs between' ' the given datasets. Can not perform the calculation' ', please review operation documentation.') if len(array_x['time']) < 3: raise ValidationError('The length of the time dimension should not be less' ' than three to run the calculation.') # Do pixel by pixel correlation retset = _pearsonr(array_x, array_y, monitor) retset.attrs['Cate_Description'] = f'Correlation between {var_y} {var_x}' return adjust_spatial_attrs(retset) def _pearsonr(x: xr.DataArray, y: xr.DataArray, monitor: Monitor) -> xr.Dataset: """ Calculate Pearson correlation coefficients and p-values for testing non-correlation of lon/lat/time xarray datasets for each lon/lat point. Heavily influenced by scipy.stats.pearsonr The Pearson correlation coefficient measures the linear relationship between two datasets. Strictly speaking, Pearson's correlation requires that each dataset be normally distributed, and not necessarily zero-mean. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. :param x: lon/lat/time xr.DataArray :param y: xr.DataArray of the same spatiotemporal extents and resolution as x. :param monitor: Monitor to use for monitoring the calculation :return: A dataset containing the correlation coefficients and p_values on the lon/lat grid of x and y. References ---------- http://www.statsoft.com/textbook/glosp.html#Pearson%20Correlation """ with monitor.starting("Calculate Pearson correlation", total_work=6): n = len(x['time']) xm, ym = x - x.mean(dim='time'), y - y.mean(dim='time') xm['time'] = [i for i in range(0, len(xm.time))] ym['time'] = [i for i in range(0, len(ym.time))] xm_ym = xm * ym r_num = xm_ym.sum(dim='time') xm_squared = np.square(xm) ym_squared = np.square(ym) r_den = np.sqrt(xm_squared.sum(dim='time') * ym_squared.sum(dim='time')) r_den = r_den.where(r_den != 0) r = r_num / r_den # Presumably, if abs(r) > 1, then it is only some small artifact of floating # point arithmetic. # At this point r should be a lon/lat dataArray, so it should be safe to # load it in memory explicitly. This may take time as it will kick-start # deferred processing. # Comparing with NaN produces warnings that can be safely ignored default_warning_settings = np.seterr(invalid='ignore') with monitor.child(1).observing("task 1"): negativ_r = r.values < -1.0 with monitor.child(1).observing("task 2"): r.values[negativ_r] = -1.0 with monitor.child(1).observing("task 3"): positiv_r = r.values > 1.0 with monitor.child(1).observing("task 4"): r.values[positiv_r] = 1.0 np.seterr(**default_warning_settings) r.attrs = {'description': 'Correlation coefficients between' ' {} and {}.'.format(x.name, y.name)} df = n - 2 t_squared = np.square(r) * (df / ((1.0 - r.where(r != 1)) * (1.0 + r.where(r != -1)))) prob = df / (df + t_squared) with monitor.child(1).observing("task 5"): prob_values_in = prob.values with monitor.child(1).observing("task 6"): prob.values = betainc(0.5 * df, 0.5, prob_values_in) prob.attrs = {'description': 'Rough indicator of probability of an' ' uncorrelated system producing datasets that have a Pearson' ' correlation at least as extreme as the one computed from' ' these datsets. Not entirely reliable, but reasonable for' ' datasets larger than 500 or so.'} retset = xr.Dataset({'corr_coef': r, 'p_value': prob}) return retset
mit
oaelhara/numbbo
code-postprocessing/bbob_pproc/compall/ppfigs.py
1
22256
#! /usr/bin/env python # -*- coding: utf-8 -*- """Creates ERTs and convergence figures for multiple algorithms.""" from __future__ import absolute_import import os import matplotlib.pyplot as plt import numpy from pdb import set_trace from .. import toolsdivers, toolsstats, bestalg, pproc, genericsettings, htmldesc, ppfigparam from ..ppfig import saveFigure from ..pptex import color_to_latex, marker_to_latex, marker_to_html, writeLabels # styles = [{'color': 'k', 'marker': 'o', 'markeredgecolor': 'k'}, # {'color': 'b'}, # {'color': 'c', 'marker': 'v', 'markeredgecolor': 'c'}, # {'color': 'g'}, # {'color': 'y', 'marker': '^', 'markeredgecolor': 'y'}, # {'color': 'm'}, # {'color': 'r', 'marker': 's', 'markeredgecolor': 'r'}] # sort of rainbow style show_significance = 0.01 # for zero nothing is shown scaling_figure_caption_start_fixed = (r"""Expected running time (\ERT\ in number of $f$-evaluations as $\log_{10}$ value), divided by dimension for target function value $BBOBPPFIGSFTARGET$ versus dimension. Slanted grid lines indicate quadratic scaling with the dimension. """ ) scaling_figure_caption_start_rlbased = (r"""Expected running time (\ERT\ in number of $f$-evaluations as $\log_{10}$ value) divided by dimension versus dimension. The target function value is chosen such that the REFERENCE_ALGORITHM artificial algorithm just failed to achieve an \ERT\ of $BBOBPPFIGSFTARGET\times\DIM$. """ ) scaling_figure_caption_end = ( r"Different symbols " + r"correspond to different algorithms given in the legend of #1. " + r"Light symbols give the maximum number of function evaluations from the longest trial " + r"divided by dimension. " + (r"Black stars indicate a statistically better result compared to all other algorithms " + r"with $p<0.01$ and Bonferroni correction number of dimensions (six). ") if show_significance else '' ) ecdfs_figure_caption_standard = ( r"Bootstrapped empirical cumulative distribution of the number " + r"of objective function evaluations divided by dimension " + r"(FEvals/DIM) for 50 targets in $10^{[-8..2]}$ for all "+ r"functions and subgroups in #1-D. The ``best 2009'' line "+ r"corresponds to the best \ERT\ observed during BBOB 2009 " + r"for each single target." ) ecdfs_figure_caption_rlbased = ( r"Bootstrapped empirical cumulative distribution of the number " + r"of objective function evaluations divided by dimension " + r"(FEvals/DIM) for all functions and subgroups in #1-D." + r" The targets are chosen from $10^{[-8..2]}$ " + r"such that the REFERENCE_ALGORITHM artificial algorithm just " + r"not reached them within a given budget of $k$ $\times$ DIM, " + r"with $k\in \{0.5, 1.2, 3, 10, 50\}$. " + r"The ``best 2009'' line " + r"corresponds to the best \ERT\ observed during BBOB 2009 " + r"for each selected target." ) styles = genericsettings.line_styles def fix_styles(number, styles=styles): """a short hack to fix length of styles""" m = len(styles) while len(styles) < number: styles.append(styles[len(styles) % m]) for i in xrange(len(styles)): styles[i].update({'linewidth': 5 - min([2, i/3.0]), # thinner lines over thicker lines 'markeredgewidth': 6 - min([2, i / 2.0]), 'markerfacecolor': 'None'}) refcolor = 'wheat' show_algorithms = [] fontsize = 10.0 legend = False def scaling_figure_caption(target): # need to be used in rungenericmany.py!? assert len(target) == 1 if isinstance(target, pproc.RunlengthBasedTargetValues): s = scaling_figure_caption_start_rlbased.replace('BBOBPPFIGSFTARGET', toolsdivers.number_to_latex(target.label(0))) s = s.replace('REFERENCE_ALGORITHM', target.reference_algorithm) else: s = scaling_figure_caption_start_fixed.replace('BBOBPPFIGSFTARGET', toolsdivers.number_to_latex(target.label(0))) s += scaling_figure_caption_end return s def ecdfs_figure_caption(target): assert len(target) == 1 if isinstance(target, pproc.RunlengthBasedTargetValues): s = ecdfs_figure_caption_rlbased.replace('REFERENCE_ALGORITHM', target.reference_algorithm) else: s = ecdfs_figure_caption_standard return s def scaling_figure_caption_html(target): # need to be used in rungenericmany.py!? assert len(target) == 1 if isinstance(target, pproc.RunlengthBasedTargetValues): s = htmldesc.getValue('##bbobppfigslegendrlbased##').replace('BBOBPPFIGSFTARGET', toolsdivers.number_to_html(target.label(0))) s = s.replace('REFERENCEALGORITHM', target.reference_algorithm) else: s = htmldesc.getValue('##bbobppfigslegendfixed##').replace('BBOBPPFIGSFTARGET', toolsdivers.number_to_html(target.label(0))) if show_significance: s += htmldesc.getValue('##bbobppfigslegendend##') return s def ecdfs_figure_caption_html(target, dimension): assert len(target) == 1 if isinstance(target, pproc.RunlengthBasedTargetValues): s = htmldesc.getValue('##bbobECDFslegendrlbased%d##' % dimension).replace('REFERENCEALGORITHM', target.reference_algorithm) else: s = htmldesc.getValue('##bbobECDFslegendstandard%d##' % dimension) return s def plotLegend(handles, maxval=None): """Display right-side legend. Sorted from smaller to larger y-coordinate values. """ ys = {} lh = 0 # Number of labels to display on the right if not maxval: maxval = [] for h in handles: x2 = [] y2 = [] for i in h: x2.append(plt.getp(i, "xdata")) x2 = numpy.sort(numpy.hstack(x2)) maxval.append(max(x2)) maxval = max(maxval) for h in handles: x2 = [] y2 = [] for i in h: x2.append(plt.getp(i, "xdata")) y2.append(plt.getp(i, "ydata")) x2 = numpy.array(numpy.hstack(x2)) y2 = numpy.array(numpy.hstack(y2)) tmp = numpy.argsort(x2) x2 = x2[tmp] y2 = y2[tmp] h = h[-1] # ybis is used to sort in case of ties try: tmp = x2 <= maxval y = y2[tmp][-1] ybis = y2[tmp][y2[tmp] < y] if len(ybis) > 0: ybis = ybis[-1] else: ybis = y2[tmp][-2] ys.setdefault(y, {}).setdefault(ybis, []).append(h) lh += 1 except IndexError: pass if len(show_algorithms) > 0: lh = min(lh, len(show_algorithms)) if lh <= 1: lh = 2 ymin, ymax = plt.ylim() xmin, xmax = plt.xlim() i = 0 # loop over the elements of ys for j in sorted(ys.keys()): for k in sorted(ys[j].keys()): #enforce best 2009 comes first in case of equality tmp = [] for h in ys[j][k]: if plt.getp(h, 'label') == 'best 2009': tmp.insert(0, h) else: tmp.append(h) #tmp.reverse() ys[j][k] = tmp for h in ys[j][k]: if (not plt.getp(h, 'label').startswith('_line') and (len(show_algorithms) == 0 or plt.getp(h, 'label') in show_algorithms)): y = 0.02 + i * 0.96/(lh-1) # transform y in the axis coordinates #inv = plt.gca().transLimits.inverted() #legx, ydat = inv.transform((.9, y)) #leglabx, ydat = inv.transform((.92, y)) #set_trace() ydat = 10**(y * numpy.log10(ymax/ymin)) * ymin legx = 10**(.85 * numpy.log10(xmax/xmin)) * xmin leglabx = 10**(.87 * numpy.log10(xmax/xmin)) * xmin tmp = {} for attr in ('lw', 'ls', 'marker', 'markeredgewidth', 'markerfacecolor', 'markeredgecolor', 'markersize', 'zorder'): tmp[attr] = plt.getp(h, attr) plt.plot((maxval, legx), (j, ydat), color=plt.getp(h, 'markeredgecolor'), **tmp) plt.text(leglabx, ydat, plt.getp(h, 'label'), horizontalalignment="left", verticalalignment="center", size=fontsize) i += 1 plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) if maxval: plt.axvline(maxval, color='k') def beautify(legend=False, rightlegend=False): """Customize figure format. adding a legend, axis label, etc :param bool legend: if True, display a box legend :param bool rightlegend: if True, makes some space on the right for legend """ # Get axis handle and set scale for each axis axisHandle = plt.gca() axisHandle.set_xscale("log") try: axisHandle.set_yscale("log") except OverflowError: set_trace() # Grid options axisHandle.yaxis.grid(True) ymin, ymax = plt.ylim() # quadratic slanted "grid" if 1 < 3: for i in xrange(-2, 7, 1 if ymax < 1e5 else 2): plt.plot((0.2, 20000), (10**i, 10**(i + 5)), 'k:', linewidth=0.5) # grid should be on top else: # to be removed plt.plot((2,200), (1, 1e2), 'k:', zorder=-1) # -1 -> plotted below? # plt.plot((2,200), (1, 1e4), 'k:', zorder=-1) plt.plot((2,200), (1e3, 1e5), 'k:', zorder=-1) # plt.plot((2,200), (1e3, 1e7), 'k:', zorder=-1) plt.plot((2,200), (1e6, 1e8), 'k:', zorder=-1) # plt.plot((2,200), (1e6, 1e10), 'k:', zorder=-1) plt.ylim(ymin=10**-0.2, ymax=ymax) # Set back the default maximum. # ticks on axes #axisHandle.invert_xaxis() dimticklist = (2, 3, 5, 10, 20, 40) # TODO: should become input arg at some point? dimannlist = (2, 3, 5, 10, 20, 40) # TODO: should become input arg at some point? # TODO: All these should depend on (xlim, ylim) axisHandle.set_xticks(dimticklist) axisHandle.set_xticklabels([str(n) for n in dimannlist]) # axes limites if rightlegend: plt.xlim(1.8, 101) # 101 is 10 ** (numpy.log10(45/1.8)*1.25) * 1.8 else: plt.xlim(1.8, 45) # Should depend on xmin and xmax tmp = axisHandle.get_yticks() tmp2 = [] for i in tmp: tmp2.append('%d' % round(numpy.log10(i))) axisHandle.set_yticklabels(tmp2) if legend: plt.legend(loc=0, numpoints=1) def generateData(dataSet, target): """Returns an array of results to be plotted. Oth column is ert, 1st is the success rate, 2nd the number of successes, 3rd the mean of the number of function evaluations, and 4th the median of number of function evaluations of successful runs or numpy.nan. """ res = [] data = dataSet.detEvals([target])[0] succ = (numpy.isnan(data) == False) data[numpy.isnan(data)] = dataSet.maxevals[numpy.isnan(data)] res.extend(toolsstats.sp(data, issuccessful=succ, allowinf=False)) res.append(numpy.mean(data)) if res[2] > 0: res.append(toolsstats.prctile(data[succ], 50)[0]) else: res.append(numpy.nan) res[3] = numpy.max(dataSet.maxevals) return res def main(dictAlg, htmlFilePrefix, isBiobjective, target, sortedAlgs=None, outputdir='ppdata', verbose=True): """From a DataSetList, returns figures showing the scaling: ERT/dim vs dim. One function and one target per figure. ``target`` can be a scalar, a list with one element or a ``pproc.TargetValues`` instance with one target. ``sortedAlgs`` is a list of string-identifies (folder names) """ # target becomes a TargetValues "list" with one element target = pproc.TargetValues.cast([target] if numpy.isscalar(target) else target) latex_commands_filename = os.path.join(outputdir, 'bbob_pproc_commands.tex') assert isinstance(target, pproc.TargetValues) if len(target) != 1: raise ValueError('only a single target can be managed in ppfigs, ' + str(len(target)) + ' targets were given') funInfos = ppfigparam.read_fun_infos(isBiobjective) dictFunc = pproc.dictAlgByFun(dictAlg) if sortedAlgs is None: sortedAlgs = sorted(dictAlg.keys()) if not os.path.isdir(outputdir): os.mkdir(outputdir) for f in dictFunc: filename = os.path.join(outputdir,'ppfigs_f%03d' % (f)) handles = [] fix_styles(len(sortedAlgs)) # for i, alg in enumerate(sortedAlgs): dictDim = dictFunc[f][alg].dictByDim() # this does not look like the most obvious solution #Collect data dimert = [] ert = [] dimnbsucc = [] ynbsucc = [] nbsucc = [] dimmaxevals = [] maxevals = [] dimmedian = [] medianfes = [] for dim in sorted(dictDim): assert len(dictDim[dim]) == 1 entry = dictDim[dim][0] data = generateData(entry, target((f, dim))[0]) # TODO: here we might want a different target for each function if 1 < 3 or data[2] == 0: # No success dimmaxevals.append(dim) maxevals.append(float(data[3])/dim) if data[2] > 0: dimmedian.append(dim) medianfes.append(data[4]/dim) dimert.append(dim) ert.append(float(data[0])/dim) if data[1] < 1.: dimnbsucc.append(dim) ynbsucc.append(float(data[0])/dim) nbsucc.append('%d' % data[2]) # Draw lines if 1 < 3: # new version # omit the line if a point in between is missing for idim in range(len(dimert)): # plot line only if next dim < 2.1*dim (a hack) if idim < len(dimert) - 1 and dimert[idim + 1] < 2.1 * dimert[idim]: tmp = plt.plot(dimert[idim:idim+2], ert[idim:idim+2], **styles[i]) #label=alg, ) else: # plot remaining single points (some twice) tmp = plt.plot(dimert[idim], ert[idim], **styles[i]) #label=alg, ) plt.setp(tmp[0], markeredgecolor=plt.getp(tmp[0], 'color')) else: # to be removed tmp = plt.plot(dimert, ert, **styles[i]) #label=alg, ) plt.setp(tmp[0], markeredgecolor=plt.getp(tmp[0], 'color')) # For legend # tmp = plt.plot([], [], label=alg.replace('..' + os.sep, '').strip(os.sep), **styles[i]) algorithmName = toolsdivers.str_to_latex(toolsdivers.strip_pathname1(alg)) tmp = plt.plot([], [], label = algorithmName, **styles[i]) plt.setp(tmp[0], markersize=12., markeredgecolor=plt.getp(tmp[0], 'color')) if dimmaxevals: tmp = plt.plot(dimmaxevals, maxevals, **styles[i]) plt.setp(tmp[0], markersize=20, #label=alg, markeredgecolor=plt.getp(tmp[0], 'color'), markeredgewidth=1, markerfacecolor='None', linestyle='None') handles.append(tmp) #tmp2 = plt.plot(dimmedian, medianfes, ls='', marker='+', # markersize=30, markeredgewidth=5, # markeredgecolor=plt.getp(tmp, 'color'))[0] #for i, n in enumerate(nbsucc): # plt.text(dimnbsucc[i], numpy.array(ynbsucc[i])*1.85, n, # verticalalignment='bottom', # horizontalalignment='center') bestalgentries = bestalg.loadBestAlgorithm(isBiobjective) if bestalgentries: bestalgdata = [] dimbestalg = list(df[0] for df in bestalgentries if df[1] == f) dimbestalg.sort() dimbestalg2 = [] for d in dimbestalg: entry = bestalgentries[(d, f)] tmp = entry.detERT(target((f, d)))[0] if numpy.isfinite(tmp): bestalgdata.append(float(tmp)/d) dimbestalg2.append(d) tmp = plt.plot(dimbestalg2, bestalgdata, color=refcolor, linewidth=10, marker='d', markersize=25, markeredgecolor=refcolor, zorder=-1 #label='best 2009', ) handles.append(tmp) if show_significance: # plot significance-stars xstar, ystar = [], [] dims = sorted(pproc.dictAlgByDim(dictFunc[f])) for i, dim in enumerate(dims): datasets = pproc.dictAlgByDim(dictFunc[f])[dim] assert all([len(datasets[ialg]) == 1 for ialg in sortedAlgs if datasets[ialg]]) dsetlist = [datasets[ialg][0] for ialg in sortedAlgs if datasets[ialg]] if len(dsetlist) > 1: arzp, arialg = toolsstats.significance_all_best_vs_other(dsetlist, target((f, dim))) if arzp[0][1] * len(dims) < show_significance: ert = dsetlist[arialg[0]].detERT(target((f, dim)))[0] if ert < numpy.inf: xstar.append(dim) ystar.append(ert/dim) plt.plot(xstar, ystar, 'k*', markerfacecolor=None, markeredgewidth=2, markersize=0.5*styles[0]['markersize']) if f in funInfos.keys(): plt.gca().set_title(funInfos[f]) isLegend = False if legend: plotLegend(handles) elif 1 < 3: if f in (1, 24, 101, 130) and len(sortedAlgs) < 6: # 6 elements at most in the boxed legend isLegend = True beautify(legend=isLegend, rightlegend=legend) plt.text(plt.xlim()[0], plt.ylim()[0], 'target ' + target.label_name() + ': ' + target.label(0)) # TODO: check saveFigure(filename, verbose=verbose) plt.close() htmlFile = os.path.join(outputdir, htmlFilePrefix + '.html') # generate commands in tex file: try: abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' alg_definitions = [] alg_definitions_html = '' for i in range(len(sortedAlgs)): symb = r'{%s%s}' % (color_to_latex(styles[i]['color']), marker_to_latex(styles[i]['marker'])) symb_html = '<span style="color:%s;">%s</span>' % (styles[i]['color'], marker_to_html(styles[i]['marker'])) alg_definitions.append((', ' if i > 0 else '') + '%s: %s' % (symb, '\\algorithm' + abc[i % len(abc)])) alg_definitions_html += (', ' if i > 0 else '') + '%s: %s' % (symb_html, toolsdivers.str_to_latex(toolsdivers.strip_pathname1(sortedAlgs[i]))) toolsdivers.prepend_to_file(latex_commands_filename, [#'\\providecommand{\\bbobppfigsftarget}{\\ensuremath{10^{%s}}}' # % target.loglabel(0), # int(numpy.round(numpy.log10(target))), '\\providecommand{\\bbobppfigslegend}[1]{', scaling_figure_caption(target), 'Legend: '] + alg_definitions + ['}'] ) toolsdivers.prepend_to_file(latex_commands_filename, ['\\providecommand{\\bbobECDFslegend}[1]{', ecdfs_figure_caption(target), '}'] ) toolsdivers.replace_in_file(htmlFile, '##bbobppfigslegend##', scaling_figure_caption_html(target) + 'Legend: ' + alg_definitions_html) toolsdivers.replace_in_file(htmlFile, '##bbobECDFslegend5##', ecdfs_figure_caption_html(target, 5)) toolsdivers.replace_in_file(htmlFile, '##bbobECDFslegend20##', ecdfs_figure_caption_html(target, 20)) if verbose: print 'Wrote commands and legend to %s' % filename # this is obsolete (however check templates) filename = os.path.join(outputdir,'ppfigs.tex') f = open(filename, 'w') f.write('% Do not modify this file: calls to post-processing software' + ' will overwrite any modification.\n') f.write('Legend: ') for i in range(0, len(sortedAlgs)): symb = r'{%s%s}' % (color_to_latex(styles[i]['color']), marker_to_latex(styles[i]['marker'])) f.write((', ' if i > 0 else '') + '%s:%s' % (symb, writeLabels(sortedAlgs[i]))) f.close() if verbose: print '(obsolete) Wrote legend in %s' % filename except IOError: raise handles.append(tmp) if f in funInfos.keys(): plt.gca().set_title(funInfos[f]) beautify(rightlegend=legend) if legend: plotLegend(handles) else: if f in (1, 24, 101, 130): plt.legend() saveFigure(filename, figFormat=genericsettings.getFigFormats(), verbose=verbose) plt.close()
bsd-3-clause
LohithBlaze/scikit-learn
examples/svm/plot_separating_hyperplane_unbalanced.py
326
1850
""" ================================================= SVM: Separating hyperplane for unbalanced classes ================================================= Find the optimal separating hyperplane using an SVC for classes that are unbalanced. We first find the separating plane with a plain SVC and then plot (dashed) the separating hyperplane with automatically correction for unbalanced classes. .. currentmodule:: sklearn.linear_model .. note:: This example will also work by replacing ``SVC(kernel="linear")`` with ``SGDClassifier(loss="hinge")``. Setting the ``loss`` parameter of the :class:`SGDClassifier` equal to ``hinge`` will yield behaviour such as that of a SVC with a linear kernel. For example try instead of the ``SVC``:: clf = SGDClassifier(n_iter=100, alpha=0.01) """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm #from sklearn.linear_model import SGDClassifier # we create 40 separable points rng = np.random.RandomState(0) n_samples_1 = 1000 n_samples_2 = 100 X = np.r_[1.5 * rng.randn(n_samples_1, 2), 0.5 * rng.randn(n_samples_2, 2) + [2, 2]] y = [0] * (n_samples_1) + [1] * (n_samples_2) # fit the model and get the separating hyperplane clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - clf.intercept_[0] / w[1] # get the separating hyperplane using weighted classes wclf = svm.SVC(kernel='linear', class_weight={1: 10}) wclf.fit(X, y) ww = wclf.coef_[0] wa = -ww[0] / ww[1] wyy = wa * xx - wclf.intercept_[0] / ww[1] # plot separating hyperplanes and samples h0 = plt.plot(xx, yy, 'k-', label='no weights') h1 = plt.plot(xx, wyy, 'k--', label='with weights') plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.legend() plt.axis('tight') plt.show()
bsd-3-clause
jzt5132/scikit-learn
examples/svm/plot_separating_hyperplane_unbalanced.py
326
1850
""" ================================================= SVM: Separating hyperplane for unbalanced classes ================================================= Find the optimal separating hyperplane using an SVC for classes that are unbalanced. We first find the separating plane with a plain SVC and then plot (dashed) the separating hyperplane with automatically correction for unbalanced classes. .. currentmodule:: sklearn.linear_model .. note:: This example will also work by replacing ``SVC(kernel="linear")`` with ``SGDClassifier(loss="hinge")``. Setting the ``loss`` parameter of the :class:`SGDClassifier` equal to ``hinge`` will yield behaviour such as that of a SVC with a linear kernel. For example try instead of the ``SVC``:: clf = SGDClassifier(n_iter=100, alpha=0.01) """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm #from sklearn.linear_model import SGDClassifier # we create 40 separable points rng = np.random.RandomState(0) n_samples_1 = 1000 n_samples_2 = 100 X = np.r_[1.5 * rng.randn(n_samples_1, 2), 0.5 * rng.randn(n_samples_2, 2) + [2, 2]] y = [0] * (n_samples_1) + [1] * (n_samples_2) # fit the model and get the separating hyperplane clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - clf.intercept_[0] / w[1] # get the separating hyperplane using weighted classes wclf = svm.SVC(kernel='linear', class_weight={1: 10}) wclf.fit(X, y) ww = wclf.coef_[0] wa = -ww[0] / ww[1] wyy = wa * xx - wclf.intercept_[0] / ww[1] # plot separating hyperplanes and samples h0 = plt.plot(xx, yy, 'k-', label='no weights') h1 = plt.plot(xx, wyy, 'k--', label='with weights') plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.legend() plt.axis('tight') plt.show()
bsd-3-clause
glouppe/scikit-learn
sklearn/cross_decomposition/cca_.py
145
3192
from .pls_ import _PLS __all__ = ['CCA'] class CCA(_PLS): """CCA Canonical Correlation Analysis. CCA inherits from PLS with mode="B" and deflation_mode="canonical". Read more in the :ref:`User Guide <cross_decomposition>`. Parameters ---------- n_components : int, (default 2). number of components to keep. scale : boolean, (default True) whether to scale the data? max_iter : an integer, (default 500) the maximum number of iterations of the NIPALS inner loop tol : non-negative real, default 1e-06. the tolerance used in the iterative algorithm copy : boolean Whether the deflation be done on a copy. Let the default value to True unless you don't care about side effects Attributes ---------- x_weights_ : array, [p, n_components] X block weights vectors. y_weights_ : array, [q, n_components] Y block weights vectors. x_loadings_ : array, [p, n_components] X block loadings vectors. y_loadings_ : array, [q, n_components] Y block loadings vectors. x_scores_ : array, [n_samples, n_components] X scores. y_scores_ : array, [n_samples, n_components] Y scores. x_rotations_ : array, [p, n_components] X block to latents rotations. y_rotations_ : array, [q, n_components] Y block to latents rotations. n_iter_ : array-like Number of iterations of the NIPALS inner loop for each component. Notes ----- For each component k, find the weights u, v that maximizes max corr(Xk u, Yk v), such that ``|u| = |v| = 1`` Note that it maximizes only the correlations between the scores. The residual matrix of X (Xk+1) block is obtained by the deflation on the current X score: x_score. The residual matrix of Y (Yk+1) block is obtained by deflation on the current Y score. Examples -------- >>> from sklearn.cross_decomposition import CCA >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [3.,5.,4.]] >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]] >>> cca = CCA(n_components=1) >>> cca.fit(X, Y) ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE CCA(copy=True, max_iter=500, n_components=1, scale=True, tol=1e-06) >>> X_c, Y_c = cca.transform(X, Y) References ---------- Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with emphasis on the two-block case. Technical Report 371, Department of Statistics, University of Washington, Seattle, 2000. In french but still a reference: Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris: Editions Technic. See also -------- PLSCanonical PLSSVD """ def __init__(self, n_components=2, scale=True, max_iter=500, tol=1e-06, copy=True): super(CCA, self).__init__(n_components=n_components, scale=scale, deflation_mode="canonical", mode="B", norm_y_weights=True, algorithm="nipals", max_iter=max_iter, tol=tol, copy=copy)
bsd-3-clause
eadgarchen/tensorflow
tensorflow/contrib/learn/python/learn/estimators/stability_test.py
110
6455
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Estimator regression tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random from tensorflow.contrib.framework.python.ops import variables from tensorflow.contrib.layers.python.layers import feature_column from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.contrib.learn.python.learn.estimators import dnn from tensorflow.contrib.learn.python.learn.estimators import linear from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.contrib.learn.python.learn.learn_io import data_feeder from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import random_ops from tensorflow.python.platform import test from tensorflow.python.training import optimizer as optimizer_lib def _get_input_fn(x, y, batch_size=None): df = data_feeder.setup_train_data_feeder( x, y, n_classes=None, batch_size=batch_size) return df.input_builder, df.get_feed_dict_fn() # We use a null optimizer since we can't get deterministic results out of # supervisor's multiple threads. class _NullOptimizer(optimizer_lib.Optimizer): def __init__(self): super(_NullOptimizer, self).__init__(use_locking=False, name='Null') def _apply_dense(self, grad, var): return control_flow_ops.no_op() def _apply_sparse(self, grad, var): return control_flow_ops.no_op() def _prepare(self): pass _NULL_OPTIMIZER = _NullOptimizer() class StabilityTest(test.TestCase): """Tests that estiamtors are reproducible.""" def testRandomStability(self): my_seed = 42 minval = -0.3333 maxval = 0.3333 with ops.Graph().as_default() as g: with self.test_session(graph=g) as session: g.seed = my_seed x = random_ops.random_uniform([10, 10], minval=minval, maxval=maxval) val1 = session.run(x) with ops.Graph().as_default() as g: with self.test_session(graph=g) as session: g.seed = my_seed x = random_ops.random_uniform([10, 10], minval=minval, maxval=maxval) val2 = session.run(x) self.assertAllClose(val1, val2) def testLinearRegression(self): my_seed = 42 config = run_config.RunConfig(tf_random_seed=my_seed) boston = base.load_boston() columns = [feature_column.real_valued_column('', dimension=13)] # We train with with ops.Graph().as_default() as g1: random.seed(my_seed) g1.seed = my_seed variables.create_global_step() regressor1 = linear.LinearRegressor( optimizer=_NULL_OPTIMIZER, feature_columns=columns, config=config) regressor1.fit(x=boston.data, y=boston.target, steps=1) with ops.Graph().as_default() as g2: random.seed(my_seed) g2.seed = my_seed variables.create_global_step() regressor2 = linear.LinearRegressor( optimizer=_NULL_OPTIMIZER, feature_columns=columns, config=config) regressor2.fit(x=boston.data, y=boston.target, steps=1) variable_names = regressor1.get_variable_names() self.assertIn('linear//weight', variable_names) self.assertIn('linear/bias_weight', variable_names) regressor1_weights = regressor1.get_variable_value('linear//weight') regressor2_weights = regressor2.get_variable_value('linear//weight') regressor1_bias = regressor1.get_variable_value('linear/bias_weight') regressor2_bias = regressor2.get_variable_value('linear/bias_weight') self.assertAllClose(regressor1_weights, regressor2_weights) self.assertAllClose(regressor1_bias, regressor2_bias) self.assertAllClose( list(regressor1.predict_scores( boston.data, as_iterable=True)), list(regressor2.predict_scores( boston.data, as_iterable=True)), atol=1e-05) def testDNNRegression(self): my_seed = 42 config = run_config.RunConfig(tf_random_seed=my_seed) boston = base.load_boston() columns = [feature_column.real_valued_column('', dimension=13)] with ops.Graph().as_default() as g1: random.seed(my_seed) g1.seed = my_seed variables.create_global_step() regressor1 = dnn.DNNRegressor( hidden_units=[10], feature_columns=columns, optimizer=_NULL_OPTIMIZER, config=config) regressor1.fit(x=boston.data, y=boston.target, steps=1) with ops.Graph().as_default() as g2: random.seed(my_seed) g2.seed = my_seed variables.create_global_step() regressor2 = dnn.DNNRegressor( hidden_units=[10], feature_columns=columns, optimizer=_NULL_OPTIMIZER, config=config) regressor2.fit(x=boston.data, y=boston.target, steps=1) weights1 = ([regressor1.get_variable_value('dnn/hiddenlayer_0/weights')] + [regressor1.get_variable_value('dnn/logits/weights')]) weights2 = ([regressor2.get_variable_value('dnn/hiddenlayer_0/weights')] + [regressor2.get_variable_value('dnn/logits/weights')]) for w1, w2 in zip(weights1, weights2): self.assertAllClose(w1, w2) biases1 = ([regressor1.get_variable_value('dnn/hiddenlayer_0/biases')] + [regressor1.get_variable_value('dnn/logits/biases')]) biases2 = ([regressor2.get_variable_value('dnn/hiddenlayer_0/biases')] + [regressor2.get_variable_value('dnn/logits/biases')]) for b1, b2 in zip(biases1, biases2): self.assertAllClose(b1, b2) self.assertAllClose( list(regressor1.predict_scores( boston.data, as_iterable=True)), list(regressor2.predict_scores( boston.data, as_iterable=True)), atol=1e-05) if __name__ == '__main__': test.main()
apache-2.0
glouppe/scikit-learn
sklearn/svm/tests/test_sparse.py
21
13181
from nose.tools import assert_raises, assert_true, assert_false import numpy as np from scipy import sparse from numpy.testing import (assert_array_almost_equal, assert_array_equal, assert_equal) from sklearn import datasets, svm, linear_model, base from sklearn.datasets import make_classification, load_digits, make_blobs from sklearn.svm.tests import test_svm from sklearn.exceptions import ConvergenceWarning from sklearn.utils.extmath import safe_sparse_dot from sklearn.utils.testing import assert_warns, assert_raise_message # test sample 1 X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) X_sp = sparse.lil_matrix(X) Y = [1, 1, 1, 2, 2, 2] T = np.array([[-1, -1], [2, 2], [3, 2]]) true_result = [1, 2, 2] # test sample 2 X2 = np.array([[0, 0, 0], [1, 1, 1], [2, 0, 0, ], [0, 0, 2], [3, 3, 3]]) X2_sp = sparse.dok_matrix(X2) Y2 = [1, 2, 2, 2, 3] T2 = np.array([[-1, -1, -1], [1, 1, 1], [2, 2, 2]]) true_result2 = [1, 2, 3] iris = datasets.load_iris() # permute rng = np.random.RandomState(0) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # sparsify iris.data = sparse.csr_matrix(iris.data) def check_svm_model_equal(dense_svm, sparse_svm, X_train, y_train, X_test): dense_svm.fit(X_train.toarray(), y_train) if sparse.isspmatrix(X_test): X_test_dense = X_test.toarray() else: X_test_dense = X_test sparse_svm.fit(X_train, y_train) assert_true(sparse.issparse(sparse_svm.support_vectors_)) assert_true(sparse.issparse(sparse_svm.dual_coef_)) assert_array_almost_equal(dense_svm.support_vectors_, sparse_svm.support_vectors_.toarray()) assert_array_almost_equal(dense_svm.dual_coef_, sparse_svm.dual_coef_.toarray()) if dense_svm.kernel == "linear": assert_true(sparse.issparse(sparse_svm.coef_)) assert_array_almost_equal(dense_svm.coef_, sparse_svm.coef_.toarray()) assert_array_almost_equal(dense_svm.support_, sparse_svm.support_) assert_array_almost_equal(dense_svm.predict(X_test_dense), sparse_svm.predict(X_test)) assert_array_almost_equal(dense_svm.decision_function(X_test_dense), sparse_svm.decision_function(X_test)) assert_array_almost_equal(dense_svm.decision_function(X_test_dense), sparse_svm.decision_function(X_test_dense)) if isinstance(dense_svm, svm.OneClassSVM): msg = "cannot use sparse input in 'OneClassSVM' trained on dense data" else: assert_array_almost_equal(dense_svm.predict_proba(X_test_dense), sparse_svm.predict_proba(X_test), 4) msg = "cannot use sparse input in 'SVC' trained on dense data" if sparse.isspmatrix(X_test): assert_raise_message(ValueError, msg, dense_svm.predict, X_test) def test_svc(): """Check that sparse SVC gives the same result as SVC""" # many class dataset: X_blobs, y_blobs = make_blobs(n_samples=100, centers=10, random_state=0) X_blobs = sparse.csr_matrix(X_blobs) datasets = [[X_sp, Y, T], [X2_sp, Y2, T2], [X_blobs[:80], y_blobs[:80], X_blobs[80:]], [iris.data, iris.target, iris.data]] kernels = ["linear", "poly", "rbf", "sigmoid"] for dataset in datasets: for kernel in kernels: clf = svm.SVC(kernel=kernel, probability=True, random_state=0, decision_function_shape='ovo') sp_clf = svm.SVC(kernel=kernel, probability=True, random_state=0, decision_function_shape='ovo') check_svm_model_equal(clf, sp_clf, *dataset) def test_unsorted_indices(): # test that the result with sorted and unsorted indices in csr is the same # we use a subset of digits as iris, blobs or make_classification didn't # show the problem digits = load_digits() X, y = digits.data[:50], digits.target[:50] X_test = sparse.csr_matrix(digits.data[50:100]) X_sparse = sparse.csr_matrix(X) coef_dense = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X, y).coef_ sparse_svc = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X_sparse, y) coef_sorted = sparse_svc.coef_ # make sure dense and sparse SVM give the same result assert_array_almost_equal(coef_dense, coef_sorted.toarray()) X_sparse_unsorted = X_sparse[np.arange(X.shape[0])] X_test_unsorted = X_test[np.arange(X_test.shape[0])] # make sure we scramble the indices assert_false(X_sparse_unsorted.has_sorted_indices) assert_false(X_test_unsorted.has_sorted_indices) unsorted_svc = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X_sparse_unsorted, y) coef_unsorted = unsorted_svc.coef_ # make sure unsorted indices give same result assert_array_almost_equal(coef_unsorted.toarray(), coef_sorted.toarray()) assert_array_almost_equal(sparse_svc.predict_proba(X_test_unsorted), sparse_svc.predict_proba(X_test)) def test_svc_with_custom_kernel(): kfunc = lambda x, y: safe_sparse_dot(x, y.T) clf_lin = svm.SVC(kernel='linear').fit(X_sp, Y) clf_mylin = svm.SVC(kernel=kfunc).fit(X_sp, Y) assert_array_equal(clf_lin.predict(X_sp), clf_mylin.predict(X_sp)) def test_svc_iris(): # Test the sparse SVC with the iris dataset for k in ('linear', 'poly', 'rbf'): sp_clf = svm.SVC(kernel=k).fit(iris.data, iris.target) clf = svm.SVC(kernel=k).fit(iris.data.toarray(), iris.target) assert_array_almost_equal(clf.support_vectors_, sp_clf.support_vectors_.toarray()) assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) assert_array_almost_equal( clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) if k == 'linear': assert_array_almost_equal(clf.coef_, sp_clf.coef_.toarray()) def test_sparse_decision_function(): #Test decision_function #Sanity check, test that decision_function implemented in python #returns the same as the one in libsvm # multi class: svc = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovo') clf = svc.fit(iris.data, iris.target) dec = safe_sparse_dot(iris.data, clf.coef_.T) + clf.intercept_ assert_array_almost_equal(dec, clf.decision_function(iris.data)) # binary: clf.fit(X, Y) dec = np.dot(X, clf.coef_.T) + clf.intercept_ prediction = clf.predict(X) assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) assert_array_almost_equal( prediction, clf.classes_[(clf.decision_function(X) > 0).astype(np.int).ravel()]) expected = np.array([-1., -0.66, -1., 0.66, 1., 1.]) assert_array_almost_equal(clf.decision_function(X), expected, 2) def test_error(): # Test that it gives proper exception on deficient input # impossible value of C assert_raises(ValueError, svm.SVC(C=-1).fit, X, Y) # impossible value of nu clf = svm.NuSVC(nu=0.0) assert_raises(ValueError, clf.fit, X_sp, Y) Y2 = Y[:-1] # wrong dimensions for labels assert_raises(ValueError, clf.fit, X_sp, Y2) clf = svm.SVC() clf.fit(X_sp, Y) assert_array_equal(clf.predict(T), true_result) def test_linearsvc(): # Similar to test_SVC clf = svm.LinearSVC(random_state=0).fit(X, Y) sp_clf = svm.LinearSVC(random_state=0).fit(X_sp, Y) assert_true(sp_clf.fit_intercept) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) assert_array_almost_equal(clf.predict(X), sp_clf.predict(X_sp)) clf.fit(X2, Y2) sp_clf.fit(X2_sp, Y2) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) def test_linearsvc_iris(): # Test the sparse LinearSVC with the iris dataset sp_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target) clf = svm.LinearSVC(random_state=0).fit(iris.data.toarray(), iris.target) assert_equal(clf.fit_intercept, sp_clf.fit_intercept) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=1) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=1) assert_array_almost_equal( clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) # check decision_function pred = np.argmax(sp_clf.decision_function(iris.data), 1) assert_array_almost_equal(pred, clf.predict(iris.data.toarray())) # sparsify the coefficients on both models and check that they still # produce the same results clf.sparsify() assert_array_equal(pred, clf.predict(iris.data)) sp_clf.sparsify() assert_array_equal(pred, sp_clf.predict(iris.data)) def test_weight(): # Test class weights X_, y_ = make_classification(n_samples=200, n_features=100, weights=[0.833, 0.167], random_state=0) X_ = sparse.csr_matrix(X_) for clf in (linear_model.LogisticRegression(), svm.LinearSVC(random_state=0), svm.SVC()): clf.set_params(class_weight={0: 5}) clf.fit(X_[:180], y_[:180]) y_pred = clf.predict(X_[180:]) assert_true(np.sum(y_pred == y_[180:]) >= 11) def test_sample_weights(): # Test weights on individual samples clf = svm.SVC() clf.fit(X_sp, Y) assert_array_equal(clf.predict([X[2]]), [1.]) sample_weight = [.1] * 3 + [10] * 3 clf.fit(X_sp, Y, sample_weight=sample_weight) assert_array_equal(clf.predict([X[2]]), [2.]) def test_sparse_liblinear_intercept_handling(): # Test that sparse liblinear honours intercept_scaling param test_svm.test_dense_liblinear_intercept_handling(svm.LinearSVC) def test_sparse_oneclasssvm(): """Check that sparse OneClassSVM gives the same result as dense OneClassSVM""" # many class dataset: X_blobs, _ = make_blobs(n_samples=100, centers=10, random_state=0) X_blobs = sparse.csr_matrix(X_blobs) datasets = [[X_sp, None, T], [X2_sp, None, T2], [X_blobs[:80], None, X_blobs[80:]], [iris.data, None, iris.data]] kernels = ["linear", "poly", "rbf", "sigmoid"] for dataset in datasets: for kernel in kernels: clf = svm.OneClassSVM(kernel=kernel, random_state=0) sp_clf = svm.OneClassSVM(kernel=kernel, random_state=0) check_svm_model_equal(clf, sp_clf, *dataset) def test_sparse_realdata(): # Test on a subset from the 20newsgroups dataset. # This catchs some bugs if input is not correctly converted into # sparse format or weights are not correctly initialized. data = np.array([0.03771744, 0.1003567, 0.01174647, 0.027069]) indices = np.array([6, 5, 35, 31]) indptr = np.array( [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4]) X = sparse.csr_matrix((data, indices, indptr)) y = np.array( [1., 0., 2., 2., 1., 1., 1., 2., 2., 0., 1., 2., 2., 0., 2., 0., 3., 0., 3., 0., 1., 1., 3., 2., 3., 2., 0., 3., 1., 0., 2., 1., 2., 0., 1., 0., 2., 3., 1., 3., 0., 1., 0., 0., 2., 0., 1., 2., 2., 2., 3., 2., 0., 3., 2., 1., 2., 3., 2., 2., 0., 1., 0., 1., 2., 3., 0., 0., 2., 2., 1., 3., 1., 1., 0., 1., 2., 1., 1., 3.]) clf = svm.SVC(kernel='linear').fit(X.toarray(), y) sp_clf = svm.SVC(kernel='linear').fit(sparse.coo_matrix(X), y) assert_array_equal(clf.support_vectors_, sp_clf.support_vectors_.toarray()) assert_array_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) def test_sparse_svc_clone_with_callable_kernel(): # Test that the "dense_fit" is called even though we use sparse input # meaning that everything works fine. a = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, random_state=0) b = base.clone(a) b.fit(X_sp, Y) pred = b.predict(X_sp) b.predict_proba(X_sp) dense_svm = svm.SVC(C=1, kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0) pred_dense = dense_svm.fit(X, Y).predict(X) assert_array_equal(pred_dense, pred) # b.decision_function(X_sp) # XXX : should be supported def test_timeout(): sp = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, random_state=0, max_iter=1) assert_warns(ConvergenceWarning, sp.fit, X_sp, Y) def test_consistent_proba(): a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_1 = a.fit(X, Y).predict_proba(X) a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_2 = a.fit(X, Y).predict_proba(X) assert_array_almost_equal(proba_1, proba_2)
bsd-3-clause
elkingtonmcb/h2o-2
py/testdir_kevin/test_parse_specific_case5.py
9
4807
import unittest, random, sys, time, os sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_import as h2i import codecs, unicodedata print "create some specific small datasets with exp row/col combinations" print "This is trying a random sample of utf8 symbols inserted in an enum" # 0x1 can be the hive separator? if we force comma it should be treated as char # should try without and change expected cols # the full list of legal UTF8 toDoList = range(0x000000,0x00007f) # 1byte toDoList += range(0x000080,0x00009f) # 2byte toDoList += range(0x0000a0,0x0003ff) # 2byte toDoList += range(0x000400,0x0007ff) # 2byte toDoList += range(0x000800,0x003fff) # 3byte toDoList += range(0x004000,0x00ffff) # 3byte toDoList += range(0x010000,0x03ffff) # 3byte toDoList += range(0x040000,0x10ffff) # 4byte def removeIfThere(d): if d in toDoList: toDoList.remove(d) H2O_COL_SEPARATOR = 0x2c # comma # H2O_COL_SEPARATOR = 0x1 # hive separator # removeIfThere(0x1) # hive separator okay if we force comma below removeIfThere(0x0) # nul. known issue removeIfThere(0xa) # LF. causes EOL removeIfThere(0xd) # CR. causes EOL removeIfThere(0x22) # double quote. known issue removeIfThere(0x2c) # comma. don't mess up my expected col count # could try single quote if enabled, to see if does damage. probably like double quote tryList = [] # do just 100 for i in random.sample(toDoList, 100): # ignore illegal try: unicodeSymbol = unichr(i) tryList.append( (( 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' 'a,b,c,d' + unicodeSymbol + 's,n\n' ), 10, 5, [0,0,0,0,0], ['Enum', 'Enum', 'Enum', 'Enum', 'Enum'], i) ) except ValueError: # for now, we don't expect any illegal values in toDoList raise Exception("0x%x isn't valid unicode point" % i) def write_syn_dataset(csvPathname, dataset): dsf = codecs.open(csvPathname, encoding='utf-8', mode='w+') encoded = dataset.encode('utf-8') # print "utf8:" , repr(encoded), type(encoded) # print "str or utf8:" , repr(dataset), type(dataset) dsf.write(dataset) dsf.close() class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): global SEED SEED = h2o.setup_random_seed() h2o.init(java_heap_GB=1) @classmethod def tearDownClass(cls): h2o.tear_down_cloud() def test_parse_specific_case5(self): SYNDATASETS_DIR = h2o.make_syn_dir() hex_key = "a.hex" for (dataset, expNumRows, expNumCols, expNaCnt, expType, unicodeNum) in tryList: csvFilename = 'specific_' + str(expNumRows) + str(expNumCols) + '.csv' csvPathname = SYNDATASETS_DIR + '/' + csvFilename write_syn_dataset(csvPathname, dataset) parseResult = h2i.import_parse(path=csvPathname, schema='put', header=0, # force col separator hex_key=hex_key, timeoutSecs=10, doSummary=False, separator=H2O_COL_SEPARATOR) inspect = h2o_cmd.runInspect(None, parseResult['destination_key'], timeoutSecs=60) print "Parsed with special unichr(%s) which is %s:" % (unicodeNum, unichr(unicodeNum)) # print "inspect:", h2o.dump_json(inspect) numRows = inspect['numRows'] self.assertEqual(numRows, expNumRows, msg='Using unichr(0x%x) Wrong numRows: %s Expected: %s' % \ (unicodeNum, numRows, expNumRows)) numCols = inspect['numCols'] self.assertEqual(numCols, expNumCols, msg='Using unichr(0x%x) Wrong numCols: %s Expected: %s' % \ (unicodeNum, numCols, expNumCols)) # this is required for the test setup assert(len(expNaCnt)>=expNumCols) assert(len(expType)>=expNumCols) for k in range(expNumCols): naCnt = inspect['cols'][k]['naCnt'] self.assertEqual(expNaCnt[k], naCnt, msg='Using unichr(0x%x) col: %s naCnt: %d should be: %s' % \ (unicodeNum, k, naCnt, expNaCnt[k])) stype = inspect['cols'][k]['type'] self.assertEqual(expType[k], stype, msg='Using unichr(0x%x) col: %s type: %s should be: %s' % \ (unicodeNum, k, stype, expType[k])) if __name__ == '__main__': h2o.unit_main()
apache-2.0
glouppe/scikit-learn
examples/mixture/plot_gmm.py
35
2875
""" ================================= Gaussian Mixture Model Ellipsoids ================================= Plot the confidence ellipsoids of a mixture of two Gaussians with EM and variational Dirichlet process. Both models have access to five components with which to fit the data. Note that the EM model will necessarily use all five components while the DP model will effectively only use as many as are needed for a good fit. This is a property of the Dirichlet Process prior. Here we can see that the EM model splits some components arbitrarily, because it is trying to fit too many components, while the Dirichlet Process model adapts it number of state automatically. This example doesn't show it, as we're in a low-dimensional space, but another advantage of the Dirichlet process model is that it can fit full covariance matrices effectively even when there are less examples per cluster than there are dimensions in the data, due to regularization properties of the inference algorithm. """ import itertools import numpy as np from scipy import linalg import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import mixture # Number of samples per component n_samples = 500 # Generate random sample, two components np.random.seed(0) C = np.array([[0., -0.1], [1.7, .4]]) X = np.r_[np.dot(np.random.randn(n_samples, 2), C), .7 * np.random.randn(n_samples, 2) + np.array([-6, 3])] # Fit a mixture of Gaussians with EM using five components gmm = mixture.GMM(n_components=5, covariance_type='full') gmm.fit(X) # Fit a Dirichlet process mixture of Gaussians using five components dpgmm = mixture.DPGMM(n_components=5, covariance_type='full') dpgmm.fit(X) color_iter = itertools.cycle(['navy', 'c', 'cornflowerblue', 'gold', 'darkorange']) for i, (clf, title) in enumerate([(gmm, 'GMM'), (dpgmm, 'Dirichlet Process GMM')]): splot = plt.subplot(2, 1, 1 + i) Y_ = clf.predict(X) for i, (mean, covar, color) in enumerate(zip( clf.means_, clf._get_covars(), color_iter)): v, w = linalg.eigh(covar) u = w[0] / linalg.norm(w[0]) # as the DP will not use every component it has access to # unless it needs it, we shouldn't plot the redundant # components. if not np.any(Y_ == i): continue plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) # Plot an ellipse to show the Gaussian component angle = np.arctan(u[1] / u[0]) angle = 180 * angle / np.pi # convert to degrees ell = mpl.patches.Ellipse(mean, v[0], v[1], 180 + angle, color=color) ell.set_clip_box(splot.bbox) ell.set_alpha(0.5) splot.add_artist(ell) plt.xlim(-10, 10) plt.ylim(-3, 6) plt.xticks(()) plt.yticks(()) plt.title(title) plt.show()
bsd-3-clause
sgenoud/scikit-learn
sklearn/semi_supervised/label_propagation.py
4
13783
# coding=utf8 """ Label propagation in the context of this module refers to a set of semisupervised classification algorithms. In the high level, these algorithms work by forming a fully-connected graph between all points given and solving for the steady-state distribution of labels at each point. These algorithms perform very well in practice. The cost of running can be very expensive, at approximately O(N^3) where N is the number of (labeled and unlabeled) points. The theory (why they perform so well) is motivated by intuitions from random walk algorithms and geometric relationships in the data. For more information see the references below. Model Features -------------- Label clamping: The algorithm tries to learn distributions of labels over the dataset. In the "Hard Clamp" mode, the true ground labels are never allowed to change. They are clamped into position. In the "Soft Clamp" mode, they are allowed some wiggle room, but some alpha of their original value will always be retained. Hard clamp is the same as soft clamping with alpha set to 1. Kernel: A function which projects a vector into some higher dimensional space. This implementation supprots RBF and KNN kernels. Using the RBF kernel generates a dense matrix of size O(N^2). KNN kernel will generate a sparse matrix of size O(k*N) which will run much faster. See the documentation for SVMs for more info on kernels. Example ------- >>> from sklearn import datasets >>> from sklearn.semi_supervised import LabelPropagation >>> label_prop_model = LabelPropagation() >>> iris = datasets.load_iris() >>> random_unlabeled_points = np.where(np.random.random_integers(0, 1, ... size=len(iris.target))) >>> labels = np.copy(iris.target) >>> labels[random_unlabeled_points] = -1 >>> label_prop_model.fit(iris.data, labels) ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS LabelPropagation(...) Notes ----- References: [1] Yoshua Bengio, Olivier Delalleau, Nicolas Le Roux. In Semi-Supervised Learning (2006), pp. 193-216 [2] Olivier Delalleau, Yoshua Bengio, Nicolas Le Roux. Efficient Non-Parametric Function Induction in Semi-Supervised Learning. AISTAT 2005 """ # Authors: Clay Woolam <clay@woolam.org> # Licence: BSD import numpy as np from scipy import sparse from abc import ABCMeta, abstractmethod from ..base import BaseEstimator, ClassifierMixin from ..metrics.pairwise import rbf_kernel from ..utils.graph import graph_laplacian from ..utils.extmath import safe_sparse_dot from ..neighbors.unsupervised import NearestNeighbors ### Helper functions def _not_converged(y_truth, y_prediction, tol=1e-3): """basic convergence check""" return np.abs(y_truth - y_prediction).sum() > tol class BaseLabelPropagation(BaseEstimator, ClassifierMixin): """Base class for label propagation module. Parameters ---------- kernel : {'knn', 'rbf'} String identifier for kernel function to use. Only 'rbf' and 'knn' kernels are currently supported.. gamma : float Parameter for rbf kernel alpha : float Clamping factor max_iters : float Change maximum number of iterations allowed tol : float Convergence tolerance: threshold to consider the system at steady state """ __metaclass__ = ABCMeta def __init__(self, kernel='rbf', gamma=20, n_neighbors=7, alpha=1, max_iters=30, tol=1e-3): self.max_iters = max_iters self.tol = tol # kernel parameters self.kernel = kernel self.gamma = gamma self.n_neighbors = n_neighbors # clamping factor self.alpha = alpha def _get_kernel(self, X, y=None): if self.kernel == "rbf": if y is None: return rbf_kernel(X, X, gamma=self.gamma) else: return rbf_kernel(X, y, gamma=self.gamma) elif self.kernel == "knn": if self.nn_fit is None: self.nn_fit = NearestNeighbors(self.n_neighbors).fit(X) if y is None: return self.nn_fit.kneighbors_graph(self.nn_fit._fit_X, self.n_neighbors, mode='connectivity') else: return self.nn_fit.kneighbors(y, return_distance=False) else: raise ValueError("%s is not a valid kernel. Only rbf and knn" " are supported at this time" % self.kernel) @abstractmethod def _build_graph(self): raise NotImplementedError("Graph construction must be implemented" " to fit a label propagation model.") def predict(self, X): """Performs inductive inference across the model. Parameters ---------- X : array_like, shape = [n_samples, n_features] Returns ------- y : array_like, shape = [n_samples] Predictions for input data """ probas = self.predict_proba(X) return self.classes_[np.argmax(probas, axis=1)].ravel() def predict_proba(self, X): """Predict probability for each possible outcome. Compute the probability estimates for each single sample in X and each possible outcome seen during training (categorical distribution). Parameters ---------- X : array_like, shape = [n_samples, n_features] Returns ------- probabilities : array, shape = [n_samples, n_classes] Normalized probability distributions across class labels """ if sparse.isspmatrix(X): X_2d = X else: X_2d = np.atleast_2d(X) weight_matrices = self._get_kernel(self.X_, X_2d) if self.kernel == 'knn': probabilities = [] for weight_matrix in weight_matrices: ine = np.sum(self.label_distributions_[weight_matrix], axis=0) probabilities.append(ine) probabilities = np.array(probabilities) else: weight_matrices = weight_matrices.T probabilities = np.dot(weight_matrices, self.label_distributions_) normalizer = np.atleast_2d(np.sum(probabilities, axis=1)).T probabilities /= normalizer return probabilities def fit(self, X, y): """Fit a semi-supervised label propagation model based All the input data is provided matrix X (labeled and unlabeled) and corresponding label matrix y with a dedicated marker value for unlabeled samples. Parameters ---------- X : array-like, shape = [n_samples, n_features] A {n_samples by n_samples} size matrix will be created from this y : array_like, shape = [n_samples] n_labeled_samples (unlabeled points are marked as -1) All unlabeled samples will be transductively assigned labels Returns ------- self : returns an instance of self. """ if sparse.isspmatrix(X): self.X_ = X else: self.X_ = np.asarray(X) # actual graph construction (implementations should override this) graph_matrix = self._build_graph() # label construction # construct a categorical distribution for classification only classes = np.unique(y) classes = (classes[classes != -1]) self.classes_ = classes n_samples, n_classes = len(y), len(classes) y = np.asarray(y) unlabeled = y == -1 clamp_weights = np.ones((n_samples, 1)) clamp_weights[unlabeled, 0] = self.alpha # initialize distributions self.label_distributions_ = np.zeros((n_samples, n_classes)) for label in classes: self.label_distributions_[y == label, classes == label] = 1 y_static = np.copy(self.label_distributions_) if self.alpha > 0.: y_static *= 1 - self.alpha y_static[unlabeled] = 0 l_previous = np.zeros((self.X_.shape[0], n_classes)) remaining_iter = self.max_iters if sparse.isspmatrix(graph_matrix): graph_matrix = graph_matrix.tocsr() while (_not_converged(self.label_distributions_, l_previous, self.tol) and remaining_iter > 1): l_previous = self.label_distributions_ self.label_distributions_ = safe_sparse_dot(graph_matrix, self.label_distributions_) # clamp self.label_distributions_ = np.multiply(clamp_weights, self.label_distributions_) + y_static remaining_iter -= 1 normalizer = np.sum(self.label_distributions_, axis=1)[:, np.newaxis] self.label_distributions_ /= normalizer # set the transduction item transduction = self.classes_[np.argmax(self.label_distributions_, axis=1)] self.transduction_ = transduction.ravel() return self class LabelPropagation(BaseLabelPropagation): """Label Propagation classifier Parameters ---------- kernel : {'knn', 'rbf'} String identifier for kernel function to use. Only 'rbf' and 'knn' kernels are currently supported.. gamma : float parameter for rbf kernel n_neighbors : integer > 0 parameter for knn kernel alpha : float clamping factor max_iters : float change maximum number of iterations allowed tol : float Convergence tolerance: threshold to consider the system at steady state Examples -------- >>> from sklearn import datasets >>> from sklearn.semi_supervised import LabelPropagation >>> label_prop_model = LabelPropagation() >>> iris = datasets.load_iris() >>> random_unlabeled_points = np.where(np.random.random_integers(0, 1, ... size=len(iris.target))) >>> labels = np.copy(iris.target) >>> labels[random_unlabeled_points] = -1 >>> label_prop_model.fit(iris.data, labels) ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS LabelPropagation(...) References ---------- Xiaojin Zhu and Zoubin Ghahramani. Learning from labeled and unlabeled data with label propagation. Technical Report CMU-CALD-02-107, Carnegie Mellon University, 2002 http://pages.cs.wisc.edu/~jerryzhu/pub/CMU-CALD-02-107.pdf See Also -------- LabelSpreading : Alternate label proagation strategy more robust to noise """ def _build_graph(self): """Matrix representing a fully connected graph between each sample This basic implementation creates a non-stochastic affinity matrix, so class distributions will exceed 1 (normalization may be desired). """ if self.kernel == 'knn': self.nn_fit = None affinity_matrix = self._get_kernel(self.X_) normalizer = affinity_matrix.sum(axis=0) if sparse.isspmatrix(affinity_matrix): affinity_matrix.data /= np.diag(np.array(normalizer)) else: affinity_matrix /= normalizer[:, np.newaxis] return affinity_matrix class LabelSpreading(BaseLabelPropagation): """LabelSpreading model for semi-supervised learning This model is similar to the basic Label Propgation algorithm, but uses affinity matrix based on the normalized graph Laplacian and soft clamping across the labels. Parameters ---------- kernel : {'knn', 'rbf'} String identifier for kernel function to use. Only 'rbf' and 'knn' kernels are currently supported. gamma : float parameter for rbf kernel n_neighbors : integer > 0 parameter for knn kernel alpha : float clamping factor max_iters : float maximum number of iterations allowed tol : float Convergence tolerance: threshold to consider the system at steady state Examples -------- >>> from sklearn import datasets >>> from sklearn.semi_supervised import LabelSpreading >>> label_prop_model = LabelSpreading() >>> iris = datasets.load_iris() >>> random_unlabeled_points = np.where(np.random.random_integers(0, 1, ... size=len(iris.target))) >>> labels = np.copy(iris.target) >>> labels[random_unlabeled_points] = -1 >>> label_prop_model.fit(iris.data, labels) ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS LabelSpreading(...) References ---------- Dengyong Zhou, Olivier Bousquet, Thomas Navin Lal, Jason Weston, Bernhard Schölkopf. Learning with local and global consistency (2004) http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.115.3219 See Also -------- LabelPropagation : Unregularized graph based semi-supervised learning """ def __init__(self, kernel='rbf', gamma=20, n_neighbors=7, alpha=0.2, max_iters=30, tol=1e-3): # this one has different base parameters super(LabelSpreading, self).__init__(kernel=kernel, gamma=gamma, n_neighbors=n_neighbors, alpha=alpha, max_iters=max_iters, tol=tol) def _build_graph(self): """Graph matrix for Label Spreading computes the graph laplacian""" # compute affinity matrix (or gram matrix) if self.kernel == 'knn': self.nn_fit = None n_samples = self.X_.shape[0] affinity_matrix = self._get_kernel(self.X_) laplacian = graph_laplacian(affinity_matrix, normed=True) laplacian = -laplacian if sparse.isspmatrix(laplacian): diag_mask = (laplacian.row == laplacian.col) laplacian.data[diag_mask] = 0.0 else: laplacian.flat[::n_samples + 1] = 0.0 # set diag to 0.0 return laplacian
bsd-3-clause
mlflow/mlflow
examples/ray_serve/train_model.py
1
1302
import mlflow from sklearn.datasets import load_iris from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import mean_squared_error from sklearn.utils import shuffle if __name__ == "__main__": # Enable auto-logging mlflow.set_tracking_uri("sqlite:///mlruns.db") mlflow.sklearn.autolog() # Load data iris_dataset = load_iris() data, target, target_names = ( iris_dataset["data"], iris_dataset["target"], iris_dataset["target_names"], ) # Instantiate model model = GradientBoostingClassifier() # Split training and validation data data, target = shuffle(data, target) train_x, train_y = data[:100], target[:100] val_x, val_y = data[100:], target[100:] # Train and evaluate model model.fit(train_x, train_y) run_id = mlflow.last_active_run().info.run_id print("MSE:", mean_squared_error(model.predict(val_x), val_y)) print("Target names: ", target_names) print("run_id: {}".format(run_id)) # Register the auto-logged model model_uri = "runs:/{}/model".format(run_id) registered_model_name = "RayMLflowIntegration" mv = mlflow.register_model(model_uri, registered_model_name) print("Name: {}".format(mv.name)) print("Version: {}".format(mv.version))
apache-2.0
mileistone/test
vedanet/models/yolo_abc.py
1
2243
# # Darknet YOLOv2 model # Copyright EAVISE # import os from collections import OrderedDict, Iterable import torch import torch.nn as nn from .. import data as vnd from ._darknet import Darknet __all__ = ['YoloABC'] class YoloABC(Darknet): def __init__(self): """ Network initialisation """ super().__init__() # Parameters self.num_classes = None self.anchors = None self.anchors_mask = None self.nloss = None self.loss = None self.postprocess = None self.is_train = None self.test_args = None # Network # backbone #self.backbone = backbone() # head #self.head = head() #if weights_file is not None: # self.load_weights(weights_file, clear) def _forward(self, x): pass def compose(self, x, features, loss_fn): """ generate loss and postprocess """ if self.is_train: if self.loss is None: self.loss = [] # for training for idx in range(self.nloss): reduction = float(x.shape[2] / features[idx].shape[2]) # n, c, h, w self.loss.append(loss_fn(self.num_classes, self.anchors, self.anchors_mask[idx], reduction, self.seen, head_idx=idx)) else: if self.postprocess is None: self.postprocess = [] # for testing conf_thresh = self.test_args['conf_thresh'] network_size = self.test_args['network_size'] labels = self.test_args['labels'] for idx in range(self.nloss): reduction = float(x.shape[2] / features[idx].shape[2]) # n, c, h, w cur_anchors = [self.anchors[ii] for ii in self.anchors_mask[idx]] cur_anchors = [(ii[0] / reduction, ii[1] / reduction) for ii in cur_anchors] # abs to relative self.postprocess.append(vnd.transform.Compose([ vnd.transform.GetBoundingBoxes(self.num_classes, cur_anchors, conf_thresh), vnd.transform.TensorToBrambox(network_size, labels) ]))
mit
glouppe/scikit-learn
examples/neighbors/plot_classification.py
285
1790
""" ================================ Nearest Neighbors Classification ================================ Sample usage of Nearest Neighbors classification. It will plot the decision boundaries for each class. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets n_neighbors = 15 # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim dataset y = iris.target h = .02 # step size in the mesh # Create color maps cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) for weights in ['uniform', 'distance']: # we create an instance of Neighbours Classifier and fit the data. clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights) clf.fit(X, y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure() plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.title("3-Class classification (k = %i, weights = '%s')" % (n_neighbors, weights)) plt.show()
bsd-3-clause
glouppe/scikit-learn
examples/cluster/plot_lena_segmentation.py
269
2444
""" ========================================= Segmenting the picture of Lena in regions ========================================= This example uses :ref:`spectral_clustering` on a graph created from voxel-to-voxel difference on an image to break this image into multiple partly-homogeneous regions. This procedure (spectral clustering on an image) is an efficient approximate solution for finding normalized graph cuts. There are two options to assign labels: * with 'kmeans' spectral clustering will cluster samples in the embedding space using a kmeans algorithm * whereas 'discrete' will iteratively search for the closest partition space to the embedding space. """ print(__doc__) # Author: Gael Varoquaux <gael.varoquaux@normalesup.org>, Brian Cheung # License: BSD 3 clause import time import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering lena = sp.misc.lena() # Downsample the image by a factor of 4 lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2] lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2] # Convert the image into a graph with the value of the gradient on the # edges. graph = image.img_to_graph(lena) # Take a decreasing function of the gradient: an exponential # The smaller beta is, the more independent the segmentation is of the # actual image. For beta=1, the segmentation is close to a voronoi beta = 5 eps = 1e-6 graph.data = np.exp(-beta * graph.data / lena.std()) + eps # Apply spectral clustering (this step goes much faster if you have pyamg # installed) N_REGIONS = 11 ############################################################################### # Visualize the resulting regions for assign_labels in ('kmeans', 'discretize'): t0 = time.time() labels = spectral_clustering(graph, n_clusters=N_REGIONS, assign_labels=assign_labels, random_state=1) t1 = time.time() labels = labels.reshape(lena.shape) plt.figure(figsize=(5, 5)) plt.imshow(lena, cmap=plt.cm.gray) for l in range(N_REGIONS): plt.contour(labels == l, contours=1, colors=[plt.cm.spectral(l / float(N_REGIONS)), ]) plt.xticks(()) plt.yticks(()) plt.title('Spectral clustering: %s, %.2fs' % (assign_labels, (t1 - t0))) plt.show()
bsd-3-clause
mlperf/training_results_v0.5
v0.5.0/nvidia/submission/code/translation/pytorch/eval_lm.py
7
4361
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch from fairseq import data, options, progress_bar, tasks, utils from fairseq.meters import StopwatchMeter, TimeMeter from fairseq.sequence_scorer import SequenceScorer def main(args): assert args.path is not None, '--path required for evaluation!' args.tokens_per_sample = getattr(args, 'tokens_per_sample', 1024) print(args) use_cuda = torch.cuda.is_available() and not args.cpu # Load dataset splits task = tasks.setup_task(args) task.load_dataset(args.gen_subset) print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset)))) # Load ensemble print('| loading model(s) from {}'.format(args.path)) models, _ = utils.load_ensemble_for_inference(args.path.split(':'), task) # Optimize ensemble for generation and set the source and dest dicts on the model (required by scorer) for model in models: model.make_generation_fast_() if args.fp16: model.half() assert len(models) > 0 itr = data.EpochBatchIterator( dataset=task.dataset(args.gen_subset), max_tokens=args.max_tokens or 36000, max_sentences=args.max_sentences, max_positions=models[0].max_positions(), num_shards=args.num_shards, shard_id=args.shard_id, ignore_invalid_inputs=True, ).next_epoch_itr(shuffle=False) gen_timer = StopwatchMeter() scorer = SequenceScorer(models, task.target_dictionary) if use_cuda: scorer.cuda() score_sum = 0. count = 0 if args.remove_bpe is not None: bpe_cont = args.remove_bpe.rstrip() bpe_toks = set(i for i in range(len(task.dictionary)) if task.dictionary[i].endswith(bpe_cont)) bpe_len = len(bpe_cont) else: bpe_toks = None bpe_len = 0 with progress_bar.build_progress_bar(args, itr) as t: results = scorer.score_batched_itr(t, cuda=use_cuda, timer=gen_timer) wps_meter = TimeMeter() for _, src_tokens, __, hypos in results: for hypo in hypos: pos_scores = hypo['positional_scores'] skipped_toks = 0 if bpe_toks is not None: for i in range(len(hypo['tokens']) - 1): if hypo['tokens'][i].item() in bpe_toks: skipped_toks += 1 pos_scores[i + 1] += pos_scores[i] pos_scores[i] = 0 inf_scores = pos_scores.eq(float('inf')) | pos_scores.eq(float('-inf')) if inf_scores.any(): print('| Skipping tokens with inf scores:', task.target_dictionary.string(hypo['tokens'][inf_scores.nonzero()])) pos_scores = pos_scores[(~inf_scores).nonzero()] score_sum += pos_scores.sum() count += pos_scores.numel() - skipped_toks if args.output_word_probs: w = '' word_prob = [] for i in range(len(hypo['tokens'])): w_ind = hypo['tokens'][i].item() w += task.dictionary[w_ind] if bpe_toks is not None and w_ind in bpe_toks: w = w[:-bpe_len] else: word_prob.append((w, pos_scores[i].item())) w = '' print('\t'.join('{} [{:2f}]'.format(x[0], x[1]) for x in word_prob)) wps_meter.update(src_tokens.size(0)) t.log({'wps': round(wps_meter.avg)}) avg_nll_loss = -score_sum / count print('| Evaluated {} tokens in {:.1f}s ({:.2f} tokens/s)'.format(gen_timer.n, gen_timer.sum, 1. / gen_timer.avg)) print('| Loss: {:.4f}, Perplexity: {:.2f}'.format(avg_nll_loss, np.exp(avg_nll_loss))) if __name__ == '__main__': parser = options.get_eval_lm_parser() args = options.parse_args_and_arch(parser) main(args)
apache-2.0
mlflow/mlflow
mlflow/mleap.py
1
12700
""" The ``mlflow.mleap`` module provides an API for saving Spark MLLib models using the `MLeap <https://github.com/combust/mleap>`_ persistence mechanism. NOTE: You cannot load the MLeap model flavor in Python; you must download it using the Java API method ``downloadArtifacts(String runId)`` and load the model using the method ``MLeapLoader.loadPipeline(String modelRootPath)``. """ import logging import os import sys import traceback import mlflow from mlflow.models import Model from mlflow.models.model import MLMODEL_FILE_NAME from mlflow.exceptions import MlflowException from mlflow.models.signature import ModelSignature from mlflow.models.utils import ModelInputExample, _save_example from mlflow.utils import reraise from mlflow.utils.annotations import keyword_only FLAVOR_NAME = "mleap" _logger = logging.getLogger(__name__) @keyword_only def log_model( spark_model, sample_input, artifact_path, registered_model_name=None, signature: ModelSignature = None, input_example: ModelInputExample = None, ): """ Log a Spark MLLib model in MLeap format as an MLflow artifact for the current run. The logged model will have the MLeap flavor. NOTE: You cannot load the MLeap model flavor in Python; you must download it using the Java API method ``downloadArtifacts(String runId)`` and load the model using the method ``MLeapLoader.loadPipeline(String modelRootPath)``. :param spark_model: Spark PipelineModel to be saved. This model must be MLeap-compatible and cannot contain any custom transformers. :param sample_input: Sample PySpark DataFrame input that the model can evaluate. This is required by MLeap for data schema inference. :param artifact_path: Run-relative artifact path. :param registered_model_name: If given, create a model version under ``registered_model_name``, also creating a registered model if one with the given name does not exist. :param signature: :py:class:`ModelSignature <mlflow.models.ModelSignature>` describes model input and output :py:class:`Schema <mlflow.types.Schema>`. The model signature can be :py:func:`inferred <mlflow.models.infer_signature>` from datasets with valid model input (e.g. the training dataset with target column omitted) and valid model output (e.g. model predictions generated on the training dataset), for example: .. code-block:: python from mlflow.models.signature import infer_signature train = df.drop_column("target_label") predictions = ... # compute model predictions signature = infer_signature(train, predictions) :param input_example: Input example provides one or several instances of valid model input. The example can be used as a hint of what data to feed the model. The given example will be converted to a Pandas DataFrame and then serialized to json using the Pandas split-oriented format. Bytes are base64-encoded. :return: A :py:class:`ModelInfo <mlflow.models.model.ModelInfo>` instance that contains the metadata of the logged model. .. code-block:: python :caption: Example import mlflow import mlflow.mleap import pyspark from pyspark.ml import Pipeline from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import HashingTF, Tokenizer # training DataFrame training = spark.createDataFrame([ (0, "a b c d e spark", 1.0), (1, "b d", 0.0), (2, "spark f g h", 1.0), (3, "hadoop mapreduce", 0.0) ], ["id", "text", "label"]) # testing DataFrame test_df = spark.createDataFrame([ (4, "spark i j k"), (5, "l m n"), (6, "spark hadoop spark"), (7, "apache hadoop")], ["id", "text"]) # Create an MLlib pipeline tokenizer = Tokenizer(inputCol="text", outputCol="words") hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features") lr = LogisticRegression(maxIter=10, regParam=0.001) pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) model = pipeline.fit(training) # log parameters mlflow.log_param("max_iter", 10) mlflow.log_param("reg_param", 0.001) # log the Spark MLlib model in MLeap format mlflow.mleap.log_model(spark_model=model, sample_input=test_df, artifact_path="mleap-model") """ return Model.log( artifact_path=artifact_path, flavor=mlflow.mleap, spark_model=spark_model, sample_input=sample_input, registered_model_name=registered_model_name, signature=signature, input_example=input_example, ) @keyword_only def save_model( spark_model, sample_input, path, mlflow_model=None, signature: ModelSignature = None, input_example: ModelInputExample = None, ): """ Save a Spark MLlib PipelineModel in MLeap format at a local path. The saved model will have the MLeap flavor. NOTE: You cannot load the MLeap model flavor in Python; you must download it using the Java API method ``downloadArtifacts(String runId)`` and load the model using the method ``MLeapLoader.loadPipeline(String modelRootPath)``. :param spark_model: Spark PipelineModel to be saved. This model must be MLeap-compatible and cannot contain any custom transformers. :param sample_input: Sample PySpark DataFrame input that the model can evaluate. This is required by MLeap for data schema inference. :param path: Local path where the model is to be saved. :param mlflow_model: :py:mod:`mlflow.models.Model` to which this flavor is being added. :param signature: :py:class:`ModelSignature <mlflow.models.ModelSignature>` describes model input and output :py:class:`Schema <mlflow.types.Schema>`. The model signature can be :py:func:`inferred <mlflow.models.infer_signature>` from datasets with valid model input (e.g. the training dataset) and valid model output (e.g. model predictions generated on the training dataset), for example: .. code-block:: python from mlflow.models.signature import infer_signature train = df.drop_column("target_label") signature = infer_signature(train, model.predict(train)) :param input_example: Input example provides one or several instances of valid model input. The example can be used as a hint of what data to feed the model. The given example will be converted to a Pandas DataFrame and then serialized to json using the Pandas split-oriented format. Bytes are base64-encoded. :param signature: :py:class:`ModelSignature <mlflow.models.ModelSignature>` describes model input and output :py:class:`Schema <mlflow.types.Schema>`. The model signature can be :py:func:`inferred <mlflow.models.infer_signature>` from datasets with valid model input (e.g. the training dataset with target column omitted) and valid model output (e.g. model predictions generated on the training dataset), for example: .. code-block:: python from mlflow.models.signature import infer_signature train = df.drop_column("target_label") predictions = ... # compute model predictions signature = infer_signature(train, predictions) :param input_example: Input example provides one or several instances of valid model input. The example can be used as a hint of what data to feed the model. The given example will be converted to a Pandas DataFrame and then serialized to json using the Pandas split-oriented format. Bytes are base64-encoded. """ if mlflow_model is None: mlflow_model = Model() add_to_model( mlflow_model=mlflow_model, path=path, spark_model=spark_model, sample_input=sample_input ) if signature is not None: mlflow_model.signature = signature if input_example is not None: _save_example(mlflow_model, input_example, path) mlflow_model.save(os.path.join(path, MLMODEL_FILE_NAME)) @keyword_only def add_to_model(mlflow_model, path, spark_model, sample_input): """ Add the MLeap flavor to an existing MLflow model. :param mlflow_model: :py:mod:`mlflow.models.Model` to which this flavor is being added. :param path: Path of the model to which this flavor is being added. :param spark_model: Spark PipelineModel to be saved. This model must be MLeap-compatible and cannot contain any custom transformers. :param sample_input: Sample PySpark DataFrame input that the model can evaluate. This is required by MLeap for data schema inference. """ from pyspark.ml.pipeline import PipelineModel from pyspark.sql import DataFrame import mleap.version # This import statement adds `serializeToBundle` and `deserializeFromBundle` to `Transformer`: # https://github.com/combust/mleap/blob/37f6f61634798118e2c2eb820ceeccf9d234b810/python/mleap/pyspark/spark_support.py#L32-L33 from mleap.pyspark.spark_support import SimpleSparkSerializer # pylint: disable=unused-import from py4j.protocol import Py4JError if not isinstance(spark_model, PipelineModel): raise Exception("Not a PipelineModel. MLeap can save only PipelineModels.") if sample_input is None: raise Exception("A sample input must be specified in order to add the MLeap flavor.") if not isinstance(sample_input, DataFrame): raise Exception( "The sample input must be a PySpark dataframe of type `{df_type}`".format( df_type=DataFrame.__module__ ) ) # MLeap's model serialization routine requires an absolute output path path = os.path.abspath(path) mleap_path_full = os.path.join(path, "mleap") mleap_datapath_sub = os.path.join("mleap", "model") mleap_datapath_full = os.path.join(path, mleap_datapath_sub) if os.path.exists(mleap_path_full): raise Exception( "MLeap model data path already exists at: {path}".format(path=mleap_path_full) ) os.makedirs(mleap_path_full) dataset = spark_model.transform(sample_input) model_path = "file:{mp}".format(mp=mleap_datapath_full) try: spark_model.serializeToBundle(path=model_path, dataset=dataset) except Py4JError: _handle_py4j_error( MLeapSerializationException, "MLeap encountered an error while serializing the model. Ensure that the model is" " compatible with MLeap (i.e does not contain any custom transformers).", ) try: mleap_version = mleap.version.__version__ _logger.warning( "Detected old mleap version %s. Support for logging models in mleap format with " "mleap versions 0.15.0 and below is deprecated and will be removed in a future " "MLflow release. Please upgrade to a newer mleap version.", mleap_version, ) except AttributeError: mleap_version = mleap.version mlflow_model.add_flavor(FLAVOR_NAME, mleap_version=mleap_version, model_data=mleap_datapath_sub) def _handle_py4j_error(reraised_error_type, reraised_error_text): """ Logs information about an exception that is currently being handled and reraises it with the specified error text as a message. """ traceback.print_exc() tb = sys.exc_info()[2] reraise(reraised_error_type, reraised_error_type(reraised_error_text), tb) class MLeapSerializationException(MlflowException): """Exception thrown when a model or DataFrame cannot be serialized in MLeap format."""
apache-2.0
LohithBlaze/scikit-learn
sklearn/ensemble/voting_classifier.py
177
8006
""" Soft Voting/Majority Rule classifier. This module contains a Soft Voting/Majority Rule classifier for classification estimators. """ # Authors: Sebastian Raschka <se.raschka@gmail.com>, # Gilles Louppe <g.louppe@gmail.com> # # Licence: BSD 3 clause import numpy as np from ..base import BaseEstimator from ..base import ClassifierMixin from ..base import TransformerMixin from ..base import clone from ..preprocessing import LabelEncoder from ..externals import six class VotingClassifier(BaseEstimator, ClassifierMixin, TransformerMixin): """Soft Voting/Majority Rule classifier for unfitted estimators. Read more in the :ref:`User Guide <voting_classifier>`. Parameters ---------- estimators : list of (string, estimator) tuples Invoking the `fit` method on the `VotingClassifier` will fit clones of those original estimators that will be stored in the class attribute `self.estimators_`. voting : str, {'hard', 'soft'} (default='hard') If 'hard', uses predicted class labels for majority rule voting. Else if 'soft', predicts the class label based on the argmax of the sums of the predicted probalities, which is recommended for an ensemble of well-calibrated classifiers. weights : array-like, shape = [n_classifiers], optional (default=`None`) Sequence of weights (`float` or `int`) to weight the occurances of predicted class labels (`hard` voting) or class probabilities before averaging (`soft` voting). Uses uniform weights if `None`. Attributes ---------- classes_ : array-like, shape = [n_predictions] Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.ensemble import RandomForestClassifier >>> clf1 = LogisticRegression(random_state=1) >>> clf2 = RandomForestClassifier(random_state=1) >>> clf3 = GaussianNB() >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> eclf1 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard') >>> eclf1 = eclf1.fit(X, y) >>> print(eclf1.predict(X)) [1 1 1 2 2 2] >>> eclf2 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], ... voting='soft') >>> eclf2 = eclf2.fit(X, y) >>> print(eclf2.predict(X)) [1 1 1 2 2 2] >>> eclf3 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], ... voting='soft', weights=[2,1,1]) >>> eclf3 = eclf3.fit(X, y) >>> print(eclf3.predict(X)) [1 1 1 2 2 2] >>> """ def __init__(self, estimators, voting='hard', weights=None): self.estimators = estimators self.named_estimators = dict(estimators) self.voting = voting self.weights = weights def fit(self, X, y): """ Fit the estimators. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] Target values. Returns ------- self : object """ if isinstance(y, np.ndarray) and len(y.shape) > 1 and y.shape[1] > 1: raise NotImplementedError('Multilabel and multi-output' ' classification is not supported.') if self.voting not in ('soft', 'hard'): raise ValueError("Voting must be 'soft' or 'hard'; got (voting=%r)" % self.voting) if self.weights and len(self.weights) != len(self.estimators): raise ValueError('Number of classifiers and weights must be equal' '; got %d weights, %d estimators' % (len(self.weights), len(self.estimators))) self.le_ = LabelEncoder() self.le_.fit(y) self.classes_ = self.le_.classes_ self.estimators_ = [] for name, clf in self.estimators: fitted_clf = clone(clf).fit(X, self.le_.transform(y)) self.estimators_.append(fitted_clf) return self def predict(self, X): """ Predict class labels for X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ---------- maj : array-like, shape = [n_samples] Predicted class labels. """ if self.voting == 'soft': maj = np.argmax(self.predict_proba(X), axis=1) else: # 'hard' voting predictions = self._predict(X) maj = np.apply_along_axis(lambda x: np.argmax(np.bincount(x, weights=self.weights)), axis=1, arr=predictions) maj = self.le_.inverse_transform(maj) return maj def _collect_probas(self, X): """Collect results from clf.predict calls. """ return np.asarray([clf.predict_proba(X) for clf in self.estimators_]) def _predict_proba(self, X): """Predict class probabilities for X in 'soft' voting """ avg = np.average(self._collect_probas(X), axis=0, weights=self.weights) return avg @property def predict_proba(self): """Compute probabilities of possible outcomes for samples in X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ---------- avg : array-like, shape = [n_samples, n_classes] Weighted average probability for each class per sample. """ if self.voting == 'hard': raise AttributeError("predict_proba is not available when" " voting=%r" % self.voting) return self._predict_proba def transform(self, X): """Return class labels or probabilities for X for each estimator. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- If `voting='soft'`: array-like = [n_classifiers, n_samples, n_classes] Class probabilties calculated by each classifier. If `voting='hard'`: array-like = [n_classifiers, n_samples] Class labels predicted by each classifier. """ if self.voting == 'soft': return self._collect_probas(X) else: return self._predict(X) def get_params(self, deep=True): """Return estimator parameter names for GridSearch support""" if not deep: return super(VotingClassifier, self).get_params(deep=False) else: out = super(VotingClassifier, self).get_params(deep=False) out.update(self.named_estimators.copy()) for name, step in six.iteritems(self.named_estimators): for key, value in six.iteritems(step.get_params(deep=True)): out['%s__%s' % (name, key)] = value return out def _predict(self, X): """Collect results from clf.predict calls. """ return np.asarray([clf.predict(X) for clf in self.estimators_]).T
bsd-3-clause
jnewland/home-assistant
homeassistant/components/android_ip_webcam/__init__.py
5
9513
"""Support for Android IP Webcam.""" import asyncio import logging from datetime import timedelta import voluptuous as vol from homeassistant.core import callback from homeassistant.const import ( CONF_NAME, CONF_HOST, CONF_PORT, CONF_USERNAME, CONF_PASSWORD, CONF_SENSORS, CONF_SWITCHES, CONF_TIMEOUT, CONF_SCAN_INTERVAL, CONF_PLATFORM) from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_send, async_dispatcher_connect) from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util.dt import utcnow from homeassistant.components.mjpeg.camera import ( CONF_MJPEG_URL, CONF_STILL_IMAGE_URL) _LOGGER = logging.getLogger(__name__) ATTR_AUD_CONNS = 'Audio Connections' ATTR_HOST = 'host' ATTR_VID_CONNS = 'Video Connections' CONF_MOTION_SENSOR = 'motion_sensor' DATA_IP_WEBCAM = 'android_ip_webcam' DEFAULT_NAME = 'IP Webcam' DEFAULT_PORT = 8080 DEFAULT_TIMEOUT = 10 DOMAIN = 'android_ip_webcam' SCAN_INTERVAL = timedelta(seconds=10) SIGNAL_UPDATE_DATA = 'android_ip_webcam_update' KEY_MAP = { 'audio_connections': 'Audio Connections', 'adet_limit': 'Audio Trigger Limit', 'antibanding': 'Anti-banding', 'audio_only': 'Audio Only', 'battery_level': 'Battery Level', 'battery_temp': 'Battery Temperature', 'battery_voltage': 'Battery Voltage', 'coloreffect': 'Color Effect', 'exposure': 'Exposure Level', 'exposure_lock': 'Exposure Lock', 'ffc': 'Front-facing Camera', 'flashmode': 'Flash Mode', 'focus': 'Focus', 'focus_homing': 'Focus Homing', 'focus_region': 'Focus Region', 'focusmode': 'Focus Mode', 'gps_active': 'GPS Active', 'idle': 'Idle', 'ip_address': 'IPv4 Address', 'ipv6_address': 'IPv6 Address', 'ivideon_streaming': 'Ivideon Streaming', 'light': 'Light Level', 'mirror_flip': 'Mirror Flip', 'motion': 'Motion', 'motion_active': 'Motion Active', 'motion_detect': 'Motion Detection', 'motion_event': 'Motion Event', 'motion_limit': 'Motion Limit', 'night_vision': 'Night Vision', 'night_vision_average': 'Night Vision Average', 'night_vision_gain': 'Night Vision Gain', 'orientation': 'Orientation', 'overlay': 'Overlay', 'photo_size': 'Photo Size', 'pressure': 'Pressure', 'proximity': 'Proximity', 'quality': 'Quality', 'scenemode': 'Scene Mode', 'sound': 'Sound', 'sound_event': 'Sound Event', 'sound_timeout': 'Sound Timeout', 'torch': 'Torch', 'video_connections': 'Video Connections', 'video_chunk_len': 'Video Chunk Length', 'video_recording': 'Video Recording', 'video_size': 'Video Size', 'whitebalance': 'White Balance', 'whitebalance_lock': 'White Balance Lock', 'zoom': 'Zoom' } ICON_MAP = { 'audio_connections': 'mdi:speaker', 'battery_level': 'mdi:battery', 'battery_temp': 'mdi:thermometer', 'battery_voltage': 'mdi:battery-charging-100', 'exposure_lock': 'mdi:camera', 'ffc': 'mdi:camera-front-variant', 'focus': 'mdi:image-filter-center-focus', 'gps_active': 'mdi:crosshairs-gps', 'light': 'mdi:flashlight', 'motion': 'mdi:run', 'night_vision': 'mdi:weather-night', 'overlay': 'mdi:monitor', 'pressure': 'mdi:gauge', 'proximity': 'mdi:map-marker-radius', 'quality': 'mdi:quality-high', 'sound': 'mdi:speaker', 'sound_event': 'mdi:speaker', 'sound_timeout': 'mdi:speaker', 'torch': 'mdi:white-balance-sunny', 'video_chunk_len': 'mdi:video', 'video_connections': 'mdi:eye', 'video_recording': 'mdi:record-rec', 'whitebalance_lock': 'mdi:white-balance-auto' } SWITCHES = ['exposure_lock', 'ffc', 'focus', 'gps_active', 'motion_detect', 'night_vision', 'overlay', 'torch', 'whitebalance_lock', 'video_recording'] SENSORS = ['audio_connections', 'battery_level', 'battery_temp', 'battery_voltage', 'light', 'motion', 'pressure', 'proximity', 'sound', 'video_connections'] CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.All(cv.ensure_list, [vol.Schema({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, vol.Inclusive(CONF_USERNAME, 'authentication'): cv.string, vol.Inclusive(CONF_PASSWORD, 'authentication'): cv.string, vol.Optional(CONF_SWITCHES): vol.All(cv.ensure_list, [vol.In(SWITCHES)]), vol.Optional(CONF_SENSORS): vol.All(cv.ensure_list, [vol.In(SENSORS)]), vol.Optional(CONF_MOTION_SENSOR): cv.boolean, })]) }, extra=vol.ALLOW_EXTRA) async def async_setup(hass, config): """Set up the IP Webcam component.""" from pydroid_ipcam import PyDroidIPCam webcams = hass.data[DATA_IP_WEBCAM] = {} websession = async_get_clientsession(hass) async def async_setup_ipcamera(cam_config): """Set up an IP camera.""" host = cam_config[CONF_HOST] username = cam_config.get(CONF_USERNAME) password = cam_config.get(CONF_PASSWORD) name = cam_config[CONF_NAME] interval = cam_config[CONF_SCAN_INTERVAL] switches = cam_config.get(CONF_SWITCHES) sensors = cam_config.get(CONF_SENSORS) motion = cam_config.get(CONF_MOTION_SENSOR) # Init ip webcam cam = PyDroidIPCam( hass.loop, websession, host, cam_config[CONF_PORT], username=username, password=password, timeout=cam_config[CONF_TIMEOUT] ) if switches is None: switches = [setting for setting in cam.enabled_settings if setting in SWITCHES] if sensors is None: sensors = [sensor for sensor in cam.enabled_sensors if sensor in SENSORS] sensors.extend(['audio_connections', 'video_connections']) if motion is None: motion = 'motion_active' in cam.enabled_sensors async def async_update_data(now): """Update data from IP camera in SCAN_INTERVAL.""" await cam.update() async_dispatcher_send(hass, SIGNAL_UPDATE_DATA, host) async_track_point_in_utc_time( hass, async_update_data, utcnow() + interval) await async_update_data(None) # Load platforms webcams[host] = cam mjpeg_camera = { CONF_PLATFORM: 'mjpeg', CONF_MJPEG_URL: cam.mjpeg_url, CONF_STILL_IMAGE_URL: cam.image_url, CONF_NAME: name, } if username and password: mjpeg_camera.update({ CONF_USERNAME: username, CONF_PASSWORD: password }) hass.async_create_task(discovery.async_load_platform( hass, 'camera', 'mjpeg', mjpeg_camera, config)) if sensors: hass.async_create_task(discovery.async_load_platform( hass, 'sensor', DOMAIN, { CONF_NAME: name, CONF_HOST: host, CONF_SENSORS: sensors, }, config)) if switches: hass.async_create_task(discovery.async_load_platform( hass, 'switch', DOMAIN, { CONF_NAME: name, CONF_HOST: host, CONF_SWITCHES: switches, }, config)) if motion: hass.async_create_task(discovery.async_load_platform( hass, 'binary_sensor', DOMAIN, { CONF_HOST: host, CONF_NAME: name, }, config)) tasks = [async_setup_ipcamera(conf) for conf in config[DOMAIN]] if tasks: await asyncio.wait(tasks, loop=hass.loop) return True class AndroidIPCamEntity(Entity): """The Android device running IP Webcam.""" def __init__(self, host, ipcam): """Initialize the data object.""" self._host = host self._ipcam = ipcam async def async_added_to_hass(self): """Register update dispatcher.""" @callback def async_ipcam_update(host): """Update callback.""" if self._host != host: return self.async_schedule_update_ha_state(True) async_dispatcher_connect( self.hass, SIGNAL_UPDATE_DATA, async_ipcam_update) @property def should_poll(self): """Return True if entity has to be polled for state.""" return False @property def available(self): """Return True if entity is available.""" return self._ipcam.available @property def device_state_attributes(self): """Return the state attributes.""" state_attr = {ATTR_HOST: self._host} if self._ipcam.status_data is None: return state_attr state_attr[ATTR_VID_CONNS] = \ self._ipcam.status_data.get('video_connections') state_attr[ATTR_AUD_CONNS] = \ self._ipcam.status_data.get('audio_connections') return state_attr
apache-2.0
eadgarchen/tensorflow
tensorflow/contrib/keras/api/keras/__init__.py
128
1935
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of the Keras API meant to be a high-level API for TensorFlow. Detailed documentation and user guides are available at [keras.io](https://keras.io). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.api.keras import activations from tensorflow.contrib.keras.api.keras import applications from tensorflow.contrib.keras.api.keras import backend from tensorflow.contrib.keras.api.keras import callbacks from tensorflow.contrib.keras.api.keras import constraints from tensorflow.contrib.keras.api.keras import datasets from tensorflow.contrib.keras.api.keras import initializers from tensorflow.contrib.keras.api.keras import layers from tensorflow.contrib.keras.api.keras import losses from tensorflow.contrib.keras.api.keras import metrics from tensorflow.contrib.keras.api.keras import models from tensorflow.contrib.keras.api.keras import optimizers from tensorflow.contrib.keras.api.keras import preprocessing from tensorflow.contrib.keras.api.keras import regularizers from tensorflow.contrib.keras.api.keras import utils from tensorflow.contrib.keras.api.keras import wrappers del absolute_import del division del print_function
apache-2.0
mlperf/training_results_v0.5
v0.5.0/google/cloud_v2.8/resnet-tpuv2-8/code/resnet/model/models/official/recommendation/neumf_model.py
4
19328
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines NeuMF model for NCF framework. Some abbreviations used in the code base: NeuMF: Neural Matrix Factorization NCF: Neural Collaborative Filtering GMF: Generalized Matrix Factorization MLP: Multi-Layer Perceptron GMF applies a linear kernel to model the latent feature interactions, and MLP uses a nonlinear kernel to learn the interaction function from data. NeuMF model is a fused model of GMF and MLP to better model the complex user-item interactions, and unifies the strengths of linearity of MF and non-linearity of MLP for modeling the user-item latent structures. In NeuMF model, it allows GMF and MLP to learn separate embeddings, and combine the two models by concatenating their last hidden layer. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import typing from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from official.datasets import movielens # pylint: disable=g-bad-import-order from official.recommendation import constants as rconst from official.recommendation import stat_utils from official.utils.logs import mlperf_helper def _sparse_to_dense_grads(grads_and_vars): """Convert sparse gradients to dense gradients. All sparse gradients, which are represented as instances of tf.IndexedSlices, are converted to dense Tensors. Dense gradients, which are represents as Tensors, are unchanged. The purpose of this conversion is that for small embeddings, which are used by this model, applying dense gradients with the AdamOptimizer is faster than applying sparse gradients. Args grads_and_vars: A list of (gradient, variable) tuples. Each gradient can be a Tensor or an IndexedSlices. Tensors are unchanged, and IndexedSlices are converted to dense Tensors. Returns: The same list of (gradient, variable) as `grads_and_vars`, except each IndexedSlices gradient is converted to a Tensor. """ # Calling convert_to_tensor changes IndexedSlices into Tensors, and leaves # Tensors unchanged. return [(tf.convert_to_tensor(g), v) for g, v in grads_and_vars] def neumf_model_fn(features, labels, mode, params): """Model Function for NeuMF estimator.""" if params.get("use_seed"): tf.set_random_seed(stat_utils.random_int32()) users = features[movielens.USER_COLUMN] items = tf.cast(features[movielens.ITEM_COLUMN], tf.int32) keras_model = params.get("keras_model") if keras_model: logits = keras_model([users, items], training=mode == tf.estimator.ModeKeys.TRAIN) else: keras_model = construct_model(users=users, items=items, params=params) logits = keras_model.output if not params["use_estimator"] and "keras_model" not in params: # When we are not using estimator, we need to reuse the Keras model when # this model_fn is called again, so that the variables are shared between # training and eval. So we mutate params to add the Keras model. params["keras_model"] = keras_model # Softmax with the first column of zeros is equivalent to sigmoid. softmax_logits = tf.concat([tf.zeros(logits.shape, dtype=logits.dtype), logits], axis=1) if mode == tf.estimator.ModeKeys.PREDICT: predictions = { movielens.ITEM_COLUMN: items, movielens.RATING_COLUMN: logits, } if params["use_tpu"]: return tf.contrib.tpu.TPUEstimatorSpec(mode=mode, predictions=predictions) return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: duplicate_mask = tf.cast(features[rconst.DUPLICATE_MASK], tf.float32) return compute_eval_loss_and_metrics( logits, softmax_logits, duplicate_mask, params["num_neg"], params["match_mlperf"], use_tpu_spec=params["use_tpu"] or params["use_xla_for_gpu"]) elif mode == tf.estimator.ModeKeys.TRAIN: labels = tf.cast(labels, tf.int32) mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_NAME, value="adam") mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_LR, value=params["learning_rate"]) mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_HP_ADAM_BETA1, value=params["beta1"]) mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_HP_ADAM_BETA2, value=params["beta2"]) mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_HP_ADAM_EPSILON, value=params["epsilon"]) optimizer = tf.train.AdamOptimizer( learning_rate=params["learning_rate"], beta1=params["beta1"], beta2=params["beta2"], epsilon=params["epsilon"]) if params["use_tpu"]: optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) mlperf_helper.ncf_print(key=mlperf_helper.TAGS.MODEL_HP_LOSS_FN, value=mlperf_helper.TAGS.BCE) loss = tf.losses.sparse_softmax_cross_entropy( labels=labels, logits=softmax_logits ) # This tensor is used by logging hooks. tf.identity(loss, name="cross_entropy") global_step = tf.train.get_global_step() tvars = tf.trainable_variables() gradients = optimizer.compute_gradients( loss, tvars, colocate_gradients_with_ops=True) gradients = _sparse_to_dense_grads(gradients) minimize_op = optimizer.apply_gradients( gradients, global_step=global_step, name="train") update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) train_op = tf.group(minimize_op, update_ops) if params["use_tpu"]: return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=loss, train_op=train_op) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) else: raise NotImplementedError def construct_model(users, items, params): # type: (tf.Tensor, tf.Tensor, dict) -> tf.Tensor """Initialize NeuMF model. Args: users: Tensor of user ids. items: Tensor of item ids. params: Dict of hyperparameters. Raises: ValueError: if the first model layer is not even. Returns: logits: network logits """ num_users = params["num_users"] num_items = params["num_items"] model_layers = params["model_layers"] mf_regularization = params["mf_regularization"] mlp_reg_layers = params["mlp_reg_layers"] mf_dim = params["mf_dim"] mlperf_helper.ncf_print(key=mlperf_helper.TAGS.MODEL_HP_MF_DIM, value=mf_dim) mlperf_helper.ncf_print(key=mlperf_helper.TAGS.MODEL_HP_MLP_LAYER_SIZES, value=model_layers) if model_layers[0] % 2 != 0: raise ValueError("The first layer size should be multiple of 2!") # Input variables user_input = tf.keras.layers.Input(tensor=users) item_input = tf.keras.layers.Input(tensor=items) batch_size = user_input.get_shape()[0] if params["use_tpu"]: with tf.variable_scope("embed_weights", reuse=tf.AUTO_REUSE): cmb_embedding_user = tf.get_variable( name="embeddings_mf_user", shape=[num_users, mf_dim + model_layers[0] // 2], initializer=tf.glorot_uniform_initializer()) cmb_embedding_item = tf.get_variable( name="embeddings_mf_item", shape=[num_items, mf_dim + model_layers[0] // 2], initializer=tf.glorot_uniform_initializer()) cmb_user_latent = tf.keras.layers.Lambda(lambda ids: tf.gather( cmb_embedding_user, ids))(user_input) cmb_item_latent = tf.keras.layers.Lambda(lambda ids: tf.gather( cmb_embedding_item, ids))(item_input) mlp_user_latent = tf.keras.layers.Lambda( lambda x: tf.slice(x, [0, 0], [batch_size, model_layers[0] // 2]) )(cmb_user_latent) mlp_item_latent = tf.keras.layers.Lambda( lambda x: tf.slice(x, [0, 0], [batch_size, model_layers[0] // 2]) )(cmb_item_latent) mf_user_latent = tf.keras.layers.Lambda( lambda x: tf.slice(x, [0, model_layers[0] // 2], [batch_size, mf_dim]) )(cmb_user_latent) mf_item_latent = tf.keras.layers.Lambda( lambda x: tf.slice(x, [0, model_layers[0] // 2], [batch_size, mf_dim]) )(cmb_item_latent) else: # Initializer for embedding layers embedding_initializer = "glorot_uniform" # Embedding layers of GMF and MLP mf_embedding_user = tf.keras.layers.Embedding( num_users, mf_dim, embeddings_initializer=embedding_initializer, embeddings_regularizer=tf.keras.regularizers.l2(mf_regularization), input_length=1) mf_embedding_item = tf.keras.layers.Embedding( num_items, mf_dim, embeddings_initializer=embedding_initializer, embeddings_regularizer=tf.keras.regularizers.l2(mf_regularization), input_length=1) mlp_embedding_user = tf.keras.layers.Embedding( num_users, model_layers[0]//2, embeddings_initializer=embedding_initializer, embeddings_regularizer=tf.keras.regularizers.l2(mlp_reg_layers[0]), input_length=1) mlp_embedding_item = tf.keras.layers.Embedding( num_items, model_layers[0]//2, embeddings_initializer=embedding_initializer, embeddings_regularizer=tf.keras.regularizers.l2(mlp_reg_layers[0]), input_length=1) # GMF part mf_user_latent = mf_embedding_user(user_input) mf_item_latent = mf_embedding_item(item_input) # MLP part mlp_user_latent = mlp_embedding_user(user_input) mlp_item_latent = mlp_embedding_item(item_input) # Element-wise multiply mf_vector = tf.keras.layers.multiply([mf_user_latent, mf_item_latent]) # Concatenation of two latent features mlp_vector = tf.keras.layers.concatenate([mlp_user_latent, mlp_item_latent]) num_layer = len(model_layers) # Number of layers in the MLP for layer in xrange(1, num_layer): model_layer = tf.keras.layers.Dense( model_layers[layer], kernel_regularizer=tf.keras.regularizers.l2(mlp_reg_layers[layer]), activation="relu") mlp_vector = model_layer(mlp_vector) # Concatenate GMF and MLP parts predict_vector = tf.keras.layers.concatenate([mf_vector, mlp_vector]) # Final prediction layer logits = tf.keras.layers.Dense( 1, activation=None, kernel_initializer="lecun_uniform", name=movielens.RATING_COLUMN)(predict_vector) # Print model topology. model = tf.keras.models.Model([user_input, item_input], logits) model.summary() sys.stdout.flush() return model def compute_eval_loss_and_metrics(logits, # type: tf.Tensor softmax_logits, # type: tf.Tensor duplicate_mask, # type: tf.Tensor num_training_neg, # type: int match_mlperf=False, # type: bool use_tpu_spec=False # type: bool ): # type: (...) -> tf.estimator.EstimatorSpec """Model evaluation with HR and NDCG metrics. The evaluation protocol is to rank the test interacted item (truth items) among the randomly chosen 999 items that are not interacted by the user. The performance of the ranked list is judged by Hit Ratio (HR) and Normalized Discounted Cumulative Gain (NDCG). For evaluation, the ranked list is truncated at 10 for both metrics. As such, the HR intuitively measures whether the test item is present on the top-10 list, and the NDCG accounts for the position of the hit by assigning higher scores to hits at top ranks. Both metrics are calculated for each test user, and the average scores are reported. If `match_mlperf` is True, then the HR and NDCG computations are done in a slightly unusual way to match the MLPerf reference implementation. Specifically, if the evaluation negatives contain duplicate items, it will be treated as if the item only appeared once. Effectively, for duplicate items in a row, the predicted score for all but one of the items will be set to -infinity For example, suppose we have that following inputs: logits_by_user: [[ 2, 3, 3], [ 5, 4, 4]] items_by_user: [[10, 20, 20], [30, 40, 40]] # Note: items_by_user is not explicitly present. Instead the relevant \ information is contained within `duplicate_mask` top_k: 2 Then with match_mlperf=True, the HR would be 2/2 = 1.0. With match_mlperf=False, the HR would be 1/2 = 0.5. This is because each user has predicted scores for only 2 unique items: 10 and 20 for the first user, and 30 and 40 for the second. Therefore, with match_mlperf=True, it's guaranteed the first item's score is in the top 2. With match_mlperf=False, this function would compute the first user's first item is not in the top 2, because item 20 has a higher score, and item 20 occurs twice. Args: logits: A tensor containing the predicted logits for each user. The shape of logits is (num_users_per_batch * (1 + NUM_EVAL_NEGATIVES),) Logits for a user are grouped, and the first element of the group is the true element. softmax_logits: The same tensor, but with zeros left-appended. duplicate_mask: A vector with the same shape as logits, with a value of 1 if the item corresponding to the logit at that position has already appeared for that user. num_training_neg: The number of negatives per positive during training. match_mlperf: Use the MLPerf reference convention for computing rank. use_tpu_spec: Should a TPUEstimatorSpec be returned instead of an EstimatorSpec. Required for TPUs and if XLA is done on a GPU. Despite its name, TPUEstimatorSpecs work with GPUs Returns: An EstimatorSpec for evaluation. """ in_top_k, ndcg, metric_weights, logits_by_user = compute_top_k_and_ndcg( logits, duplicate_mask, match_mlperf) # Examples are provided by the eval Dataset in a structured format, so eval # labels can be reconstructed on the fly. eval_labels = tf.reshape(tf.one_hot( tf.zeros(shape=(logits_by_user.shape[0],), dtype=tf.int32), logits_by_user.shape[1], dtype=tf.int32), (-1,)) eval_labels_float = tf.cast(eval_labels, tf.float32) # During evaluation, the ratio of negatives to positives is much higher # than during training. (Typically 999 to 1 vs. 4 to 1) By adjusting the # weights for the negative examples we compute a loss which is consistent with # the training data. (And provides apples-to-apples comparison) negative_scale_factor = num_training_neg / rconst.NUM_EVAL_NEGATIVES example_weights = ( (eval_labels_float + (1 - eval_labels_float) * negative_scale_factor) * (1 + rconst.NUM_EVAL_NEGATIVES) / (1 + num_training_neg)) # Tile metric weights back to logit dimensions expanded_metric_weights = tf.reshape(tf.tile( metric_weights[:, tf.newaxis], (1, rconst.NUM_EVAL_NEGATIVES + 1)), (-1,)) # ignore padded examples example_weights *= tf.cast(expanded_metric_weights, tf.float32) cross_entropy = tf.losses.sparse_softmax_cross_entropy( logits=softmax_logits, labels=eval_labels, weights=example_weights) def metric_fn(top_k_tensor, ndcg_tensor, weight_tensor): return { rconst.HR_KEY: tf.metrics.mean(top_k_tensor, weights=weight_tensor, name=rconst.HR_METRIC_NAME), rconst.NDCG_KEY: tf.metrics.mean(ndcg_tensor, weights=weight_tensor, name=rconst.NDCG_METRIC_NAME), } if use_tpu_spec: return tf.contrib.tpu.TPUEstimatorSpec( mode=tf.estimator.ModeKeys.EVAL, loss=cross_entropy, eval_metrics=(metric_fn, [in_top_k, ndcg, metric_weights])) return tf.estimator.EstimatorSpec( mode=tf.estimator.ModeKeys.EVAL, loss=cross_entropy, eval_metric_ops=metric_fn(in_top_k, ndcg, metric_weights) ) def compute_top_k_and_ndcg(logits, # type: tf.Tensor duplicate_mask, # type: tf.Tensor match_mlperf=False # type: bool ): """Compute inputs of metric calculation. Args: logits: A tensor containing the predicted logits for each user. The shape of logits is (num_users_per_batch * (1 + NUM_EVAL_NEGATIVES),) Logits for a user are grouped, and the first element of the group is the true element. duplicate_mask: A vector with the same shape as logits, with a value of 1 if the item corresponding to the logit at that position has already appeared for that user. match_mlperf: Use the MLPerf reference convention for computing rank. Returns: is_top_k, ndcg and weights, all of which has size (num_users_in_batch,), and logits_by_user which has size (num_users_in_batch, (rconst.NUM_EVAL_NEGATIVES + 1)). """ logits_by_user = tf.reshape(logits, (-1, rconst.NUM_EVAL_NEGATIVES + 1)) duplicate_mask_by_user = tf.reshape(duplicate_mask, (-1, rconst.NUM_EVAL_NEGATIVES + 1)) if match_mlperf: # Set duplicate logits to the min value for that dtype. The MLPerf # reference dedupes during evaluation. logits_by_user *= (1 - duplicate_mask_by_user) logits_by_user += duplicate_mask_by_user * logits_by_user.dtype.min # Determine the location of the first element in each row after the elements # are sorted. sort_indices = tf.contrib.framework.argsort( logits_by_user, axis=1, direction="DESCENDING") # Use matrix multiplication to extract the position of the true item from the # tensor of sorted indices. This approach is chosen because both GPUs and TPUs # perform matrix multiplications very quickly. This is similar to np.argwhere. # However this is a special case because the target will only appear in # sort_indices once. one_hot_position = tf.cast(tf.equal(sort_indices, 0), tf.int32) sparse_positions = tf.multiply( one_hot_position, tf.range(logits_by_user.shape[1])[tf.newaxis, :]) position_vector = tf.reduce_sum(sparse_positions, axis=1) in_top_k = tf.cast(tf.less(position_vector, rconst.TOP_K), tf.float32) ndcg = tf.log(2.) / tf.log(tf.cast(position_vector, tf.float32) + 2) ndcg *= in_top_k # If a row is a padded row, all but the first element will be a duplicate. metric_weights = tf.not_equal(tf.reduce_sum(duplicate_mask_by_user, axis=1), rconst.NUM_EVAL_NEGATIVES) return in_top_k, ndcg, metric_weights, logits_by_user
apache-2.0
luo66/scikit-learn
sklearn/utils/tests/test_seq_dataset.py
93
2471
# Author: Tom Dupre la Tour <tom.dupre-la-tour@m4x.org> # # License: BSD 3 clause import numpy as np import scipy.sparse as sp from sklearn.utils.seq_dataset import ArrayDataset, CSRDataset from sklearn.datasets import load_iris from numpy.testing import assert_array_equal from nose.tools import assert_equal iris = load_iris() X = iris.data.astype(np.float64) y = iris.target.astype(np.float64) X_csr = sp.csr_matrix(X) sample_weight = np.arange(y.size, dtype=np.float64) def test_seq_dataset(): dataset1 = ArrayDataset(X, y, sample_weight, seed=42) dataset2 = CSRDataset(X_csr.data, X_csr.indptr, X_csr.indices, y, sample_weight, seed=42) for dataset in (dataset1, dataset2): for i in range(5): # next sample xi_, yi, swi, idx = dataset._next_py() xi = sp.csr_matrix((xi_), shape=(1, X.shape[1])) assert_array_equal(xi.data, X_csr[idx].data) assert_array_equal(xi.indices, X_csr[idx].indices) assert_array_equal(xi.indptr, X_csr[idx].indptr) assert_equal(yi, y[idx]) assert_equal(swi, sample_weight[idx]) # random sample xi_, yi, swi, idx = dataset._random_py() xi = sp.csr_matrix((xi_), shape=(1, X.shape[1])) assert_array_equal(xi.data, X_csr[idx].data) assert_array_equal(xi.indices, X_csr[idx].indices) assert_array_equal(xi.indptr, X_csr[idx].indptr) assert_equal(yi, y[idx]) assert_equal(swi, sample_weight[idx]) def test_seq_dataset_shuffle(): dataset1 = ArrayDataset(X, y, sample_weight, seed=42) dataset2 = CSRDataset(X_csr.data, X_csr.indptr, X_csr.indices, y, sample_weight, seed=42) # not shuffled for i in range(5): _, _, _, idx1 = dataset1._next_py() _, _, _, idx2 = dataset2._next_py() assert_equal(idx1, i) assert_equal(idx2, i) for i in range(5): _, _, _, idx1 = dataset1._random_py() _, _, _, idx2 = dataset2._random_py() assert_equal(idx1, idx2) seed = 77 dataset1._shuffle_py(seed) dataset2._shuffle_py(seed) for i in range(5): _, _, _, idx1 = dataset1._next_py() _, _, _, idx2 = dataset2._next_py() assert_equal(idx1, idx2) _, _, _, idx1 = dataset1._random_py() _, _, _, idx2 = dataset2._random_py() assert_equal(idx1, idx2)
bsd-3-clause
lukeiwanski/tensorflow
tensorflow/python/data/kernel_tests/sequence_dataset_op_test.py
18
7947
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.data.ops import dataset_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class SequenceDatasetTest(test.TestCase): def testRepeatTensorDataset(self): """Test a dataset that repeats its input multiple times.""" components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) # This placeholder can be fed when dataset-definition subgraph # runs (i.e. `init_op` below) to configure the number of # repetitions used in a particular iterator. count_placeholder = array_ops.placeholder(dtypes.int64, shape=[]) iterator = (dataset_ops.Dataset.from_tensors(components) .repeat(count_placeholder).make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([c.shape for c in components], [t.shape for t in get_next]) with self.test_session() as sess: # Test a finite repetition. sess.run(init_op, feed_dict={count_placeholder: 3}) for _ in range(3): results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Test a different finite repetition. sess.run(init_op, feed_dict={count_placeholder: 7}) for _ in range(7): results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Test an empty repetition. sess.run(init_op, feed_dict={count_placeholder: 0}) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Test an infinite repetition. # NOTE(mrry): There's not a good way to test that the sequence # actually is infinite. sess.run(init_op, feed_dict={count_placeholder: -1}) for _ in range(17): results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) def testTakeTensorDataset(self): components = (np.arange(10),) count_placeholder = array_ops.placeholder(dtypes.int64, shape=[]) iterator = (dataset_ops.Dataset.from_tensor_slices(components) .take(count_placeholder).make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([c.shape[1:] for c in components], [t.shape for t in get_next]) with self.test_session() as sess: # Take fewer than input size sess.run(init_op, feed_dict={count_placeholder: 4}) for i in range(4): results = sess.run(get_next) self.assertAllEqual(results, components[0][i:i+1]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Take more than input size sess.run(init_op, feed_dict={count_placeholder: 25}) for i in range(10): results = sess.run(get_next) self.assertAllEqual(results, components[0][i:i+1]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Take all of input sess.run(init_op, feed_dict={count_placeholder: -1}) for i in range(10): results = sess.run(get_next) self.assertAllEqual(results, components[0][i:i+1]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Take nothing sess.run(init_op, feed_dict={count_placeholder: 0}) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testSkipTensorDataset(self): components = (np.arange(10),) count_placeholder = array_ops.placeholder(dtypes.int64, shape=[]) iterator = (dataset_ops.Dataset.from_tensor_slices(components) .skip(count_placeholder).make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([c.shape[1:] for c in components], [t.shape for t in get_next]) with self.test_session() as sess: # Skip fewer than input size, we should skip # the first 4 elements and then read the rest. sess.run(init_op, feed_dict={count_placeholder: 4}) for i in range(4, 10): results = sess.run(get_next) self.assertAllEqual(results, components[0][i:i+1]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Skip more than input size: get nothing. sess.run(init_op, feed_dict={count_placeholder: 25}) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Skip exactly input size. sess.run(init_op, feed_dict={count_placeholder: 10}) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Set -1 for 'count': skip the entire dataset. sess.run(init_op, feed_dict={count_placeholder: -1}) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Skip nothing sess.run(init_op, feed_dict={count_placeholder: 0}) for i in range(0, 10): results = sess.run(get_next) self.assertAllEqual(results, components[0][i:i+1]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testRepeatRepeatTensorDataset(self): """Test the composition of repeat datasets.""" components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) inner_count = array_ops.placeholder(dtypes.int64, shape=[]) outer_count = array_ops.placeholder(dtypes.int64, shape=[]) iterator = (dataset_ops.Dataset.from_tensors(components).repeat(inner_count) .repeat(outer_count).make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([c.shape for c in components], [t.shape for t in get_next]) with self.test_session() as sess: sess.run(init_op, feed_dict={inner_count: 7, outer_count: 14}) for _ in range(7 * 14): results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testRepeatEmptyDataset(self): """Test that repeating an empty dataset does not hang.""" iterator = (dataset_ops.Dataset.from_tensors(0).repeat(10).skip(10) .repeat(-1).make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() with self.test_session() as sess: sess.run(init_op) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) if __name__ == "__main__": test.main()
apache-2.0
mlperf/training_results_v0.5
v0.5.0/google/cloud_v2.8/gnmt-tpuv2-8/code/gnmt/model/t2t/tensor2tensor/data_generators/algorithmic_math.py
3
21962
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Algorithmic data generators for symbolic math tasks. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple import random import six from six.moves import range # pylint: disable=redefined-builtin import sympy class ExprOp(object): """Represents an algebraic operation, such as '+', '-', etc.""" def __init__(self, symbol, precedence, associative=False): """Constructor. Args: symbol: The character which represents this operation, such as '+' for addition. precedence: Operator precedence. This will determine where parentheses are used. associative: If true, the order of the operands does not matter. """ self.symbol = symbol self.precedence = precedence self.associative = associative def __str__(self): return self.symbol def __eq__(self, other): return isinstance(other, ExprOp) and self.symbol == other.symbol class ExprNode(object): """A node in an expression tree. ExprNode always holds an operator. Leaves are strings. """ def __init__(self, left, right, op): self.left = left self.right = right self.op = op left_depth = left.depth if isinstance(left, ExprNode) else 0 right_depth = right.depth if isinstance(right, ExprNode) else 0 self.depth = max(left_depth, right_depth) + 1 def __str__(self): left_str = str(self.left) right_str = str(self.right) left_use_parens = (isinstance(self.left, ExprNode) and self.left.op.precedence < self.op.precedence) right_use_parens = (isinstance(self.right, ExprNode) and self.right.op.precedence <= self.op.precedence and not (self.op.associative and self.right.op == self.op)) left_final = "(" + left_str + ")" if left_use_parens else left_str right_final = "(" + right_str + ")" if right_use_parens else right_str return left_final + str(self.op) + right_final def is_in(self, expr): """Returns True if `expr` is a subtree.""" if expr == self: return True is_in_left = is_in_expr(self.left, expr) is_in_right = is_in_expr(self.right, expr) return is_in_left or is_in_right def is_in_expr(expr, find): """Returns True if `find` is a subtree of `expr`.""" return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find)) def random_expr_with_required_var(depth, required_var, optional_list, ops): """Generate a random expression tree with a required variable. The required variable appears exactly once in the expression. Args: depth: At least one leaf will be this many levels down from the top. required_var: A char. This char is guaranteed to be placed exactly once at a leaf somewhere in the tree. This is the var to solve for. optional_list: A list of chars. These chars are randomly selected as leaf values. These are constant vars. ops: A list of ExprOp instances. Returns: An ExprNode instance which is the root of the generated expression tree. """ if not depth: if required_var: return required_var return str(optional_list[random.randrange(len(optional_list))]) max_depth_side = random.randrange(2) other_side_depth = random.randrange(depth) required_var_side = random.randrange(2) left = random_expr_with_required_var( depth - 1 if max_depth_side else other_side_depth, required_var if required_var_side else None, optional_list, ops) right = random_expr_with_required_var( depth - 1 if not max_depth_side else other_side_depth, required_var if not required_var_side else None, optional_list, ops) op = ops[random.randrange(len(ops))] return ExprNode(left, right, op) def random_expr(depth, vlist, ops): """Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is the root of the generated expression tree. """ if not depth: return str(vlist[random.randrange(len(vlist))]) max_depth_side = random.randrange(2) other_side_depth = random.randrange(depth) left = random_expr(depth - 1 if max_depth_side else other_side_depth, vlist, ops) right = random_expr(depth - 1 if not max_depth_side else other_side_depth, vlist, ops) op = ops[random.randrange(len(ops))] return ExprNode(left, right, op) def algebra_inverse_solve(left, right, var, solve_ops): """Solves for the value of the given var in an expression. Args: left: The root of the ExprNode tree on the left side of the equals sign. right: The root of the ExprNode tree on the right side of the equals sign. var: A char. The variable to solve for. solve_ops: A dictionary with the following properties. * For each operator in the expression, there is a rule that determines how to cancel out a value either to the left or the right of that operator. * For each rule, there is an entry in the dictionary. The key is two chars- the op char, and either 'l' or 'r' meaning rule for canceling out the left or right sides. For example, '+l', '+r', '-l', '-r'. * The value of each entry is a function with the following signature: (left, right, to_tree) -> (new_from_tree, new_to_tree) left- Expression on left side of the op. right- Expression on the right side of the op. to_tree- The tree on the other side of the equal sign. The canceled out expression will be moved here. new_from_tree- The resulting from_tree after the algebraic manipulation. new_to_tree- The resulting to_tree after the algebraic manipulation. Returns: The root of an ExprNode tree which holds the value of `var` after solving. Raises: ValueError: If `var` does not appear exactly once in the equation (which includes the left and right sides). """ is_in_left = is_in_expr(left, var) is_in_right = is_in_expr(right, var) if is_in_left == is_in_right: if is_in_left: raise ValueError("Solve-variable '%s' is on both sides of the equation. " "Only equations where the solve variable-appears once " "are supported by this solver. Left: '%s', right: '%s'" % (var, str(left), str(right))) else: raise ValueError("Solve-variable '%s' is not present in the equation. It " "must appear once. Left: '%s', right: '%s'" % (var, str(left), str(right))) from_tree = left if is_in_left else right to_tree = left if not is_in_left else right while from_tree != var: is_in_left = is_in_expr(from_tree.left, var) is_in_right = is_in_expr(from_tree.right, var) from_tree, to_tree = (solve_ops[str(from_tree.op) + ("l" if is_in_left else "r")]( from_tree.left, from_tree.right, to_tree)) return to_tree def format_sympy_expr(sympy_expr, functions=None): """Convert sympy expression into a string which can be encoded. Args: sympy_expr: Any sympy expression tree or string. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to single chars. Each function gets a unique token, like "L" for "log". Returns: A string representation of the expression suitable for encoding as a sequence input. """ if functions is None: functions = {} str_expr = str(sympy_expr) result = str_expr.replace(" ", "") for fn_name, char in six.iteritems(functions): result = result.replace(fn_name, char) return result def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth, max_depth): """Randomly generate an algebra inverse dataset sample. Given an input equation and variable, produce the expression equal to the variable. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. solve_ops: See `solve_ops` documentation in `algebra_inverse_solve`. min_depth: Expression trees will not have a smaller depth than this. 0 means there is just a variable. 1 means there is one operation. max_depth: Expression trees will not have a larger depth than this. To make all trees have the same depth, set this equal to `min_depth`. Returns: sample: String representation of the input. Will be of the form 'solve_var:left_side=right_side'. target: String representation of the solution. """ side = random.randrange(2) left_depth = random.randrange(min_depth if side else 0, max_depth + 1) right_depth = random.randrange(min_depth if not side else 0, max_depth + 1) var_index = random.randrange(len(vlist)) var = vlist[var_index] consts = vlist[:var_index] + vlist[var_index + 1:] left = random_expr_with_required_var(left_depth, var if side else None, consts, ops) right = random_expr_with_required_var(right_depth, var if not side else None, consts, ops) left_str = str(left) right_str = str(right) target = str(algebra_inverse_solve(left, right, var, solve_ops)) sample = "%s:%s=%s" % (var, left_str, right_str) return sample, target def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will not have a smaller depth than this. 0 means there is just a variable. 1 means there is one operation. max_depth: Expression trees will not have a larger depth than this. To make all trees have the same depth, set this equal to `min_depth`. Returns: sample: String representation of the input. target: String representation of the solution. """ depth = random.randrange(min_depth, max_depth + 1) expr = random_expr(depth, vlist, ops) sample = str(expr) target = format_sympy_expr(sympy.simplify(sample)) return sample, target def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth, functions): """Randomly generate a symbolic integral dataset sample. Given an input expression, produce the indefinite integral. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will not have a smaller depth than this. 0 means there is just a variable. 1 means there is one operation. max_depth: Expression trees will not have a larger depth than this. To make all trees have the same depth, set this equal to `min_depth`. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to single chars. Each function gets a unique token, like "L" for "log". Returns: sample: String representation of the input. Will be of the form 'var:expression'. target: String representation of the solution. """ var_index = random.randrange(len(vlist)) var = vlist[var_index] consts = vlist[:var_index] + vlist[var_index + 1:] depth = random.randrange(min_depth, max_depth + 1) expr = random_expr_with_required_var(depth, var, consts, ops) expr_str = str(expr) sample = var + ":" + expr_str target = format_sympy_expr( sympy.integrate(expr_str, sympy.Symbol(var)), functions=functions) return sample, target # AlgebraConfig holds objects required to generate the algebra inverse # dataset. # vlist: Variable list. A list of chars. # dlist: Numberical digit list. A list of chars. # flist: List of special function names. A list of chars. # functions: Dict of special function names. Maps human readable string names to # single char names used in flist. # ops: Dict mapping op symbols (chars) to ExprOp instances. # solve_ops: Encodes rules for how to algebraically cancel out each operation. # See doc-string for `algebra_inverse_solve`. # int_encoder: Function that maps a string to a list of tokens. Use this to # encode an expression to feed into a model. # int_decoder: Function that maps a list of tokens to a string. Use this to # convert model input or output into a human readable string. AlgebraConfig = namedtuple("AlgebraConfig", [ "vlist", "dlist", "flist", "functions", "ops", "solve_ops", "int_encoder", "int_decoder" ]) def math_dataset_init(alphabet_size=26, digits=None, functions=None): """Initializes required objects to generate symbolic math datasets. Produces token set, ExprOp instances, solve_op dictionary, encoders, and decoders needed to generate the algebra inverse dataset. Args: alphabet_size: How many possible variables there are. Max 52. digits: How many numerical digits to encode as tokens, "0" through str(digits-1), or None to encode no digits. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to single chars. Each function gets a unique token, like "L" for "log". WARNING, Make sure these tokens do not conflict with the list of possible variable names. Returns: AlgebraConfig instance holding all the objects listed above. Raises: ValueError: If `alphabet_size` is not in range [2, 52]. """ ops_list = ["+", "-", "*", "/"] ops = { "+": ExprOp("+", 0, True), "-": ExprOp("-", 0, False), "*": ExprOp("*", 1, True), "/": ExprOp("/", 1, False) } solve_ops = { "+l": lambda l, r, to: (l, ExprNode(to, r, ops["-"])), "+r": lambda l, r, to: (r, ExprNode(to, l, ops["-"])), "-l": lambda l, r, to: (l, ExprNode(to, r, ops["+"])), "-r": lambda l, r, to: (r, ExprNode(l, to, ops["-"])), "*l": lambda l, r, to: (l, ExprNode(to, r, ops["/"])), "*r": lambda l, r, to: (r, ExprNode(to, l, ops["/"])), "/l": lambda l, r, to: (l, ExprNode(to, r, ops["*"])), "/r": lambda l, r, to: (r, ExprNode(l, to, ops["/"])), } alphabet = ( [six.int2byte(ord("a") + c).decode("utf-8") for c in range(26)] + [six.int2byte(ord("A") + c).decode("utf-8") for c in range(26)]) if alphabet_size > 52: raise ValueError( "alphabet_size cannot be greater than 52. Got %s." % alphabet_size) if alphabet_size < 2: raise ValueError( "alphabet_size cannot be less than 2. Got %s." % alphabet_size) if digits is not None and not 1 <= digits <= 10: raise ValueError("digits cannot must be between 1 and 10. Got %s." % digits) vlist = alphabet[:alphabet_size] if digits is not None: dlist = [str(d) for d in range(digits)] else: dlist = [] if functions is None: functions = {} flist = sorted(functions.values()) pad = "_" tokens = [pad] + [":", "(", ")", "="] + ops_list + vlist + dlist + flist if len(tokens) != len(set(tokens)): raise ValueError("Duplicate token. Tokens: %s" % tokens) token_map = dict([(t, i) for i, t in enumerate(tokens)]) def int_encoder(sequence): return [token_map[s] for s in sequence] def int_decoder(tensor_1d): return "".join([tokens[i] for i in tensor_1d]) return AlgebraConfig( vlist=vlist, dlist=dlist, flist=flist, functions=functions, ops=ops, solve_ops=solve_ops, int_encoder=int_encoder, int_decoder=int_decoder) def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra inverse dataset. Each sample is a symbolic math equation involving unknown variables. The task is to solve for the given variable. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 52. min_depth: Minimum depth of the expression trees on both sides of the equals sign in the equation. max_depth: Maximum depth of the expression trees on both sides of the equals sign in the equation. nbr_cases: The number of cases to generate. Yields: A dictionary {"inputs": input-list, "targets": target-list} where input-list are the tokens encoding the variable to solve for and the math equation, and target-list is a list of tokens encoding the resulting math expression after solving for the variable. Raises: ValueError: If `max_depth` < `min_depth`. """ if max_depth < min_depth: raise ValueError("max_depth must be greater than or equal to min_depth. " "Got max_depth=%s, min_depth=%s" % (max_depth, min_depth)) alg_cfg = math_dataset_init(alphabet_size) for _ in range(nbr_cases): sample, target = generate_algebra_inverse_sample( alg_cfg.vlist, list(alg_cfg.ops.values()), alg_cfg.solve_ops, min_depth, max_depth) yield { "inputs": alg_cfg.int_encoder(sample), "targets": alg_cfg.int_encoder(target) } def algebra_simplify(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra simplify dataset. Each sample is a symbolic math expression involving unknown variables. The task is to simplify the expression. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 52. min_depth: Minimum depth of the expression trees on both sides of the equals sign in the equation. max_depth: Maximum depth of the expression trees on both sides of the equals sign in the equation. nbr_cases: The number of cases to generate. Yields: A dictionary {"inputs": input-list, "targets": target-list} where input-list are the tokens encoding the expression to simplify, and target-list is a list of tokens encoding the resulting math expression after simplifying. Raises: ValueError: If `max_depth` < `min_depth`. """ if max_depth < min_depth: raise ValueError("max_depth must be greater than or equal to min_depth. " "Got max_depth=%s, min_depth=%s" % (max_depth, min_depth)) alg_cfg = math_dataset_init(alphabet_size, digits=5) for _ in range(nbr_cases): sample, target = generate_algebra_simplify_sample( alg_cfg.vlist, list(alg_cfg.ops.values()), min_depth, max_depth) yield { "inputs": alg_cfg.int_encoder(sample), "targets": alg_cfg.int_encoder(target) } def calculus_integrate(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the calculus integrate dataset. Each sample is a symbolic math expression involving unknown variables. The task is to take the indefinite integral of the expression. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 26. min_depth: Minimum depth of the expression trees on both sides of the equals sign in the equation. max_depth: Maximum depth of the expression trees on both sides of the equals sign in the equation. nbr_cases: The number of cases to generate. Yields: A dictionary {"inputs": input-list, "targets": target-list} where input-list are the tokens encoding the variable to integrate with respect to and the expression to integrate, and target-list is a list of tokens encoding the resulting math expression after integrating. Raises: ValueError: If `max_depth` < `min_depth`, or if alphabet_size > 26. """ if max_depth < min_depth: raise ValueError("max_depth must be greater than or equal to min_depth. " "Got max_depth=%s, min_depth=%s" % (max_depth, min_depth)) # Don't allow alphabet to use capital letters. Those are reserved for function # names. if alphabet_size > 26: raise ValueError( "alphabet_size must not be greater than 26. Got %s." % alphabet_size) functions = {"log": "L"} alg_cfg = math_dataset_init(alphabet_size, digits=5, functions=functions) nbr_case = 0 while nbr_case < nbr_cases: try: sample, target = generate_calculus_integrate_sample( alg_cfg.vlist, list(alg_cfg.ops.values()), min_depth, max_depth, alg_cfg.functions) yield { "inputs": alg_cfg.int_encoder(sample), "targets": alg_cfg.int_encoder(target) } except: # pylint:disable=bare-except continue if nbr_case % 10000 == 0: print(" calculus_integrate: generating case %d." % nbr_case) nbr_case += 1
apache-2.0
manipopopo/tensorflow
tensorflow/python/data/kernel_tests/iterator_ops_test.py
3
35917
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import os import warnings import numpy as np from tensorflow.core.protobuf import cluster_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.compat import compat as forward_compat from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import iterator_ops from tensorflow.python.data.ops import readers from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import function from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import gen_dataset_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import io_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.ops import script_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import checkpoint_management from tensorflow.python.training import server_lib from tensorflow.python.training.checkpointable import util as checkpointable_utils from tensorflow.python.util import compat class IteratorTest(test.TestCase): def testNoGradients(self): component = constant_op.constant([1.]) side = constant_op.constant(0.) add = lambda x: x + side dataset = dataset_ops.Dataset.from_tensor_slices(component).map(add) value = dataset.make_one_shot_iterator().get_next() self.assertIsNone(gradients_impl.gradients(value, component)[0]) self.assertIsNone(gradients_impl.gradients(value, side)[0]) self.assertIsNone(gradients_impl.gradients(value, [component, side])[0]) def testCapturingStateInOneShotRaisesException(self): var = variables.Variable(37.0, name="myvar") dataset = ( dataset_ops.Dataset.from_tensor_slices([0.0, 1.0, 2.0]) .map(lambda x: x + var)) with self.assertRaisesRegexp( ValueError, r"`Dataset.make_one_shot_iterator\(\)` does not support " "datasets that capture stateful objects.+myvar"): dataset.make_one_shot_iterator() def testOneShotIterator(self): components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) iterator = ( dataset_ops.Dataset.from_tensor_slices(components).map(_map_fn) .repeat(14).make_one_shot_iterator()) get_next = iterator.get_next() self.assertEqual([c.shape[1:] for c in components], [t.shape for t in get_next]) with self.test_session() as sess: for _ in range(14): for i in range(7): result = sess.run(get_next) for component, result_component in zip(components, result): self.assertAllEqual(component[i]**2, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testOneShotIteratorCaptureByValue(self): components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) tensor_components = tuple([ops.convert_to_tensor(c) for c in components]) def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) iterator = ( dataset_ops.Dataset.from_tensor_slices(tensor_components) .map(_map_fn).repeat(14).make_one_shot_iterator()) get_next = iterator.get_next() self.assertEqual([c.shape[1:] for c in components], [t.shape for t in get_next]) with self.test_session() as sess: for _ in range(14): for i in range(7): result = sess.run(get_next) for component, result_component in zip(components, result): self.assertAllEqual(component[i]**2, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testOneShotIteratorInsideContainer(self): components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) def within_container(): def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) iterator = ( dataset_ops.Dataset.from_tensor_slices(components) .map(_map_fn).repeat(14).make_one_shot_iterator()) return iterator.get_next() server = server_lib.Server.create_local_server() # Create two iterators within unique containers, and run them to # make sure that the resources aren't shared. # # The test below would fail if cname were the same across both # sessions. for i in range(2): with session.Session(server.target) as sess: cname = "iteration%d" % i with ops.container(cname): get_next = within_container() for _ in range(14): for i in range(7): result = sess.run(get_next) for component, result_component in zip(components, result): self.assertAllEqual(component[i]**2, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testOneShotIteratorNonBlocking(self): dataset = dataset_ops.Dataset.from_tensors([1, 2, 3]).map(lambda x: x * x) iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() # Create a session with a single thread to ensure that the # one-shot iterator initializer does not deadlock. config = config_pb2.ConfigProto( inter_op_parallelism_threads=1, use_per_session_threads=True) with session.Session(config=config) as sess: self.assertAllEqual([1, 4, 9], sess.run(next_element)) with self.assertRaises(errors.OutOfRangeError): sess.run(next_element) # Test with multiple threads invoking the one-shot iterator concurrently. with session.Session(config=config) as sess: results = [] def consumer_thread(): try: results.append(sess.run(next_element)) except errors.OutOfRangeError: results.append(None) num_threads = 8 threads = [ self.checkedThread(consumer_thread) for _ in range(num_threads) ] for t in threads: t.start() for t in threads: t.join() self.assertEqual(num_threads, len(results)) self.assertEqual(num_threads - 1, len([None for r in results if r is None])) self.assertAllEqual([[1, 4, 9]], [r for r in results if r is not None]) def testOneShotIteratorInitializerFails(self): # Define a dataset whose initialization will always fail. dataset = dataset_ops.Dataset.from_tensors( array_ops.check_numerics( constant_op.constant(1.0) / constant_op.constant(0.0), "oops")) iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() with self.test_session() as sess: with self.assertRaisesRegexp(errors.InvalidArgumentError, "oops"): sess.run(next_element) # Test that subsequent attempts to use the iterator also fail. with self.assertRaisesRegexp(errors.InvalidArgumentError, "oops"): sess.run(next_element) with self.test_session() as sess: def consumer_thread(): with self.assertRaisesRegexp(errors.InvalidArgumentError, "oops"): sess.run(next_element) num_threads = 8 threads = [ self.checkedThread(consumer_thread) for _ in range(num_threads) ] for t in threads: t.start() for t in threads: t.join() def testSimpleSharedResource(self): components = (np.array(1, dtype=np.int64), np.array([1, 2, 3], dtype=np.int64), np.array(37.0, dtype=np.float64)) server = server_lib.Server.create_local_server() # Create two non-overlapping sessions that share the same iterator # resource on the same server, and verify that an action of the # first session (initializing the iterator) is visible in the # second session. with ops.Graph().as_default(): iterator = ( dataset_ops.Dataset.from_tensors(components) .map(lambda x, y, z: (x, y, z)).make_initializable_iterator( shared_name="shared_iterator")) init_op = iterator.initializer get_next = iterator.get_next() with session.Session(server.target) as sess: sess.run(init_op) results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Re-initialize the iterator in the first session. sess.run(init_op) with ops.Graph().as_default(): # Re-define the iterator manually, without defining any of the # functions in this graph, to ensure that we are not # accidentally redefining functions with the same names in the # new graph. iterator = iterator_ops.Iterator.from_structure( shared_name="shared_iterator", output_types=(dtypes.int64, dtypes.int64, dtypes.float64), output_shapes=([], [3], [])) get_next = iterator.get_next() with session.Session(server.target) as sess: # Use the iterator without re-initializing in the second session. results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testNotInitializedError(self): components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) iterator = ( dataset_ops.Dataset.from_tensors(components) .make_initializable_iterator()) get_next = iterator.get_next() with self.test_session() as sess: with self.assertRaisesRegexp(errors.FailedPreconditionError, "iterator has not been initialized"): sess.run(get_next) def testReinitializableIterator(self): dataset_3 = dataset_ops.Dataset.from_tensors( constant_op.constant([1, 2, 3])) dataset_4 = dataset_ops.Dataset.from_tensors( constant_op.constant([4, 5, 6, 7])) iterator = iterator_ops.Iterator.from_structure(dataset_3.output_types, [None]) dataset_3_init_op = iterator.make_initializer(dataset_3) dataset_4_init_op = iterator.make_initializer(dataset_4) get_next = iterator.get_next() self.assertEqual(dataset_3.output_types, iterator.output_types) self.assertEqual(dataset_4.output_types, iterator.output_types) self.assertEqual([None], iterator.output_shapes.as_list()) with self.test_session() as sess: # The iterator is initially uninitialized. with self.assertRaises(errors.FailedPreconditionError): sess.run(get_next) # Initialize with one dataset. sess.run(dataset_3_init_op) self.assertAllEqual([1, 2, 3], sess.run(get_next)) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Initialize with a different dataset. sess.run(dataset_4_init_op) self.assertAllEqual([4, 5, 6, 7], sess.run(get_next)) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Reinitialize with the first dataset. sess.run(dataset_3_init_op) self.assertAllEqual([1, 2, 3], sess.run(get_next)) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testReinitializableIteratorStaticErrors(self): # Non-matching structure for types and shapes. with self.assertRaises(TypeError): iterator = iterator_ops.Iterator.from_structure( (dtypes.int64, dtypes.float64), [None]) # Test validation of dataset argument. iterator = iterator_ops.Iterator.from_structure((dtypes.int64, dtypes.float64)) # Incompatible structure. with self.assertRaises(ValueError): iterator.make_initializer( dataset_ops.Dataset.from_tensors(((constant_op.constant( [1, 2, 3], dtype=dtypes.int64),), (constant_op.constant( [4., 5., 6., 7.], dtype=dtypes.float64),)))) # Incompatible types. with self.assertRaises(TypeError): iterator.make_initializer( dataset_ops.Dataset.from_tensors( (constant_op.constant([1, 2, 3], dtype=dtypes.int32), constant_op.constant([4., 5., 6., 7.], dtype=dtypes.float32)))) # Incompatible shapes. iterator = iterator_ops.Iterator.from_structure( (dtypes.int64, dtypes.float64), ([None], [])) with self.assertRaises(TypeError): iterator.make_initializer( dataset_ops.Dataset.from_tensors( (constant_op.constant([1, 2, 3], dtype=dtypes.int64), constant_op.constant([4., 5., 6., 7.], dtype=dtypes.float64)))) def testIteratorStringHandle(self): dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3]) dataset_4 = dataset_ops.Dataset.from_tensor_slices([10, 20, 30, 40]) iterator_3 = dataset_3.make_one_shot_iterator() iterator_4 = dataset_4.make_one_shot_iterator() handle_placeholder = array_ops.placeholder(dtypes.string, shape=[]) feedable_iterator = iterator_ops.Iterator.from_string_handle( handle_placeholder, dataset_3.output_types, dataset_3.output_shapes) next_element = feedable_iterator.get_next() self.assertEqual(dataset_3.output_types, feedable_iterator.output_types) self.assertEqual(dataset_4.output_types, feedable_iterator.output_types) self.assertEqual([], feedable_iterator.output_shapes) with self.test_session() as sess: iterator_3_handle = sess.run(iterator_3.string_handle()) iterator_4_handle = sess.run(iterator_4.string_handle()) self.assertEqual(10, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) self.assertEqual(1, sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle})) self.assertEqual(20, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) self.assertEqual(2, sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle})) self.assertEqual(30, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) self.assertEqual(3, sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle})) self.assertEqual(40, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) with self.assertRaises(errors.OutOfRangeError): sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle}) with self.assertRaises(errors.OutOfRangeError): sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle}) def testIteratorStringHandleFuture(self): with forward_compat.forward_compatibility_horizon(2018, 8, 4): dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3]) dataset_4 = dataset_ops.Dataset.from_tensor_slices([10, 20, 30, 40]) iterator_3 = dataset_3.make_one_shot_iterator() iterator_4 = dataset_4.make_one_shot_iterator() handle_placeholder = array_ops.placeholder(dtypes.string, shape=[]) feedable_iterator = iterator_ops.Iterator.from_string_handle( handle_placeholder, dataset_3.output_types, dataset_3.output_shapes) next_element = feedable_iterator.get_next() self.assertEqual(dataset_3.output_types, feedable_iterator.output_types) self.assertEqual(dataset_4.output_types, feedable_iterator.output_types) self.assertEqual([], feedable_iterator.output_shapes) with self.test_session() as sess: iterator_3_handle = sess.run(iterator_3.string_handle()) iterator_4_handle = sess.run(iterator_4.string_handle()) self.assertEqual( 10, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) self.assertEqual( 1, sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle})) self.assertEqual( 20, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) self.assertEqual( 2, sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle})) self.assertEqual( 30, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) self.assertEqual( 3, sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle})) self.assertEqual( 40, sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle})) with self.assertRaises(errors.OutOfRangeError): sess.run( next_element, feed_dict={handle_placeholder: iterator_3_handle}) with self.assertRaises(errors.OutOfRangeError): sess.run( next_element, feed_dict={handle_placeholder: iterator_4_handle}) def testIteratorStringHandleReuseTensorObject(self): dataset = dataset_ops.Dataset.from_tensor_slices([1, 2, 3]) one_shot_iterator = dataset.make_one_shot_iterator() initializable_iterator = dataset.make_initializable_iterator() structure_iterator = iterator_ops.Iterator.from_structure( dataset.output_types) created_ops = len(ops.get_default_graph().get_operations()) self.assertIs(one_shot_iterator.string_handle(), one_shot_iterator.string_handle()) self.assertIs(initializable_iterator.string_handle(), initializable_iterator.string_handle()) self.assertIs(structure_iterator.string_handle(), structure_iterator.string_handle()) # Assert that getting the (default) string handle creates no ops. self.assertEqual(created_ops, len(ops.get_default_graph().get_operations())) # Specifying an explicit name will create a new op. handle_with_name = one_shot_iterator.string_handle(name="foo") self.assertEqual("foo", handle_with_name.op.name) self.assertIsNot(one_shot_iterator.string_handle(), handle_with_name) handle_with_same_name = one_shot_iterator.string_handle(name="foo") self.assertEqual("foo_1", handle_with_same_name.op.name) self.assertIsNot(handle_with_name, handle_with_same_name) def testIteratorStringHandleError(self): dataset_int_scalar = ( dataset_ops.Dataset.from_tensor_slices([1, 2, 3]).repeat()) dataset_float_vector = (dataset_ops.Dataset.from_tensors([1.0, 2.0, 3.0])) handle_placeholder = array_ops.placeholder(dtypes.string, shape=[]) feedable_int_scalar = iterator_ops.Iterator.from_string_handle( handle_placeholder, dtypes.int32, []) feedable_int_vector = iterator_ops.Iterator.from_string_handle( handle_placeholder, dtypes.int32, [None]) feedable_int_any = iterator_ops.Iterator.from_string_handle( handle_placeholder, dtypes.int32) with self.test_session() as sess: handle_int_scalar = sess.run( dataset_int_scalar.make_one_shot_iterator().string_handle()) handle_float_vector = sess.run( dataset_float_vector.make_one_shot_iterator().string_handle()) self.assertEqual(1, sess.run( feedable_int_scalar.get_next(), feed_dict={handle_placeholder: handle_int_scalar})) self.assertEqual(2, sess.run( feedable_int_any.get_next(), feed_dict={handle_placeholder: handle_int_scalar})) with self.assertRaises(errors.InvalidArgumentError): print(sess.run( feedable_int_vector.get_next(), feed_dict={handle_placeholder: handle_int_scalar})) with self.assertRaises(errors.InvalidArgumentError): print(sess.run( feedable_int_vector.get_next(), feed_dict={handle_placeholder: handle_float_vector})) def testRemoteIteratorUsingRemoteCallOpDirectSession(self): worker_config = config_pb2.ConfigProto() worker_config.device_count["CPU"] = 3 with ops.device("/job:localhost/replica:0/task:0/cpu:1"): dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3]) iterator_3 = dataset_3.make_one_shot_iterator() iterator_3_handle = iterator_3.string_handle() @function.Defun(dtypes.string) def _remote_fn(h): remote_iterator = iterator_ops.Iterator.from_string_handle( h, dataset_3.output_types, dataset_3.output_shapes) return remote_iterator.get_next() with ops.device("/job:localhost/replica:0/task:0/cpu:0"): target_placeholder = array_ops.placeholder(dtypes.string, shape=[]) remote_op = functional_ops.remote_call( args=[iterator_3_handle], Tout=[dtypes.int32], f=_remote_fn, target=target_placeholder) with self.test_session(config=worker_config) as sess: elem = sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:1" }) self.assertEqual(elem, [1]) # Fails when target is cpu:2 where the resource is not located. with self.assertRaises(errors.InvalidArgumentError): sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:2" }) elem = sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:1" }) self.assertEqual(elem, [2]) elem = sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:1" }) self.assertEqual(elem, [3]) with self.assertRaises(errors.OutOfRangeError): sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:1" }) def testRemoteIteratorUsingRemoteCallOpMultiWorkers(self): s1 = server_lib.Server.create_local_server() s2 = server_lib.Server.create_local_server() s3 = server_lib.Server.create_local_server() cluster_def = cluster_pb2.ClusterDef() workers = cluster_def.job.add() workers.name = "worker" workers.tasks[0] = s1.target[len("grpc://"):] workers.tasks[1] = s2.target[len("grpc://"):] client = cluster_def.job.add() client.name = "client" client.tasks[0] = s3.target[len("grpc://"):] config = config_pb2.ConfigProto(cluster_def=cluster_def) worker_devices = [ "/job:worker/replica:0/task:%d/cpu:0" % i for i in range(2) ] itr_handles = [] for device in worker_devices: with ops.device(device): src = dataset_ops.Dataset.from_tensor_slices([device]) itr = src.make_one_shot_iterator() itr_handles.append(itr.string_handle()) targets = dataset_ops.Dataset.from_tensor_slices(worker_devices) handles = dataset_ops.Dataset.from_tensor_slices(itr_handles) @function.Defun(dtypes.string) def loading_func(h): remote_itr = iterator_ops.Iterator.from_string_handle( h, itr.output_types, itr.output_shapes) return remote_itr.get_next() def map_fn(target, handle): return functional_ops.remote_call( args=[handle], Tout=[dtypes.string], f=loading_func, target=target) with ops.device("/job:client"): client_dataset = dataset_ops.Dataset.zip((targets, handles)).map(map_fn) itr = client_dataset.make_initializable_iterator() n = itr.get_next() with session.Session(s3.target, config=config) as sess: sess.run(itr.initializer) expected_values = worker_devices for expected in expected_values: self.assertEqual((compat.as_bytes(expected),), sess.run(n)) with self.assertRaises(errors.OutOfRangeError): sess.run(n) def testRemoteIteratorUsingRemoteCallOpDirectSessionGPUCPU(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") with ops.device("/job:localhost/replica:0/task:0/cpu:0"): dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3]) iterator_3 = dataset_3.make_one_shot_iterator() iterator_3_handle = iterator_3.string_handle() def _encode_raw(byte_array): return bytes(bytearray(byte_array)) @function.Defun(dtypes.uint8) def _remote_fn(h): handle = script_ops.py_func(_encode_raw, [h], dtypes.string) remote_iterator = iterator_ops.Iterator.from_string_handle( handle, dataset_3.output_types, dataset_3.output_shapes) return remote_iterator.get_next() with ops.device("/job:localhost/replica:0/task:0/device:GPU:0"): target_placeholder = array_ops.placeholder(dtypes.string, shape=[]) iterator_3_handle_uint8 = parsing_ops.decode_raw( bytes=iterator_3_handle, out_type=dtypes.uint8) remote_op = functional_ops.remote_call( args=[iterator_3_handle_uint8], Tout=[dtypes.int32], f=_remote_fn, target=target_placeholder) with self.test_session() as sess: elem = sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:0" }) self.assertEqual(elem, [1]) elem = sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:0" }) self.assertEqual(elem, [2]) elem = sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:0" }) self.assertEqual(elem, [3]) with self.assertRaises(errors.OutOfRangeError): sess.run( remote_op, feed_dict={ target_placeholder: "/job:localhost/replica:0/task:0/cpu:0" }) def testIncorrectIteratorRestore(self): def _path(): return os.path.join(self.get_temp_dir(), "iterator") def _save_op(iterator_resource): iterator_state_variant = gen_dataset_ops.serialize_iterator( iterator_resource) save_op = io_ops.write_file( _path(), parsing_ops.serialize_tensor(iterator_state_variant)) return save_op def _restore_op(iterator_resource): iterator_state_variant = parsing_ops.parse_tensor( io_ops.read_file(_path()), dtypes.variant) restore_op = gen_dataset_ops.deserialize_iterator(iterator_resource, iterator_state_variant) return restore_op def _build_range_dataset_graph(): start = 1 stop = 10 iterator = dataset_ops.Dataset.range(start, stop).make_initializable_iterator() init_op = iterator.initializer get_next = iterator.get_next() save_op = _save_op(iterator._iterator_resource) restore_op = _restore_op(iterator._iterator_resource) return init_op, get_next, save_op, restore_op def _build_reader_dataset_graph(): filenames = ["test"] # Does not exist but we don't care in this test. iterator = readers.FixedLengthRecordDataset( filenames, 1, 0, 0).make_initializable_iterator() init_op = iterator.initializer get_next_op = iterator.get_next() save_op = _save_op(iterator._iterator_resource) restore_op = _restore_op(iterator._iterator_resource) return init_op, get_next_op, save_op, restore_op # Saving iterator for RangeDataset graph. with ops.Graph().as_default() as g: init_op, _, save_op, _ = _build_range_dataset_graph() with self.test_session(graph=g) as sess: sess.run(init_op) sess.run(save_op) # Attempt to restore the saved iterator into an IteratorResource of # incompatible type. An iterator of RangeDataset has output type int64, # while an iterator of FixedLengthRecordDataset has output type string. # So an InvalidArgumentError should be raised by # IteratorResource::set_iterator. with ops.Graph().as_default() as g: _, _, _, restore_op = _build_reader_dataset_graph() with self.test_session(graph=g) as sess: with self.assertRaises(errors.InvalidArgumentError): sess.run(restore_op) def testRepeatedGetNextWarning(self): iterator = dataset_ops.Dataset.range(10).make_one_shot_iterator() warnings.simplefilter("always") with warnings.catch_warnings(record=True) as w: for _ in range(100): iterator.get_next() self.assertEqual(100 - iterator_ops.GET_NEXT_CALL_WARNING_THRESHOLD, len(w)) for warning in w: self.assertTrue( iterator_ops.GET_NEXT_CALL_WARNING_MESSAGE in str(warning.message)) def testEagerIteratorAsync(self): with context.eager_mode(), context.execution_mode(context.ASYNC): val = 0 dataset = dataset_ops.Dataset.range(10) for foo in dataset: self.assertEqual(val, foo.numpy()) val += 1 class IteratorCheckpointingTest(test.TestCase): @test_util.run_in_graph_and_eager_modes def testSaveRestoreOneShotIterator(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") dataset = dataset_ops.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6]).map( math_ops.square).batch(2) iterator = dataset.make_one_shot_iterator() get_next = iterator.get_next if context.executing_eagerly( ) else functools.partial(self.evaluate, iterator.get_next()) checkpoint = checkpointable_utils.Checkpoint(iterator=iterator) with self.test_session() as sess: self.assertAllEqual([1, 4], get_next()) save_path = checkpoint.save(checkpoint_prefix) self.assertAllEqual([9, 16], get_next()) self.assertAllEqual([25, 36], get_next()) checkpoint.restore(save_path).run_restore_ops(sess) self.assertAllEqual([9, 16], get_next()) self.assertAllEqual([25, 36], get_next()) with self.assertRaises(errors.OutOfRangeError): get_next() @test_util.run_in_graph_and_eager_modes def testSaveRestoreMultipleIterator(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") dataset = dataset_ops.Dataset.from_tensor_slices( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) dataset = dataset.map(math_ops.square).batch(2) iterator_1 = dataset.make_one_shot_iterator() get_next_1 = iterator_1.get_next if context.executing_eagerly( ) else functools.partial(self.evaluate, iterator_1.get_next()) iterator_2 = dataset.make_one_shot_iterator() get_next_2 = iterator_2.get_next if context.executing_eagerly( ) else functools.partial(self.evaluate, iterator_2.get_next()) dataset_2 = dataset_ops.Dataset.range(10) iterator_3 = dataset_2.make_one_shot_iterator() get_next_3 = iterator_3.get_next if context.executing_eagerly( ) else functools.partial(self.evaluate, iterator_3.get_next()) checkpoint = checkpointable_utils.Checkpoint( iterator_1=iterator_1, iterator_2=iterator_2, iterator_3=iterator_3) with self.test_session() as sess: self.assertAllEqual([1, 4], get_next_1()) self.assertAllEqual(0, get_next_3()) self.assertAllEqual(1, get_next_3()) self.assertAllEqual(2, get_next_3()) save_path = checkpoint.save(checkpoint_prefix) self.assertAllEqual([1, 4], get_next_2()) self.assertAllEqual([9, 16], get_next_2()) self.assertAllEqual(3, get_next_3()) checkpoint.restore(save_path).run_restore_ops(sess) self.assertAllEqual([9, 16], get_next_1()) self.assertAllEqual([1, 4], get_next_2()) self.assertAllEqual(3, get_next_3()) @test_util.run_in_graph_and_eager_modes def testRestoreExhaustedIterator(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") dataset = dataset_ops.Dataset.range(3) iterator = dataset.make_one_shot_iterator() get_next = iterator.get_next if context.executing_eagerly( ) else functools.partial(self.evaluate, iterator.get_next()) checkpoint = checkpointable_utils.Checkpoint(iterator=iterator) with self.test_session() as sess: self.assertAllEqual(0, get_next()) self.assertAllEqual(1, get_next()) save_path = checkpoint.save(checkpoint_prefix) self.assertAllEqual(2, get_next()) checkpoint.restore(save_path).run_restore_ops(sess) self.assertAllEqual(2, get_next()) save_path = checkpoint.save(checkpoint_prefix) checkpoint.restore(save_path).run_restore_ops(sess) with self.assertRaises(errors.OutOfRangeError): get_next() def testRestoreInReconstructedIteratorInitializable(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") dataset = dataset_ops.Dataset.range(10) iterator = dataset.make_initializable_iterator() get_next = iterator.get_next() checkpoint = checkpointable_utils.Checkpoint(iterator=iterator) for i in range(5): with self.test_session() as sess: checkpoint.restore(checkpoint_management.latest_checkpoint( checkpoint_directory)).initialize_or_restore(sess) for j in range(2): self.assertEqual(i * 2 + j, sess.run(get_next)) checkpoint.save(file_prefix=checkpoint_prefix) if __name__ == "__main__": test.main()
apache-2.0
luo66/scikit-learn
sklearn/datasets/tests/test_base.py
204
5878
import os import shutil import tempfile import warnings import nose import numpy from pickle import loads from pickle import dumps from sklearn.datasets import get_data_home from sklearn.datasets import clear_data_home from sklearn.datasets import load_files from sklearn.datasets import load_sample_images from sklearn.datasets import load_sample_image from sklearn.datasets import load_digits from sklearn.datasets import load_diabetes from sklearn.datasets import load_linnerud from sklearn.datasets import load_iris from sklearn.datasets import load_boston from sklearn.datasets.base import Bunch from sklearn.externals.six import b, u from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_raises DATA_HOME = tempfile.mkdtemp(prefix="scikit_learn_data_home_test_") LOAD_FILES_ROOT = tempfile.mkdtemp(prefix="scikit_learn_load_files_test_") TEST_CATEGORY_DIR1 = "" TEST_CATEGORY_DIR2 = "" def _remove_dir(path): if os.path.isdir(path): shutil.rmtree(path) def teardown_module(): """Test fixture (clean up) run once after all tests of this module""" for path in [DATA_HOME, LOAD_FILES_ROOT]: _remove_dir(path) def setup_load_files(): global TEST_CATEGORY_DIR1 global TEST_CATEGORY_DIR2 TEST_CATEGORY_DIR1 = tempfile.mkdtemp(dir=LOAD_FILES_ROOT) TEST_CATEGORY_DIR2 = tempfile.mkdtemp(dir=LOAD_FILES_ROOT) sample_file = tempfile.NamedTemporaryFile(dir=TEST_CATEGORY_DIR1, delete=False) sample_file.write(b("Hello World!\n")) sample_file.close() def teardown_load_files(): _remove_dir(TEST_CATEGORY_DIR1) _remove_dir(TEST_CATEGORY_DIR2) def test_data_home(): # get_data_home will point to a pre-existing folder data_home = get_data_home(data_home=DATA_HOME) assert_equal(data_home, DATA_HOME) assert_true(os.path.exists(data_home)) # clear_data_home will delete both the content and the folder it-self clear_data_home(data_home=data_home) assert_false(os.path.exists(data_home)) # if the folder is missing it will be created again data_home = get_data_home(data_home=DATA_HOME) assert_true(os.path.exists(data_home)) def test_default_empty_load_files(): res = load_files(LOAD_FILES_ROOT) assert_equal(len(res.filenames), 0) assert_equal(len(res.target_names), 0) assert_equal(res.DESCR, None) @nose.tools.with_setup(setup_load_files, teardown_load_files) def test_default_load_files(): res = load_files(LOAD_FILES_ROOT) assert_equal(len(res.filenames), 1) assert_equal(len(res.target_names), 2) assert_equal(res.DESCR, None) assert_equal(res.data, [b("Hello World!\n")]) @nose.tools.with_setup(setup_load_files, teardown_load_files) def test_load_files_w_categories_desc_and_encoding(): category = os.path.abspath(TEST_CATEGORY_DIR1).split('/').pop() res = load_files(LOAD_FILES_ROOT, description="test", categories=category, encoding="utf-8") assert_equal(len(res.filenames), 1) assert_equal(len(res.target_names), 1) assert_equal(res.DESCR, "test") assert_equal(res.data, [u("Hello World!\n")]) @nose.tools.with_setup(setup_load_files, teardown_load_files) def test_load_files_wo_load_content(): res = load_files(LOAD_FILES_ROOT, load_content=False) assert_equal(len(res.filenames), 1) assert_equal(len(res.target_names), 2) assert_equal(res.DESCR, None) assert_equal(res.get('data'), None) def test_load_sample_images(): try: res = load_sample_images() assert_equal(len(res.images), 2) assert_equal(len(res.filenames), 2) assert_true(res.DESCR) except ImportError: warnings.warn("Could not load sample images, PIL is not available.") def test_load_digits(): digits = load_digits() assert_equal(digits.data.shape, (1797, 64)) assert_equal(numpy.unique(digits.target).size, 10) def test_load_digits_n_class_lt_10(): digits = load_digits(9) assert_equal(digits.data.shape, (1617, 64)) assert_equal(numpy.unique(digits.target).size, 9) def test_load_sample_image(): try: china = load_sample_image('china.jpg') assert_equal(china.dtype, 'uint8') assert_equal(china.shape, (427, 640, 3)) except ImportError: warnings.warn("Could not load sample images, PIL is not available.") def test_load_missing_sample_image_error(): have_PIL = True try: try: from scipy.misc import imread except ImportError: from scipy.misc.pilutil import imread except ImportError: have_PIL = False if have_PIL: assert_raises(AttributeError, load_sample_image, 'blop.jpg') else: warnings.warn("Could not load sample images, PIL is not available.") def test_load_diabetes(): res = load_diabetes() assert_equal(res.data.shape, (442, 10)) assert_true(res.target.size, 442) def test_load_linnerud(): res = load_linnerud() assert_equal(res.data.shape, (20, 3)) assert_equal(res.target.shape, (20, 3)) assert_equal(len(res.target_names), 3) assert_true(res.DESCR) def test_load_iris(): res = load_iris() assert_equal(res.data.shape, (150, 4)) assert_equal(res.target.size, 150) assert_equal(res.target_names.size, 3) assert_true(res.DESCR) def test_load_boston(): res = load_boston() assert_equal(res.data.shape, (506, 13)) assert_equal(res.target.size, 506) assert_equal(res.feature_names.size, 13) assert_true(res.DESCR) def test_loads_dumps_bunch(): bunch = Bunch(x="x") bunch_from_pkl = loads(dumps(bunch)) bunch_from_pkl.x = "y" assert_equal(bunch_from_pkl['x'], bunch_from_pkl.x)
bsd-3-clause
automl/auto-sklearn
autosklearn/pipeline/classification.py
1
14739
from typing import Optional, Union import copy from itertools import product import numpy as np from ConfigSpace.configuration_space import Configuration, ConfigurationSpace from ConfigSpace.forbidden import ForbiddenAndConjunction, ForbiddenEqualsClause from sklearn.base import ClassifierMixin from autosklearn.askl_typing import FEAT_TYPE_TYPE from autosklearn.pipeline.base import BasePipeline from autosklearn.pipeline.components.classification import ClassifierChoice from autosklearn.pipeline.components.data_preprocessing import DataPreprocessorChoice from autosklearn.pipeline.components.data_preprocessing.balancing.balancing import ( Balancing, ) from autosklearn.pipeline.components.feature_preprocessing import ( FeaturePreprocessorChoice, ) from autosklearn.pipeline.constants import SPARSE class SimpleClassificationPipeline(BasePipeline, ClassifierMixin): """This class implements the classification task. It implements a pipeline, which includes one preprocessing step and one classification algorithm. It can render a search space including all known classification and preprocessing algorithms. Contrary to the sklearn API it is not possible to enumerate the possible parameters in the __init__ function because we only know the available classifiers at runtime. For this reason the user must specifiy the parameters by passing an instance of ConfigSpace.configuration_space.Configuration. Parameters ---------- config : ConfigSpace.configuration_space.Configuration The configuration to evaluate. random_state : Optional[int | RandomState] If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Attributes ---------- _estimator : The underlying scikit-learn classification model. This variable is assigned after a call to the :meth:`autosklearn.pipeline.classification.SimpleClassificationPipeline .fit` method. _preprocessor : The underlying scikit-learn preprocessing algorithm. This variable is only assigned if a preprocessor is specified and after a call to the :meth:`autosklearn.pipeline.classification.SimpleClassificationPipeline .fit` method. See also -------- References ---------- Examples -------- """ def __init__( self, config: Optional[Configuration] = None, feat_type: Optional[FEAT_TYPE_TYPE] = None, steps=None, dataset_properties=None, include=None, exclude=None, random_state: Optional[Union[int, np.random.RandomState]] = None, init_params=None, ): self._output_dtype = np.int32 if dataset_properties is None: dataset_properties = dict() if "target_type" not in dataset_properties: dataset_properties["target_type"] = "classification" super().__init__( feat_type=feat_type, config=config, steps=steps, dataset_properties=dataset_properties, include=include, exclude=exclude, random_state=random_state, init_params=init_params, ) def fit_transformer(self, X, y, fit_params=None): if fit_params is None: fit_params = {} if self.config["balancing:strategy"] == "weighting": balancing = Balancing(strategy="weighting") _init_params, _fit_params = balancing.get_weights( y, self.config["classifier:__choice__"], self.config["feature_preprocessor:__choice__"], {}, {}, ) _init_params.update(self.init_params) self.set_hyperparameters( feat_type=self.feat_type, configuration=self.config, init_params=_init_params, ) if _fit_params is not None: fit_params.update(_fit_params) X, fit_params = super().fit_transformer(X, y, fit_params=fit_params) return X, fit_params def predict_proba(self, X, batch_size=None): """predict_proba. Parameters ---------- X : array-like, shape = (n_samples, n_features) batch_size: int or None, defaults to None batch_size controls whether the pipeline will be called on small chunks of the data. Useful when calling the predict method on the whole array X results in a MemoryError. Returns ------- array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes) """ if batch_size is None: return super().predict_proba(X) else: if not isinstance(batch_size, int): raise ValueError( "Argument 'batch_size' must be of type int, " "but is '%s'" % type(batch_size) ) if batch_size <= 0: raise ValueError( "Argument 'batch_size' must be positive, " "but is %d" % batch_size ) else: # Probe for the target array dimensions target = self.predict_proba(X[0:2].copy()) y = np.zeros((X.shape[0], target.shape[1]), dtype=np.float32) for k in range(max(1, int(np.ceil(float(X.shape[0]) / batch_size)))): batch_from = k * batch_size batch_to = min([(k + 1) * batch_size, X.shape[0]]) pred_prob = self.predict_proba( X[batch_from:batch_to], batch_size=None ) y[batch_from:batch_to] = pred_prob.astype(np.float32) return y def _get_hyperparameter_search_space( self, feat_type: Optional[FEAT_TYPE_TYPE] = None, include=None, exclude=None, dataset_properties=None, ): """Create the hyperparameter configuration space. Parameters ---------- feat_type : dict, maps columns to there datatypes include : dict (optional, default=None) Returns ------- cs : ConfigSpace.configuration_space.Configuration The configuration space describing the SimpleRegressionClassifier. """ cs = ConfigurationSpace() if dataset_properties is None or not isinstance(dataset_properties, dict): dataset_properties = dict() if "target_type" not in dataset_properties: dataset_properties["target_type"] = "classification" if dataset_properties["target_type"] != "classification": dataset_properties["target_type"] = "classification" if "sparse" not in dataset_properties: # This dataset is probably dense dataset_properties["sparse"] = False cs = self._get_base_search_space( cs=cs, feat_type=feat_type, dataset_properties=dataset_properties, exclude=exclude, include=include, pipeline=self.steps, ) classifiers = cs.get_hyperparameter("classifier:__choice__").choices preprocessors = cs.get_hyperparameter("feature_preprocessor:__choice__").choices available_classifiers = self._final_estimator.get_available_components( dataset_properties ) possible_default_classifier = copy.copy(list(available_classifiers.keys())) default = cs.get_hyperparameter("classifier:__choice__").default_value del possible_default_classifier[possible_default_classifier.index(default)] # A classifier which can handle sparse data after the densifier is # forbidden for memory issues for key in classifiers: if SPARSE in available_classifiers[key].get_properties()["input"]: if "densifier" in preprocessors: while True: try: forb_cls = ForbiddenEqualsClause( cs.get_hyperparameter("classifier:__choice__"), key ) forb_fpp = ForbiddenEqualsClause( cs.get_hyperparameter( "feature_preprocessor:__choice__" ), "densifier", ) cs.add_forbidden_clause( ForbiddenAndConjunction(forb_cls, forb_fpp) ) # Success break except ValueError: # Change the default and try again try: default = possible_default_classifier.pop() except IndexError: raise ValueError( "Cannot find a legal default configuration." ) cs.get_hyperparameter( "classifier:__choice__" ).default_value = default # which would take too long # Combinations of non-linear models with feature learning: classifiers_ = [ "adaboost", "decision_tree", "extra_trees", "gradient_boosting", "k_nearest_neighbors", "libsvm_svc", "mlp", "random_forest", "gaussian_nb", ] feature_learning = [ "kernel_pca", "kitchen_sinks", "nystroem_sampler", ] for c, f in product(classifiers_, feature_learning): if c not in classifiers: continue if f not in preprocessors: continue while True: try: cs.add_forbidden_clause( ForbiddenAndConjunction( ForbiddenEqualsClause( cs.get_hyperparameter("classifier:__choice__"), c ), ForbiddenEqualsClause( cs.get_hyperparameter( "feature_preprocessor:__choice__" ), f, ), ) ) break except KeyError: break except ValueError: # Change the default and try again try: default = possible_default_classifier.pop() except IndexError: raise ValueError("Cannot find a legal default configuration.") cs.get_hyperparameter( "classifier:__choice__" ).default_value = default # Won't work # Multinomial NB etc don't use with features learning, pca etc classifiers_ = ["multinomial_nb"] preproc_with_negative_X = [ "kitchen_sinks", "pca", "truncatedSVD", "fast_ica", "kernel_pca", "nystroem_sampler", ] for c, f in product(classifiers_, preproc_with_negative_X): if c not in classifiers: continue if f not in preprocessors: continue while True: try: cs.add_forbidden_clause( ForbiddenAndConjunction( ForbiddenEqualsClause( cs.get_hyperparameter( "feature_preprocessor:__choice__" ), f, ), ForbiddenEqualsClause( cs.get_hyperparameter("classifier:__choice__"), c ), ) ) break except KeyError: break except ValueError: # Change the default and try again try: default = possible_default_classifier.pop() except IndexError: raise ValueError("Cannot find a legal default configuration.") cs.get_hyperparameter( "classifier:__choice__" ).default_value = default self.configuration_space = cs self.dataset_properties = dataset_properties return cs def _get_pipeline_steps( self, dataset_properties, feat_type: Optional[FEAT_TYPE_TYPE] = None ): steps = [] default_dataset_properties = {"target_type": "classification"} if dataset_properties is not None and isinstance(dataset_properties, dict): default_dataset_properties.update(dataset_properties) steps.extend( [ [ "data_preprocessor", DataPreprocessorChoice( feat_type=feat_type, dataset_properties=default_dataset_properties, random_state=self.random_state, ), ], ["balancing", Balancing(random_state=self.random_state)], [ "feature_preprocessor", FeaturePreprocessorChoice( feat_type=feat_type, dataset_properties=default_dataset_properties, random_state=self.random_state, ), ], [ "classifier", ClassifierChoice( feat_type=feat_type, dataset_properties=default_dataset_properties, random_state=self.random_state, ), ], ] ) return steps def _get_estimator_hyperparameter_name(self): return "classifier"
bsd-3-clause
tomsilver/nupic
tests/swarming/nupic/swarming/experiments/delta/description.py
1
14792
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Template file used by the OPF Experiment Generator to generate the actual description.py file by replacing $XXXXXXXX tokens with desired values. This description.py file was generated by: '/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py' """ from nupic.frameworks.opf.expdescriptionapi import ExperimentDescriptionAPI from nupic.frameworks.opf.expdescriptionhelpers import ( updateConfigFromSubConfig, applyValueGettersToContainer, DeferredDictLookup) from nupic.frameworks.opf.clamodelcallbacks import * from nupic.frameworks.opf.metrics import MetricSpec from nupic.frameworks.opf.opfutils import (InferenceType, InferenceElement) from nupic.support import aggregationDivide from nupic.frameworks.opf.opftaskdriver import ( IterationPhaseSpecLearnOnly, IterationPhaseSpecInferOnly, IterationPhaseSpecLearnAndInfer) # Model Configuration Dictionary: # # Define the model parameters and adjust for any modifications if imported # from a sub-experiment. # # These fields might be modified by a sub-experiment; this dict is passed # between the sub-experiment and base experiment # # # NOTE: Use of DEFERRED VALUE-GETTERs: dictionary fields and list elements # within the config dictionary may be assigned futures derived from the # ValueGetterBase class, such as DeferredDictLookup. # This facility is particularly handy for enabling substitution of values in # the config dictionary from other values in the config dictionary, which is # needed by permutation.py-based experiments. These values will be resolved # during the call to applyValueGettersToContainer(), # which we call after the base experiment's config dictionary is updated from # the sub-experiment. See ValueGetterBase and # DeferredDictLookup for more details about value-getters. # # For each custom encoder parameter to be exposed to the sub-experiment/ # permutation overrides, define a variable in this section, using key names # beginning with a single underscore character to avoid collisions with # pre-defined keys (e.g., _dsEncoderFieldName2_N). # # Example: # config = dict( # _dsEncoderFieldName2_N = 70, # _dsEncoderFieldName2_W = 5, # dsEncoderSchema = [ # base=dict( # fieldname='Name2', type='ScalarEncoder', # name='Name2', minval=0, maxval=270, clipInput=True, # n=DeferredDictLookup('_dsEncoderFieldName2_N'), # w=DeferredDictLookup('_dsEncoderFieldName2_W')), # ], # ) # updateConfigFromSubConfig(config) # applyValueGettersToContainer(config) config = { # Type of model that the rest of these parameters apply to. 'model': "CLA", # Version that specifies the format of the config. 'version': 1, # Intermediate variables used to compute fields in modelParams and also # referenced from the control section. 'aggregationInfo': { 'days': 0, 'fields': [], 'hours': 0, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0}, 'predictAheadTime': None, # Model parameter dictionary. 'modelParams': { # The type of inference that this model will perform 'inferenceType': 'TemporalMultiStep', 'sensorParams': { # Sensor diagnostic output verbosity control; # if > 0: sensor region will print out on screen what it's sensing # at each step 0: silent; >=1: some info; >=2: more info; # >=3: even more info (see compute() in py/regions/RecordSensor.py) 'verbosity' : 0, # Example: # dsEncoderSchema = [ # DeferredDictLookup('__field_name_encoder'), # ], # # (value generated from DS_ENCODER_SCHEMA) 'encoders': { 'value': { 'clipInput': True, 'fieldname': u'value', 'n': 100, 'name': u'value', 'type': 'ScalarSpaceEncoder', 'w': 21}, '_classifierInput': { 'name': u'_classifierInput', 'fieldname': u'value', 'classifierOnly': True, 'type': 'ScalarSpaceEncoder', 'n': 100, 'w': 21}, }, # A dictionary specifying the period for automatically-generated # resets from a RecordSensor; # # None = disable automatically-generated resets (also disabled if # all of the specified values evaluate to 0). # Valid keys is the desired combination of the following: # days, hours, minutes, seconds, milliseconds, microseconds, weeks # # Example for 1.5 days: sensorAutoReset = dict(days=1,hours=12), # # (value generated from SENSOR_AUTO_RESET) 'sensorAutoReset' : None, }, 'spEnable': True, 'spParams': { # SP diagnostic output verbosity control; # 0: silent; >=1: some info; >=2: more info; 'spVerbosity' : 0, 'globalInhibition': 1, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, 'inputWidth': 0, # SP inhibition control (absolute value); # Maximum number of active columns in the SP region's output (when # there are more, the weaker ones are suppressed) 'numActiveColumnsPerInhArea': 40, 'seed': 1956, # potentialPct # What percent of the columns's receptive field is available # for potential synapses. At initialization time, we will # choose potentialPct * (2*potentialRadius+1)^2 'potentialPct': 0.5, # The default connected threshold. Any synapse whose # permanence value is above the connected threshold is # a "connected synapse", meaning it can contribute to the # cell's firing. Typical value is 0.10. Cells whose activity # level before inhibition falls below minDutyCycleBeforeInh # will have their own internal synPermConnectedCell # threshold set below this default value. # (This concept applies to both SP and TP and so 'cells' # is correct here as opposed to 'columns') 'synPermConnected': 0.1, 'synPermActiveInc': 0.1, 'synPermInactiveDec': 0.01, }, # Controls whether TP is enabled or disabled; # TP is necessary for making temporal predictions, such as predicting # the next inputs. Without TP, the model is only capable of # reconstructing missing sensor inputs (via SP). 'tpEnable' : True, 'tpParams': { # TP diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity # (see verbosity in nupic/trunk/py/nupic/research/TP.py and TP10X*.py) 'verbosity': 0, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, # The number of cells (i.e., states), allocated per column. 'cellsPerColumn': 32, 'inputWidth': 2048, 'seed': 1960, # Temporal Pooler implementation selector (see _getTPClass in # CLARegion.py). 'temporalImp': 'cpp', # New Synapse formation count # NOTE: If None, use spNumActivePerInhArea # # TODO: need better explanation 'newSynapseCount': 20, # Maximum number of synapses per segment # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. 'maxSynapsesPerSegment': 32, # Maximum number of segments per cell # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. 'maxSegmentsPerCell': 128, # Initial Permanence # TODO: need better explanation 'initialPerm': 0.21, # Permanence Increment 'permanenceInc': 0.1, # Permanence Decrement # If set to None, will automatically default to tpPermanenceInc # value. 'permanenceDec' : 0.1, 'globalDecay': 0.0, 'maxAge': 0, # Minimum number of active synapses for a segment to be considered # during search for the best-matching segments. # None=use default # Replaces: tpMinThreshold 'minThreshold': 12, # Segment activation threshold. # A segment is active if it has >= tpSegmentActivationThreshold # connected synapses that are active due to infActiveState # None=use default # Replaces: tpActivationThreshold 'activationThreshold': 16, 'outputType': 'normal', # "Pay Attention Mode" length. This tells the TP how many new # elements to append to the end of a learned sequence at a time. # Smaller values are better for datasets with short sequences, # higher values are better for datasets with long sequences. 'pamLength': 1, }, 'clParams': { 'regionName' : 'CLAClassifierRegion', # Classifier diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity 'clVerbosity' : 0, # This controls how fast the classifier learns/forgets. Higher values # make it adapt faster and forget older patterns faster. 'alpha': 0.001, # This is set after the call to updateConfigFromSubConfig and is # computed from the aggregationInfo and predictAheadTime. 'steps': '1,5', }, 'trainSPNetOnlyIfRequested': False, }, } # end of config dictionary # Adjust base config dictionary for any modifications if imported from a # sub-experiment updateConfigFromSubConfig(config) # Compute predictionSteps based on the predictAheadTime and the aggregation # period, which may be permuted over. if config['predictAheadTime'] is not None: predictionSteps = int(round(aggregationDivide( config['predictAheadTime'], config['aggregationInfo']))) assert (predictionSteps >= 1) config['modelParams']['clParams']['steps'] = str(predictionSteps) # Adjust config by applying ValueGetterBase-derived # futures. NOTE: this MUST be called after updateConfigFromSubConfig() in order # to support value-getter-based substitutions from the sub-experiment (if any) applyValueGettersToContainer(config) control = { # The environment that the current model is being run in "environment": 'nupic', # Input stream specification per py/nupicengine/cluster/database/StreamDef.json. # 'dataset' : { u'info': u'sawtooth test', u'streams': [ { u'columns': [u'value'], u'info': u'sawtooth', u'source': u'file://extra/sawtooth/sawtooth.csv'}], u'version': 1}, # Iteration count: maximum number of iterations. Each iteration corresponds # to one record from the (possibly aggregated) dataset. The task is # terminated when either number of iterations reaches iterationCount or # all records in the (possibly aggregated) database have been processed, # whichever occurs first. # # iterationCount of -1 = iterate over the entire dataset 'iterationCount' : 20, # A dictionary containing all the supplementary parameters for inference "inferenceArgs":{u'predictedField': u'value', u'predictionSteps': [1, 5]}, # Metrics: A list of MetricSpecs that instantiate the metrics that are # computed for this experiment 'metrics':[ MetricSpec(field=u'value', metric='multiStep', inferenceElement='multiStepBestPredictions', params={'window': 10, 'steps': 1, 'errorMetric': 'aae'}), MetricSpec(field=u'value', metric='multiStep', inferenceElement='multiStepBestPredictions', params={'window': 10, 'steps': 5, 'errorMetric': 'aae'}), ], # Logged Metrics: A sequence of regular expressions that specify which of # the metrics from the Inference Specifications section MUST be logged for # every prediction. The regex's correspond to the automatically generated # metric labels. This is similar to the way the optimization metric is # specified in permutations.py. 'loggedMetrics': ['.*nupicScore.*'], } ################################################################################ ################################################################################ descriptionInterface = ExperimentDescriptionAPI(modelConfig=config, control=control)
gpl-3.0
fx2003/tensorflow-study
TensorFlow实战/models/slim/datasets/download_and_convert_flowers.py
7
7201
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Downloads and converts Flowers data to TFRecords of TF-Example protos. This module downloads the Flowers data, uncompresses it, reads the files that make up the Flowers data and creates two TFRecord datasets: one for train and one for test. Each TFRecord dataset is comprised of a set of TF-Example protocol buffers, each of which contain a single image and label. The script should take about a minute to run. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import os import random import sys import tensorflow as tf from datasets import dataset_utils # The URL where the Flowers data can be downloaded. _DATA_URL = 'http://download.tensorflow.org/example_images/flower_photos.tgz' # The number of images in the validation set. _NUM_VALIDATION = 350 # Seed for repeatability. _RANDOM_SEED = 0 # The number of shards per dataset split. _NUM_SHARDS = 5 class ImageReader(object): """Helper class that provides TensorFlow image coding utilities.""" def __init__(self): # Initializes function that decodes RGB JPEG data. self._decode_jpeg_data = tf.placeholder(dtype=tf.string) self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3) def read_image_dims(self, sess, image_data): image = self.decode_jpeg(sess, image_data) return image.shape[0], image.shape[1] def decode_jpeg(self, sess, image_data): image = sess.run(self._decode_jpeg, feed_dict={self._decode_jpeg_data: image_data}) assert len(image.shape) == 3 assert image.shape[2] == 3 return image def _get_filenames_and_classes(dataset_dir): """Returns a list of filenames and inferred class names. Args: dataset_dir: A directory containing a set of subdirectories representing class names. Each subdirectory should contain PNG or JPG encoded images. Returns: A list of image file paths, relative to `dataset_dir` and the list of subdirectories, representing class names. """ flower_root = os.path.join(dataset_dir, 'flower_photos') directories = [] class_names = [] for filename in os.listdir(flower_root): path = os.path.join(flower_root, filename) if os.path.isdir(path): directories.append(path) class_names.append(filename) photo_filenames = [] for directory in directories: for filename in os.listdir(directory): path = os.path.join(directory, filename) photo_filenames.append(path) return photo_filenames, sorted(class_names) def _get_dataset_filename(dataset_dir, split_name, shard_id): output_filename = 'flowers_%s_%05d-of-%05d.tfrecord' % ( split_name, shard_id, _NUM_SHARDS) return os.path.join(dataset_dir, output_filename) def _convert_dataset(split_name, filenames, class_names_to_ids, dataset_dir): """Converts the given filenames to a TFRecord dataset. Args: split_name: The name of the dataset, either 'train' or 'validation'. filenames: A list of absolute paths to png or jpg images. class_names_to_ids: A dictionary from class names (strings) to ids (integers). dataset_dir: The directory where the converted datasets are stored. """ assert split_name in ['train', 'validation'] num_per_shard = int(math.ceil(len(filenames) / float(_NUM_SHARDS))) with tf.Graph().as_default(): image_reader = ImageReader() with tf.Session('') as sess: for shard_id in range(_NUM_SHARDS): output_filename = _get_dataset_filename( dataset_dir, split_name, shard_id) with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer: start_ndx = shard_id * num_per_shard end_ndx = min((shard_id+1) * num_per_shard, len(filenames)) for i in range(start_ndx, end_ndx): sys.stdout.write('\r>> Converting image %d/%d shard %d' % ( i+1, len(filenames), shard_id)) sys.stdout.flush() # Read the filename: image_data = tf.gfile.FastGFile(filenames[i], 'rb').read() height, width = image_reader.read_image_dims(sess, image_data) class_name = os.path.basename(os.path.dirname(filenames[i])) class_id = class_names_to_ids[class_name] example = dataset_utils.image_to_tfexample( image_data, b'jpg', height, width, class_id) tfrecord_writer.write(example.SerializeToString()) sys.stdout.write('\n') sys.stdout.flush() def _clean_up_temporary_files(dataset_dir): """Removes temporary files used to create the dataset. Args: dataset_dir: The directory where the temporary files are stored. """ filename = _DATA_URL.split('/')[-1] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'flower_photos') tf.gfile.DeleteRecursively(tmp_dir) def _dataset_exists(dataset_dir): for split_name in ['train', 'validation']: for shard_id in range(_NUM_SHARDS): output_filename = _get_dataset_filename( dataset_dir, split_name, shard_id) if not tf.gfile.Exists(output_filename): return False return True def run(dataset_dir): """Runs the download and conversion operation. Args: dataset_dir: The dataset directory where the dataset is stored. """ if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) if _dataset_exists(dataset_dir): print('Dataset files already exist. Exiting without re-creating them.') return dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir) photo_filenames, class_names = _get_filenames_and_classes(dataset_dir) class_names_to_ids = dict(zip(class_names, range(len(class_names)))) # Divide into train and test: random.seed(_RANDOM_SEED) random.shuffle(photo_filenames) training_filenames = photo_filenames[_NUM_VALIDATION:] validation_filenames = photo_filenames[:_NUM_VALIDATION] # First, convert the training and validation sets. _convert_dataset('train', training_filenames, class_names_to_ids, dataset_dir) _convert_dataset('validation', validation_filenames, class_names_to_ids, dataset_dir) # Finally, write the labels file: labels_to_class_names = dict(zip(range(len(class_names)), class_names)) dataset_utils.write_label_file(labels_to_class_names, dataset_dir) _clean_up_temporary_files(dataset_dir) print('\nFinished converting the Flowers dataset!')
mit
elkingtonmcb/h2o-2
py/testdir_release/c5/test_c5_KMeans_sphere15_180GB_fvec.py
9
6725
import unittest, time, sys, random, math, json sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_kmeans, h2o_import as h2i, h2o_common import socket print "Assumes you ran ../build_for_clone.py in this directory" print "Using h2o-nodes.json. Also the sandbox dir" DO_KMEANS = True # assumes the cloud was built with CDH3? maybe doesn't matter as long as the file is there FROM_HDFS = 'CDH3' class releaseTest(h2o_common.ReleaseCommon, unittest.TestCase): def test_KMeans_sphere15_180GB(self): # a kludge h2o.setup_benchmark_log() csvFilename = 'syn_sphere15_2711545732row_6col_180GB_from_7x.csv' totalBytes = 183538602156 if FROM_HDFS: importFolderPath = "datasets/kmeans_big" csvPathname = importFolderPath + '/' + csvFilename else: importFolderPath = "/home3/0xdiag/datasets/kmeans_big" csvPathname = importFolderPath + '/' + csvFilename # FIX! put right values in # will there be different expected for random vs the other inits? # removed 0's from first col because we set "ignored_cols" expected = [ ([0.0, -113.00566692375459, -89.99595447985321, -455.9970643424373, 4732.0, 49791778.0, 36800.0], 248846122, 1308149283316.2988) , ([0.0, 1.0, 1.0, -525.0093818313685, 2015.001629398412, 25654042.00592703, 28304.0], 276924291, 1800760152555.98) , ([0.0, 5.0, 2.0, 340.0, 1817.995920197288, 33970406.992053084, 31319.99486705394], 235089554, 375419158808.3253) , ([0.0, 10.0, -72.00113070337981, -171.0198611715457, 4430.00952228909, 37007399.0, 29894.0], 166180630, 525423632323.6474) , ([0.0, 11.0, 3.0, 578.0043558141306, 1483.0163188052604, 22865824.99639042, 5335.0], 167234179, 1845362026223.1094) , ([0.0, 12.0, 3.0, 168.0, -4066.995950679284, 41077063.00269915, -47537.998050740985], 195420925, 197941282992.43475) , ([0.0, 19.00092954923767, -10.999565572612255, 90.00028669073289, 1928.0, 39967190.0, 27202.0], 214401768, 11868360232.658035) , ([0.0, 20.0, 0.0, 141.0, -3263.0030236302937, 6163210.990273981, 30712.99115201907], 258853406, 598863991074.3276) , ([0.0, 21.0, 114.01584574295777, 242.99690338815898, 1674.0029079209912, 33089556.0, 36415.0], 190979054, 1505088759456.314) , ([0.0, 25.0, 1.0, 614.0032787274755, -2275.9931284021022, -48473733.04122273, 47343.0], 87794427, 1124697008162.3955) , ([0.0, 39.0, 3.0, 470.0, -3337.9880599007597, 28768057.98852736, 16716.003410920028], 78226988, 1151439441529.0215) , ([0.0, 40.0, 1.0, 145.0, 950.9990795199593, 14602680.991458317, -14930.007919032574], 167273589, 693036940951.0249) , ([0.0, 42.0, 4.0, 479.0, -3678.0033024834297, 8209673.001421165, 11767.998552236539], 148426180, 35942838893.32379) , ([0.0, 48.0, 4.0, 71.0, -951.0035145455234, 49882273.00063991, -23336.998167498707], 157533313, 88431531357.62982) , ([0.0, 147.00394564757505, 122.98729664236723, 311.0047920137008, 2320.0, 46602185.0, 11212.0], 118361306, 1111537045743.7646) , ] benchmarkLogging = ['cpu','disk', 'network', 'iostats', 'jstack'] benchmarkLogging = ['cpu','disk', 'network', 'iostats'] # IOStatus can hang? benchmarkLogging = ['cpu', 'disk', 'network'] benchmarkLogging = [] for trial in range(6): # IMPORT********************************************** # since H2O deletes the source key, re-import every iteration. # PARSE **************************************** print "Parse starting: " + csvFilename hex_key = csvFilename + "_" + str(trial) + ".hex" start = time.time() timeoutSecs = 2 * 3600 kwargs = {} if FROM_HDFS: parseResult = h2i.import_parse(path=csvPathname, schema='hdfs', hex_key=hex_key, timeoutSecs=timeoutSecs, pollTimeoutSecs=60, retryDelaySecs=2, benchmarkLogging=benchmarkLogging, **kwargs) else: parseResult = h2i.import_parse(path=csvPathname, schema='local', hex_key=hex_key, timeoutSecs=timeoutSecs, pollTimeoutSecs=60, retryDelaySecs=2, benchmarkLogging=benchmarkLogging, **kwargs) elapsed = time.time() - start fileMBS = (totalBytes/1e6)/elapsed l = '{!s} jvms, {!s}GB heap, {:s} {:s} {:6.2f} MB/sec for {:.2f} secs'.format( len(h2o.nodes), h2o.nodes[0].java_heap_GB, 'Parse', csvPathname, fileMBS, elapsed) print "\n"+l h2o.cloudPerfH2O.message(l) # KMeans **************************************** if not DO_KMEANS: continue print "col 0 is enum in " + csvFilename + " but KMeans should skip that automatically?? or no?" kwargs = { 'max_iter': 30, 'k': 15, 'initialization': 'Furthest', 'cols': None, 'destination_key': 'junk.hex', # reuse the same seed, to get deterministic results 'seed': 265211114317615310, } if (trial%3)==0: kwargs['initialization'] = 'PlusPlus' elif (trial%3)==1: kwargs['initialization'] = 'Furthest' else: kwargs['initialization'] = None timeoutSecs = 4 * 3600 params = kwargs paramsString = json.dumps(params) start = time.time() kmeans = h2o_cmd.runKMeans(parseResult=parseResult, timeoutSecs=timeoutSecs, benchmarkLogging=benchmarkLogging, **kwargs) elapsed = time.time() - start print "kmeans end on ", csvPathname, 'took', elapsed, 'seconds.', "%d pct. of timeout" % ((elapsed/timeoutSecs) * 100) l = '{!s} jvms, {!s}GB heap, {:s} {:s} {:s} for {:.2f} secs {:s}' .format( len(h2o.nodes), h2o.nodes[0].java_heap_GB, "KMeans", "trial "+str(trial), csvFilename, elapsed, paramsString) print l h2o.cloudPerfH2O.message(l) (centers, tupleResultList) = h2o_kmeans.bigCheckResults(self, kmeans, csvPathname, parseResult, 'd', **kwargs) # all are multipliers of expected tuple value allowedDelta = (0.01, 0.01, 0.01) h2o_kmeans.compareResultsToExpected(self, tupleResultList, expected, allowedDelta, allowError=True, trial=trial) h2i.delete_keys_at_all_nodes() if __name__ == '__main__': h2o.unit_main()
apache-2.0
lilleswing/deepchem
examples/factors/FACTORS_datasets.py
8
4118
""" FACTORS dataset loader. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os import shutil import time import numpy as np import deepchem as dc from factors_features import factors_descriptors def remove_missing_entries(dataset): """Remove missing entries. Some of the datasets have missing entries that sneak in as zero'd out feature vectors. Get rid of them. """ for i, (X, y, w, ids) in enumerate(dataset.itershards()): available_rows = X.any(axis=1) print("Shard %d has %d missing entries." % (i, np.count_nonzero(~available_rows))) X = X[available_rows] y = y[available_rows] w = w[available_rows] ids = ids[available_rows] dataset.set_shard(i, X, y, w, ids) def get_transformers(train_dataset): """Get transformers applied to datasets.""" transformers = [] return transformers def gen_factors(FACTORS_tasks, raw_train_dir, train_dir, valid_dir, test_dir, shard_size=10000): """Load Factor datasets.""" train_files = ("FACTORS_training_disguised_combined_full.csv.gz") valid_files = ("FACTORS_test1_disguised_combined_full.csv.gz") test_files = ("FACTORS_test2_disguised_combined_full.csv.gz") # Featurize FACTORS dataset print("About to featurize FACTORS dataset.") featurizer = dc.feat.UserDefinedFeaturizer(factors_descriptors) loader = dc.data.UserCSVLoader( tasks=FACTORS_tasks, id_field="Molecule", featurizer=featurizer) train_datasets, valid_datasets, test_datasets = [], [], [] print("Featurizing train datasets") train_dataset = loader.featurize(train_files, shard_size=shard_size) print("Featurizing valid datasets") valid_dataset = loader.featurize(valid_files, shard_size=shard_size) print("Featurizing test datasets") test_dataset = loader.featurize(test_files, shard_size=shard_size) print("Remove missing entries from datasets.") remove_missing_entries(train_dataset) remove_missing_entries(valid_dataset) remove_missing_entries(test_dataset) print("Transforming datasets with transformers.") transformers = get_transformers(train_dataset) raw_train_dataset = train_dataset for transformer in transformers: print("Performing transformations with %s" % transformer.__class__.__name__) print("Transforming datasets") train_dataset = transformer.transform(train_dataset) valid_dataset = transformer.transform(valid_dataset) test_dataset = transformer.transform(test_dataset) print("Shuffling order of train dataset.") train_dataset.sparse_shuffle() print("Moving directories") raw_train_dataset.move(raw_train_dir) train_dataset.move(train_dir) valid_dataset.move(valid_dir) test_dataset.move(test_dir) return (raw_train_dataset, train_dataset, valid_dataset, test_dataset) def load_factors(shard_size): """Loads factors datasets. Generates if not stored already.""" FACTORS_tasks = (['T_0000%d' % i for i in range(1, 10)] + ['T_000%d' % i for i in range(10, 13)]) current_dir = os.path.dirname(os.path.realpath(__file__)) raw_train_dir = os.path.join(current_dir, "raw_train_dir") train_dir = os.path.join(current_dir, "train_dir") valid_dir = os.path.join(current_dir, "valid_dir") test_dir = os.path.join(current_dir, "test_dir") if (os.path.exists(raw_train_dir) and os.path.exists(train_dir) and os.path.exists(valid_dir) and os.path.exists(test_dir)): print("Reloading existing datasets") raw_train_dataset = dc.data.DiskDataset(raw_train_dir) train_dataset = dc.data.DiskDataset(train_dir) valid_dataset = dc.data.DiskDataset(valid_dir) test_dataset = dc.data.DiskDataset(test_dir) else: print("Featurizing datasets") (raw_train_dataset, train_dataset, valid_dataset, test_dataset) = \ gen_factors(FACTORS_tasks, raw_train_dir, train_dir, valid_dir, test_dir, shard_size=shard_size) transformers = get_transformers(raw_train_dataset) return FACTORS_tasks, (train_dataset, valid_dataset, test_dataset), transformers
mit
rcln/tag.suggestion
code_python27/tfidfANDclasification/classByTags.py
1
6011
# -*- coding: utf-8 -*- """ Created on Sat Sep 19 15:21:27 2015 @author: ivan """ from __future__ import division import numpy as np from lxml import etree import os import argparse from sklearn import svm from sklearn.naive_bayes import MultinomialNB from sklearn import metrics from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import KFold #=======================FUNCTION DEFINITION=================================== #Loads the list of different tags from a file def loadVocabulary(tagsListFile): vocab=[] return vocab #returns a vector of the tags of a post def tagsToVector(tagsPost,fullTagsList,n): tagVector=np.zeros(n,dtype='int') for tp in tagsPost: if tp in fullTagsList: tagVector[fullTagsList.index(tp)]=1 return tagVector def getVocabulary(postSetTags): allTags=[] for postTags in postSetTags: allTags+=postTags return list(set(allTags)) def parseBlogFile(myfile): f=open(myfile) document = etree.fromstring(f.read()) date=document.xpath("date/text()") # print date[0] title=document.xpath("title/text()") # print title[0] author=document.xpath("author/text()") # print author[0] tags=document.xpath("tags_set/tag/text()") # for tag in tags: # print tag.text cats=document.xpath("categories_set/category/text()") # for cat in cats: # print cat.text text=document.xpath("text/text()")[0] # print text return (date, author, tags, cats, text, title) def exploreDir(targetDir): f=[] for (dirpath,dirnames,filenames) in os.walk(targetDir): f.extend(filenames) break return f def arArToSt(aA): st=[] for a in aA: st.append(a[0]) return st def readXMLCorpusFrom(thisDirectory): corpusFiles=exploreDir(thisDirectory) corpus=[] targets=[] #indx=0 for doc in corpusFiles: #print doc [dat,aut,tag,cat,txt,tit]=parseBlogFile(thisDirectory+doc) if len(tag)>0 and len(cat)>0: corpus.append(tag) targets.append(cat) return [corpus,targets] #transforms a list of post in a directory into a matrix #listOfPosts = a list of lists of tags one list per post #tagsList = the complete list of tags def vectorizePostSetToTags(listOfPosts,tagsList): #explore the directory and get tags list per post matrxList=[] n=len(tagsList) for post in listOfPosts: matrxList.append(tagsToVector(post,tagsList,n)) matrixTG=np.matrix(matrxList) return matrixTG #============================================================================ #======================ACTUAL RUNNING PROGRAM================================ #-----------[mod1]-Receive and parse program arguments------------------------ parser = argparse.ArgumentParser() parser.add_argument('corpusloc', help='corpus location') parser.add_argument('-f', dest="nkf", type=int, default=10, help='Number of Folds, default=15') args = parser.parse_args() if args.corpusloc[-1]!='/': args.corpusloc+='/' #-----------[mod1]-End-------------------------------------------------------- #-----------[mod2]-Loading corpus, instances and target labels---------------- [inst,labels]=readXMLCorpusFrom(args.corpusloc) classs=arArToSt(labels) #-----------[mod2]-End-------------------------------------------------------- #-----------[mod3]-Features space calculation and vectorizing instances------- features=getVocabulary(inst) matrix=vectorizePostSetToTags(inst,features) #-----------[mod3]-End-------------------------------------------------------- #-----------[mod4]-KFold cross validation experiment on 4 classifiers--------- f=1 print "<Experiment for data located in "+args.corpusloc+">" print "Size of matrix:"+str(matrix.shape) kf = KFold(len(inst), n_folds=args.nkf) for train, test in kf: #Split set into fold train and test sets x_train=np.array(inst)[train] x_test=np.array(inst)[test] y_train=np.array(classs)[train] y_test=np.array(classs)[test] print "<Results for Fold["+str(f)+"]>" features=getVocabulary(x_train) X_train=vectorizePostSetToTags(x_train,features) print "Fold train Matrix["+str(f)+"]:"+str(X_train.shape) X_test=vectorizePostSetToTags(x_test,features) print "Fold test Matrix["+str(f)+"]:"+str(X_test.shape) #Create and train classifiers clf_svm = svm.SVC(kernel='linear') clf_svm.fit(X_train, y_train) clf_mNB=MultinomialNB() clf_mNB.fit(X_train, y_train) clf_knn = KNeighborsClassifier() clf_knn.fit(X_train, y_train) clf_ada=RandomForestClassifier(n_estimators=25) clf_ada.fit(X_train, y_train) #Evaluate the models and output accuracies print "Linear SVM Classifier Accuracy:"+str(clf_svm.score(X_test, y_test)) print "Multinomial Naive Bayes Accuracy:"+str(clf_mNB.score(X_test, y_test)) print "5 Nearest Neighbors Accuracy:"+str(clf_knn.score(X_test, y_test)) print "Random Forest (25 learners) Accuracy:"+str(clf_ada.score(X_test, y_test)) #Obtain the predicted labels for the test subsets predicted_svm = clf_svm.predict(X_test) predicted_mNB = clf_mNB.predict(X_test) predicted_knn = clf_knn.predict(X_test) predicted_ada = clf_ada.predict(X_test) #output metrics on the evaluation print "<Linear SVM Classifier Metrics>" print(metrics.classification_report(y_test, predicted_svm)) print "<Multinomial Naive Bayes Classifier Metrics>" print(metrics.classification_report(y_test, predicted_mNB)) print "<5 Nearest Neighbors Classifier Metrics>" print(metrics.classification_report(y_test, predicted_knn)) print "<Random Forest (25 learners) Classifier Metrics>" print(metrics.classification_report(y_test, predicted_ada)) f+=1 #-----------[mod4]-End--------------------------------------------------------
gpl-2.0
dahlstrom-g/intellij-community
python/helpers/third_party/thriftpy/_shaded_ply/ctokens.py
206
3177
# ---------------------------------------------------------------------- # ctokens.py # # Token specifications for symbols in ANSI C and C++. This file is # meant to be used as a library in other tokenizers. # ---------------------------------------------------------------------- # Reserved words tokens = [ # Literals (identifier, integer constant, float constant, string constant, char const) 'ID', 'TYPEID', 'INTEGER', 'FLOAT', 'STRING', 'CHARACTER', # Operators (+,-,*,/,%,|,&,~,^,<<,>>, ||, &&, !, <, <=, >, >=, ==, !=) 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MODULO', 'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT', 'LOR', 'LAND', 'LNOT', 'LT', 'LE', 'GT', 'GE', 'EQ', 'NE', # Assignment (=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=) 'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL', 'PLUSEQUAL', 'MINUSEQUAL', 'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL', 'OREQUAL', # Increment/decrement (++,--) 'INCREMENT', 'DECREMENT', # Structure dereference (->) 'ARROW', # Ternary operator (?) 'TERNARY', # Delimeters ( ) [ ] { } , . ; : 'LPAREN', 'RPAREN', 'LBRACKET', 'RBRACKET', 'LBRACE', 'RBRACE', 'COMMA', 'PERIOD', 'SEMI', 'COLON', # Ellipsis (...) 'ELLIPSIS', ] # Operators t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_MODULO = r'%' t_OR = r'\|' t_AND = r'&' t_NOT = r'~' t_XOR = r'\^' t_LSHIFT = r'<<' t_RSHIFT = r'>>' t_LOR = r'\|\|' t_LAND = r'&&' t_LNOT = r'!' t_LT = r'<' t_GT = r'>' t_LE = r'<=' t_GE = r'>=' t_EQ = r'==' t_NE = r'!=' # Assignment operators t_EQUALS = r'=' t_TIMESEQUAL = r'\*=' t_DIVEQUAL = r'/=' t_MODEQUAL = r'%=' t_PLUSEQUAL = r'\+=' t_MINUSEQUAL = r'-=' t_LSHIFTEQUAL = r'<<=' t_RSHIFTEQUAL = r'>>=' t_ANDEQUAL = r'&=' t_OREQUAL = r'\|=' t_XOREQUAL = r'\^=' # Increment/decrement t_INCREMENT = r'\+\+' t_DECREMENT = r'--' # -> t_ARROW = r'->' # ? t_TERNARY = r'\?' # Delimeters t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACKET = r'\[' t_RBRACKET = r'\]' t_LBRACE = r'\{' t_RBRACE = r'\}' t_COMMA = r',' t_PERIOD = r'\.' t_SEMI = r';' t_COLON = r':' t_ELLIPSIS = r'\.\.\.' # Identifiers t_ID = r'[A-Za-z_][A-Za-z0-9_]*' # Integer literal t_INTEGER = r'\d+([uU]|[lL]|[uU][lL]|[lL][uU])?' # Floating literal t_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?' # String literal t_STRING = r'\"([^\\\n]|(\\.))*?\"' # Character constant 'c' or L'c' t_CHARACTER = r'(L)?\'([^\\\n]|(\\.))*?\'' # Comment (C-Style) def t_COMMENT(t): r'/\*(.|\n)*?\*/' t.lexer.lineno += t.value.count('\n') return t # Comment (C++-Style) def t_CPPCOMMENT(t): r'//.*\n' t.lexer.lineno += 1 return t
apache-2.0
lukeiwanski/tensorflow
tensorflow/contrib/learn/python/learn/preprocessing/categorical.py
40
4795
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implements preprocessing transformers for categorical variables (deprecated). This module and all its submodules are deprecated. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for migration instructions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from tensorflow.python.util.deprecation import deprecated # pylint: disable=g-bad-import-order from . import categorical_vocabulary from ..learn_io.data_feeder import setup_processor_data_feeder # pylint: enable=g-bad-import-order class CategoricalProcessor(object): """Maps documents to sequences of word ids. THIS CLASS IS DEPRECATED. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for general migration instructions. As a common convention, Nan values are handled as unknown tokens. Both float('nan') and np.nan are accepted. """ @deprecated(None, 'Please use tensorflow/transform or tf.data for sequence ' 'processing.') def __init__(self, min_frequency=0, share=False, vocabularies=None): """Initializes a CategoricalProcessor instance. Args: min_frequency: Minimum frequency of categories in the vocabulary. share: Share vocabulary between variables. vocabularies: list of CategoricalVocabulary objects for each variable in the input dataset. Attributes: vocabularies_: list of CategoricalVocabulary objects. """ self.min_frequency = min_frequency self.share = share self.vocabularies_ = vocabularies def freeze(self, freeze=True): """Freeze or unfreeze all vocabularies. Args: freeze: Boolean, indicate if vocabularies should be frozen. """ for vocab in self.vocabularies_: vocab.freeze(freeze) def fit(self, x, unused_y=None): """Learn a vocabulary dictionary of all categories in `x`. Args: x: numpy matrix or iterable of lists/numpy arrays. unused_y: to match fit format signature of estimators. Returns: self """ x = setup_processor_data_feeder(x) for row in x: # Create vocabularies if not given. if self.vocabularies_ is None: # If not share, one per column, else one shared across. if not self.share: self.vocabularies_ = [ categorical_vocabulary.CategoricalVocabulary() for _ in row ] else: vocab = categorical_vocabulary.CategoricalVocabulary() self.vocabularies_ = [vocab for _ in row] for idx, value in enumerate(row): # Nans are handled as unknowns. if (isinstance(value, float) and math.isnan(value)) or value == np.nan: continue self.vocabularies_[idx].add(value) if self.min_frequency > 0: for vocab in self.vocabularies_: vocab.trim(self.min_frequency) self.freeze() return self def fit_transform(self, x, unused_y=None): """Learn the vocabulary dictionary and return indexies of categories. Args: x: numpy matrix or iterable of lists/numpy arrays. unused_y: to match fit_transform signature of estimators. Returns: x: iterable, [n_samples]. Category-id matrix. """ self.fit(x) return self.transform(x) def transform(self, x): """Transform documents to category-id matrix. Converts categories to ids give fitted vocabulary from `fit` or one provided in the constructor. Args: x: numpy matrix or iterable of lists/numpy arrays. Yields: x: iterable, [n_samples]. Category-id matrix. """ self.freeze() x = setup_processor_data_feeder(x) for row in x: output_row = [] for idx, value in enumerate(row): # Return <UNK> when it's Nan. if (isinstance(value, float) and math.isnan(value)) or value == np.nan: output_row.append(0) continue output_row.append(self.vocabularies_[idx].get(value)) yield np.array(output_row, dtype=np.int64)
apache-2.0
farizrahman4u/keras-contrib
tests/tooling/test_codeowners.py
2
4034
import os import pytest from github import Github try: import pathlib except ImportError: import pathlib2 as pathlib path_to_keras_contrib = pathlib.Path(__file__).resolve().parents[2] path_to_codeowners = path_to_keras_contrib / 'CODEOWNERS' authenticated = True try: github_client = Github(os.environ['GITHUB_TOKEN']) except KeyError: try: github_client = Github(os.environ['GITHUB_USER'], os.environ['GITHUB_PASSWORD']) except KeyError: authenticated = False def parse_codeowners(): map_path_owner = [] for line in open(path_to_codeowners, 'r'): line = line.strip() if line.startswith('#') or line == '': continue x = line.split(' ') path = path_to_keras_contrib / x[0] owner = x[-1] map_path_owner.append((path, owner)) return map_path_owner def test_codeowners_file_exist(): for path, _ in parse_codeowners(): assert path.exists() @pytest.mark.skipif(not authenticated, reason='It should be possible to run the test without' 'authentication, but we might get our request refused' 'by github. To be deterministic, we\'ll disable it.') def test_codeowners_user_exist(): for _, user in parse_codeowners(): assert user[0] == '@' assert github_client.get_user(user[1:]) directories_to_test = [ 'examples', 'keras_contrib/activations', 'keras_contrib/applications', 'keras_contrib/callbacks', 'keras_contrib/constraints', 'keras_contrib/datasets', 'keras_contrib/initializers', 'keras_contrib/layers', 'keras_contrib/losses', 'keras_contrib/metrics', 'keras_contrib/optimizers', 'keras_contrib/preprocessing', 'keras_contrib/regularizers', 'keras_contrib/wrappers' ] directories_to_test = [path_to_keras_contrib / x for x in directories_to_test] # TODO: remove those files or find them owners. exclude = [ 'examples/cifar10_clr.py', 'examples/cifar10_densenet.py', 'examples/cifar10_nasnet.py', 'examples/cifar10_resnet.py', 'examples/cifar10_ror.py', 'examples/cifar10_wide_resnet.py', 'examples/conll2000_chunking_crf.py', 'examples/improved_wgan.py', 'examples/jaccard_loss.py', 'keras_contrib/callbacks/cyclical_learning_rate.py', 'keras_contrib/callbacks/dead_relu_detector.py', 'keras_contrib/applications/resnet.py', 'keras_contrib/constraints/clip.py', 'keras_contrib/datasets/coco.py', 'keras_contrib/datasets/conll2000.py', 'keras_contrib/datasets/pascal_voc.py', 'keras_contrib/initializers/convaware.py', 'keras_contrib/losses/crf_losses.py', 'keras_contrib/losses/dssim.py', 'keras_contrib/losses/jaccard.py', 'keras_contrib/layers/advanced_activations/pelu.py', 'keras_contrib/layers/advanced_activations/srelu.py', 'keras_contrib/layers/convolutional/cosineconvolution2d.py', 'keras_contrib/layers/core.py', 'keras_contrib/layers/crf.py', 'keras_contrib/layers/normalization/instancenormalization.py', 'keras_contrib/optimizers/ftml.py', 'keras_contrib/optimizers/lars.py', 'keras_contrib/metrics/crf_accuracies.py', ] exclude = [path_to_keras_contrib / x for x in exclude] @pytest.mark.parametrize('directory', directories_to_test) def test_all_files_have_owners(directory): files_with_owners = [x[0] for x in parse_codeowners()] for root, dirs, files in os.walk(directory): for name in files: file_path = pathlib.Path(root) / name if file_path.suffix != '.py': continue if file_path.name == '__init__.py': continue if file_path in exclude: continue assert file_path in files_with_owners if __name__ == '__main__': pytest.main([__file__])
mit
ishanic/scikit-learn
sklearn/decomposition/base.py
310
5647
"""Principal Component Analysis Base Classes""" # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Olivier Grisel <olivier.grisel@ensta.org> # Mathieu Blondel <mathieu@mblondel.org> # Denis A. Engemann <d.engemann@fz-juelich.de> # Kyle Kastner <kastnerkyle@gmail.com> # # License: BSD 3 clause import numpy as np from scipy import linalg from ..base import BaseEstimator, TransformerMixin from ..utils import check_array from ..utils.extmath import fast_dot from ..utils.validation import check_is_fitted from ..externals import six from abc import ABCMeta, abstractmethod class _BasePCA(six.with_metaclass(ABCMeta, BaseEstimator, TransformerMixin)): """Base class for PCA methods. Warning: This class should not be used directly. Use derived classes instead. """ def get_covariance(self): """Compute data covariance with the generative model. ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)`` where S**2 contains the explained variances, and sigma2 contains the noise variances. Returns ------- cov : array, shape=(n_features, n_features) Estimated covariance of data. """ components_ = self.components_ exp_var = self.explained_variance_ if self.whiten: components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) cov = np.dot(components_.T * exp_var_diff, components_) cov.flat[::len(cov) + 1] += self.noise_variance_ # modify diag inplace return cov def get_precision(self): """Compute data precision matrix with the generative model. Equals the inverse of the covariance but computed with the matrix inversion lemma for efficiency. Returns ------- precision : array, shape=(n_features, n_features) Estimated precision of data. """ n_features = self.components_.shape[1] # handle corner cases first if self.n_components_ == 0: return np.eye(n_features) / self.noise_variance_ if self.n_components_ == n_features: return linalg.inv(self.get_covariance()) # Get precision using matrix inversion lemma components_ = self.components_ exp_var = self.explained_variance_ if self.whiten: components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) precision = np.dot(components_, components_.T) / self.noise_variance_ precision.flat[::len(precision) + 1] += 1. / exp_var_diff precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_)) precision /= -(self.noise_variance_ ** 2) precision.flat[::len(precision) + 1] += 1. / self.noise_variance_ return precision @abstractmethod def fit(X, y=None): """Placeholder for fit. Subclasses should implement this method! Fit the model with X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. Returns ------- self : object Returns the instance itself. """ def transform(self, X, y=None): """Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_new : array-like, shape (n_samples, n_components) Examples -------- >>> import numpy as np >>> from sklearn.decomposition import IncrementalPCA >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> ipca = IncrementalPCA(n_components=2, batch_size=3) >>> ipca.fit(X) IncrementalPCA(batch_size=3, copy=True, n_components=2, whiten=False) >>> ipca.transform(X) # doctest: +SKIP """ check_is_fitted(self, ['mean_', 'components_'], all_or_any=all) X = check_array(X) if self.mean_ is not None: X = X - self.mean_ X_transformed = fast_dot(X, self.components_.T) if self.whiten: X_transformed /= np.sqrt(self.explained_variance_) return X_transformed def inverse_transform(self, X, y=None): """Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- X_original array-like, shape (n_samples, n_features) Notes ----- If whitening is enabled, inverse_transform will compute the exact inverse operation, which includes reversing whitening. """ if self.whiten: return fast_dot(X, np.sqrt(self.explained_variance_[:, np.newaxis]) * self.components_) + self.mean_ else: return fast_dot(X, self.components_) + self.mean_
bsd-3-clause
ChanChiChoi/scikit-learn
sklearn/decomposition/base.py
310
5647
"""Principal Component Analysis Base Classes""" # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Olivier Grisel <olivier.grisel@ensta.org> # Mathieu Blondel <mathieu@mblondel.org> # Denis A. Engemann <d.engemann@fz-juelich.de> # Kyle Kastner <kastnerkyle@gmail.com> # # License: BSD 3 clause import numpy as np from scipy import linalg from ..base import BaseEstimator, TransformerMixin from ..utils import check_array from ..utils.extmath import fast_dot from ..utils.validation import check_is_fitted from ..externals import six from abc import ABCMeta, abstractmethod class _BasePCA(six.with_metaclass(ABCMeta, BaseEstimator, TransformerMixin)): """Base class for PCA methods. Warning: This class should not be used directly. Use derived classes instead. """ def get_covariance(self): """Compute data covariance with the generative model. ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)`` where S**2 contains the explained variances, and sigma2 contains the noise variances. Returns ------- cov : array, shape=(n_features, n_features) Estimated covariance of data. """ components_ = self.components_ exp_var = self.explained_variance_ if self.whiten: components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) cov = np.dot(components_.T * exp_var_diff, components_) cov.flat[::len(cov) + 1] += self.noise_variance_ # modify diag inplace return cov def get_precision(self): """Compute data precision matrix with the generative model. Equals the inverse of the covariance but computed with the matrix inversion lemma for efficiency. Returns ------- precision : array, shape=(n_features, n_features) Estimated precision of data. """ n_features = self.components_.shape[1] # handle corner cases first if self.n_components_ == 0: return np.eye(n_features) / self.noise_variance_ if self.n_components_ == n_features: return linalg.inv(self.get_covariance()) # Get precision using matrix inversion lemma components_ = self.components_ exp_var = self.explained_variance_ if self.whiten: components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) precision = np.dot(components_, components_.T) / self.noise_variance_ precision.flat[::len(precision) + 1] += 1. / exp_var_diff precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_)) precision /= -(self.noise_variance_ ** 2) precision.flat[::len(precision) + 1] += 1. / self.noise_variance_ return precision @abstractmethod def fit(X, y=None): """Placeholder for fit. Subclasses should implement this method! Fit the model with X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. Returns ------- self : object Returns the instance itself. """ def transform(self, X, y=None): """Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_new : array-like, shape (n_samples, n_components) Examples -------- >>> import numpy as np >>> from sklearn.decomposition import IncrementalPCA >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> ipca = IncrementalPCA(n_components=2, batch_size=3) >>> ipca.fit(X) IncrementalPCA(batch_size=3, copy=True, n_components=2, whiten=False) >>> ipca.transform(X) # doctest: +SKIP """ check_is_fitted(self, ['mean_', 'components_'], all_or_any=all) X = check_array(X) if self.mean_ is not None: X = X - self.mean_ X_transformed = fast_dot(X, self.components_.T) if self.whiten: X_transformed /= np.sqrt(self.explained_variance_) return X_transformed def inverse_transform(self, X, y=None): """Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- X_original array-like, shape (n_samples, n_features) Notes ----- If whitening is enabled, inverse_transform will compute the exact inverse operation, which includes reversing whitening. """ if self.whiten: return fast_dot(X, np.sqrt(self.explained_variance_[:, np.newaxis]) * self.components_) + self.mean_ else: return fast_dot(X, self.components_) + self.mean_
bsd-3-clause
dsquareindia/scikit-learn
benchmarks/bench_glm.py
95
1515
""" A comparison of different methods in GLM Data comes from a random square matrix. """ from datetime import datetime import numpy as np from sklearn import linear_model from sklearn.utils.bench import total_seconds if __name__ == '__main__': import matplotlib.pyplot as plt n_iter = 40 time_ridge = np.empty(n_iter) time_ols = np.empty(n_iter) time_lasso = np.empty(n_iter) dimensions = 500 * np.arange(1, n_iter + 1) for i in range(n_iter): print('Iteration %s of %s' % (i, n_iter)) n_samples, n_features = 10 * i + 3, 10 * i + 3 X = np.random.randn(n_samples, n_features) Y = np.random.randn(n_samples) start = datetime.now() ridge = linear_model.Ridge(alpha=1.) ridge.fit(X, Y) time_ridge[i] = total_seconds(datetime.now() - start) start = datetime.now() ols = linear_model.LinearRegression() ols.fit(X, Y) time_ols[i] = total_seconds(datetime.now() - start) start = datetime.now() lasso = linear_model.LassoLars() lasso.fit(X, Y) time_lasso[i] = total_seconds(datetime.now() - start) plt.figure('scikit-learn GLM benchmark results') plt.xlabel('Dimensions') plt.ylabel('Time (s)') plt.plot(dimensions, time_ridge, color='r') plt.plot(dimensions, time_ols, color='g') plt.plot(dimensions, time_lasso, color='b') plt.legend(['Ridge', 'OLS', 'LassoLars'], loc='upper left') plt.axis('tight') plt.show()
bsd-3-clause
dsquareindia/scikit-learn
sklearn/neural_network/rbm.py
46
12291
"""Restricted Boltzmann Machine """ # Authors: Yann N. Dauphin <dauphiya@iro.umontreal.ca> # Vlad Niculae # Gabriel Synnaeve # Lars Buitinck # License: BSD 3 clause import time import numpy as np import scipy.sparse as sp from ..base import BaseEstimator from ..base import TransformerMixin from ..externals.six.moves import xrange from ..utils import check_array from ..utils import check_random_state from ..utils import gen_even_slices from ..utils import issparse from ..utils.extmath import safe_sparse_dot from ..utils.extmath import log_logistic from ..utils.fixes import expit # logistic function from ..utils.validation import check_is_fitted class BernoulliRBM(BaseEstimator, TransformerMixin): """Bernoulli Restricted Boltzmann Machine (RBM). A Restricted Boltzmann Machine with binary visible units and binary hidden units. Parameters are estimated using Stochastic Maximum Likelihood (SML), also known as Persistent Contrastive Divergence (PCD) [2]. The time complexity of this implementation is ``O(d ** 2)`` assuming d ~ n_features ~ n_components. Read more in the :ref:`User Guide <rbm>`. Parameters ---------- n_components : int, optional Number of binary hidden units. learning_rate : float, optional The learning rate for weight updates. It is *highly* recommended to tune this hyper-parameter. Reasonable values are in the 10**[0., -3.] range. batch_size : int, optional Number of examples per minibatch. n_iter : int, optional Number of iterations/sweeps over the training dataset to perform during training. verbose : int, optional The verbosity level. The default, zero, means silent mode. random_state : integer or numpy.RandomState, optional A random number generator instance to define the state of the random permutations generator. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- intercept_hidden_ : array-like, shape (n_components,) Biases of the hidden units. intercept_visible_ : array-like, shape (n_features,) Biases of the visible units. components_ : array-like, shape (n_components, n_features) Weight matrix, where n_features in the number of visible units and n_components is the number of hidden units. Examples -------- >>> import numpy as np >>> from sklearn.neural_network import BernoulliRBM >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) >>> model = BernoulliRBM(n_components=2) >>> model.fit(X) BernoulliRBM(batch_size=10, learning_rate=0.1, n_components=2, n_iter=10, random_state=None, verbose=0) References ---------- [1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for deep belief nets. Neural Computation 18, pp 1527-1554. http://www.cs.toronto.edu/~hinton/absps/fastnc.pdf [2] Tieleman, T. Training Restricted Boltzmann Machines using Approximations to the Likelihood Gradient. International Conference on Machine Learning (ICML) 2008 """ def __init__(self, n_components=256, learning_rate=0.1, batch_size=10, n_iter=10, verbose=0, random_state=None): self.n_components = n_components self.learning_rate = learning_rate self.batch_size = batch_size self.n_iter = n_iter self.verbose = verbose self.random_state = random_state def transform(self, X): """Compute the hidden layer activation probabilities, P(h=1|v=X). Parameters ---------- X : {array-like, sparse matrix} shape (n_samples, n_features) The data to be transformed. Returns ------- h : array, shape (n_samples, n_components) Latent representations of the data. """ check_is_fitted(self, "components_") X = check_array(X, accept_sparse='csr', dtype=np.float64) return self._mean_hiddens(X) def _mean_hiddens(self, v): """Computes the probabilities P(h=1|v). Parameters ---------- v : array-like, shape (n_samples, n_features) Values of the visible layer. Returns ------- h : array-like, shape (n_samples, n_components) Corresponding mean field values for the hidden layer. """ p = safe_sparse_dot(v, self.components_.T) p += self.intercept_hidden_ return expit(p, out=p) def _sample_hiddens(self, v, rng): """Sample from the distribution P(h|v). Parameters ---------- v : array-like, shape (n_samples, n_features) Values of the visible layer to sample from. rng : RandomState Random number generator to use. Returns ------- h : array-like, shape (n_samples, n_components) Values of the hidden layer. """ p = self._mean_hiddens(v) return (rng.random_sample(size=p.shape) < p) def _sample_visibles(self, h, rng): """Sample from the distribution P(v|h). Parameters ---------- h : array-like, shape (n_samples, n_components) Values of the hidden layer to sample from. rng : RandomState Random number generator to use. Returns ------- v : array-like, shape (n_samples, n_features) Values of the visible layer. """ p = np.dot(h, self.components_) p += self.intercept_visible_ expit(p, out=p) return (rng.random_sample(size=p.shape) < p) def _free_energy(self, v): """Computes the free energy F(v) = - log sum_h exp(-E(v,h)). Parameters ---------- v : array-like, shape (n_samples, n_features) Values of the visible layer. Returns ------- free_energy : array-like, shape (n_samples,) The value of the free energy. """ return (- safe_sparse_dot(v, self.intercept_visible_) - np.logaddexp(0, safe_sparse_dot(v, self.components_.T) + self.intercept_hidden_).sum(axis=1)) def gibbs(self, v): """Perform one Gibbs sampling step. Parameters ---------- v : array-like, shape (n_samples, n_features) Values of the visible layer to start from. Returns ------- v_new : array-like, shape (n_samples, n_features) Values of the visible layer after one Gibbs step. """ check_is_fitted(self, "components_") if not hasattr(self, "random_state_"): self.random_state_ = check_random_state(self.random_state) h_ = self._sample_hiddens(v, self.random_state_) v_ = self._sample_visibles(h_, self.random_state_) return v_ def partial_fit(self, X, y=None): """Fit the model to the data X which should contain a partial segment of the data. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data. Returns ------- self : BernoulliRBM The fitted model. """ X = check_array(X, accept_sparse='csr', dtype=np.float64) if not hasattr(self, 'random_state_'): self.random_state_ = check_random_state(self.random_state) if not hasattr(self, 'components_'): self.components_ = np.asarray( self.random_state_.normal( 0, 0.01, (self.n_components, X.shape[1]) ), order='F') if not hasattr(self, 'intercept_hidden_'): self.intercept_hidden_ = np.zeros(self.n_components, ) if not hasattr(self, 'intercept_visible_'): self.intercept_visible_ = np.zeros(X.shape[1], ) if not hasattr(self, 'h_samples_'): self.h_samples_ = np.zeros((self.batch_size, self.n_components)) self._fit(X, self.random_state_) def _fit(self, v_pos, rng): """Inner fit for one mini-batch. Adjust the parameters to maximize the likelihood of v using Stochastic Maximum Likelihood (SML). Parameters ---------- v_pos : array-like, shape (n_samples, n_features) The data to use for training. rng : RandomState Random number generator to use for sampling. """ h_pos = self._mean_hiddens(v_pos) v_neg = self._sample_visibles(self.h_samples_, rng) h_neg = self._mean_hiddens(v_neg) lr = float(self.learning_rate) / v_pos.shape[0] update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T update -= np.dot(h_neg.T, v_neg) self.components_ += lr * update self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0)) self.intercept_visible_ += lr * (np.asarray( v_pos.sum(axis=0)).squeeze() - v_neg.sum(axis=0)) h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial self.h_samples_ = np.floor(h_neg, h_neg) def score_samples(self, X): """Compute the pseudo-likelihood of X. Parameters ---------- X : {array-like, sparse matrix} shape (n_samples, n_features) Values of the visible layer. Must be all-boolean (not checked). Returns ------- pseudo_likelihood : array-like, shape (n_samples,) Value of the pseudo-likelihood (proxy for likelihood). Notes ----- This method is not deterministic: it computes a quantity called the free energy on X, then on a randomly corrupted version of X, and returns the log of the logistic function of the difference. """ check_is_fitted(self, "components_") v = check_array(X, accept_sparse='csr') rng = check_random_state(self.random_state) # Randomly corrupt one feature in each sample in v. ind = (np.arange(v.shape[0]), rng.randint(0, v.shape[1], v.shape[0])) if issparse(v): data = -2 * v[ind] + 1 v_ = v + sp.csr_matrix((data.A.ravel(), ind), shape=v.shape) else: v_ = v.copy() v_[ind] = 1 - v_[ind] fe = self._free_energy(v) fe_ = self._free_energy(v_) return v.shape[1] * log_logistic(fe_ - fe) def fit(self, X, y=None): """Fit the model to the data X. Parameters ---------- X : {array-like, sparse matrix} shape (n_samples, n_features) Training data. Returns ------- self : BernoulliRBM The fitted model. """ X = check_array(X, accept_sparse='csr', dtype=np.float64) n_samples = X.shape[0] rng = check_random_state(self.random_state) self.components_ = np.asarray( rng.normal(0, 0.01, (self.n_components, X.shape[1])), order='F') self.intercept_hidden_ = np.zeros(self.n_components, ) self.intercept_visible_ = np.zeros(X.shape[1], ) self.h_samples_ = np.zeros((self.batch_size, self.n_components)) n_batches = int(np.ceil(float(n_samples) / self.batch_size)) batch_slices = list(gen_even_slices(n_batches * self.batch_size, n_batches, n_samples)) verbose = self.verbose begin = time.time() for iteration in xrange(1, self.n_iter + 1): for batch_slice in batch_slices: self._fit(X[batch_slice], rng) if verbose: end = time.time() print("[%s] Iteration %d, pseudo-likelihood = %.2f," " time = %.2fs" % (type(self).__name__, iteration, self.score_samples(X).mean(), end - begin)) begin = end return self
bsd-3-clause
krdyke/OGP-metadata-py
src/arcgis2ogp.py
1
9925
from time import clock from datetime import datetime import os, math, sys import pytz import urllib import StringIO import glob import json from logger import Logger from keyword_parse import keywordParse from datatype_parse import * import xml.etree.ElementTree as ET from xml.etree.ElementTree import ElementTree, Element, SubElement import arcpy ######################### ##ArcGIS to FGDC to OGP## ######################### def ARCGIS(workspace): """ Set workspace (where datasets to be processed are located) below """ arcpy.env.workspace = workspace ws = arcpy.env.workspace print 'ws: ',ws """ Get ArcGIS Install Location """ ARCGIS_INSTALL_LOCATION = arcpy.GetInstallInfo()['InstallDir'] """ Get location of XSL Translator to go from ArcGIS to FGDC """ FGDC_XSL_FILE = ARCGIS_INSTALL_LOCATION + "Metadata\\Translator\\Transforms\\ArcGIS2FGDC.xsl" """ Set output location for OGP metadata and log file, then instantiate Logger """ if os.path.exists(ws+"\\output\\"): OUTPUT_LOCATION = ws+"\\output\\" else: os.mkdir(ws+"\\output\\") OUTPUT_LOCATION = ws+"\\output\\" print 'output location: ',OUTPUT_LOCATION d=datetime.today() LOG_NAME = "OGP_MD_LOG_" + d.strftime("%y%m%d%M%S") + ".txt" sys.stdout = Logger(OUTPUT_LOCATION,LOG_NAME) files = arcpy.ListFiles() datasets = arcpy.ListDatasets() fields = ['LayerId', 'Name', 'CollectionId', 'Institution', 'InstitutionSort', 'Access', 'DataType', 'DataTypeSort', 'Availability', 'LayerDisplayName', 'LayerDisplayNameSort', 'Publisher', 'PublisherSort', 'Originator', 'OriginatorSort', 'ThemeKeywords', 'PlaceKeywords', 'Abstract', 'MaxY', 'MinY', 'MinX', 'MaxX', 'CenterX', 'CenterY', 'HalfWidth', 'HalfHeight', 'Area', 'ContentDate','Location'] if os.path.exists(ws + "\\temp.xml"): print "removed temp xml file" os.remove(ws + "\\temp.xml") """ Set UTC timezone for ContentDate field """ utc = pytz.utc for i in datasets[:5]: """ start the clock! obviously not at all necessary """ start = clock() """ converting metadata from ArcGIS to FGDC using XSL transformation (super fast) and writing it to a temporary XML file that is then parsed and translated into final OGP format """ print "======================================" print "Current item is " + i print "======================================\n" print "Converting ArcGIS metadata into temporary FGDC XML file" XSLtrans = arcpy.XSLTransform_conversion(i,FGDC_XSL_FILE,"temp.xml") print XSLtrans.getMessages(),'\n' FGDCtree=ElementTree() root = FGDCtree.parse(ws + "\\temp.xml") DATATYPE = dataTypeParseFGDC(root) DATATYPESORT = DATATYPE #create string representation of FGDC md to be appended at end of OGP md FGDC_TEXT = ET.tostring(root) #layerID equals filename sans extension LAYERID = i[:i.find(".")] #name equals FGDC title field #NAME = root.find("idinfo/citation/citeinfo/title").text try: NAME = root.findtext("idinfo/citation/citeinfo/title") except AttributeError as e: print "Name field doesn't exist! Setting to UNKNOWN for now" NAME = "UNKNOWN" COLLECTIONID = "initial collection" INSTITUTION = "University of Minnesota" INSTITUTIONSORT = "University of Minnesota" try: ACCESS = root.find("idinfo/accconst").text except AttributeError as e: print "Access field doesn't exist! Setting to UNKNOWN for now" ACCESS = "UNKNOWN" AVAILABILITY = "Online" LAYERDISPLAYNAME = NAME LAYERDISPLAYNAMESORT = NAME try: #PUBLISHER = root.find("idinfo/citation/citeinfo/pubinfo/publish").text PUBLISHER = root.findtext("idinfo/citation/citeinfo/pubinfo/publish") except AttributeError as e: print "Publisher field doesn't exist! Setting to UNKNOWN for now" PUBLISHER = "UNKNOWN" finally: PUBLISHERSORT = PUBLISHER try: ORIGINATOR = root.find("idinfo/citation/citeinfo/origin").text except AttributeError as e: print "Originator field doesn't exist! Setting to UNKNOWN for now" ORIGINATOR = "UNKNOWN" finally: ORIGINATORSORT = ORIGINATOR #Combine multiple Keyword elements into a string rep THEMEKEYWORDS= keywordParse(FGDCtree,"themekey") PLACEKEYWORDS = keywordParse(FGDCtree,"placekey") try: ABSTRACT = root.find("idinfo/descript/abstract").text except AttributeError as e: print "No abstract found. Setting to UNKNOWN for now" ABSTRACT = "UNKNOWN" try: MINX=root.find("idinfo/spdom/bounding/westbc").text MINY=root.find("idinfo/spdom/bounding/southbc").text MAXX=root.find("idinfo/spdom/bounding/eastbc").text MAXY=root.find("idinfo/spdom/bounding/northbc").text except AttributeError as e: print "extent information not found!" #SRSPROJECTIONCODE= #try: if root.find("idinfo/timeperd/timeinfo/sngdate/caldate") is not None: dateText = root.find("idinfo/timeperd/timeinfo/sngdate/caldate").text year = int(dateText[0:4]) month = int(dateText[4:6]) day = int(dateText[6:8]) date = datetime(year,month,day) CONTENTDATE = date.isoformat() + "Z" elif root.find("idinfo/timeperd/timeinfo/rngdates/begdate") is not None: dateText = root.find("idinfo/timeperd/timeinfo/rngdates/begdate").text year = int(dateText[0:4]) month = int(dateText[4:6]) day = int(dateText[6:8]) date = datetime(year,month,day) CONTENTDATE = date.isoformat() + "Z" #except AttributeError as e: # print "No content date found! setting to UNKNOWN for now" # CONTENTDATE = "UNKNOWN" """ LOCATION <field name="Location"> { "ArcGIS93Rest": ["(the url for the REST service)"], "tilecache": ["(the url for the tilecache, which I believe ArcGIS server does not have)"], "download": "(downloading URL for the layer)","wfs": "(WFS URL, if has one)" } </field> """ ## #base URL for all images ## REST_URL_BASE = "http://lib-geo1.lib.umn.edu:6080/arcgis/rest/services/OGP/mosaic_ogp_4/ImageServer/exportImage?" ## ## #parameters to pass to URL, in the form of a dictionary ## DOWNLOAD_URL_PARAMS = {} ## DOWNLOAD_URL_PARAMS['bbox'] = MINX+','+MINY+','+MAXX+','+MAXY ## DOWNLOAD_URL_PARAMS['bboxSR'] = '4269' ## DOWNLOAD_URL_PARAMS['imageSR'] = '26915' ## DOWNLOAD_URL_PARAMS['format'] = 'tiff' ## DOWNLOAD_URL_PARAMS['pixelType'] = 'U8' ## DOWNLOAD_URL_PARAMS['size'] = '3000,3000' ## DOWNLOAD_URL_PARAMS['restrictUTurns'] = 'esriNoDataMatchAny' ## DOWNLOAD_URL_PARAMS['interpolation'] = 'RSP_BilinearInterpolation' ## cursor = arcpy.SearchCursor(u"\\mosaic245.gdb\\mosaic_ogp_1","name = '"+ LAYERID+"'") ## raster_ID = cursor.next().OBJECTID ## DOWNLOAD_URL_PARAMS['mosaicRule'] ={} ## DOWNLOAD_URL_PARAMS['mosaicRule']['mosaicMethod'] = 'esriMosaicLockRaster' ## DOWNLOAD_URL_PARAMS['mosaicRule']['lockRasterIds'] = [raster_ID] ## DOWNLOAD_URL_PARAMS['f']='image' ## ## DOWNLOAD_URL = REST_URL_BASE + urllib.urlencode(DOWNLOAD_URL_PARAMS) ## ## REST_URL= REST_URL_BASE + urllib.urlencode({'mosaicRule': DOWNLOAD_URL_PARAMS['mosaicRule']}) ## ## LOCATION = '{"ArcGIS93Rest" : "' + REST_URL + '", "tilecache" : "None", "download" : "' + DOWNLOAD_URL + '", "wfs" : "None"}' """ Put it all together to make the OGP metadata xml file """ OGPtree = ElementTree() OGProot = Element("add",allowDups="false") doc = SubElement(OGProot,"doc") OGPtree._setroot(OGProot) try: for field in fields: fieldEle = SubElement(doc,"field",name=field) fieldEle.text = locals()[field.upper()] except KeyError as e: print "Nonexistant key: ", field fgdc_text=SubElement(doc,"field",name="FgdcText") fgdc_text.text = '<?xml version="1.0"?>'+FGDC_TEXT if os.path.exists(OUTPUT_LOCATION + LAYERID + "_OGP.xml"): existsPrompt =raw_input('OGP metadata already exists! Overwrite? (Y/N): ') if existsPrompt == 'Y': OGPtree.write(OUTPUT_LOCATION + LAYERID + "_OGP.xml") print "Output file: " + OUTPUT_LOCATION + LAYERID + "_OGP.xml" else: pass else: OGPtree.write(OUTPUT_LOCATION + LAYERID + "_OGP.xml") print "Output file: " + OUTPUT_LOCATION + LAYERID + "_OGP.xml" os.remove(ws+"\\temp.xml") print "Next!\n" end = clock() if (end-start) > 60: mins = str(math.ceil((end - start) / 60)) secs = str(math.ceil((end - start) % 60)) print str(len(datasets)) + " datasets processed in " + mins + " minutes and " + secs + " seconds" else: secs = str(math.ceil(end-start)) print str(len(datasets)) + " datasets processed in " + secs + " seconds" sys.stdout=sys.__stdout__ print 'Done. See log file for information'
mit
ishanic/scikit-learn
examples/gaussian_process/plot_gp_regression.py
252
4054
#!/usr/bin/python # -*- coding: utf-8 -*- r""" ========================================================= Gaussian Processes regression: basic introductory example ========================================================= A simple one-dimensional regression exercise computed in two different ways: 1. A noise-free case with a cubic correlation model 2. A noisy case with a squared Euclidean correlation model In both cases, the model parameters are estimated using the maximum likelihood principle. The figures illustrate the interpolating property of the Gaussian Process model as well as its probabilistic nature in the form of a pointwise 95% confidence interval. Note that the parameter ``nugget`` is applied as a Tikhonov regularization of the assumed covariance between the training points. In the special case of the squared euclidean correlation model, nugget is mathematically equivalent to a normalized variance: That is .. math:: \mathrm{nugget}_i = \left[\frac{\sigma_i}{y_i}\right]^2 """ print(__doc__) # Author: Vincent Dubourg <vincent.dubourg@gmail.com> # Jake Vanderplas <vanderplas@astro.washington.edu> # Licence: BSD 3 clause import numpy as np from sklearn.gaussian_process import GaussianProcess from matplotlib import pyplot as pl np.random.seed(1) def f(x): """The function to predict.""" return x * np.sin(x) #---------------------------------------------------------------------- # First the noiseless case X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T # Observations y = f(X).ravel() # Mesh the input space for evaluations of the real function, the prediction and # its MSE x = np.atleast_2d(np.linspace(0, 10, 1000)).T # Instanciate a Gaussian Process model gp = GaussianProcess(corr='cubic', theta0=1e-2, thetaL=1e-4, thetaU=1e-1, random_start=100) # Fit to data using Maximum Likelihood Estimation of the parameters gp.fit(X, y) # Make the prediction on the meshed x-axis (ask for MSE as well) y_pred, MSE = gp.predict(x, eval_MSE=True) sigma = np.sqrt(MSE) # Plot the function, the prediction and the 95% confidence interval based on # the MSE fig = pl.figure() pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$') pl.plot(X, y, 'r.', markersize=10, label=u'Observations') pl.plot(x, y_pred, 'b-', label=u'Prediction') pl.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.5, fc='b', ec='None', label='95% confidence interval') pl.xlabel('$x$') pl.ylabel('$f(x)$') pl.ylim(-10, 20) pl.legend(loc='upper left') #---------------------------------------------------------------------- # now the noisy case X = np.linspace(0.1, 9.9, 20) X = np.atleast_2d(X).T # Observations and noise y = f(X).ravel() dy = 0.5 + 1.0 * np.random.random(y.shape) noise = np.random.normal(0, dy) y += noise # Mesh the input space for evaluations of the real function, the prediction and # its MSE x = np.atleast_2d(np.linspace(0, 10, 1000)).T # Instanciate a Gaussian Process model gp = GaussianProcess(corr='squared_exponential', theta0=1e-1, thetaL=1e-3, thetaU=1, nugget=(dy / y) ** 2, random_start=100) # Fit to data using Maximum Likelihood Estimation of the parameters gp.fit(X, y) # Make the prediction on the meshed x-axis (ask for MSE as well) y_pred, MSE = gp.predict(x, eval_MSE=True) sigma = np.sqrt(MSE) # Plot the function, the prediction and the 95% confidence interval based on # the MSE fig = pl.figure() pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$') pl.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label=u'Observations') pl.plot(x, y_pred, 'b-', label=u'Prediction') pl.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.5, fc='b', ec='None', label='95% confidence interval') pl.xlabel('$x$') pl.ylabel('$f(x)$') pl.ylim(-10, 20) pl.legend(loc='upper left') pl.show()
bsd-3-clause
kylerbrown/scikit-learn
examples/gaussian_process/plot_gp_regression.py
252
4054
#!/usr/bin/python # -*- coding: utf-8 -*- r""" ========================================================= Gaussian Processes regression: basic introductory example ========================================================= A simple one-dimensional regression exercise computed in two different ways: 1. A noise-free case with a cubic correlation model 2. A noisy case with a squared Euclidean correlation model In both cases, the model parameters are estimated using the maximum likelihood principle. The figures illustrate the interpolating property of the Gaussian Process model as well as its probabilistic nature in the form of a pointwise 95% confidence interval. Note that the parameter ``nugget`` is applied as a Tikhonov regularization of the assumed covariance between the training points. In the special case of the squared euclidean correlation model, nugget is mathematically equivalent to a normalized variance: That is .. math:: \mathrm{nugget}_i = \left[\frac{\sigma_i}{y_i}\right]^2 """ print(__doc__) # Author: Vincent Dubourg <vincent.dubourg@gmail.com> # Jake Vanderplas <vanderplas@astro.washington.edu> # Licence: BSD 3 clause import numpy as np from sklearn.gaussian_process import GaussianProcess from matplotlib import pyplot as pl np.random.seed(1) def f(x): """The function to predict.""" return x * np.sin(x) #---------------------------------------------------------------------- # First the noiseless case X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T # Observations y = f(X).ravel() # Mesh the input space for evaluations of the real function, the prediction and # its MSE x = np.atleast_2d(np.linspace(0, 10, 1000)).T # Instanciate a Gaussian Process model gp = GaussianProcess(corr='cubic', theta0=1e-2, thetaL=1e-4, thetaU=1e-1, random_start=100) # Fit to data using Maximum Likelihood Estimation of the parameters gp.fit(X, y) # Make the prediction on the meshed x-axis (ask for MSE as well) y_pred, MSE = gp.predict(x, eval_MSE=True) sigma = np.sqrt(MSE) # Plot the function, the prediction and the 95% confidence interval based on # the MSE fig = pl.figure() pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$') pl.plot(X, y, 'r.', markersize=10, label=u'Observations') pl.plot(x, y_pred, 'b-', label=u'Prediction') pl.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.5, fc='b', ec='None', label='95% confidence interval') pl.xlabel('$x$') pl.ylabel('$f(x)$') pl.ylim(-10, 20) pl.legend(loc='upper left') #---------------------------------------------------------------------- # now the noisy case X = np.linspace(0.1, 9.9, 20) X = np.atleast_2d(X).T # Observations and noise y = f(X).ravel() dy = 0.5 + 1.0 * np.random.random(y.shape) noise = np.random.normal(0, dy) y += noise # Mesh the input space for evaluations of the real function, the prediction and # its MSE x = np.atleast_2d(np.linspace(0, 10, 1000)).T # Instanciate a Gaussian Process model gp = GaussianProcess(corr='squared_exponential', theta0=1e-1, thetaL=1e-3, thetaU=1, nugget=(dy / y) ** 2, random_start=100) # Fit to data using Maximum Likelihood Estimation of the parameters gp.fit(X, y) # Make the prediction on the meshed x-axis (ask for MSE as well) y_pred, MSE = gp.predict(x, eval_MSE=True) sigma = np.sqrt(MSE) # Plot the function, the prediction and the 95% confidence interval based on # the MSE fig = pl.figure() pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$') pl.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label=u'Observations') pl.plot(x, y_pred, 'b-', label=u'Prediction') pl.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.5, fc='b', ec='None', label='95% confidence interval') pl.xlabel('$x$') pl.ylabel('$f(x)$') pl.ylim(-10, 20) pl.legend(loc='upper left') pl.show()
bsd-3-clause
fredhusser/scikit-learn
sklearn/cluster/tests/test_affinity_propagation.py
338
2620
""" Testing for Clustering methods """ import numpy as np from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.cluster.affinity_propagation_ import AffinityPropagation from sklearn.cluster.affinity_propagation_ import affinity_propagation from sklearn.datasets.samples_generator import make_blobs from sklearn.metrics import euclidean_distances n_clusters = 3 centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 X, _ = make_blobs(n_samples=60, n_features=2, centers=centers, cluster_std=0.4, shuffle=True, random_state=0) def test_affinity_propagation(): # Affinity Propagation algorithm # Compute similarities S = -euclidean_distances(X, squared=True) preference = np.median(S) * 10 # Compute Affinity Propagation cluster_centers_indices, labels = affinity_propagation( S, preference=preference) n_clusters_ = len(cluster_centers_indices) assert_equal(n_clusters, n_clusters_) af = AffinityPropagation(preference=preference, affinity="precomputed") labels_precomputed = af.fit(S).labels_ af = AffinityPropagation(preference=preference, verbose=True) labels = af.fit(X).labels_ assert_array_equal(labels, labels_precomputed) cluster_centers_indices = af.cluster_centers_indices_ n_clusters_ = len(cluster_centers_indices) assert_equal(np.unique(labels).size, n_clusters_) assert_equal(n_clusters, n_clusters_) # Test also with no copy _, labels_no_copy = affinity_propagation(S, preference=preference, copy=False) assert_array_equal(labels, labels_no_copy) # Test input validation assert_raises(ValueError, affinity_propagation, S[:, :-1]) assert_raises(ValueError, affinity_propagation, S, damping=0) af = AffinityPropagation(affinity="unknown") assert_raises(ValueError, af.fit, X) def test_affinity_propagation_predict(): # Test AffinityPropagation.predict af = AffinityPropagation(affinity="euclidean") labels = af.fit_predict(X) labels2 = af.predict(X) assert_array_equal(labels, labels2) def test_affinity_propagation_predict_error(): # Test exception in AffinityPropagation.predict # Not fitted. af = AffinityPropagation(affinity="euclidean") assert_raises(ValueError, af.predict, X) # Predict not supported when affinity="precomputed". S = np.dot(X, X.T) af = AffinityPropagation(affinity="precomputed") af.fit(S) assert_raises(ValueError, af.predict, X)
bsd-3-clause
kylerbrown/scikit-learn
sklearn/cluster/tests/test_affinity_propagation.py
338
2620
""" Testing for Clustering methods """ import numpy as np from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.cluster.affinity_propagation_ import AffinityPropagation from sklearn.cluster.affinity_propagation_ import affinity_propagation from sklearn.datasets.samples_generator import make_blobs from sklearn.metrics import euclidean_distances n_clusters = 3 centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 X, _ = make_blobs(n_samples=60, n_features=2, centers=centers, cluster_std=0.4, shuffle=True, random_state=0) def test_affinity_propagation(): # Affinity Propagation algorithm # Compute similarities S = -euclidean_distances(X, squared=True) preference = np.median(S) * 10 # Compute Affinity Propagation cluster_centers_indices, labels = affinity_propagation( S, preference=preference) n_clusters_ = len(cluster_centers_indices) assert_equal(n_clusters, n_clusters_) af = AffinityPropagation(preference=preference, affinity="precomputed") labels_precomputed = af.fit(S).labels_ af = AffinityPropagation(preference=preference, verbose=True) labels = af.fit(X).labels_ assert_array_equal(labels, labels_precomputed) cluster_centers_indices = af.cluster_centers_indices_ n_clusters_ = len(cluster_centers_indices) assert_equal(np.unique(labels).size, n_clusters_) assert_equal(n_clusters, n_clusters_) # Test also with no copy _, labels_no_copy = affinity_propagation(S, preference=preference, copy=False) assert_array_equal(labels, labels_no_copy) # Test input validation assert_raises(ValueError, affinity_propagation, S[:, :-1]) assert_raises(ValueError, affinity_propagation, S, damping=0) af = AffinityPropagation(affinity="unknown") assert_raises(ValueError, af.fit, X) def test_affinity_propagation_predict(): # Test AffinityPropagation.predict af = AffinityPropagation(affinity="euclidean") labels = af.fit_predict(X) labels2 = af.predict(X) assert_array_equal(labels, labels2) def test_affinity_propagation_predict_error(): # Test exception in AffinityPropagation.predict # Not fitted. af = AffinityPropagation(affinity="euclidean") assert_raises(ValueError, af.predict, X) # Predict not supported when affinity="precomputed". S = np.dot(X, X.T) af = AffinityPropagation(affinity="precomputed") af.fit(S) assert_raises(ValueError, af.predict, X)
bsd-3-clause
BayesWatch/tf-variational-dropout
models/resnet.py
1
4928
''' Functional definition for resnet inspired by https://github.com/szagoruyko/functional-zoo Unlike the original code, we're going to access the variables in the model in the orthodox tensorflow way with variable_scopes. It wouldn't be hard to write an iterator that accesses variables defined in the same scope and modifies them, so we could load from pytorch the same way illustrated in the zoo. ''' import tensorflow as tf from .init import pytorch_initializer from tensorflow.contrib.layers import batch_norm as tf_default_batch_norm def batch_norm(x, is_training, scope): # pytorch batch_norm defaults return tf_default_batch_norm(x, is_training=is_training, scope=scope, decay=0.9, epsilon=1e-5) def convert_params(params): '''Convert the channel order of parameters between PyTorch and Tensorflow.''' def tr(v): if v.ndim == 4: return v.transpose(2,3,1,0) elif v.ndim == 2: return v.transpose() return v params = {k: tr(v) for k, v in params.iteritems()} return params def conv2d(x, phase, n_filters, kernel_size, strides=[1,1,1,1], activation_fn=tf.nn.relu, initializer=pytorch_initializer, padding='SAME', scope=None, bias=True): with tf.variable_scope(scope): n_input_channels = int(x.shape[3]) # define parameters conv_param_shape = kernel_size+[n_input_channels, n_filters] w = tf.get_variable("w", conv_param_shape, initializer=initializer()) if bias: b = tf.get_variable("b", [n_filters], initializer=tf.constant_initializer()) activations = tf.nn.conv2d(x, w, strides=strides, padding=padding) if bias: return activation_fn(activations + b) else: return activation_fn(activations) def resnet50(inputs, phase, conv2d=conv2d): '''Using bottleneck that matches those used in the PyTorch model definition: https://github.com/kuangliu/pytorch-cifar/blob/master/models/resnet.py#L41-L66 ''' def conv2d_norelu(x, phase, n_filters, kernel_size, strides=[1,1,1,1], initializer=pytorch_initializer, padding='SAME', scope=None, bias=True): return conv2d(x, phase, n_filters, kernel_size, strides=strides, activation_fn=lambda x:x, initializer=initializer, padding=padding, scope=scope, bias=bias) expansion = 4 def group(input, base, in_planes, planes, num_blocks, stride): strides = [stride]+[1]*(num_blocks-1) o = input for i,stride in enumerate(strides): b_base = ('%s.block%d.conv') % (base, i) x = o o = bottleneck(x, b_base, in_planes, planes, stride) in_planes = planes*expansion return o, in_planes def bottleneck(input, base, in_planes, planes, stride=1): o = conv2d_norelu(input, phase, planes, [1,1], scope=base+'0', bias=False) o = tf.nn.relu(batch_norm(o, is_training=phase, scope=base+'0')) o = conv2d_norelu(o, phase, planes, [3,3], scope=base+'1', strides=[1,stride,stride,1], padding='SAME', bias=False) o = tf.nn.relu(batch_norm(o, is_training=phase, scope=base+'1')) o = conv2d_norelu(o, phase, planes*expansion, [1,1], scope=base+'2', bias=False) o = batch_norm(o, is_training=phase, scope=base+'2') if stride != 1 or in_planes != expansion*planes: # shortcut s = conv2d_norelu(input, phase, expansion*planes, [1,1], strides=[1,stride,stride,1], bias=False, scope=base+'short') s = batch_norm(s, is_training=phase, scope=base+'short') o = o+s else: o = o+input return tf.nn.relu(o) blocks = [3,4,6,3] o = conv2d_norelu(inputs, phase, 64, [3,3], scope='conv0', padding='SAME') o = tf.nn.relu(batch_norm(o, is_training=phase, scope='bn0')) #o = tf.pad(o, [[0,0], [1,1], [1,1], [0,0]]) #o = tf.nn.max_pool(o, ksize=[1,3,3,1], strides=[1,2,2,1], padding='VALID') in_planes = 64 o_g0, in_planes = group(o, 'group0', in_planes, 64, blocks[0], 1) o_g1, in_planes = group(o_g0, 'group1', in_planes, 128, blocks[1], 2) o_g2, in_planes = group(o_g1, 'group2', in_planes, 256, blocks[2], 2) o_g3, in_planes = group(o_g2, 'group3', in_planes, 512, blocks[3], 2) o = tf.nn.avg_pool(o_g3, ksize=[1,4,4,1], strides=[1,1,1,1], padding='VALID') o = conv2d_norelu(o, phase, 10, [1,1], scope='fc') o = tf.reshape(o, [-1,10]) return o if __name__ == '__main__': import numpy.random as npr inputs = tf.Variable(npr.randn(16,32,32,3), dtype=tf.float32) phase = True out = resnet50(inputs, phase) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(out).shape)
gpl-3.0
kylerbrown/scikit-learn
sklearn/utils/tests/test_fixes.py
278
1829
# Authors: Gael Varoquaux <gael.varoquaux@normalesup.org> # Justin Vincent # Lars Buitinck # License: BSD 3 clause import numpy as np from nose.tools import assert_equal from nose.tools import assert_false from nose.tools import assert_true from numpy.testing import (assert_almost_equal, assert_array_almost_equal) from sklearn.utils.fixes import divide, expit from sklearn.utils.fixes import astype def test_expit(): # Check numerical stability of expit (logistic function). # Simulate our previous Cython implementation, based on #http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression assert_almost_equal(expit(1000.), 1. / (1. + np.exp(-1000.)), decimal=16) assert_almost_equal(expit(-1000.), np.exp(-1000.) / (1. + np.exp(-1000.)), decimal=16) x = np.arange(10) out = np.zeros_like(x, dtype=np.float32) assert_array_almost_equal(expit(x), expit(x, out=out)) def test_divide(): assert_equal(divide(.6, 1), .600000000000) def test_astype_copy_memory(): a_int32 = np.ones(3, np.int32) # Check that dtype conversion works b_float32 = astype(a_int32, dtype=np.float32, copy=False) assert_equal(b_float32.dtype, np.float32) # Changing dtype forces a copy even if copy=False assert_false(np.may_share_memory(b_float32, a_int32)) # Check that copy can be skipped if requested dtype match c_int32 = astype(a_int32, dtype=np.int32, copy=False) assert_true(c_int32 is a_int32) # Check that copy can be forced, and is the case by default: d_int32 = astype(a_int32, dtype=np.int32, copy=True) assert_false(np.may_share_memory(d_int32, a_int32)) e_int32 = astype(a_int32, dtype=np.int32) assert_false(np.may_share_memory(e_int32, a_int32))
bsd-3-clause
fredhusser/scikit-learn
examples/svm/plot_separating_hyperplane.py
291
1273
""" ========================================= SVM: Maximum margin separating hyperplane ========================================= Plot the maximum margin separating hyperplane within a two-class separable dataset using a Support Vector Machine classifier with linear kernel. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm # we create 40 separable points np.random.seed(0) X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] Y = [0] * 20 + [1] * 20 # fit the model clf = svm.SVC(kernel='linear') clf.fit(X, Y) # get the separating hyperplane w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - (clf.intercept_[0]) / w[1] # plot the parallels to the separating hyperplane that pass through the # support vectors b = clf.support_vectors_[0] yy_down = a * xx + (b[1] - a * b[0]) b = clf.support_vectors_[-1] yy_up = a * xx + (b[1] - a * b[0]) # plot the line, the points, and the nearest vectors to the plane plt.plot(xx, yy, 'k-') plt.plot(xx, yy_down, 'k--') plt.plot(xx, yy_up, 'k--') plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors='none') plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) plt.axis('tight') plt.show()
bsd-3-clause
ishanic/scikit-learn
examples/applications/svm_gui.py
285
11161
""" ========== Libsvm GUI ========== A simple graphical frontend for Libsvm mainly intended for didactic purposes. You can create data points by point and click and visualize the decision region induced by different kernels and parameter settings. To create positive examples click the left mouse button; to create negative examples click the right button. If all examples are from the same class, it uses a one-class SVM. """ from __future__ import division, print_function print(__doc__) # Author: Peter Prettenhoer <peter.prettenhofer@gmail.com> # # License: BSD 3 clause import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.contour import ContourSet import Tkinter as Tk import sys import numpy as np from sklearn import svm from sklearn.datasets import dump_svmlight_file from sklearn.externals.six.moves import xrange y_min, y_max = -50, 50 x_min, x_max = -50, 50 class Model(object): """The Model which hold the data. It implements the observable in the observer pattern and notifies the registered observers on change event. """ def __init__(self): self.observers = [] self.surface = None self.data = [] self.cls = None self.surface_type = 0 def changed(self, event): """Notify the observers. """ for observer in self.observers: observer.update(event, self) def add_observer(self, observer): """Register an observer. """ self.observers.append(observer) def set_surface(self, surface): self.surface = surface def dump_svmlight_file(self, file): data = np.array(self.data) X = data[:, 0:2] y = data[:, 2] dump_svmlight_file(X, y, file) class Controller(object): def __init__(self, model): self.model = model self.kernel = Tk.IntVar() self.surface_type = Tk.IntVar() # Whether or not a model has been fitted self.fitted = False def fit(self): print("fit the model") train = np.array(self.model.data) X = train[:, 0:2] y = train[:, 2] C = float(self.complexity.get()) gamma = float(self.gamma.get()) coef0 = float(self.coef0.get()) degree = int(self.degree.get()) kernel_map = {0: "linear", 1: "rbf", 2: "poly"} if len(np.unique(y)) == 1: clf = svm.OneClassSVM(kernel=kernel_map[self.kernel.get()], gamma=gamma, coef0=coef0, degree=degree) clf.fit(X) else: clf = svm.SVC(kernel=kernel_map[self.kernel.get()], C=C, gamma=gamma, coef0=coef0, degree=degree) clf.fit(X, y) if hasattr(clf, 'score'): print("Accuracy:", clf.score(X, y) * 100) X1, X2, Z = self.decision_surface(clf) self.model.clf = clf self.model.set_surface((X1, X2, Z)) self.model.surface_type = self.surface_type.get() self.fitted = True self.model.changed("surface") def decision_surface(self, cls): delta = 1 x = np.arange(x_min, x_max + delta, delta) y = np.arange(y_min, y_max + delta, delta) X1, X2 = np.meshgrid(x, y) Z = cls.decision_function(np.c_[X1.ravel(), X2.ravel()]) Z = Z.reshape(X1.shape) return X1, X2, Z def clear_data(self): self.model.data = [] self.fitted = False self.model.changed("clear") def add_example(self, x, y, label): self.model.data.append((x, y, label)) self.model.changed("example_added") # update decision surface if already fitted. self.refit() def refit(self): """Refit the model if already fitted. """ if self.fitted: self.fit() class View(object): """Test docstring. """ def __init__(self, root, controller): f = Figure() ax = f.add_subplot(111) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim((x_min, x_max)) ax.set_ylim((y_min, y_max)) canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas.mpl_connect('button_press_event', self.onclick) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() self.controllbar = ControllBar(root, controller) self.f = f self.ax = ax self.canvas = canvas self.controller = controller self.contours = [] self.c_labels = None self.plot_kernels() def plot_kernels(self): self.ax.text(-50, -60, "Linear: $u^T v$") self.ax.text(-20, -60, "RBF: $\exp (-\gamma \| u-v \|^2)$") self.ax.text(10, -60, "Poly: $(\gamma \, u^T v + r)^d$") def onclick(self, event): if event.xdata and event.ydata: if event.button == 1: self.controller.add_example(event.xdata, event.ydata, 1) elif event.button == 3: self.controller.add_example(event.xdata, event.ydata, -1) def update_example(self, model, idx): x, y, l = model.data[idx] if l == 1: color = 'w' elif l == -1: color = 'k' self.ax.plot([x], [y], "%so" % color, scalex=0.0, scaley=0.0) def update(self, event, model): if event == "examples_loaded": for i in xrange(len(model.data)): self.update_example(model, i) if event == "example_added": self.update_example(model, -1) if event == "clear": self.ax.clear() self.ax.set_xticks([]) self.ax.set_yticks([]) self.contours = [] self.c_labels = None self.plot_kernels() if event == "surface": self.remove_surface() self.plot_support_vectors(model.clf.support_vectors_) self.plot_decision_surface(model.surface, model.surface_type) self.canvas.draw() def remove_surface(self): """Remove old decision surface.""" if len(self.contours) > 0: for contour in self.contours: if isinstance(contour, ContourSet): for lineset in contour.collections: lineset.remove() else: contour.remove() self.contours = [] def plot_support_vectors(self, support_vectors): """Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.""" cs = self.ax.scatter(support_vectors[:, 0], support_vectors[:, 1], s=80, edgecolors="k", facecolors="none") self.contours.append(cs) def plot_decision_surface(self, surface, type): X1, X2, Z = surface if type == 0: levels = [-1.0, 0.0, 1.0] linestyles = ['dashed', 'solid', 'dashed'] colors = 'k' self.contours.append(self.ax.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)) elif type == 1: self.contours.append(self.ax.contourf(X1, X2, Z, 10, cmap=matplotlib.cm.bone, origin='lower', alpha=0.85)) self.contours.append(self.ax.contour(X1, X2, Z, [0.0], colors='k', linestyles=['solid'])) else: raise ValueError("surface type unknown") class ControllBar(object): def __init__(self, root, controller): fm = Tk.Frame(root) kernel_group = Tk.Frame(fm) Tk.Radiobutton(kernel_group, text="Linear", variable=controller.kernel, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="RBF", variable=controller.kernel, value=1, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="Poly", variable=controller.kernel, value=2, command=controller.refit).pack(anchor=Tk.W) kernel_group.pack(side=Tk.LEFT) valbox = Tk.Frame(fm) controller.complexity = Tk.StringVar() controller.complexity.set("1.0") c = Tk.Frame(valbox) Tk.Label(c, text="C:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(c, width=6, textvariable=controller.complexity).pack( side=Tk.LEFT) c.pack() controller.gamma = Tk.StringVar() controller.gamma.set("0.01") g = Tk.Frame(valbox) Tk.Label(g, text="gamma:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(g, width=6, textvariable=controller.gamma).pack(side=Tk.LEFT) g.pack() controller.degree = Tk.StringVar() controller.degree.set("3") d = Tk.Frame(valbox) Tk.Label(d, text="degree:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(d, width=6, textvariable=controller.degree).pack(side=Tk.LEFT) d.pack() controller.coef0 = Tk.StringVar() controller.coef0.set("0") r = Tk.Frame(valbox) Tk.Label(r, text="coef0:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(r, width=6, textvariable=controller.coef0).pack(side=Tk.LEFT) r.pack() valbox.pack(side=Tk.LEFT) cmap_group = Tk.Frame(fm) Tk.Radiobutton(cmap_group, text="Hyperplanes", variable=controller.surface_type, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(cmap_group, text="Surface", variable=controller.surface_type, value=1, command=controller.refit).pack(anchor=Tk.W) cmap_group.pack(side=Tk.LEFT) train_button = Tk.Button(fm, text='Fit', width=5, command=controller.fit) train_button.pack() fm.pack(side=Tk.LEFT) Tk.Button(fm, text='Clear', width=5, command=controller.clear_data).pack(side=Tk.LEFT) def get_parser(): from optparse import OptionParser op = OptionParser() op.add_option("--output", action="store", type="str", dest="output", help="Path where to dump data.") return op def main(argv): op = get_parser() opts, args = op.parse_args(argv[1:]) root = Tk.Tk() model = Model() controller = Controller(model) root.wm_title("Scikit-learn Libsvm GUI") view = View(root, controller) model.add_observer(view) Tk.mainloop() if opts.output: model.dump_svmlight_file(opts.output) if __name__ == "__main__": main(sys.argv)
bsd-3-clause
andrewnc/scikit-learn
sklearn/__check_build/__init__.py
342
1671
""" Module to give helpful messages to the user that did not compile the scikit properly. """ import os INPLACE_MSG = """ It appears that you are importing a local scikit-learn source tree. For this, you need to have an inplace install. Maybe you are in the source directory and you need to try from another location.""" STANDARD_MSG = """ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG dir_content = list() for i, filename in enumerate(os.listdir(local_dir)): if ((i + 1) % 3): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s ___________________________________________________________________________ It seems that scikit-learn has not been built correctly. If you have installed scikit-learn from source, please do not forget to build the package before using it: run `python setup.py install` or `make` in the source directory. %s""" % (e, local_dir, ''.join(dir_content).strip(), msg)) try: from ._check_build import check_build except ImportError as e: raise_build_error(e)
bsd-3-clause
ishanic/scikit-learn
sklearn/__check_build/__init__.py
342
1671
""" Module to give helpful messages to the user that did not compile the scikit properly. """ import os INPLACE_MSG = """ It appears that you are importing a local scikit-learn source tree. For this, you need to have an inplace install. Maybe you are in the source directory and you need to try from another location.""" STANDARD_MSG = """ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG dir_content = list() for i, filename in enumerate(os.listdir(local_dir)): if ((i + 1) % 3): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s ___________________________________________________________________________ It seems that scikit-learn has not been built correctly. If you have installed scikit-learn from source, please do not forget to build the package before using it: run `python setup.py install` or `make` in the source directory. %s""" % (e, local_dir, ''.join(dir_content).strip(), msg)) try: from ._check_build import check_build except ImportError as e: raise_build_error(e)
bsd-3-clause
kylerbrown/scikit-learn
sklearn/__check_build/__init__.py
342
1671
""" Module to give helpful messages to the user that did not compile the scikit properly. """ import os INPLACE_MSG = """ It appears that you are importing a local scikit-learn source tree. For this, you need to have an inplace install. Maybe you are in the source directory and you need to try from another location.""" STANDARD_MSG = """ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG dir_content = list() for i, filename in enumerate(os.listdir(local_dir)): if ((i + 1) % 3): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s ___________________________________________________________________________ It seems that scikit-learn has not been built correctly. If you have installed scikit-learn from source, please do not forget to build the package before using it: run `python setup.py install` or `make` in the source directory. %s""" % (e, local_dir, ''.join(dir_content).strip(), msg)) try: from ._check_build import check_build except ImportError as e: raise_build_error(e)
bsd-3-clause
kylerbrown/scikit-learn
sklearn/metrics/cluster/unsupervised.py
228
8281
""" Unsupervised evaluation metrics. """ # Authors: Robert Layton <robertlayton@gmail.com> # # License: BSD 3 clause import numpy as np from ...utils import check_random_state from ..pairwise import pairwise_distances def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. To clarify, ``b`` is the distance between a sample and the nearest cluster that the sample is not a part of. Note that Silhouette Coefficent is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the mean Silhouette Coefficient over all samples. To obtain the values for each sample, use :func:`silhouette_samples`. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Negative values generally indicate that a sample has been assigned to the wrong cluster, as a different cluster is more similar. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] Predicted labels for each sample. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`metrics.pairwise.pairwise_distances <sklearn.metrics.pairwise.pairwise_distances>`. If X is the distance array itself, use ``metric="precomputed"``. sample_size : int or None The size of the sample to use when computing the Silhouette Coefficient on a random subset of the data. If ``sample_size is None``, no sampling is used. random_state : integer or numpy.RandomState, optional The generator used to randomly select a subset of samples if ``sample_size is not None``. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : float Mean Silhouette Coefficient for all samples. References ---------- .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <http://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ n_labels = len(np.unique(labels)) n_samples = X.shape[0] if not 1 < n_labels < n_samples: raise ValueError("Number of labels is %d. Valid values are 2 " "to n_samples - 1 (inclusive)" % n_labels) if sample_size is not None: random_state = check_random_state(random_state) indices = random_state.permutation(X.shape[0])[:sample_size] if metric == "precomputed": X, labels = X[indices].T[indices].T, labels[indices] else: X, labels = X[indices], labels[indices] return np.mean(silhouette_samples(X, labels, metric=metric, **kwds)) def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each other, and well separated, where samples in different clusters are not very similar to each other. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. Note that Silhouette Coefficent is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the Silhouette Coefficient for each sample. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] label values for each sample metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is the distance array itself, use "precomputed" as the metric. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a ``scipy.spatial.distance`` metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : array, shape = [n_samples] Silhouette Coefficient for each samples. References ---------- .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <http://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ distances = pairwise_distances(X, metric=metric, **kwds) n = labels.shape[0] A = np.array([_intra_cluster_distance(distances[i], labels, i) for i in range(n)]) B = np.array([_nearest_cluster_distance(distances[i], labels, i) for i in range(n)]) sil_samples = (B - A) / np.maximum(A, B) return sil_samples def _intra_cluster_distance(distances_row, labels, i): """Calculate the mean intra-cluster distance for sample i. Parameters ---------- distances_row : array, shape = [n_samples] Pairwise distance matrix between sample i and each sample. labels : array, shape = [n_samples] label values for each sample i : int Sample index being calculated. It is excluded from calculation and used to determine the current label Returns ------- a : float Mean intra-cluster distance for sample i """ mask = labels == labels[i] mask[i] = False if not np.any(mask): # cluster of size 1 return 0 a = np.mean(distances_row[mask]) return a def _nearest_cluster_distance(distances_row, labels, i): """Calculate the mean nearest-cluster distance for sample i. Parameters ---------- distances_row : array, shape = [n_samples] Pairwise distance matrix between sample i and each sample. labels : array, shape = [n_samples] label values for each sample i : int Sample index being calculated. It is used to determine the current label. Returns ------- b : float Mean nearest-cluster distance for sample i """ label = labels[i] b = np.min([np.mean(distances_row[labels == cur_label]) for cur_label in set(labels) if not cur_label == label]) return b
bsd-3-clause
ChanChiChoi/scikit-learn
sklearn/__check_build/__init__.py
342
1671
""" Module to give helpful messages to the user that did not compile the scikit properly. """ import os INPLACE_MSG = """ It appears that you are importing a local scikit-learn source tree. For this, you need to have an inplace install. Maybe you are in the source directory and you need to try from another location.""" STANDARD_MSG = """ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG dir_content = list() for i, filename in enumerate(os.listdir(local_dir)): if ((i + 1) % 3): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s ___________________________________________________________________________ It seems that scikit-learn has not been built correctly. If you have installed scikit-learn from source, please do not forget to build the package before using it: run `python setup.py install` or `make` in the source directory. %s""" % (e, local_dir, ''.join(dir_content).strip(), msg)) try: from ._check_build import check_build except ImportError as e: raise_build_error(e)
bsd-3-clause
fredhusser/scikit-learn
examples/ensemble/plot_voting_decision_regions.py
228
2386
""" ================================================== Plot the decision boundaries of a VotingClassifier ================================================== Plot the decision boundaries of a `VotingClassifier` for two features of the Iris dataset. Plot the class probabilities of the first sample in a toy dataset predicted by three different classifiers and averaged by the `VotingClassifier`. First, three examplary classifiers are initialized (`DecisionTreeClassifier`, `KNeighborsClassifier`, and `SVC`) and used to initialize a soft-voting `VotingClassifier` with weights `[2, 1, 2]`, which means that the predicted probabilities of the `DecisionTreeClassifier` and `SVC` count 5 times as much as the weights of the `KNeighborsClassifier` classifier when the averaged probability is calculated. """ print(__doc__) from itertools import product import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.ensemble import VotingClassifier # Loading some example data iris = datasets.load_iris() X = iris.data[:, [0, 2]] y = iris.target # Training classifiers clf1 = DecisionTreeClassifier(max_depth=4) clf2 = KNeighborsClassifier(n_neighbors=7) clf3 = SVC(kernel='rbf', probability=True) eclf = VotingClassifier(estimators=[('dt', clf1), ('knn', clf2), ('svc', clf3)], voting='soft', weights=[2, 1, 2]) clf1.fit(X, y) clf2.fit(X, y) clf3.fit(X, y) eclf.fit(X, y) # Plotting decision regions x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8)) for idx, clf, tt in zip(product([0, 1], [0, 1]), [clf1, clf2, clf3, eclf], ['Decision Tree (depth=4)', 'KNN (k=7)', 'Kernel SVM', 'Soft Voting']): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4) axarr[idx[0], idx[1]].scatter(X[:, 0], X[:, 1], c=y, alpha=0.8) axarr[idx[0], idx[1]].set_title(tt) plt.show()
bsd-3-clause
kylerbrown/scikit-learn
examples/ensemble/plot_voting_decision_regions.py
228
2386
""" ================================================== Plot the decision boundaries of a VotingClassifier ================================================== Plot the decision boundaries of a `VotingClassifier` for two features of the Iris dataset. Plot the class probabilities of the first sample in a toy dataset predicted by three different classifiers and averaged by the `VotingClassifier`. First, three examplary classifiers are initialized (`DecisionTreeClassifier`, `KNeighborsClassifier`, and `SVC`) and used to initialize a soft-voting `VotingClassifier` with weights `[2, 1, 2]`, which means that the predicted probabilities of the `DecisionTreeClassifier` and `SVC` count 5 times as much as the weights of the `KNeighborsClassifier` classifier when the averaged probability is calculated. """ print(__doc__) from itertools import product import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.ensemble import VotingClassifier # Loading some example data iris = datasets.load_iris() X = iris.data[:, [0, 2]] y = iris.target # Training classifiers clf1 = DecisionTreeClassifier(max_depth=4) clf2 = KNeighborsClassifier(n_neighbors=7) clf3 = SVC(kernel='rbf', probability=True) eclf = VotingClassifier(estimators=[('dt', clf1), ('knn', clf2), ('svc', clf3)], voting='soft', weights=[2, 1, 2]) clf1.fit(X, y) clf2.fit(X, y) clf3.fit(X, y) eclf.fit(X, y) # Plotting decision regions x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8)) for idx, clf, tt in zip(product([0, 1], [0, 1]), [clf1, clf2, clf3, eclf], ['Decision Tree (depth=4)', 'KNN (k=7)', 'Kernel SVM', 'Soft Voting']): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4) axarr[idx[0], idx[1]].scatter(X[:, 0], X[:, 1], c=y, alpha=0.8) axarr[idx[0], idx[1]].set_title(tt) plt.show()
bsd-3-clause
fredhusser/scikit-learn
doc/tutorial/text_analytics/skeletons/exercise_02_sentiment.py
255
2406
"""Build a sentiment analysis / polarity model Sentiment analysis can be casted as a binary text classification problem, that is fitting a linear classifier on features extracted from the text of the user messages so as to guess wether the opinion of the author is positive or negative. In this examples we will use a movie review dataset. """ # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: Simplified BSD import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn import metrics if __name__ == "__main__": # NOTE: we put the following in a 'if __name__ == "__main__"' protected # block to be able to use a multi-core grid search that also works under # Windows, see: http://docs.python.org/library/multiprocessing.html#windows # The multiprocessing module is used as the backend of joblib.Parallel # that is used when n_jobs != 1 in GridSearchCV # the training data folder must be passed as first argument movie_reviews_data_folder = sys.argv[1] dataset = load_files(movie_reviews_data_folder, shuffle=False) print("n_samples: %d" % len(dataset.data)) # split the dataset in training and test set: docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.25, random_state=None) # TASK: Build a vectorizer / classifier pipeline that filters out tokens # that are too rare or too frequent # TASK: Build a grid search to find out whether unigrams or bigrams are # more useful. # Fit the pipeline on the training set using grid search for the parameters # TASK: print the cross-validated scores for the each parameters set # explored by the grid search # TASK: Predict the outcome on the testing set and store it in a variable # named y_predicted # Print the classification report print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) # Print and plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print(cm) # import matplotlib.pyplot as plt # plt.matshow(cm) # plt.show()
bsd-3-clause
dsquareindia/scikit-learn
benchmarks/bench_plot_neighbors.py
96
6469
""" Plot the scaling of the nearest neighbors algorithms with k, D, and N """ from time import time import numpy as np import matplotlib.pyplot as plt from matplotlib import ticker from sklearn import neighbors, datasets def get_data(N, D, dataset='dense'): if dataset == 'dense': np.random.seed(0) return np.random.random((N, D)) elif dataset == 'digits': X = datasets.load_digits().data i = np.argsort(X[0])[::-1] X = X[:, i] return X[:N, :D] else: raise ValueError("invalid dataset: %s" % dataset) def barplot_neighbors(Nrange=2 ** np.arange(1, 11), Drange=2 ** np.arange(7), krange=2 ** np.arange(10), N=1000, D=64, k=5, leaf_size=30, dataset='digits'): algorithms = ('kd_tree', 'brute', 'ball_tree') fiducial_values = {'N': N, 'D': D, 'k': k} #------------------------------------------------------------ # varying N N_results_build = dict([(alg, np.zeros(len(Nrange))) for alg in algorithms]) N_results_query = dict([(alg, np.zeros(len(Nrange))) for alg in algorithms]) for i, NN in enumerate(Nrange): print("N = %i (%i out of %i)" % (NN, i + 1, len(Nrange))) X = get_data(NN, D, dataset) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors(n_neighbors=min(NN, k), algorithm=algorithm, leaf_size=leaf_size) t0 = time() nbrs.fit(X) t1 = time() nbrs.kneighbors(X) t2 = time() N_results_build[algorithm][i] = (t1 - t0) N_results_query[algorithm][i] = (t2 - t1) #------------------------------------------------------------ # varying D D_results_build = dict([(alg, np.zeros(len(Drange))) for alg in algorithms]) D_results_query = dict([(alg, np.zeros(len(Drange))) for alg in algorithms]) for i, DD in enumerate(Drange): print("D = %i (%i out of %i)" % (DD, i + 1, len(Drange))) X = get_data(N, DD, dataset) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors(n_neighbors=k, algorithm=algorithm, leaf_size=leaf_size) t0 = time() nbrs.fit(X) t1 = time() nbrs.kneighbors(X) t2 = time() D_results_build[algorithm][i] = (t1 - t0) D_results_query[algorithm][i] = (t2 - t1) #------------------------------------------------------------ # varying k k_results_build = dict([(alg, np.zeros(len(krange))) for alg in algorithms]) k_results_query = dict([(alg, np.zeros(len(krange))) for alg in algorithms]) X = get_data(N, DD, dataset) for i, kk in enumerate(krange): print("k = %i (%i out of %i)" % (kk, i + 1, len(krange))) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors(n_neighbors=kk, algorithm=algorithm, leaf_size=leaf_size) t0 = time() nbrs.fit(X) t1 = time() nbrs.kneighbors(X) t2 = time() k_results_build[algorithm][i] = (t1 - t0) k_results_query[algorithm][i] = (t2 - t1) plt.figure(figsize=(8, 11)) for (sbplt, vals, quantity, build_time, query_time) in [(311, Nrange, 'N', N_results_build, N_results_query), (312, Drange, 'D', D_results_build, D_results_query), (313, krange, 'k', k_results_build, k_results_query)]: ax = plt.subplot(sbplt, yscale='log') plt.grid(True) tick_vals = [] tick_labels = [] bottom = 10 ** np.min([min(np.floor(np.log10(build_time[alg]))) for alg in algorithms]) for i, alg in enumerate(algorithms): xvals = 0.1 + i * (1 + len(vals)) + np.arange(len(vals)) width = 0.8 c_bar = plt.bar(xvals, build_time[alg] - bottom, width, bottom, color='r') q_bar = plt.bar(xvals, query_time[alg], width, build_time[alg], color='b') tick_vals += list(xvals + 0.5 * width) tick_labels += ['%i' % val for val in vals] plt.text((i + 0.02) / len(algorithms), 0.98, alg, transform=ax.transAxes, ha='left', va='top', bbox=dict(facecolor='w', edgecolor='w', alpha=0.5)) plt.ylabel('Time (s)') ax.xaxis.set_major_locator(ticker.FixedLocator(tick_vals)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(tick_labels)) for label in ax.get_xticklabels(): label.set_rotation(-90) label.set_fontsize(10) title_string = 'Varying %s' % quantity descr_string = '' for s in 'NDk': if s == quantity: pass else: descr_string += '%s = %i, ' % (s, fiducial_values[s]) descr_string = descr_string[:-2] plt.text(1.01, 0.5, title_string, transform=ax.transAxes, rotation=-90, ha='left', va='center', fontsize=20) plt.text(0.99, 0.5, descr_string, transform=ax.transAxes, rotation=-90, ha='right', va='center') plt.gcf().suptitle("%s data set" % dataset.capitalize(), fontsize=16) plt.figlegend((c_bar, q_bar), ('construction', 'N-point query'), 'upper right') if __name__ == '__main__': barplot_neighbors(dataset='digits') barplot_neighbors(dataset='dense') plt.show()
bsd-3-clause
lukovnikov/qelos
qelos/scripts/webqa/preprocessing/checkentities.py
1
2030
from __future__ import print_function import csv, re import qelos as q ##################################################################### ## CHECK WHAT ENTITY LINKING FILE COVERS FROM IDEAL ENTITY LINKING ## ##################################################################### def run(graphp="../../../../datasets/webqsp/webqsp.test.lin", elp="../../../../datasets/webqsp/webqsp.test.el.tsv"): toplinkings = {} linkings = {} topicents = {} with open(elp) as elf: curq = None prevq = None elf_reader = csv.reader(elf, delimiter="\t") for q, match, start, length, ent, title, score in elf_reader: ent = ent[1:].replace("/", ".") if q != curq: linkings[q] = set() if q not in linkings else linkings[q] # ent = "{}.{}".format(ent.group(1), ent.group(2)) toplinkings[q] = (match, start, length, ent, score) curq = q linkings[q].add(ent) # print (q, match, start, length, ent, score) with open(graphp) as graphf: for line in graphf: splits = line.split("\t") if len(splits) > 2: q, question, _, _, _, _, query = splits topicent = re.findall(r'([a-z])\.([^\[\s]+)\[([^\]]+)\]\*', query)[0] topicents[q] = ("{}.{}".format(topicent[0], topicent[1]), topicent[2]) qids = set(toplinkings.keys()) & set(topicents.keys()) print(len(qids), len(toplinkings), len(topicents)) not_in_top_linking = set() not_in_linking = set() for qid in qids: if toplinkings[qid][3] != topicents[qid][0]: not_in_top_linking.add(qid) print (qid, toplinkings[qid], topicents[qid]) if topicents[qid][0] not in linkings[qid]: not_in_linking.add(qid) print (qid, linkings[qid], topicents[qid]) print(len(not_in_top_linking)) print(len(not_in_linking)) pass if __name__ == "__main__": q.argprun(run)
mit
dsquareindia/scikit-learn
examples/cluster/plot_segmentation_toy.py
89
3522
""" =========================================== Spectral clustering for image segmentation =========================================== In this example, an image with connected circles is generated and spectral clustering is used to separate the circles. In these settings, the :ref:`spectral_clustering` approach solves the problem know as 'normalized graph cuts': the image is seen as a graph of connected voxels, and the spectral clustering algorithm amounts to choosing graph cuts defining regions while minimizing the ratio of the gradient along the cut, and the volume of the region. As the algorithm tries to balance the volume (ie balance the region sizes), if we take circles with different sizes, the segmentation fails. In addition, as there is no useful information in the intensity of the image, or its gradient, we choose to perform the spectral clustering on a graph that is only weakly informed by the gradient. This is close to performing a Voronoi partition of the graph. In addition, we use the mask of the objects to restrict the graph to the outline of the objects. In this example, we are interested in separating the objects one from the other, and not from the background. """ print(__doc__) # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering ############################################################################### l = 100 x, y = np.indices((l, l)) center1 = (28, 24) center2 = (40, 50) center3 = (67, 58) center4 = (24, 70) radius1, radius2, radius3, radius4 = 16, 14, 15, 14 circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1 ** 2 circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2 ** 2 circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3 ** 2 circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4 ** 2 ############################################################################### # 4 circles img = circle1 + circle2 + circle3 + circle4 # We use a mask that limits to the foreground: the problem that we are # interested in here is not separating the objects from the background, # but separating them one from the other. mask = img.astype(bool) img = img.astype(float) img += 1 + 0.2 * np.random.randn(*img.shape) # Convert the image into a graph with the value of the gradient on the # edges. graph = image.img_to_graph(img, mask=mask) # Take a decreasing function of the gradient: we take it weakly # dependent from the gradient the segmentation is close to a voronoi graph.data = np.exp(-graph.data / graph.data.std()) # Force the solver to be arpack, since amg is numerically # unstable on this example labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack') label_im = -np.ones(mask.shape) label_im[mask] = labels plt.matshow(img) plt.matshow(label_im) ############################################################################### # 2 circles img = circle1 + circle2 mask = img.astype(bool) img = img.astype(float) img += 1 + 0.2 * np.random.randn(*img.shape) graph = image.img_to_graph(img, mask=mask) graph.data = np.exp(-graph.data / graph.data.std()) labels = spectral_clustering(graph, n_clusters=2, eigen_solver='arpack') label_im = -np.ones(mask.shape) label_im[mask] = labels plt.matshow(img) plt.matshow(label_im) plt.show()
bsd-3-clause
dsquareindia/scikit-learn
examples/manifold/plot_manifold_sphere.py
80
5055
#!/usr/bin/python # -*- coding: utf-8 -*- """ ============================================= Manifold Learning methods on a severed sphere ============================================= An application of the different :ref:`manifold` techniques on a spherical data-set. Here one can see the use of dimensionality reduction in order to gain some intuition regarding the manifold learning methods. Regarding the dataset, the poles are cut from the sphere, as well as a thin slice down its side. This enables the manifold learning techniques to 'spread it open' whilst projecting it onto two dimensions. For a similar example, where the methods are applied to the S-curve dataset, see :ref:`sphx_glr_auto_examples_manifold_plot_compare_methods.py` Note that the purpose of the :ref:`MDS <multidimensional_scaling>` is to find a low-dimensional representation of the data (here 2D) in which the distances respect well the distances in the original high-dimensional space, unlike other manifold-learning algorithms, it does not seeks an isotropic representation of the data in the low-dimensional space. Here the manifold problem matches fairly that of representing a flat map of the Earth, as with `map projection <https://en.wikipedia.org/wiki/Map_projection>`_ """ # Author: Jaques Grobler <jaques.grobler@inria.fr> # License: BSD 3 clause print(__doc__) from time import time import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from sklearn import manifold from sklearn.utils import check_random_state # Next line to silence pyflakes. Axes3D # Variables for manifold learning. n_neighbors = 10 n_samples = 1000 # Create our sphere. random_state = check_random_state(0) p = random_state.rand(n_samples) * (2 * np.pi - 0.55) t = random_state.rand(n_samples) * np.pi # Sever the poles from the sphere. indices = ((t < (np.pi - (np.pi / 8))) & (t > ((np.pi / 8)))) colors = p[indices] x, y, z = np.sin(t[indices]) * np.cos(p[indices]), \ np.sin(t[indices]) * np.sin(p[indices]), \ np.cos(t[indices]) # Plot our dataset. fig = plt.figure(figsize=(15, 8)) plt.suptitle("Manifold Learning with %i points, %i neighbors" % (1000, n_neighbors), fontsize=14) ax = fig.add_subplot(251, projection='3d') ax.scatter(x, y, z, c=p[indices], cmap=plt.cm.rainbow) ax.view_init(40, -10) sphere_data = np.array([x, y, z]).T # Perform Locally Linear Embedding Manifold learning methods = ['standard', 'ltsa', 'hessian', 'modified'] labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE'] for i, method in enumerate(methods): t0 = time() trans_data = manifold\ .LocallyLinearEmbedding(n_neighbors, 2, method=method).fit_transform(sphere_data).T t1 = time() print("%s: %.2g sec" % (methods[i], t1 - t0)) ax = fig.add_subplot(252 + i) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("%s (%.2g sec)" % (labels[i], t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform Isomap Manifold learning. t0 = time() trans_data = manifold.Isomap(n_neighbors, n_components=2)\ .fit_transform(sphere_data).T t1 = time() print("%s: %.2g sec" % ('ISO', t1 - t0)) ax = fig.add_subplot(257) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("%s (%.2g sec)" % ('Isomap', t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform Multi-dimensional scaling. t0 = time() mds = manifold.MDS(2, max_iter=100, n_init=1) trans_data = mds.fit_transform(sphere_data).T t1 = time() print("MDS: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(258) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("MDS (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform Spectral Embedding. t0 = time() se = manifold.SpectralEmbedding(n_components=2, n_neighbors=n_neighbors) trans_data = se.fit_transform(sphere_data).T t1 = time() print("Spectral Embedding: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(259) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("Spectral Embedding (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform t-distributed stochastic neighbor embedding. t0 = time() tsne = manifold.TSNE(n_components=2, init='pca', random_state=0) trans_data = tsne.fit_transform(sphere_data).T t1 = time() print("t-SNE: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(2, 5, 10) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("t-SNE (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') plt.show()
bsd-3-clause
distributed-system-analysis/pbench
lib/pbench/test/unit/server/query_apis/test_query_builder.py
2
6545
from typing import Optional import pytest from pbench.server import JSON from pbench.server.api.resources import API_METHOD, API_OPERATION, ApiSchema from pbench.server.api.resources.query_apis import ElasticBase from pbench.server.auth.auth import Auth from pbench.server.database.models.users import User ADMIN_ID = "6" # This needs to match the current_user_admin fixture SELF_ID = "3" # This needs to match the current_user_drb fixture USER_ID = "20" # This is arbitrary, but can't match either fixture class TestQueryBuilder: @pytest.fixture() def elasticbase(self, client) -> ElasticBase: return ElasticBase( client.config, client.logger, ApiSchema(API_METHOD.POST, API_OPERATION.READ) ) @pytest.fixture() def current_user_admin(self, monkeypatch): admin_user = User( email="email@example.com", id=6, username="admin", first_name="Test", last_name="Admin", role="admin", ) class FakeHTTPTokenAuth: def current_user(self) -> User: return admin_user with monkeypatch.context() as m: m.setattr(Auth, "token_auth", FakeHTTPTokenAuth()) yield admin_user @staticmethod def assemble(term: JSON, user: Optional[str], access: Optional[str]) -> JSON: """ Create full Elasticsearch user/access query terms from the user and access parameters. Args: term: The basic Elasticsearch query user: specified to create an "authorization.user" term access: speified to create an "authorization.access" term Returns: Full expected JSON query "filter" """ filter = [term] if access: filter.append({"term": {"authorization.access": access}}) if user: filter.append({"term": {"authorization.owner": user}}) return filter @pytest.mark.parametrize( "user,access", [ (None, None), (None, "public"), (None, "private"), (USER_ID, None), (USER_ID, "private"), (USER_ID, "public"), (ADMIN_ID, None), (ADMIN_ID, "private"), (ADMIN_ID, "public"), ], ) def test_admin(self, elasticbase, server_config, current_user_admin, user, access): """ Test the query builder when we have an authenticated admin user; all of these build query terms matching the input terms since we impose no additional constraints on queries. """ term = {"term": {"icecream": "ginger"}} query = elasticbase._build_elasticsearch_query(user, access, [term]) filter = self.assemble(term, user, access) assert query == {"bool": {"filter": filter}} @pytest.mark.parametrize( "ask,expect", [ ({"access": "public"}, {"access": "public"}), ({"access": "private"}, {"user": SELF_ID, "access": "private"}), ({"user": SELF_ID}, {"user": SELF_ID}), ({"user": USER_ID}, {"user": USER_ID, "access": "public"}), ( {"user": USER_ID, "access": "private"}, {"user": USER_ID, "access": "public"}, ), ( {"user": SELF_ID, "access": "private"}, {"user": SELF_ID, "access": "private"}, ), ( {"user": SELF_ID, "access": "public"}, {"user": SELF_ID, "access": "public"}, ), ( {"user": USER_ID, "access": "public"}, {"user": USER_ID, "access": "public"}, ), ], ) def test_auth(self, elasticbase, server_config, current_user_drb, ask, expect): """ Test the query builder when we have an authenticated user. NOTE: We don't test {} here: that's left to a separate test case rather than building the unique disjunction syntax here """ term = {"term": {"icecream": "ginger"}} query = elasticbase._build_elasticsearch_query( ask.get("user"), ask.get("access"), [term] ) filter = self.assemble(term, expect.get("user"), expect.get("access")) assert query == {"bool": {"filter": filter}} @pytest.mark.parametrize( "ask,expect", [ ({}, {"access": "public"}), ({"access": "public"}, {"access": "public"}), ({"access": "private"}, {"access": "public"}), ({"user": USER_ID}, {"user": USER_ID, "access": "public"}), ( {"user": USER_ID, "access": "public"}, {"user": USER_ID, "access": "public"}, ), ( {"user": USER_ID, "access": "private"}, {"user": USER_ID, "access": "public"}, ), ], ) def test_noauth(self, elasticbase, server_config, current_user_none, ask, expect): """ Test the query builder when we have an unauthenticated client. """ term = {"term": {"icecream": "ginger"}} query = elasticbase._build_elasticsearch_query( ask.get("user"), ask.get("access"), [term] ) filter = self.assemble(term, expect.get("user"), expect.get("access")) assert query == {"bool": {"filter": filter}} def test_neither_auth(self, elasticbase, server_config, current_user_drb): """ Test the query builder for {} when the client is authenticated with a non-admin account. This is the most complicated query, translating to matching owner OR public access. (That is, all datasets owned by the authenticated user plus all public datasets regardless of owner.) """ id = str(current_user_drb.id) query: JSON = elasticbase._build_elasticsearch_query( None, None, [{"term": {"icecream": "vanilla"}}] ) assert query == { "bool": { "filter": [ {"term": {"icecream": "vanilla"}}, { "dis_max": { "queries": [ {"term": {"authorization.owner": id}}, {"term": {"authorization.access": "public"}}, ] } }, ] } }
gpl-3.0
ChanChiChoi/scikit-learn
sklearn/manifold/t_sne.py
105
20057
# Author: Alexander Fabisch -- <afabisch@informatik.uni-bremen.de> # License: BSD 3 clause (C) 2014 # This is the standard t-SNE implementation. There are faster modifications of # the algorithm: # * Barnes-Hut-SNE: reduces the complexity of the gradient computation from # N^2 to N log N (http://arxiv.org/abs/1301.3342) # * Fast Optimization for t-SNE: # http://cseweb.ucsd.edu/~lvdmaaten/workshops/nips2010/papers/vandermaaten.pdf import numpy as np from scipy import linalg from scipy.spatial.distance import pdist from scipy.spatial.distance import squareform from ..base import BaseEstimator from ..utils import check_array from ..utils import check_random_state from ..utils.extmath import _ravel from ..decomposition import RandomizedPCA from ..metrics.pairwise import pairwise_distances from . import _utils MACHINE_EPSILON = np.finfo(np.double).eps def _joint_probabilities(distances, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances. Parameters ---------- distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and duplicate entries and store everything in a one-dimensional array. desired_perplexity : float Desired perplexity of the joint probability distributions. verbose : int Verbosity level. Returns ------- P : array, shape (n_samples * (n_samples-1) / 2,) Condensed joint probability matrix. """ # Compute conditional probabilities such that they approximately match # the desired perplexity conditional_P = _utils._binary_search_perplexity( distances, desired_perplexity, verbose) P = conditional_P + conditional_P.T sum_P = np.maximum(np.sum(P), MACHINE_EPSILON) P = np.maximum(squareform(P) / sum_P, MACHINE_EPSILON) return P def _kl_divergence(params, P, alpha, n_samples, n_components): """t-SNE objective function: KL divergence of p_ijs and q_ijs. Parameters ---------- params : array, shape (n_params,) Unraveled embedding. P : array, shape (n_samples * (n_samples-1) / 2,) Condensed joint probability matrix. alpha : float Degrees of freedom of the Student's-t distribution. n_samples : int Number of samples. n_components : int Dimension of the embedded space. Returns ------- kl_divergence : float Kullback-Leibler divergence of p_ij and q_ij. grad : array, shape (n_params,) Unraveled gradient of the Kullback-Leibler divergence with respect to the embedding. """ X_embedded = params.reshape(n_samples, n_components) # Q is a heavy-tailed distribution: Student's t-distribution n = pdist(X_embedded, "sqeuclidean") n += 1. n /= alpha n **= (alpha + 1.0) / -2.0 Q = np.maximum(n / (2.0 * np.sum(n)), MACHINE_EPSILON) # Optimization trick below: np.dot(x, y) is faster than # np.sum(x * y) because it calls BLAS # Objective: C (Kullback-Leibler divergence of P and Q) kl_divergence = 2.0 * np.dot(P, np.log(P / Q)) # Gradient: dC/dY grad = np.ndarray((n_samples, n_components)) PQd = squareform((P - Q) * n) for i in range(n_samples): np.dot(_ravel(PQd[i]), X_embedded[i] - X_embedded, out=grad[i]) grad = grad.ravel() c = 2.0 * (alpha + 1.0) / alpha grad *= c return kl_divergence, grad def _gradient_descent(objective, p0, it, n_iter, n_iter_without_progress=30, momentum=0.5, learning_rate=1000.0, min_gain=0.01, min_grad_norm=1e-7, min_error_diff=1e-7, verbose=0, args=None): """Batch gradient descent with momentum and individual gains. Parameters ---------- objective : function or callable Should return a tuple of cost and gradient for a given parameter vector. p0 : array-like, shape (n_params,) Initial parameter vector. it : int Current number of iterations (this function will be called more than once during the optimization). n_iter : int Maximum number of gradient descent iterations. n_iter_without_progress : int, optional (default: 30) Maximum number of iterations without progress before we abort the optimization. momentum : float, within (0.0, 1.0), optional (default: 0.5) The momentum generates a weight for previous gradients that decays exponentially. learning_rate : float, optional (default: 1000.0) The learning rate should be extremely high for t-SNE! Values in the range [100.0, 1000.0] are common. min_gain : float, optional (default: 0.01) Minimum individual gain for each parameter. min_grad_norm : float, optional (default: 1e-7) If the gradient norm is below this threshold, the optimization will be aborted. min_error_diff : float, optional (default: 1e-7) If the absolute difference of two successive cost function values is below this threshold, the optimization will be aborted. verbose : int, optional (default: 0) Verbosity level. args : sequence Arguments to pass to objective function. Returns ------- p : array, shape (n_params,) Optimum parameters. error : float Optimum. i : int Last iteration. """ if args is None: args = [] p = p0.copy().ravel() update = np.zeros_like(p) gains = np.ones_like(p) error = np.finfo(np.float).max best_error = np.finfo(np.float).max best_iter = 0 for i in range(it, n_iter): new_error, grad = objective(p, *args) error_diff = np.abs(new_error - error) error = new_error grad_norm = linalg.norm(grad) if error < best_error: best_error = error best_iter = i elif i - best_iter > n_iter_without_progress: if verbose >= 2: print("[t-SNE] Iteration %d: did not make any progress " "during the last %d episodes. Finished." % (i + 1, n_iter_without_progress)) break if min_grad_norm >= grad_norm: if verbose >= 2: print("[t-SNE] Iteration %d: gradient norm %f. Finished." % (i + 1, grad_norm)) break if min_error_diff >= error_diff: if verbose >= 2: print("[t-SNE] Iteration %d: error difference %f. Finished." % (i + 1, error_diff)) break inc = update * grad >= 0.0 dec = np.invert(inc) gains[inc] += 0.05 gains[dec] *= 0.95 np.clip(gains, min_gain, np.inf) grad *= gains update = momentum * update - learning_rate * grad p += update if verbose >= 2 and (i + 1) % 10 == 0: print("[t-SNE] Iteration %d: error = %.7f, gradient norm = %.7f" % (i + 1, error, grad_norm)) return p, error, i def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i (r(i, j) - k)} where :math:`r(i, j)` is the rank of the embedded datapoint j according to the pairwise distances between the embedded datapoints, :math:`U^{(k)}_i` is the set of points that are in the k nearest neighbors in the embedded space but not in the original space. * "Neighborhood Preservation in Nonlinear Projection Methods: An Experimental Study" J. Venna, S. Kaski * "Learning a Parametric Embedding by Preserving Local Structure" L.J.P. van der Maaten Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a sample per row. X_embedded : array, shape (n_samples, n_components) Embedding of the training data in low-dimensional space. n_neighbors : int, optional (default: 5) Number of neighbors k that will be considered. precomputed : bool, optional (default: False) Set this flag if X is a precomputed square distance matrix. Returns ------- trustworthiness : float Trustworthiness of the low-dimensional embedding. """ if precomputed: dist_X = X else: dist_X = pairwise_distances(X, squared=True) dist_X_embedded = pairwise_distances(X_embedded, squared=True) ind_X = np.argsort(dist_X, axis=1) ind_X_embedded = np.argsort(dist_X_embedded, axis=1)[:, 1:n_neighbors + 1] n_samples = X.shape[0] t = 0.0 ranks = np.zeros(n_neighbors) for i in range(n_samples): for j in range(n_neighbors): ranks[j] = np.where(ind_X[i] == ind_X_embedded[i, j])[0][0] ranks -= n_neighbors t += np.sum(ranks[ranks > 0]) t = 1.0 - t * (2.0 / (n_samples * n_neighbors * (2.0 * n_samples - 3.0 * n_neighbors - 1.0))) return t class TSNE(BaseEstimator): """t-distributed Stochastic Neighbor Embedding. t-SNE [1] is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results. It is highly recommended to use another dimensionality reduction method (e.g. PCA for dense data or TruncatedSVD for sparse data) to reduce the number of dimensions to a reasonable amount (e.g. 50) if the number of features is very high. This will suppress some noise and speed up the computation of pairwise distances between samples. For more tips see Laurens van der Maaten's FAQ [2]. Read more in the :ref:`User Guide <t_sne>`. Parameters ---------- n_components : int, optional (default: 2) Dimension of the embedded space. perplexity : float, optional (default: 30) The perplexity is related to the number of nearest neighbors that is used in other manifold learning algorithms. Larger datasets usually require a larger perplexity. Consider selcting a value between 5 and 50. The choice is not extremely critical since t-SNE is quite insensitive to this parameter. early_exaggeration : float, optional (default: 4.0) Controls how tight natural clusters in the original space are in the embedded space and how much space will be between them. For larger values, the space between natural clusters will be larger in the embedded space. Again, the choice of this parameter is not very critical. If the cost function increases during initial optimization, the early exaggeration factor or the learning rate might be too high. learning_rate : float, optional (default: 1000) The learning rate can be a critical parameter. It should be between 100 and 1000. If the cost function increases during initial optimization, the early exaggeration factor or the learning rate might be too high. If the cost function gets stuck in a bad local minimum increasing the learning rate helps sometimes. n_iter : int, optional (default: 1000) Maximum number of iterations for the optimization. Should be at least 200. metric : string or callable, optional The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by scipy.spatial.distance.pdist for its metric parameter, or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. If metric is "precomputed", X is assumed to be a distance matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. The default is "euclidean" which is interpreted as squared euclidean distance. init : string, optional (default: "random") Initialization of embedding. Possible options are 'random' and 'pca'. PCA initialization cannot be used with precomputed distances and is usually more globally stable than random initialization. verbose : int, optional (default: 0) Verbosity level. random_state : int or RandomState instance or None (default) Pseudo Random Number generator seed control. If None, use the numpy.random singleton. Note that different initializations might result in different local minima of the cost function. Attributes ---------- embedding_ : array-like, shape (n_samples, n_components) Stores the embedding vectors. training_data_ : array-like, shape (n_samples, n_features) Stores the training data. Examples -------- >>> import numpy as np >>> from sklearn.manifold import TSNE >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) >>> model = TSNE(n_components=2, random_state=0) >>> model.fit_transform(X) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE array([[ 887.28..., 238.61...], [ -714.79..., 3243.34...], [ 957.30..., -2505.78...], [-1130.28..., -974.78...]) References ---------- [1] van der Maaten, L.J.P.; Hinton, G.E. Visualizing High-Dimensional Data Using t-SNE. Journal of Machine Learning Research 9:2579-2605, 2008. [2] van der Maaten, L.J.P. t-Distributed Stochastic Neighbor Embedding http://homepage.tudelft.nl/19j49/t-SNE.html """ def __init__(self, n_components=2, perplexity=30.0, early_exaggeration=4.0, learning_rate=1000.0, n_iter=1000, metric="euclidean", init="random", verbose=0, random_state=None): if init not in ["pca", "random"]: raise ValueError("'init' must be either 'pca' or 'random'") self.n_components = n_components self.perplexity = perplexity self.early_exaggeration = early_exaggeration self.learning_rate = learning_rate self.n_iter = n_iter self.metric = metric self.init = init self.verbose = verbose self.random_state = random_state def fit(self, X, y=None): """Fit the model using X as training data. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a sample per row. """ X = check_array(X, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64) random_state = check_random_state(self.random_state) if self.early_exaggeration < 1.0: raise ValueError("early_exaggeration must be at least 1, but is " "%f" % self.early_exaggeration) if self.n_iter < 200: raise ValueError("n_iter should be at least 200") if self.metric == "precomputed": if self.init == 'pca': raise ValueError("The parameter init=\"pca\" cannot be used " "with metric=\"precomputed\".") if X.shape[0] != X.shape[1]: raise ValueError("X should be a square distance matrix") distances = X else: if self.verbose: print("[t-SNE] Computing pairwise distances...") if self.metric == "euclidean": distances = pairwise_distances(X, metric=self.metric, squared=True) else: distances = pairwise_distances(X, metric=self.metric) # Degrees of freedom of the Student's t-distribution. The suggestion # alpha = n_components - 1 comes from "Learning a Parametric Embedding # by Preserving Local Structure" Laurens van der Maaten, 2009. alpha = max(self.n_components - 1.0, 1) n_samples = X.shape[0] self.training_data_ = X P = _joint_probabilities(distances, self.perplexity, self.verbose) if self.init == 'pca': pca = RandomizedPCA(n_components=self.n_components, random_state=random_state) X_embedded = pca.fit_transform(X) elif self.init == 'random': X_embedded = None else: raise ValueError("Unsupported initialization scheme: %s" % self.init) self.embedding_ = self._tsne(P, alpha, n_samples, random_state, X_embedded=X_embedded) return self def _tsne(self, P, alpha, n_samples, random_state, X_embedded=None): """Runs t-SNE.""" # t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P # and the Student's t-distributions Q. The optimization algorithm that # we use is batch gradient descent with three stages: # * early exaggeration with momentum 0.5 # * early exaggeration with momentum 0.8 # * final optimization with momentum 0.8 # The embedding is initialized with iid samples from Gaussians with # standard deviation 1e-4. if X_embedded is None: # Initialize embedding randomly X_embedded = 1e-4 * random_state.randn(n_samples, self.n_components) params = X_embedded.ravel() # Early exaggeration P *= self.early_exaggeration params, error, it = _gradient_descent( _kl_divergence, params, it=0, n_iter=50, momentum=0.5, min_grad_norm=0.0, min_error_diff=0.0, learning_rate=self.learning_rate, verbose=self.verbose, args=[P, alpha, n_samples, self.n_components]) params, error, it = _gradient_descent( _kl_divergence, params, it=it + 1, n_iter=100, momentum=0.8, min_grad_norm=0.0, min_error_diff=0.0, learning_rate=self.learning_rate, verbose=self.verbose, args=[P, alpha, n_samples, self.n_components]) if self.verbose: print("[t-SNE] Error after %d iterations with early " "exaggeration: %f" % (it + 1, error)) # Final optimization P /= self.early_exaggeration params, error, it = _gradient_descent( _kl_divergence, params, it=it + 1, n_iter=self.n_iter, momentum=0.8, learning_rate=self.learning_rate, verbose=self.verbose, args=[P, alpha, n_samples, self.n_components]) if self.verbose: print("[t-SNE] Error after %d iterations: %f" % (it + 1, error)) X_embedded = params.reshape(n_samples, self.n_components) return X_embedded def fit_transform(self, X, y=None): """Transform X to the embedded space. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a sample per row. Returns ------- X_new : array, shape (n_samples, n_components) Embedding of the training data in low-dimensional space. """ self.fit(X) return self.embedding_
bsd-3-clause
ChanChiChoi/scikit-learn
sklearn/utils/metaestimators.py
281
2353
"""Utilities for meta-estimators""" # Author: Joel Nothman # Andreas Mueller # Licence: BSD from operator import attrgetter from functools import update_wrapper __all__ = ['if_delegate_has_method'] class _IffHasAttrDescriptor(object): """Implements a conditional property using the descriptor protocol. Using this class to create a decorator will raise an ``AttributeError`` if the ``attribute_name`` is not present on the base object. This allows ducktyping of the decorated method based on ``attribute_name``. See https://docs.python.org/3/howto/descriptor.html for an explanation of descriptors. """ def __init__(self, fn, attribute_name): self.fn = fn self.get_attribute = attrgetter(attribute_name) # update the docstring of the descriptor update_wrapper(self, fn) def __get__(self, obj, type=None): # raise an AttributeError if the attribute is not present on the object if obj is not None: # delegate only on instances, not the classes. # this is to allow access to the docstrings. self.get_attribute(obj) # lambda, but not partial, allows help() to work with update_wrapper out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs) # update the docstring of the returned function update_wrapper(out, self.fn) return out def if_delegate_has_method(delegate): """Create a decorator for methods that are delegated to a sub-estimator This enables ducktyping by hasattr returning True according to the sub-estimator. >>> from sklearn.utils.metaestimators import if_delegate_has_method >>> >>> >>> class MetaEst(object): ... def __init__(self, sub_est): ... self.sub_est = sub_est ... ... @if_delegate_has_method(delegate='sub_est') ... def predict(self, X): ... return self.sub_est.predict(X) ... >>> class HasPredict(object): ... def predict(self, X): ... return X.sum(axis=1) ... >>> class HasNoPredict(object): ... pass ... >>> hasattr(MetaEst(HasPredict()), 'predict') True >>> hasattr(MetaEst(HasNoPredict()), 'predict') False """ return lambda fn: _IffHasAttrDescriptor(fn, '%s.%s' % (delegate, fn.__name__))
bsd-3-clause
fredhusser/scikit-learn
examples/ensemble/plot_gradient_boosting_quantile.py
385
2114
""" ===================================================== Prediction Intervals for Gradient Boosting Regression ===================================================== This example shows how quantile regression can be used to create prediction intervals. """ import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import GradientBoostingRegressor np.random.seed(1) def f(x): """The function to predict.""" return x * np.sin(x) #---------------------------------------------------------------------- # First the noiseless case X = np.atleast_2d(np.random.uniform(0, 10.0, size=100)).T X = X.astype(np.float32) # Observations y = f(X).ravel() dy = 1.5 + 1.0 * np.random.random(y.shape) noise = np.random.normal(0, dy) y += noise y = y.astype(np.float32) # Mesh the input space for evaluations of the real function, the prediction and # its MSE xx = np.atleast_2d(np.linspace(0, 10, 1000)).T xx = xx.astype(np.float32) alpha = 0.95 clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9) clf.fit(X, y) # Make the prediction on the meshed x-axis y_upper = clf.predict(xx) clf.set_params(alpha=1.0 - alpha) clf.fit(X, y) # Make the prediction on the meshed x-axis y_lower = clf.predict(xx) clf.set_params(loss='ls') clf.fit(X, y) # Make the prediction on the meshed x-axis y_pred = clf.predict(xx) # Plot the function, the prediction and the 90% confidence interval based on # the MSE fig = plt.figure() plt.plot(xx, f(xx), 'g:', label=u'$f(x) = x\,\sin(x)$') plt.plot(X, y, 'b.', markersize=10, label=u'Observations') plt.plot(xx, y_pred, 'r-', label=u'Prediction') plt.plot(xx, y_upper, 'k-') plt.plot(xx, y_lower, 'k-') plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval') plt.xlabel('$x$') plt.ylabel('$f(x)$') plt.ylim(-10, 20) plt.legend(loc='upper left') plt.show()
bsd-3-clause
MegaShow/college-programming
Homework/Principles of Artificial Neural Networks/Week 15 Image Caption/src/agent.py
1
6788
"""Agent""" import torch from torch.nn.utils.rnn import pack_padded_sequence from net import Decoder, Encoder from action import Action, AverageMeter from dataset import Dataset class Agent: def __init__(self): super(Agent, self).__init__() #self.config = config self.action = Action() self.dataset = Dataset() self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.grad_clip = 5 embed_dim = 512 # dimension of word embeddings decoder_dim = 512 # dimension of decoder RNN dropout = 0.5 #batch_size = 32 self.n_epochs = 20 self.encoder = Encoder() self.decoder = Decoder(embed_dim=embed_dim, decoder_dim=decoder_dim, vocab_size=self.dataset.get_word_map_len(), dropout=dropout) def fit(self): """fit model""" self.run(self.encoder, self.decoder) def run(self, encoder, decoder): """Main function to run""" device = self.device encoder_lr = 1e-4 # learning rate for encoder if fine-tuning decoder_lr = 4e-4 # learning rate for decoder encoder_optimizer = self.action.get_optimizer(encoder, encoder_lr) decoder_optimizer = self.action.get_optimizer(decoder, decoder_lr) encoder = encoder.to(device) decoder = decoder.to(device) loss_fn = self.action.get_loss_fn().to(device) train_loader, val_loader = self.dataset.get_dataloader() for epoch in range(self.n_epochs): self.train_epoch(train_loader, encoder, decoder, loss_fn, encoder_optimizer, decoder_optimizer, epoch) self.eval_epoch(val_loader, encoder, decoder, loss_fn, epoch) def train_epoch(self, train_loader, encoder, decoder, loss_fn, encoder_optimizer, decoder_optimizer, epoch): """ Performs one epoch's training. :param train_loader: DataLoader for training data :param encoder: encoder model :param decoder: decoder model :param criterion: loss layer :param encoder_optimizer: optimizer to update encoder's weights (if fine-tuning) :param decoder_optimizer: optimizer to update decoder's weights """ device = self.device grad_clip = self.grad_clip encoder.train() decoder.train() losses = AverageMeter() for idx, (imgs, caps, caplens) in enumerate(train_loader): # Move to GPU, if available imgs = imgs.to(device) caps = caps.to(device) caplens = caplens.to(device) # Forward prop. imgs = encoder(imgs) scores, caps_sorted, decode_lengths, alphas, sort_ind = \ decoder(imgs, caps, caplens) # Since we decoded starting with <start>, the targets are # all words after <start>, up to <end> targets = caps_sorted[:, 1:] # Remove timesteps that we didn't decode at, or are pads # pack_padded_sequence is an easy trick to do this #TODO scores = pack_padded_sequence(scores, decode_lengths, batch_first=True) targets = pack_padded_sequence(targets, decode_lengths, batch_first=True) scores = scores[0] targets = targets[0] # Calculate loss loss = loss_fn(scores, targets) if alphas is not None: loss += (1 - alphas.sum(dim=1) ** 2).mean() # Back prop. decoder_optimizer.zero_grad() if encoder_optimizer is not None: encoder_optimizer.zero_grad() loss.backward() # Clip gradients if self.grad_clip is not None: self.action.clip_gradient(decoder_optimizer, grad_clip) if encoder_optimizer is not None: self.action.clip_gradient(encoder_optimizer, grad_clip) # Update weights decoder_optimizer.step() if encoder_optimizer is not None: encoder_optimizer.step() losses.update(loss.item(), sum(decode_lengths)) if idx % 100: print(">>Epoch(Train): [{0}][{1}/{2}]\tLoss {loss.avg:.4f}".format (epoch, idx, len(train_loader), loss=losses)) def eval_epoch(self, val_loader, encoder, decoder, loss_fn, epoch): """ Performs one epoch's validation. :param val_loader: DataLoader for validation data. :param encoder: encoder model :param decoder: decoder model :param criterion: loss layer """ device = self.device decoder.eval() encoder.eval() losses = AverageMeter() with torch.no_grad(): for idx, (imgs, caps, caplens, allcaps) in enumerate(val_loader): # Move to device, if available imgs = imgs.to(device) caps = caps.to(device) caplens = caplens.to(device) # Forward prop. imgs = encoder(imgs) scores, caps_sorted, decode_lengths, alphas, sort_ind = \ decoder(imgs, caps, caplens) # Since we decoded starting with <start>, the targets are all # words after <start>, up to <end> targets = caps_sorted[:, 1:] scores = pack_padded_sequence(scores, decode_lengths, batch_first=True) targets = pack_padded_sequence(targets, decode_lengths, batch_first=True) scores = scores[0] targets = targets[0] # Calculate loss loss = loss_fn(scores, targets) if alphas is not None: loss += (1 - alphas.sum(dim=1) ** 2).mean() losses.update(loss.item(), sum(decode_lengths)) if idx % 100 == 0: print(">>Epoch(Eval): [{epoch}][{idx}/{iters}]\tLoss \ {loss.avg:.4f}".format( epoch=epoch, idx=idx, iters=len(val_loader), loss=losses)) def caption_image_beam_search(self): """ captions images with beam search. :param encoder: encoder model :param decoder: decoder model :param image_path: path to image :param word_map: word map :param beam_size: number of sequences to consider at each decode-step :return: caption, weights for visualization """ # Load image # Get caption by beam search pass
mit
codeforsanjose/MobilityMapApi
src/sa_api_v2/south_migrations/0030_auto__add_field_submittedthing_submitter.py
2
9106
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'SubmittedThing.submitter' db.add_column('sa_api_submittedthing', 'submitter', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='things', null=True, to=orm['auth.User']), keep_default=False) def backwards(self, orm): # Deleting field 'SubmittedThing.submitter' db.delete_column('sa_api_submittedthing', 'submitter_id') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'sa_api_v2.action': { 'Meta': {'ordering': "['-created_datetime']", 'object_name': 'Action', 'db_table': "'sa_api_activity'"}, 'action': ('django.db.models.fields.CharField', [], {'default': "'create'", 'max_length': '16'}), 'created_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'thing': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actions'", 'db_column': "'data_id'", 'to': "orm['sa_api_v2.SubmittedThing']"}), 'updated_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'sa_api_v2.attachment': { 'Meta': {'object_name': 'Attachment', 'db_table': "'sa_api_attachment'"}, 'created_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'thing': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'attachments'", 'to': "orm['sa_api_v2.SubmittedThing']"}), 'updated_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'sa_api_v2.client': { 'Meta': {'object_name': 'Client', 'db_table': "'sa_api_client'"}, 'created_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'clients'", 'to': "orm['auth.User']"}), 'updated_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'sa_api_v2.dataset': { 'Meta': {'unique_together': "(('owner', 'slug'),)", 'object_name': 'DataSet', 'db_table': "'sa_api_dataset'"}, 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'datasets'", 'to': "orm['auth.User']"}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "u''", 'max_length': '128'}) }, 'sa_api_v2.place': { 'Meta': {'object_name': 'Place', 'db_table': "'sa_api_place'", '_ormbases': ['sa_api_v2.SubmittedThing']}, 'geometry': ('django.contrib.gis.db.models.fields.GeometryField', [], {}), 'submittedthing_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['sa_api_v2.SubmittedThing']", 'unique': 'True', 'primary_key': 'True'}) }, 'sa_api_v2.submission': { 'Meta': {'object_name': 'Submission', 'db_table': "'sa_api_submission'", '_ormbases': ['sa_api_v2.SubmittedThing']}, 'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'to': "orm['sa_api_v2.SubmissionSet']"}), 'submittedthing_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['sa_api_v2.SubmittedThing']", 'unique': 'True', 'primary_key': 'True'}) }, 'sa_api_v2.submissionset': { 'Meta': {'unique_together': "(('place', 'name'),)", 'object_name': 'SubmissionSet', 'db_table': "'sa_api_submissionset'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'place': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'submission_sets'", 'to': "orm['sa_api_v2.Place']"}) }, 'sa_api_v2.submittedthing': { 'Meta': {'object_name': 'SubmittedThing', 'db_table': "'sa_api_submittedthing'"}, 'created_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}), 'dataset': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'things'", 'blank': 'True', 'to': "orm['sa_api_v2.DataSet']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'submitter': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'things'", 'null': 'True', 'to': "orm['auth.User']"}), 'submitter_name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'updated_datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) } } complete_apps = ['sa_api_v2']
gpl-3.0
andrewnc/scikit-learn
examples/ensemble/plot_ensemble_oob.py
257
3265
""" ============================= OOB Errors for Random Forests ============================= The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where each new tree is fit from a bootstrap sample of the training observations :math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average error for each :math:`z_i` calculated using predictions from the trees that do not contain :math:`z_i` in their respective bootstrap sample. This allows the ``RandomForestClassifier`` to be fit and validated whilst being trained [1]. The example below demonstrates how the OOB error can be measured at the addition of each new tree during training. The resulting plot allows a practitioner to approximate a suitable value of ``n_estimators`` at which the error stabilizes. .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", p592-593, Springer, 2009. """ import matplotlib.pyplot as plt from collections import OrderedDict from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier # Author: Kian Ho <hui.kian.ho@gmail.com> # Gilles Louppe <g.louppe@gmail.com> # Andreas Mueller <amueller@ais.uni-bonn.de> # # License: BSD 3 Clause print(__doc__) RANDOM_STATE = 123 # Generate a binary classification dataset. X, y = make_classification(n_samples=500, n_features=25, n_clusters_per_class=1, n_informative=15, random_state=RANDOM_STATE) # NOTE: Setting the `warm_start` construction parameter to `True` disables # support for paralellised ensembles but is necessary for tracking the OOB # error trajectory during training. ensemble_clfs = [ ("RandomForestClassifier, max_features='sqrt'", RandomForestClassifier(warm_start=True, oob_score=True, max_features="sqrt", random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features='log2'", RandomForestClassifier(warm_start=True, max_features='log2', oob_score=True, random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features=None", RandomForestClassifier(warm_start=True, max_features=None, oob_score=True, random_state=RANDOM_STATE)) ] # Map a classifier name to a list of (<n_estimators>, <error rate>) pairs. error_rate = OrderedDict((label, []) for label, _ in ensemble_clfs) # Range of `n_estimators` values to explore. min_estimators = 15 max_estimators = 175 for label, clf in ensemble_clfs: for i in range(min_estimators, max_estimators + 1): clf.set_params(n_estimators=i) clf.fit(X, y) # Record the OOB error for each `n_estimators=i` setting. oob_error = 1 - clf.oob_score_ error_rate[label].append((i, oob_error)) # Generate the "OOB error rate" vs. "n_estimators" plot. for label, clf_err in error_rate.items(): xs, ys = zip(*clf_err) plt.plot(xs, ys, label=label) plt.xlim(min_estimators, max_estimators) plt.xlabel("n_estimators") plt.ylabel("OOB error rate") plt.legend(loc="upper right") plt.show()
bsd-3-clause
fredhusser/scikit-learn
examples/ensemble/plot_ensemble_oob.py
257
3265
""" ============================= OOB Errors for Random Forests ============================= The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where each new tree is fit from a bootstrap sample of the training observations :math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average error for each :math:`z_i` calculated using predictions from the trees that do not contain :math:`z_i` in their respective bootstrap sample. This allows the ``RandomForestClassifier`` to be fit and validated whilst being trained [1]. The example below demonstrates how the OOB error can be measured at the addition of each new tree during training. The resulting plot allows a practitioner to approximate a suitable value of ``n_estimators`` at which the error stabilizes. .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", p592-593, Springer, 2009. """ import matplotlib.pyplot as plt from collections import OrderedDict from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier # Author: Kian Ho <hui.kian.ho@gmail.com> # Gilles Louppe <g.louppe@gmail.com> # Andreas Mueller <amueller@ais.uni-bonn.de> # # License: BSD 3 Clause print(__doc__) RANDOM_STATE = 123 # Generate a binary classification dataset. X, y = make_classification(n_samples=500, n_features=25, n_clusters_per_class=1, n_informative=15, random_state=RANDOM_STATE) # NOTE: Setting the `warm_start` construction parameter to `True` disables # support for paralellised ensembles but is necessary for tracking the OOB # error trajectory during training. ensemble_clfs = [ ("RandomForestClassifier, max_features='sqrt'", RandomForestClassifier(warm_start=True, oob_score=True, max_features="sqrt", random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features='log2'", RandomForestClassifier(warm_start=True, max_features='log2', oob_score=True, random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features=None", RandomForestClassifier(warm_start=True, max_features=None, oob_score=True, random_state=RANDOM_STATE)) ] # Map a classifier name to a list of (<n_estimators>, <error rate>) pairs. error_rate = OrderedDict((label, []) for label, _ in ensemble_clfs) # Range of `n_estimators` values to explore. min_estimators = 15 max_estimators = 175 for label, clf in ensemble_clfs: for i in range(min_estimators, max_estimators + 1): clf.set_params(n_estimators=i) clf.fit(X, y) # Record the OOB error for each `n_estimators=i` setting. oob_error = 1 - clf.oob_score_ error_rate[label].append((i, oob_error)) # Generate the "OOB error rate" vs. "n_estimators" plot. for label, clf_err in error_rate.items(): xs, ys = zip(*clf_err) plt.plot(xs, ys, label=label) plt.xlim(min_estimators, max_estimators) plt.xlabel("n_estimators") plt.ylabel("OOB error rate") plt.legend(loc="upper right") plt.show()
bsd-3-clause
google/uncertainty-baselines
baselines/diabetic_retinopathy_detection/jax_finetune_deterministic.py
1
22801
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Finetuning.""" import functools import itertools import multiprocessing import numbers import os import time from absl import app from absl import flags from absl import logging from clu import metric_writers from clu import parameter_overview from clu import periodic_actions from clu import preprocess_spec import flax import jax import jax.numpy as jnp import ml_collections.config_flags import numpy as np import tensorflow as tf tf.config.experimental.set_visible_devices([], 'GPU') tf.config.experimental.set_visible_devices([], 'TPU_SYSTEM') tf.config.experimental.set_visible_devices([], 'TPU') logging.info(tf.config.experimental.get_visible_devices()) # pylint: disable=g-import-not-at-top,line-too-long import uncertainty_baselines as ub import checkpoint_utils # local file import from baselines.diabetic_retinopathy_detection import input_utils # local file import from baselines.diabetic_retinopathy_detection import preprocess_utils # local file import from baselines.diabetic_retinopathy_detection import train_utils # local file import from baselines.diabetic_retinopathy_detection from utils import results_storage_utils from utils import vit_utils import wandb # pylint: enable=g-import-not-at-top,line-too-long # TODO(nband): lock config after separating total and warmup steps arguments. ml_collections.config_flags.DEFINE_config_file( 'config', None, 'Training configuration.', lock_config=False) # Set up extraneous flags for use in Googler job launching. flags.DEFINE_string('output_dir', default=None, help='Work unit directory.') flags.DEFINE_integer( 'num_cores', default=None, help='Unused. How many devices being used.') flags.DEFINE_boolean( 'use_gpu', default=None, help='Unused. Whether or not running on GPU.') flags.DEFINE_string('tpu', None, 'Unused. Name of the TPU. Only used if use_gpu is False.') FLAGS = flags.FLAGS def main(argv): del argv # unused arg config = FLAGS.config # Unpack total and warmup steps # TODO(nband): revert this to separate arguments. total_steps = config.total_and_warmup_steps[0] warmup_steps = config.total_and_warmup_steps[1] del config.total_and_warmup_steps config.total_steps = total_steps config.lr.warmup_steps = warmup_steps # Wandb and Checkpointing Setup output_dir = FLAGS.output_dir wandb_run, output_dir = vit_utils.maybe_setup_wandb(config) tf.io.gfile.makedirs(output_dir) logging.info('Saving checkpoints at %s', output_dir) # Dataset Split Flags dist_shift = config.distribution_shift print(f'Distribution Shift: {dist_shift}.') dataset_names, split_names = vit_utils.get_dataset_and_split_names(dist_shift) # LR / Optimization Flags batch_size = config.batch_size grad_clip_norm = config.grad_clip_norm weight_decay = config.weight_decay print('wandb hyperparameters:') print({ 'batch_size': batch_size, 'grad_clip_norm': grad_clip_norm, 'weight_decay': weight_decay, 'total_steps': config.total_steps, 'lr': config.lr }) # Reweighting loss for class imbalance # class_reweight_mode = config.class_reweight_mode # if class_reweight_mode == 'constant': # class_weights = utils.get_diabetic_retinopathy_class_balance_weights() # else: # class_weights = None # Shows the number of available devices. # In a CPU/GPU runtime this will be a single device. # In a TPU runtime this will be 8 cores. print('Number of Jax local devices:', jax.local_devices()) # TODO(nband): fix sigmoid loss issues. assert config.get('loss', None) == 'softmax_xent' seed = config.get('seed', 0) rng = jax.random.PRNGKey(seed) tf.random.set_seed(seed) if config.get('data_dir'): logging.info('data_dir=%s', config.data_dir) logging.info('Output dir: %s', output_dir) tf.io.gfile.makedirs(output_dir) save_checkpoint_path = None if config.get('checkpoint_steps'): save_checkpoint_path = os.path.join(output_dir, 'checkpoint.npz') # Create an asynchronous multi-metric writer. writer = metric_writers.create_default_writer( output_dir, just_logging=jax.process_index() > 0) # The pool is used to perform misc operations such as logging in async way. pool = multiprocessing.pool.ThreadPool() def write_note(note): if jax.process_index() == 0: logging.info('NOTE: %s', note) write_note('Initializing...') # Verify settings to make sure no checkpoints are accidentally missed. if config.get('keep_checkpoint_steps'): assert config.get('checkpoint_steps'), 'Specify `checkpoint_steps`.' assert config.keep_checkpoint_steps % config.checkpoint_steps == 0, ( f'`keep_checkpoint_steps` ({config.checkpoint_steps}) should be' f'divisible by `checkpoint_steps ({config.checkpoint_steps}).`') batch_size_eval = config.get('batch_size_eval', batch_size) if (batch_size % jax.device_count() != 0 or batch_size_eval % jax.device_count() != 0): raise ValueError(f'Batch sizes ({batch_size} and {batch_size_eval}) must ' f'be divisible by device number ({jax.device_count()})') local_batch_size = batch_size // jax.process_count() local_batch_size_eval = batch_size_eval // jax.process_count() logging.info( 'Global batch size %d on %d hosts results in %d local batch size. ' 'With %d devices per host (%d devices total), that\'s a %d per-device ' 'batch size.', batch_size, jax.process_count(), local_batch_size, jax.local_device_count(), jax.device_count(), local_batch_size // jax.local_device_count()) write_note('Initializing preprocessing function...') # Same preprocessing function for training and evaluation preproc_fn = preprocess_spec.parse( spec=config.pp_train, available_ops=preprocess_utils.all_ops()) write_note('Initializing train dataset...') rng, train_ds_rng = jax.random.split(rng) train_ds_rng = jax.random.fold_in(train_ds_rng, jax.process_index()) train_base_dataset = ub.datasets.get( dataset_names['in_domain_dataset'], split=split_names['train_split'], data_dir=config.get('data_dir')) train_dataset_builder = train_base_dataset._dataset_builder # pylint: disable=protected-access train_ds = input_utils.get_data( dataset=train_dataset_builder, split=split_names['train_split'], rng=train_ds_rng, process_batch_size=local_batch_size, preprocess_fn=preproc_fn, shuffle_buffer_size=config.shuffle_buffer_size, prefetch_size=config.get('prefetch_to_host', 2), data_dir=config.get('data_dir')) # Start prefetching already. train_iter = input_utils.start_input_pipeline( train_ds, config.get('prefetch_to_device', 1)) write_note('Initializing val dataset(s)...') # Load in-domain and OOD validation and/or test datasets. # Please specify the desired shift (Country Shift or Severity Shift) # in the config. eval_iter_splits = vit_utils.init_evaluation_datasets( use_validation=config.use_validation, use_test=config.use_test, dataset_names=dataset_names, split_names=split_names, config=config, preproc_fn=preproc_fn, batch_size_eval=batch_size_eval, local_batch_size_eval=local_batch_size_eval) ntrain_img = input_utils.get_num_examples( train_dataset_builder, split=split_names['train_split'], process_batch_size=local_batch_size, data_dir=config.get('data_dir')) steps_per_epoch = ntrain_img // batch_size if config.get('num_epochs'): total_steps = int(config.num_epochs * steps_per_epoch) assert not config.get('total_steps'), 'Set either num_epochs or total_steps' else: total_steps = config.total_steps logging.info('Total train data points: %d', ntrain_img) logging.info( 'Running for %d steps, that means %f epochs and %d steps per epoch', total_steps, total_steps * batch_size / ntrain_img, steps_per_epoch) write_note('Initializing model...') model_dict = vit_utils.initialize_model('deterministic', config) model = model_dict['model'] # We want all parameters to be created in host RAM, not on any device, they'll # be sent there later as needed, otherwise we already encountered two # situations where we allocate them twice. @functools.partial(jax.jit, backend='cpu') def init(rng): image_size = tuple(train_ds.element_spec['image'].shape[2:]) logging.info('image_size = %s', image_size) dummy_input = jnp.zeros((local_batch_size,) + image_size, jnp.float32) params = flax.core.unfreeze(model.init(rng, dummy_input, train=False))['params'] # Set bias in the head to a low value, such that loss is small initially. params['head']['bias'] = jnp.full_like( params['head']['bias'], config.get('init_head_bias', 0)) # init head kernel to all zeros for fine-tuning if config.get('model_init'): params['head']['kernel'] = jnp.full_like(params['head']['kernel'], 0) return params rng, rng_init = jax.random.split(rng) params_cpu = init(rng_init) if jax.process_index() == 0: num_params = sum(p.size for p in jax.tree_flatten(params_cpu)[0]) parameter_overview.log_parameter_overview(params_cpu) writer.write_scalars(step=0, scalars={'num_params': num_params}) @functools.partial(jax.pmap, axis_name='batch') def evaluation_fn(params, images, labels): logits, out = model.apply( {'params': flax.core.freeze(params)}, images, train=False) losses = getattr(train_utils, config.get('loss', 'softmax_xent'))( logits=logits, labels=labels, reduction=False) loss = jax.lax.psum(losses, axis_name='batch') top1_idx = jnp.argmax(logits, axis=1) # Extracts the label at the highest logit index for each image. top1_correct = jnp.take_along_axis(labels, top1_idx[:, None], axis=1)[:, 0] ncorrect = jax.lax.psum(top1_correct, axis_name='batch') n = batch_size_eval metric_args = jax.lax.all_gather([ logits, labels, out['pre_logits']], axis_name='batch') return ncorrect, loss, n, metric_args # Load the optimizer from flax. opt_name = config.get('optim_name') write_note(f'Initializing {opt_name} optimizer...') opt_def = getattr(flax.optim, opt_name)(**config.get('optim', {})) # We jit this, such that the arrays that are created are created on the same # device as the input is, in this case the CPU. Else they'd be on device[0]. opt_cpu = jax.jit(opt_def.create)(params_cpu) @functools.partial(jax.pmap, axis_name='batch', donate_argnums=(0,)) def update_fn(opt, lr, images, labels, rng): """Update step.""" measurements = {} # Get device-specific loss rng. rng, rng_model = jax.random.split(rng, 2) rng_model_local = jax.random.fold_in(rng_model, jax.lax.axis_index('batch')) def loss_fn(params, images, labels): logits, _ = model.apply( {'params': flax.core.freeze(params)}, images, train=True, rngs={'dropout': rng_model_local}) return getattr(train_utils, config.get('loss', 'sigmoid_xent'))( logits=logits, labels=labels) # Implementation considerations compared and summarized at # https://docs.google.com/document/d/1g3kMEvqu1DOawaflKNyUsIoQ4yIVEoyE5ZlIPkIl4Lc/edit?hl=en# l, g = train_utils.accumulate_gradient( jax.value_and_grad(loss_fn), opt.target, images, labels, config.get('grad_accum_steps')) l, g = jax.lax.pmean((l, g), axis_name='batch') # Log the gradient norm only if we need to compute it anyways (clipping) # or if we don't use grad_accum_steps, as they interact badly. if config.get('grad_accum_steps', 1) == 1 or grad_clip_norm is not None: grads, _ = jax.tree_flatten(g) l2_g = jnp.sqrt(sum([jnp.vdot(p, p) for p in grads])) measurements['l2_grads'] = l2_g # Optionally resize the global gradient to a maximum norm. We found this # useful in some cases across optimizers, hence it's in the main loop. if grad_clip_norm is not None: g_factor = jnp.minimum(1.0, grad_clip_norm / l2_g) g = jax.tree_util.tree_map(lambda p: g_factor * p, g) opt = opt.apply_gradient(g, learning_rate=lr) decay_rules = weight_decay or [] if isinstance(decay_rules, numbers.Number): decay_rules = [('.*kernel.*', decay_rules)] sched_m = lr / config.lr.base if config.get( 'weight_decay_decouple') else lr def decay_fn(v, wd): return (1.0 - sched_m * wd) * v opt = opt.replace( target=train_utils.tree_map_with_regex(decay_fn, opt.target, decay_rules)) params, _ = jax.tree_flatten(opt.target) measurements['l2_params'] = jnp.sqrt( sum([jnp.vdot(p, p) for p in params])) return opt, l, rng, measurements rng, train_loop_rngs = jax.random.split(rng) reint_params = ('head/kernel', 'head/bias') if config.get('only_eval', False) or not config.get('reint_head', True): reint_params = [] checkpoint_data = checkpoint_utils.maybe_load_checkpoint( train_loop_rngs=train_loop_rngs, save_checkpoint_path=save_checkpoint_path, init_optimizer=opt_cpu, init_params=params_cpu, init_fixed_model_states=None, default_reinit_params=reint_params, config=config, ) train_loop_rngs = checkpoint_data.train_loop_rngs opt_cpu = checkpoint_data.optimizer accumulated_train_time = checkpoint_data.accumulated_train_time write_note('Kicking off misc stuff...') first_step = int(opt_cpu.state.step) # Might be a DeviceArray type. if first_step == 0 and jax.process_index() == 0: writer.write_hparams(dict(config)) chrono = train_utils.Chrono( first_step, total_steps, batch_size, accumulated_train_time) # Note: switch to ProfileAllHosts() if you need to profile all hosts. # (Xprof data become much larger and take longer to load for analysis) profiler = periodic_actions.Profile( # Create profile after every restart to analyze pre-emption related # problems and assure we get similar performance in every run. logdir=output_dir, first_profile=first_step + 10) # Prepare the learning-rate and pre-fetch it to device to avoid delays. lr_fn = train_utils.create_learning_rate_schedule(total_steps, **config.get('lr', {})) # TODO(dusenberrymw): According to flax docs, prefetching shouldn't be # necessary for TPUs. lr_iter = train_utils.prefetch_scalar( map(lr_fn, range(total_steps)), config.get('prefetch_to_device', 1)) write_note(f'Replicating...\n{chrono.note}') opt_repl = flax.jax_utils.replicate(opt_cpu) checkpoint_writer = None # Note: we return the train loss, val loss, and fewshot best l2s for use in # reproducibility unit tests. # train_loss = -jnp.inf # val_loss = -jnp.inf # results = {'dummy': {(0, 1): -jnp.inf}} write_note(f'First step compilations...\n{chrono.note}') logging.info('first_step = %s', first_step) # Advance the iterators if we are restarting from an earlier checkpoint. # TODO(dusenberrymw): Look into checkpointing dataset state instead. if first_step > 0: write_note('Advancing iterators after resuming from a checkpoint...') lr_iter = itertools.islice(lr_iter, first_step, None) train_iter = itertools.islice(train_iter, first_step, None) # Using a python integer for step here, because opt.state.step is allocated # on TPU during replication. for step, train_batch, lr_repl in zip( range(first_step + 1, total_steps + 1), train_iter, lr_iter): with jax.profiler.TraceAnnotation('train_step', step_num=step, _r=1): if not config.get('only_eval', False): opt_repl, loss_value, train_loop_rngs, extra_measurements = update_fn( opt_repl, lr_repl, train_batch['image'], train_batch['labels'], rng=train_loop_rngs) if jax.process_index() == 0: profiler(step) # Checkpoint saving if not config.get('only_eval', False) and train_utils.itstime( step, config.get('checkpoint_steps'), total_steps, process=0): write_note('Checkpointing...') chrono.pause() train_utils.checkpointing_timeout(checkpoint_writer, config.get('checkpoint_timeout', 1)) accumulated_train_time = chrono.accum_train_time # We need to transfer the weights over now or else we risk keeping them # alive while they'll be updated in a future step, creating hard to debug # memory errors (see b/160593526). Also, takes device 0's params only. opt_cpu = jax.tree_util.tree_map(lambda x: np.array(x[0]), opt_repl) # Check whether we want to keep a copy of the current checkpoint. copy_step = None if train_utils.itstime(step, config.get('keep_checkpoint_steps'), total_steps): write_note('Keeping a checkpoint copy...') copy_step = step # Checkpoint should be a nested dictionary or FLAX datataclasses from # `flax.struct`. Both can be present in a checkpoint. checkpoint_data = checkpoint_utils.CheckpointData( train_loop_rngs=train_loop_rngs, optimizer=opt_cpu, accumulated_train_time=accumulated_train_time) checkpoint_writer = pool.apply_async( checkpoint_utils.checkpoint_trained_model, (checkpoint_data, save_checkpoint_path, copy_step)) chrono.resume() # Report training progress if not config.get('only_eval', False) and train_utils.itstime( step, config.log_training_steps, total_steps, process=0): write_note('Reporting training progress...') train_loss = loss_value[0] # Keep to return for reproducibility tests. timing_measurements, note = chrono.tick(step) write_note(note) train_measurements = {} train_measurements.update({ 'learning_rate': lr_repl[0], 'training_loss': train_loss, }) train_measurements.update(flax.jax_utils.unreplicate(extra_measurements)) train_measurements.update(timing_measurements) writer.write_scalars(step, train_measurements) # Report validation performance if train_utils.itstime(step, config.log_eval_steps, total_steps): write_note('Evaluating on the validation set...') chrono.pause() all_eval_results = {} for eval_name, (eval_iter, eval_steps) in eval_iter_splits.items(): start_time = time.time() # Runs evaluation loop. results_arrs = { 'y_true': [], 'y_pred': [], 'y_pred_entropy': [] } for _, batch in zip(range(eval_steps), eval_iter): batch_ncorrect, batch_losses, batch_n, batch_metric_args = ( # pylint: disable=unused-variable evaluation_fn( opt_repl.target, batch['image'], batch['labels'])) # All results are a replicated array shaped as follows: # (local_devices, per_device_batch_size, elem_shape...) # with each local device's entry being identical as they got psum'd. # So let's just take the first one to the host as numpy. # from jft/deterministic.py # Here we parse batch_metric_args to compute uncertainty metrics. logits, labels, _ = batch_metric_args logits = np.array(logits[0]) probs = jax.nn.softmax(logits) # From one-hot to integer labels. int_labels = np.argmax(np.array(labels[0]), axis=-1) probs = np.reshape(probs, (probs.shape[0] * probs.shape[1], -1)) int_labels = int_labels.flatten() y_pred = probs[:, 1] results_arrs['y_true'].append(int_labels) results_arrs['y_pred'].append(y_pred) # Entropy is computed at the per-epoch level (see below). results_arrs['y_pred_entropy'].append(probs) results_arrs['y_true'] = np.concatenate(results_arrs['y_true'], axis=0) results_arrs['y_pred'] = np.concatenate( results_arrs['y_pred'], axis=0).astype('float64') results_arrs['y_pred_entropy'] = vit_utils.entropy( np.concatenate(results_arrs['y_pred_entropy'], axis=0), axis=-1) time_elapsed = time.time() - start_time results_arrs['total_ms_elapsed'] = time_elapsed * 1e3 results_arrs['dataset_size'] = eval_steps * batch_size_eval all_eval_results[eval_name] = results_arrs per_pred_results, metrics_results = vit_utils.evaluate_vit_predictions( # pylint: disable=unused-variable dataset_split_to_containers=all_eval_results, is_deterministic=True, num_bins=15, return_per_pred_results=True ) # `metrics_results` is a dict of {str: jnp.ndarray} dicts, one for each # dataset. Flatten this dict so we can pass to the writer and remove empty # entries. flattened_metric_results = {} for dic in metrics_results.values(): for key, value in dic.items(): if value is not None: flattened_metric_results[key] = value writer.write_scalars(step, flattened_metric_results) # Optionally log to wandb if config.use_wandb: wandb.log(metrics_results, step=step) # Save per-prediction metrics results_storage_utils.save_per_prediction_results( output_dir, step, per_pred_results, verbose=False) chrono.resume() # End of step. if config.get('testing_failure_step'): # Break early to simulate infra failures in test cases. if config.testing_failure_step == step: break write_note(f'Done!\n{chrono.note}') pool.close() pool.join() writer.close() if wandb_run is not None: wandb_run.finish() # Return final training loss, validation loss, and fewshot results for # reproducibility test cases. # return train_loss, val_loss, results # TODO(nband): fix result reporting for DR ViT-16 reproducibility unit tests if __name__ == '__main__': # Adds jax flags to the program. jax.config.config_with_absl() app.run(main)
apache-2.0
UpSea/midProjects
01_aat-ebook-full-source-code-20160430/chapter13/reuters-svm.py
1
6726
from __future__ import print_function import pprint import re try: from html.parser import HTMLParser except ImportError: from HTMLParser import HTMLParser from sklearn.cross_validation import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import confusion_matrix from sklearn.svm import SVC class ReutersParser(HTMLParser): """ ReutersParser subclasses HTMLParser and is used to open the SGML files associated with the Reuters-21578 categorised test collection. The parser is a generator and will yield a single document at a time. Since the data will be chunked on parsing, it is necessary to keep some internal state of when tags have been "entered" and "exited". Hence the in_body, in_topics and in_topic_d boolean members. """ def __init__(self, encoding='latin-1'): """ Initialise the superclass (HTMLParser) and reset the parser. Sets the encoding of the SGML files by default to latin-1. """ HTMLParser.__init__(self) self._reset() self.encoding = encoding def _reset(self): """ This is called only on initialisation of the parser class and when a new topic-body tuple has been generated. It resets all off the state so that a new tuple can be subsequently generated. """ self.in_body = False self.in_topics = False self.in_topic_d = False self.body = "" self.topics = [] self.topic_d = "" def parse(self, fd): """ parse accepts a file descriptor and loads the data in chunks in order to minimise memory usage. It then yields new documents as they are parsed. """ self.docs = [] for chunk in fd: self.feed(chunk.decode(self.encoding)) for doc in self.docs: yield doc self.docs = [] self.close() def handle_starttag(self, tag, attrs): """ This method is used to determine what to do when the parser comes across a particular tag of type "tag". In this instance we simply set the internal state booleans to True if that particular tag has been found. """ if tag == "reuters": pass elif tag == "body": self.in_body = True elif tag == "topics": self.in_topics = True elif tag == "d": self.in_topic_d = True def handle_endtag(self, tag): """ This method is used to determine what to do when the parser finishes with a particular tag of type "tag". If the tag is a <REUTERS> tag, then we remove all white-space with a regular expression and then append the topic-body tuple. If the tag is a <BODY> or <TOPICS> tag then we simply set the internal state to False for these booleans, respectively. If the tag is a <D> tag (found within a <TOPICS> tag), then we append the particular topic to the "topics" list and finally reset it. """ if tag == "reuters": self.body = re.sub(r'\s+', r' ', self.body) self.docs.append( (self.topics, self.body) ) self._reset() elif tag == "body": self.in_body = False elif tag == "topics": self.in_topics = False elif tag == "d": self.in_topic_d = False self.topics.append(self.topic_d) self.topic_d = "" def handle_data(self, data): """ The data is simply appended to the appropriate member state for that particular tag, up until the end closing tag appears. """ if self.in_body: self.body += data elif self.in_topic_d: self.topic_d += data def obtain_topic_tags(): """ Open the topic list file and import all of the topic names taking care to strip the trailing "\n" from each word. """ topics = open( "data/all-topics-strings.lc.txt", "r" ).readlines() topics = [t.strip() for t in topics] return topics def filter_doc_list_through_topics(topics, docs): """ Reads all of the documents and creates a new list of two-tuples that contain a single feature entry and the body text, instead of a list of topics. It removes all geographic features and only retains those documents which have at least one non-geographic topic. """ ref_docs = [] for d in docs: if d[0] == [] or d[0] == "": continue for t in d[0]: if t in topics: d_tup = (t, d[1]) ref_docs.append(d_tup) break return ref_docs def create_tfidf_training_data(docs): """ Creates a document corpus list (by stripping out the class labels), then applies the TF-IDF transform to this list. The function returns both the class label vector (y) and the corpus token/feature matrix (X). """ # Create the training data class labels y = [d[0] for d in docs] # Create the document corpus list corpus = [d[1] for d in docs] # Create the TF-IDF vectoriser and transform the corpus vectorizer = TfidfVectorizer(min_df=1) X = vectorizer.fit_transform(corpus) return X, y def train_svm(X, y): """ Create and train the Support Vector Machine. """ svm = SVC(C=1000000.0, gamma=0.0, kernel='rbf') svm.fit(X, y) return svm if __name__ == "__main__": # Create the list of Reuters data and create the parser files = ["data/reut2-%03d.sgm" % r for r in range(0, 22)] parser = ReutersParser() # Parse the document and force all generated docs into # a list so that it can be printed out to the console docs = [] for fn in files: for d in parser.parse(open(fn, 'rb')): docs.append(d) # Obtain the topic tags and filter docs through it topics = obtain_topic_tags() ref_docs = filter_doc_list_through_topics(topics, docs) # Vectorise and TF-IDF transform the corpus X, y = create_tfidf_training_data(ref_docs) # Create the training-test split of the data X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) # Create and train the Support Vector Machine svm = train_svm(X_train, y_train) # Make an array of predictions on the test set pred = svm.predict(X_test) # Output the hit-rate and the confusion matrix for each model print(svm.score(X_test, y_test)) print(confusion_matrix(pred, y_test))
mit
IndraVikas/scikit-learn
examples/applications/svm_gui.py
285
11161
""" ========== Libsvm GUI ========== A simple graphical frontend for Libsvm mainly intended for didactic purposes. You can create data points by point and click and visualize the decision region induced by different kernels and parameter settings. To create positive examples click the left mouse button; to create negative examples click the right button. If all examples are from the same class, it uses a one-class SVM. """ from __future__ import division, print_function print(__doc__) # Author: Peter Prettenhoer <peter.prettenhofer@gmail.com> # # License: BSD 3 clause import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.contour import ContourSet import Tkinter as Tk import sys import numpy as np from sklearn import svm from sklearn.datasets import dump_svmlight_file from sklearn.externals.six.moves import xrange y_min, y_max = -50, 50 x_min, x_max = -50, 50 class Model(object): """The Model which hold the data. It implements the observable in the observer pattern and notifies the registered observers on change event. """ def __init__(self): self.observers = [] self.surface = None self.data = [] self.cls = None self.surface_type = 0 def changed(self, event): """Notify the observers. """ for observer in self.observers: observer.update(event, self) def add_observer(self, observer): """Register an observer. """ self.observers.append(observer) def set_surface(self, surface): self.surface = surface def dump_svmlight_file(self, file): data = np.array(self.data) X = data[:, 0:2] y = data[:, 2] dump_svmlight_file(X, y, file) class Controller(object): def __init__(self, model): self.model = model self.kernel = Tk.IntVar() self.surface_type = Tk.IntVar() # Whether or not a model has been fitted self.fitted = False def fit(self): print("fit the model") train = np.array(self.model.data) X = train[:, 0:2] y = train[:, 2] C = float(self.complexity.get()) gamma = float(self.gamma.get()) coef0 = float(self.coef0.get()) degree = int(self.degree.get()) kernel_map = {0: "linear", 1: "rbf", 2: "poly"} if len(np.unique(y)) == 1: clf = svm.OneClassSVM(kernel=kernel_map[self.kernel.get()], gamma=gamma, coef0=coef0, degree=degree) clf.fit(X) else: clf = svm.SVC(kernel=kernel_map[self.kernel.get()], C=C, gamma=gamma, coef0=coef0, degree=degree) clf.fit(X, y) if hasattr(clf, 'score'): print("Accuracy:", clf.score(X, y) * 100) X1, X2, Z = self.decision_surface(clf) self.model.clf = clf self.model.set_surface((X1, X2, Z)) self.model.surface_type = self.surface_type.get() self.fitted = True self.model.changed("surface") def decision_surface(self, cls): delta = 1 x = np.arange(x_min, x_max + delta, delta) y = np.arange(y_min, y_max + delta, delta) X1, X2 = np.meshgrid(x, y) Z = cls.decision_function(np.c_[X1.ravel(), X2.ravel()]) Z = Z.reshape(X1.shape) return X1, X2, Z def clear_data(self): self.model.data = [] self.fitted = False self.model.changed("clear") def add_example(self, x, y, label): self.model.data.append((x, y, label)) self.model.changed("example_added") # update decision surface if already fitted. self.refit() def refit(self): """Refit the model if already fitted. """ if self.fitted: self.fit() class View(object): """Test docstring. """ def __init__(self, root, controller): f = Figure() ax = f.add_subplot(111) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim((x_min, x_max)) ax.set_ylim((y_min, y_max)) canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas.mpl_connect('button_press_event', self.onclick) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() self.controllbar = ControllBar(root, controller) self.f = f self.ax = ax self.canvas = canvas self.controller = controller self.contours = [] self.c_labels = None self.plot_kernels() def plot_kernels(self): self.ax.text(-50, -60, "Linear: $u^T v$") self.ax.text(-20, -60, "RBF: $\exp (-\gamma \| u-v \|^2)$") self.ax.text(10, -60, "Poly: $(\gamma \, u^T v + r)^d$") def onclick(self, event): if event.xdata and event.ydata: if event.button == 1: self.controller.add_example(event.xdata, event.ydata, 1) elif event.button == 3: self.controller.add_example(event.xdata, event.ydata, -1) def update_example(self, model, idx): x, y, l = model.data[idx] if l == 1: color = 'w' elif l == -1: color = 'k' self.ax.plot([x], [y], "%so" % color, scalex=0.0, scaley=0.0) def update(self, event, model): if event == "examples_loaded": for i in xrange(len(model.data)): self.update_example(model, i) if event == "example_added": self.update_example(model, -1) if event == "clear": self.ax.clear() self.ax.set_xticks([]) self.ax.set_yticks([]) self.contours = [] self.c_labels = None self.plot_kernels() if event == "surface": self.remove_surface() self.plot_support_vectors(model.clf.support_vectors_) self.plot_decision_surface(model.surface, model.surface_type) self.canvas.draw() def remove_surface(self): """Remove old decision surface.""" if len(self.contours) > 0: for contour in self.contours: if isinstance(contour, ContourSet): for lineset in contour.collections: lineset.remove() else: contour.remove() self.contours = [] def plot_support_vectors(self, support_vectors): """Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.""" cs = self.ax.scatter(support_vectors[:, 0], support_vectors[:, 1], s=80, edgecolors="k", facecolors="none") self.contours.append(cs) def plot_decision_surface(self, surface, type): X1, X2, Z = surface if type == 0: levels = [-1.0, 0.0, 1.0] linestyles = ['dashed', 'solid', 'dashed'] colors = 'k' self.contours.append(self.ax.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)) elif type == 1: self.contours.append(self.ax.contourf(X1, X2, Z, 10, cmap=matplotlib.cm.bone, origin='lower', alpha=0.85)) self.contours.append(self.ax.contour(X1, X2, Z, [0.0], colors='k', linestyles=['solid'])) else: raise ValueError("surface type unknown") class ControllBar(object): def __init__(self, root, controller): fm = Tk.Frame(root) kernel_group = Tk.Frame(fm) Tk.Radiobutton(kernel_group, text="Linear", variable=controller.kernel, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="RBF", variable=controller.kernel, value=1, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="Poly", variable=controller.kernel, value=2, command=controller.refit).pack(anchor=Tk.W) kernel_group.pack(side=Tk.LEFT) valbox = Tk.Frame(fm) controller.complexity = Tk.StringVar() controller.complexity.set("1.0") c = Tk.Frame(valbox) Tk.Label(c, text="C:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(c, width=6, textvariable=controller.complexity).pack( side=Tk.LEFT) c.pack() controller.gamma = Tk.StringVar() controller.gamma.set("0.01") g = Tk.Frame(valbox) Tk.Label(g, text="gamma:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(g, width=6, textvariable=controller.gamma).pack(side=Tk.LEFT) g.pack() controller.degree = Tk.StringVar() controller.degree.set("3") d = Tk.Frame(valbox) Tk.Label(d, text="degree:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(d, width=6, textvariable=controller.degree).pack(side=Tk.LEFT) d.pack() controller.coef0 = Tk.StringVar() controller.coef0.set("0") r = Tk.Frame(valbox) Tk.Label(r, text="coef0:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(r, width=6, textvariable=controller.coef0).pack(side=Tk.LEFT) r.pack() valbox.pack(side=Tk.LEFT) cmap_group = Tk.Frame(fm) Tk.Radiobutton(cmap_group, text="Hyperplanes", variable=controller.surface_type, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(cmap_group, text="Surface", variable=controller.surface_type, value=1, command=controller.refit).pack(anchor=Tk.W) cmap_group.pack(side=Tk.LEFT) train_button = Tk.Button(fm, text='Fit', width=5, command=controller.fit) train_button.pack() fm.pack(side=Tk.LEFT) Tk.Button(fm, text='Clear', width=5, command=controller.clear_data).pack(side=Tk.LEFT) def get_parser(): from optparse import OptionParser op = OptionParser() op.add_option("--output", action="store", type="str", dest="output", help="Path where to dump data.") return op def main(argv): op = get_parser() opts, args = op.parse_args(argv[1:]) root = Tk.Tk() model = Model() controller = Controller(model) root.wm_title("Scikit-learn Libsvm GUI") view = View(root, controller) model.add_observer(view) Tk.mainloop() if opts.output: model.dump_svmlight_file(opts.output) if __name__ == "__main__": main(sys.argv)
bsd-3-clause
frank-tancf/scikit-learn
sklearn/cluster/tests/test_k_means.py
40
27789
"""Testing for K-means""" import sys import numpy as np from scipy import sparse as sp from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import SkipTest from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regex from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_warns from sklearn.utils.testing import if_safe_multiprocessing_with_blas from sklearn.utils.testing import if_not_mac_os from sklearn.utils.testing import assert_raise_message from sklearn.utils.extmath import row_norms from sklearn.metrics.cluster import v_measure_score from sklearn.cluster import KMeans, k_means from sklearn.cluster import MiniBatchKMeans from sklearn.cluster.k_means_ import _labels_inertia from sklearn.cluster.k_means_ import _mini_batch_step from sklearn.datasets.samples_generator import make_blobs from sklearn.externals.six.moves import cStringIO as StringIO from sklearn.exceptions import DataConversionWarning # non centered, sparse centers to check the centers = np.array([ [0.0, 5.0, 0.0, 0.0, 0.0], [1.0, 1.0, 4.0, 0.0, 0.0], [1.0, 0.0, 0.0, 5.0, 1.0], ]) n_samples = 100 n_clusters, n_features = centers.shape X, true_labels = make_blobs(n_samples=n_samples, centers=centers, cluster_std=1., random_state=42) X_csr = sp.csr_matrix(X) def test_kmeans_dtype(): rnd = np.random.RandomState(0) X = rnd.normal(size=(40, 2)) X = (X * 10).astype(np.uint8) km = KMeans(n_init=1).fit(X) pred_x = assert_warns(DataConversionWarning, km.predict, X) assert_array_equal(km.labels_, pred_x) def test_labels_assignment_and_inertia(): # pure numpy implementation as easily auditable reference gold # implementation rng = np.random.RandomState(42) noisy_centers = centers + rng.normal(size=centers.shape) labels_gold = - np.ones(n_samples, dtype=np.int) mindist = np.empty(n_samples) mindist.fill(np.infty) for center_id in range(n_clusters): dist = np.sum((X - noisy_centers[center_id]) ** 2, axis=1) labels_gold[dist < mindist] = center_id mindist = np.minimum(dist, mindist) inertia_gold = mindist.sum() assert_true((mindist >= 0.0).all()) assert_true((labels_gold != -1).all()) # perform label assignment using the dense array input x_squared_norms = (X ** 2).sum(axis=1) labels_array, inertia_array = _labels_inertia( X, x_squared_norms, noisy_centers) assert_array_almost_equal(inertia_array, inertia_gold) assert_array_equal(labels_array, labels_gold) # perform label assignment using the sparse CSR input x_squared_norms_from_csr = row_norms(X_csr, squared=True) labels_csr, inertia_csr = _labels_inertia( X_csr, x_squared_norms_from_csr, noisy_centers) assert_array_almost_equal(inertia_csr, inertia_gold) assert_array_equal(labels_csr, labels_gold) def test_minibatch_update_consistency(): # Check that dense and sparse minibatch update give the same results rng = np.random.RandomState(42) old_centers = centers + rng.normal(size=centers.shape) new_centers = old_centers.copy() new_centers_csr = old_centers.copy() counts = np.zeros(new_centers.shape[0], dtype=np.int32) counts_csr = np.zeros(new_centers.shape[0], dtype=np.int32) x_squared_norms = (X ** 2).sum(axis=1) x_squared_norms_csr = row_norms(X_csr, squared=True) buffer = np.zeros(centers.shape[1], dtype=np.double) buffer_csr = np.zeros(centers.shape[1], dtype=np.double) # extract a small minibatch X_mb = X[:10] X_mb_csr = X_csr[:10] x_mb_squared_norms = x_squared_norms[:10] x_mb_squared_norms_csr = x_squared_norms_csr[:10] # step 1: compute the dense minibatch update old_inertia, incremental_diff = _mini_batch_step( X_mb, x_mb_squared_norms, new_centers, counts, buffer, 1, None, random_reassign=False) assert_greater(old_inertia, 0.0) # compute the new inertia on the same batch to check that it decreased labels, new_inertia = _labels_inertia( X_mb, x_mb_squared_norms, new_centers) assert_greater(new_inertia, 0.0) assert_less(new_inertia, old_inertia) # check that the incremental difference computation is matching the # final observed value effective_diff = np.sum((new_centers - old_centers) ** 2) assert_almost_equal(incremental_diff, effective_diff) # step 2: compute the sparse minibatch update old_inertia_csr, incremental_diff_csr = _mini_batch_step( X_mb_csr, x_mb_squared_norms_csr, new_centers_csr, counts_csr, buffer_csr, 1, None, random_reassign=False) assert_greater(old_inertia_csr, 0.0) # compute the new inertia on the same batch to check that it decreased labels_csr, new_inertia_csr = _labels_inertia( X_mb_csr, x_mb_squared_norms_csr, new_centers_csr) assert_greater(new_inertia_csr, 0.0) assert_less(new_inertia_csr, old_inertia_csr) # check that the incremental difference computation is matching the # final observed value effective_diff = np.sum((new_centers_csr - old_centers) ** 2) assert_almost_equal(incremental_diff_csr, effective_diff) # step 3: check that sparse and dense updates lead to the same results assert_array_equal(labels, labels_csr) assert_array_almost_equal(new_centers, new_centers_csr) assert_almost_equal(incremental_diff, incremental_diff_csr) assert_almost_equal(old_inertia, old_inertia_csr) assert_almost_equal(new_inertia, new_inertia_csr) def _check_fitted_model(km): # check that the number of clusters centers and distinct labels match # the expectation centers = km.cluster_centers_ assert_equal(centers.shape, (n_clusters, n_features)) labels = km.labels_ assert_equal(np.unique(labels).shape[0], n_clusters) # check that the labels assignment are perfect (up to a permutation) assert_equal(v_measure_score(true_labels, labels), 1.0) assert_greater(km.inertia_, 0.0) # check error on dataset being too small assert_raises(ValueError, km.fit, [[0., 1.]]) def test_k_means_plus_plus_init(): km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42).fit(X) _check_fitted_model(km) def test_k_means_new_centers(): # Explore the part of the code where a new center is reassigned X = np.array([[0, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0]]) labels = [0, 1, 2, 1, 1, 2] bad_centers = np.array([[+0, 1, 0, 0], [.2, 0, .2, .2], [+0, 0, 0, 0]]) km = KMeans(n_clusters=3, init=bad_centers, n_init=1, max_iter=10, random_state=1) for this_X in (X, sp.coo_matrix(X)): km.fit(this_X) this_labels = km.labels_ # Reorder the labels so that the first instance is in cluster 0, # the second in cluster 1, ... this_labels = np.unique(this_labels, return_index=True)[1][this_labels] np.testing.assert_array_equal(this_labels, labels) @if_safe_multiprocessing_with_blas def test_k_means_plus_plus_init_2_jobs(): if sys.version_info[:2] < (3, 4): raise SkipTest( "Possible multi-process bug with some BLAS under Python < 3.4") km = KMeans(init="k-means++", n_clusters=n_clusters, n_jobs=2, random_state=42).fit(X) _check_fitted_model(km) def test_k_means_precompute_distances_flag(): # check that a warning is raised if the precompute_distances flag is not # supported km = KMeans(precompute_distances="wrong") assert_raises(ValueError, km.fit, X) def test_k_means_plus_plus_init_sparse(): km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42) km.fit(X_csr) _check_fitted_model(km) def test_k_means_random_init(): km = KMeans(init="random", n_clusters=n_clusters, random_state=42) km.fit(X) _check_fitted_model(km) def test_k_means_random_init_sparse(): km = KMeans(init="random", n_clusters=n_clusters, random_state=42) km.fit(X_csr) _check_fitted_model(km) def test_k_means_plus_plus_init_not_precomputed(): km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42, precompute_distances=False).fit(X) _check_fitted_model(km) def test_k_means_random_init_not_precomputed(): km = KMeans(init="random", n_clusters=n_clusters, random_state=42, precompute_distances=False).fit(X) _check_fitted_model(km) def test_k_means_perfect_init(): km = KMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=1) km.fit(X) _check_fitted_model(km) def test_k_means_n_init(): rnd = np.random.RandomState(0) X = rnd.normal(size=(40, 2)) # two regression tests on bad n_init argument # previous bug: n_init <= 0 threw non-informative TypeError (#3858) assert_raises_regex(ValueError, "n_init", KMeans(n_init=0).fit, X) assert_raises_regex(ValueError, "n_init", KMeans(n_init=-1).fit, X) def test_k_means_explicit_init_shape(): # test for sensible errors when giving explicit init # with wrong number of features or clusters rnd = np.random.RandomState(0) X = rnd.normal(size=(40, 3)) for Class in [KMeans, MiniBatchKMeans]: # mismatch of number of features km = Class(n_init=1, init=X[:, :2], n_clusters=len(X)) msg = "does not match the number of features of the data" assert_raises_regex(ValueError, msg, km.fit, X) # for callable init km = Class(n_init=1, init=lambda X_, k, random_state: X_[:, :2], n_clusters=len(X)) assert_raises_regex(ValueError, msg, km.fit, X) # mismatch of number of clusters msg = "does not match the number of clusters" km = Class(n_init=1, init=X[:2, :], n_clusters=3) assert_raises_regex(ValueError, msg, km.fit, X) # for callable init km = Class(n_init=1, init=lambda X_, k, random_state: X_[:2, :], n_clusters=3) assert_raises_regex(ValueError, msg, km.fit, X) def test_k_means_fortran_aligned_data(): # Check the KMeans will work well, even if X is a fortran-aligned data. X = np.asfortranarray([[0, 0], [0, 1], [0, 1]]) centers = np.array([[0, 0], [0, 1]]) labels = np.array([0, 1, 1]) km = KMeans(n_init=1, init=centers, precompute_distances=False, random_state=42, n_clusters=2) km.fit(X) assert_array_equal(km.cluster_centers_, centers) assert_array_equal(km.labels_, labels) def test_mb_k_means_plus_plus_init_dense_array(): mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, random_state=42) mb_k_means.fit(X) _check_fitted_model(mb_k_means) def test_mb_kmeans_verbose(): mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, random_state=42, verbose=1) old_stdout = sys.stdout sys.stdout = StringIO() try: mb_k_means.fit(X) finally: sys.stdout = old_stdout def test_mb_k_means_plus_plus_init_sparse_matrix(): mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, random_state=42) mb_k_means.fit(X_csr) _check_fitted_model(mb_k_means) def test_minibatch_init_with_large_k(): mb_k_means = MiniBatchKMeans(init='k-means++', init_size=10, n_clusters=20) # Check that a warning is raised, as the number clusters is larger # than the init_size assert_warns(RuntimeWarning, mb_k_means.fit, X) def test_minibatch_k_means_random_init_dense_array(): # increase n_init to make random init stable enough mb_k_means = MiniBatchKMeans(init="random", n_clusters=n_clusters, random_state=42, n_init=10).fit(X) _check_fitted_model(mb_k_means) def test_minibatch_k_means_random_init_sparse_csr(): # increase n_init to make random init stable enough mb_k_means = MiniBatchKMeans(init="random", n_clusters=n_clusters, random_state=42, n_init=10).fit(X_csr) _check_fitted_model(mb_k_means) def test_minibatch_k_means_perfect_init_dense_array(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=1).fit(X) _check_fitted_model(mb_k_means) def test_minibatch_k_means_init_multiple_runs_with_explicit_centers(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=10) assert_warns(RuntimeWarning, mb_k_means.fit, X) def test_minibatch_k_means_perfect_init_sparse_csr(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=1).fit(X_csr) _check_fitted_model(mb_k_means) def test_minibatch_sensible_reassign_fit(): # check if identical initial clusters are reassigned # also a regression test for when there are more desired reassignments than # samples. zeroed_X, true_labels = make_blobs(n_samples=100, centers=5, cluster_std=1., random_state=42) zeroed_X[::2, :] = 0 mb_k_means = MiniBatchKMeans(n_clusters=20, batch_size=10, random_state=42, init="random") mb_k_means.fit(zeroed_X) # there should not be too many exact zero cluster centers assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) # do the same with batch-size > X.shape[0] (regression test) mb_k_means = MiniBatchKMeans(n_clusters=20, batch_size=201, random_state=42, init="random") mb_k_means.fit(zeroed_X) # there should not be too many exact zero cluster centers assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) def test_minibatch_sensible_reassign_partial_fit(): zeroed_X, true_labels = make_blobs(n_samples=n_samples, centers=5, cluster_std=1., random_state=42) zeroed_X[::2, :] = 0 mb_k_means = MiniBatchKMeans(n_clusters=20, random_state=42, init="random") for i in range(100): mb_k_means.partial_fit(zeroed_X) # there should not be too many exact zero cluster centers assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) def test_minibatch_reassign(): # Give a perfect initialization, but a large reassignment_ratio, # as a result all the centers should be reassigned and the model # should not longer be good for this_X in (X, X_csr): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, random_state=42) mb_k_means.fit(this_X) score_before = mb_k_means.score(this_X) try: old_stdout = sys.stdout sys.stdout = StringIO() # Turn on verbosity to smoke test the display code _mini_batch_step(this_X, (X ** 2).sum(axis=1), mb_k_means.cluster_centers_, mb_k_means.counts_, np.zeros(X.shape[1], np.double), False, distances=np.zeros(X.shape[0]), random_reassign=True, random_state=42, reassignment_ratio=1, verbose=True) finally: sys.stdout = old_stdout assert_greater(score_before, mb_k_means.score(this_X)) # Give a perfect initialization, with a small reassignment_ratio, # no center should be reassigned for this_X in (X, X_csr): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, init=centers.copy(), random_state=42, n_init=1) mb_k_means.fit(this_X) clusters_before = mb_k_means.cluster_centers_ # Turn on verbosity to smoke test the display code _mini_batch_step(this_X, (X ** 2).sum(axis=1), mb_k_means.cluster_centers_, mb_k_means.counts_, np.zeros(X.shape[1], np.double), False, distances=np.zeros(X.shape[0]), random_reassign=True, random_state=42, reassignment_ratio=1e-15) assert_array_almost_equal(clusters_before, mb_k_means.cluster_centers_) def test_minibatch_with_many_reassignments(): # Test for the case that the number of clusters to reassign is bigger # than the batch_size n_samples = 550 rnd = np.random.RandomState(42) X = rnd.uniform(size=(n_samples, 10)) # Check that the fit works if n_clusters is bigger than the batch_size. # Run the test with 550 clusters and 550 samples, because it turned out # that this values ensure that the number of clusters to reassign # is always bigger than the batch_size n_clusters = 550 MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, init_size=n_samples, random_state=42).fit(X) def test_sparse_mb_k_means_callable_init(): def test_init(X, k, random_state): return centers # Small test to check that giving the wrong number of centers # raises a meaningful error msg = "does not match the number of clusters" assert_raises_regex(ValueError, msg, MiniBatchKMeans(init=test_init, random_state=42).fit, X_csr) # Now check that the fit actually works mb_k_means = MiniBatchKMeans(n_clusters=3, init=test_init, random_state=42).fit(X_csr) _check_fitted_model(mb_k_means) def test_mini_batch_k_means_random_init_partial_fit(): km = MiniBatchKMeans(n_clusters=n_clusters, init="random", random_state=42) # use the partial_fit API for online learning for X_minibatch in np.array_split(X, 10): km.partial_fit(X_minibatch) # compute the labeling on the complete dataset labels = km.predict(X) assert_equal(v_measure_score(true_labels, labels), 1.0) def test_minibatch_default_init_size(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, batch_size=10, random_state=42, n_init=1).fit(X) assert_equal(mb_k_means.init_size_, 3 * mb_k_means.batch_size) _check_fitted_model(mb_k_means) def test_minibatch_tol(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=10, random_state=42, tol=.01).fit(X) _check_fitted_model(mb_k_means) def test_minibatch_set_init_size(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, init_size=666, random_state=42, n_init=1).fit(X) assert_equal(mb_k_means.init_size, 666) assert_equal(mb_k_means.init_size_, n_samples) _check_fitted_model(mb_k_means) def test_k_means_invalid_init(): km = KMeans(init="invalid", n_init=1, n_clusters=n_clusters) assert_raises(ValueError, km.fit, X) def test_mini_match_k_means_invalid_init(): km = MiniBatchKMeans(init="invalid", n_init=1, n_clusters=n_clusters) assert_raises(ValueError, km.fit, X) def test_k_means_copyx(): # Check if copy_x=False returns nearly equal X after de-centering. my_X = X.copy() km = KMeans(copy_x=False, n_clusters=n_clusters, random_state=42) km.fit(my_X) _check_fitted_model(km) # check if my_X is centered assert_array_almost_equal(my_X, X) def test_k_means_non_collapsed(): # Check k_means with a bad initialization does not yield a singleton # Starting with bad centers that are quickly ignored should not # result in a repositioning of the centers to the center of mass that # would lead to collapsed centers which in turns make the clustering # dependent of the numerical unstabilities. my_X = np.array([[1.1, 1.1], [0.9, 1.1], [1.1, 0.9], [0.9, 1.1]]) array_init = np.array([[1.0, 1.0], [5.0, 5.0], [-5.0, -5.0]]) km = KMeans(init=array_init, n_clusters=3, random_state=42, n_init=1) km.fit(my_X) # centers must not been collapsed assert_equal(len(np.unique(km.labels_)), 3) centers = km.cluster_centers_ assert_true(np.linalg.norm(centers[0] - centers[1]) >= 0.1) assert_true(np.linalg.norm(centers[0] - centers[2]) >= 0.1) assert_true(np.linalg.norm(centers[1] - centers[2]) >= 0.1) def test_predict(): km = KMeans(n_clusters=n_clusters, random_state=42) km.fit(X) # sanity check: predict centroid labels pred = km.predict(km.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # sanity check: re-predict labeling for training set samples pred = km.predict(X) assert_array_equal(pred, km.labels_) # re-predict labels for training set using fit_predict pred = km.fit_predict(X) assert_array_equal(pred, km.labels_) def test_score(): km1 = KMeans(n_clusters=n_clusters, max_iter=1, random_state=42, n_init=1) s1 = km1.fit(X).score(X) km2 = KMeans(n_clusters=n_clusters, max_iter=10, random_state=42, n_init=1) s2 = km2.fit(X).score(X) assert_greater(s2, s1) def test_predict_minibatch_dense_input(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, random_state=40).fit(X) # sanity check: predict centroid labels pred = mb_k_means.predict(mb_k_means.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # sanity check: re-predict labeling for training set samples pred = mb_k_means.predict(X) assert_array_equal(mb_k_means.predict(X), mb_k_means.labels_) def test_predict_minibatch_kmeanspp_init_sparse_input(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, init='k-means++', n_init=10).fit(X_csr) # sanity check: re-predict labeling for training set samples assert_array_equal(mb_k_means.predict(X_csr), mb_k_means.labels_) # sanity check: predict centroid labels pred = mb_k_means.predict(mb_k_means.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # check that models trained on sparse input also works for dense input at # predict time assert_array_equal(mb_k_means.predict(X), mb_k_means.labels_) def test_predict_minibatch_random_init_sparse_input(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, init='random', n_init=10).fit(X_csr) # sanity check: re-predict labeling for training set samples assert_array_equal(mb_k_means.predict(X_csr), mb_k_means.labels_) # sanity check: predict centroid labels pred = mb_k_means.predict(mb_k_means.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # check that models trained on sparse input also works for dense input at # predict time assert_array_equal(mb_k_means.predict(X), mb_k_means.labels_) def test_input_dtypes(): X_list = [[0, 0], [10, 10], [12, 9], [-1, 1], [2, 0], [8, 10]] X_int = np.array(X_list, dtype=np.int32) X_int_csr = sp.csr_matrix(X_int) init_int = X_int[:2] fitted_models = [ KMeans(n_clusters=2).fit(X_list), KMeans(n_clusters=2).fit(X_int), KMeans(n_clusters=2, init=init_int, n_init=1).fit(X_list), KMeans(n_clusters=2, init=init_int, n_init=1).fit(X_int), # mini batch kmeans is very unstable on such a small dataset hence # we use many inits MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_list), MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_int), MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_int_csr), MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int, n_init=1).fit(X_list), MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int, n_init=1).fit(X_int), MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int, n_init=1).fit(X_int_csr), ] expected_labels = [0, 1, 1, 0, 0, 1] scores = np.array([v_measure_score(expected_labels, km.labels_) for km in fitted_models]) assert_array_equal(scores, np.ones(scores.shape[0])) def test_transform(): km = KMeans(n_clusters=n_clusters) km.fit(X) X_new = km.transform(km.cluster_centers_) for c in range(n_clusters): assert_equal(X_new[c, c], 0) for c2 in range(n_clusters): if c != c2: assert_greater(X_new[c, c2], 0) def test_fit_transform(): X1 = KMeans(n_clusters=3, random_state=51).fit(X).transform(X) X2 = KMeans(n_clusters=3, random_state=51).fit_transform(X) assert_array_equal(X1, X2) def test_predict_equal_labels(): km = KMeans(random_state=13, n_jobs=1, n_init=1, max_iter=1) km.fit(X) assert_array_equal(km.predict(X), km.labels_) def test_n_init(): # Check that increasing the number of init increases the quality n_runs = 5 n_init_range = [1, 5, 10] inertia = np.zeros((len(n_init_range), n_runs)) for i, n_init in enumerate(n_init_range): for j in range(n_runs): km = KMeans(n_clusters=n_clusters, init="random", n_init=n_init, random_state=j).fit(X) inertia[i, j] = km.inertia_ inertia = inertia.mean(axis=1) failure_msg = ("Inertia %r should be decreasing" " when n_init is increasing.") % list(inertia) for i in range(len(n_init_range) - 1): assert_true(inertia[i] >= inertia[i + 1], failure_msg) def test_k_means_function(): # test calling the k_means function directly # catch output old_stdout = sys.stdout sys.stdout = StringIO() try: cluster_centers, labels, inertia = k_means(X, n_clusters=n_clusters, verbose=True) finally: sys.stdout = old_stdout centers = cluster_centers assert_equal(centers.shape, (n_clusters, n_features)) labels = labels assert_equal(np.unique(labels).shape[0], n_clusters) # check that the labels assignment are perfect (up to a permutation) assert_equal(v_measure_score(true_labels, labels), 1.0) assert_greater(inertia, 0.0) # check warning when centers are passed assert_warns(RuntimeWarning, k_means, X, n_clusters=n_clusters, init=centers) # to many clusters desired assert_raises(ValueError, k_means, X, n_clusters=X.shape[0] + 1) def test_x_squared_norms_init_centroids(): """Test that x_squared_norms can be None in _init_centroids""" from sklearn.cluster.k_means_ import _init_centroids X_norms = np.sum(X**2, axis=1) precompute = _init_centroids( X, 3, "k-means++", random_state=0, x_squared_norms=X_norms) assert_array_equal( precompute, _init_centroids(X, 3, "k-means++", random_state=0)) def test_max_iter_error(): km = KMeans(max_iter=-1) assert_raise_message(ValueError, 'Number of iterations should be', km.fit, X)
bsd-3-clause
raghavrv/scikit-learn
sklearn/__check_build/__init__.py
342
1671
""" Module to give helpful messages to the user that did not compile the scikit properly. """ import os INPLACE_MSG = """ It appears that you are importing a local scikit-learn source tree. For this, you need to have an inplace install. Maybe you are in the source directory and you need to try from another location.""" STANDARD_MSG = """ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG dir_content = list() for i, filename in enumerate(os.listdir(local_dir)): if ((i + 1) % 3): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s ___________________________________________________________________________ It seems that scikit-learn has not been built correctly. If you have installed scikit-learn from source, please do not forget to build the package before using it: run `python setup.py install` or `make` in the source directory. %s""" % (e, local_dir, ''.join(dir_content).strip(), msg)) try: from ._check_build import check_build except ImportError as e: raise_build_error(e)
bsd-3-clause
IndraVikas/scikit-learn
sklearn/decomposition/tests/test_kernel_pca.py
154
8058
import numpy as np import scipy.sparse as sp from sklearn.utils.testing import (assert_array_almost_equal, assert_less, assert_equal, assert_not_equal, assert_raises) from sklearn.decomposition import PCA, KernelPCA from sklearn.datasets import make_circles from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.metrics.pairwise import rbf_kernel def test_kernel_pca(): rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) def histogram(x, y, **kwargs): # Histogram kernel implemented as a callable. assert_equal(kwargs, {}) # no kernel_params that we didn't ask for return np.minimum(x, y).sum() for eigen_solver in ("auto", "dense", "arpack"): for kernel in ("linear", "rbf", "poly", histogram): # histogram kernel produces singular matrix inside linalg.solve # XXX use a least-squares approximation? inv = not callable(kernel) # transform fit data kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver, fit_inverse_transform=inv) X_fit_transformed = kpca.fit_transform(X_fit) X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit) assert_array_almost_equal(np.abs(X_fit_transformed), np.abs(X_fit_transformed2)) # non-regression test: previously, gamma would be 0 by default, # forcing all eigenvalues to 0 under the poly kernel assert_not_equal(X_fit_transformed, []) # transform new data X_pred_transformed = kpca.transform(X_pred) assert_equal(X_pred_transformed.shape[1], X_fit_transformed.shape[1]) # inverse transform if inv: X_pred2 = kpca.inverse_transform(X_pred_transformed) assert_equal(X_pred2.shape, X_pred.shape) def test_invalid_parameters(): assert_raises(ValueError, KernelPCA, 10, fit_inverse_transform=True, kernel='precomputed') def test_kernel_pca_sparse(): rng = np.random.RandomState(0) X_fit = sp.csr_matrix(rng.random_sample((5, 4))) X_pred = sp.csr_matrix(rng.random_sample((2, 4))) for eigen_solver in ("auto", "arpack"): for kernel in ("linear", "rbf", "poly"): # transform fit data kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver, fit_inverse_transform=False) X_fit_transformed = kpca.fit_transform(X_fit) X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit) assert_array_almost_equal(np.abs(X_fit_transformed), np.abs(X_fit_transformed2)) # transform new data X_pred_transformed = kpca.transform(X_pred) assert_equal(X_pred_transformed.shape[1], X_fit_transformed.shape[1]) # inverse transform # X_pred2 = kpca.inverse_transform(X_pred_transformed) # assert_equal(X_pred2.shape, X_pred.shape) def test_kernel_pca_linear_kernel(): rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) # for a linear kernel, kernel PCA should find the same projection as PCA # modulo the sign (direction) # fit only the first four components: fifth is near zero eigenvalue, so # can be trimmed due to roundoff error assert_array_almost_equal( np.abs(KernelPCA(4).fit(X_fit).transform(X_pred)), np.abs(PCA(4).fit(X_fit).transform(X_pred))) def test_kernel_pca_n_components(): rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) for eigen_solver in ("dense", "arpack"): for c in [1, 2, 4]: kpca = KernelPCA(n_components=c, eigen_solver=eigen_solver) shape = kpca.fit(X_fit).transform(X_pred).shape assert_equal(shape, (2, c)) def test_remove_zero_eig(): X = np.array([[1 - 1e-30, 1], [1, 1], [1, 1 - 1e-20]]) # n_components=None (default) => remove_zero_eig is True kpca = KernelPCA() Xt = kpca.fit_transform(X) assert_equal(Xt.shape, (3, 0)) kpca = KernelPCA(n_components=2) Xt = kpca.fit_transform(X) assert_equal(Xt.shape, (3, 2)) kpca = KernelPCA(n_components=2, remove_zero_eig=True) Xt = kpca.fit_transform(X) assert_equal(Xt.shape, (3, 0)) def test_kernel_pca_precomputed(): rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) for eigen_solver in ("dense", "arpack"): X_kpca = KernelPCA(4, eigen_solver=eigen_solver).\ fit(X_fit).transform(X_pred) X_kpca2 = KernelPCA( 4, eigen_solver=eigen_solver, kernel='precomputed').fit( np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T)) X_kpca_train = KernelPCA( 4, eigen_solver=eigen_solver, kernel='precomputed').fit_transform(np.dot(X_fit, X_fit.T)) X_kpca_train2 = KernelPCA( 4, eigen_solver=eigen_solver, kernel='precomputed').fit( np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T)) assert_array_almost_equal(np.abs(X_kpca), np.abs(X_kpca2)) assert_array_almost_equal(np.abs(X_kpca_train), np.abs(X_kpca_train2)) def test_kernel_pca_invalid_kernel(): rng = np.random.RandomState(0) X_fit = rng.random_sample((2, 4)) kpca = KernelPCA(kernel="tototiti") assert_raises(ValueError, kpca.fit, X_fit) def test_gridsearch_pipeline(): # Test if we can do a grid-search to find parameters to separate # circles with a perceptron model. X, y = make_circles(n_samples=400, factor=.3, noise=.05, random_state=0) kpca = KernelPCA(kernel="rbf", n_components=2) pipeline = Pipeline([("kernel_pca", kpca), ("Perceptron", Perceptron())]) param_grid = dict(kernel_pca__gamma=2. ** np.arange(-2, 2)) grid_search = GridSearchCV(pipeline, cv=3, param_grid=param_grid) grid_search.fit(X, y) assert_equal(grid_search.best_score_, 1) def test_gridsearch_pipeline_precomputed(): # Test if we can do a grid-search to find parameters to separate # circles with a perceptron model using a precomputed kernel. X, y = make_circles(n_samples=400, factor=.3, noise=.05, random_state=0) kpca = KernelPCA(kernel="precomputed", n_components=2) pipeline = Pipeline([("kernel_pca", kpca), ("Perceptron", Perceptron())]) param_grid = dict(Perceptron__n_iter=np.arange(1, 5)) grid_search = GridSearchCV(pipeline, cv=3, param_grid=param_grid) X_kernel = rbf_kernel(X, gamma=2.) grid_search.fit(X_kernel, y) assert_equal(grid_search.best_score_, 1) def test_nested_circles(): # Test the linear separability of the first 2D KPCA transform X, y = make_circles(n_samples=400, factor=.3, noise=.05, random_state=0) # 2D nested circles are not linearly separable train_score = Perceptron().fit(X, y).score(X, y) assert_less(train_score, 0.8) # Project the circles data into the first 2 components of a RBF Kernel # PCA model. # Note that the gamma value is data dependent. If this test breaks # and the gamma value has to be updated, the Kernel PCA example will # have to be updated too. kpca = KernelPCA(kernel="rbf", n_components=2, fit_inverse_transform=True, gamma=2.) X_kpca = kpca.fit_transform(X) # The data is perfectly linearly separable in that space train_score = Perceptron().fit(X_kpca, y).score(X_kpca, y) assert_equal(train_score, 1.0)
bsd-3-clause
IndraVikas/scikit-learn
sklearn/metrics/cluster/unsupervised.py
228
8281
""" Unsupervised evaluation metrics. """ # Authors: Robert Layton <robertlayton@gmail.com> # # License: BSD 3 clause import numpy as np from ...utils import check_random_state from ..pairwise import pairwise_distances def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. To clarify, ``b`` is the distance between a sample and the nearest cluster that the sample is not a part of. Note that Silhouette Coefficent is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the mean Silhouette Coefficient over all samples. To obtain the values for each sample, use :func:`silhouette_samples`. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Negative values generally indicate that a sample has been assigned to the wrong cluster, as a different cluster is more similar. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] Predicted labels for each sample. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`metrics.pairwise.pairwise_distances <sklearn.metrics.pairwise.pairwise_distances>`. If X is the distance array itself, use ``metric="precomputed"``. sample_size : int or None The size of the sample to use when computing the Silhouette Coefficient on a random subset of the data. If ``sample_size is None``, no sampling is used. random_state : integer or numpy.RandomState, optional The generator used to randomly select a subset of samples if ``sample_size is not None``. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : float Mean Silhouette Coefficient for all samples. References ---------- .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <http://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ n_labels = len(np.unique(labels)) n_samples = X.shape[0] if not 1 < n_labels < n_samples: raise ValueError("Number of labels is %d. Valid values are 2 " "to n_samples - 1 (inclusive)" % n_labels) if sample_size is not None: random_state = check_random_state(random_state) indices = random_state.permutation(X.shape[0])[:sample_size] if metric == "precomputed": X, labels = X[indices].T[indices].T, labels[indices] else: X, labels = X[indices], labels[indices] return np.mean(silhouette_samples(X, labels, metric=metric, **kwds)) def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each other, and well separated, where samples in different clusters are not very similar to each other. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. Note that Silhouette Coefficent is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the Silhouette Coefficient for each sample. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] label values for each sample metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is the distance array itself, use "precomputed" as the metric. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a ``scipy.spatial.distance`` metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : array, shape = [n_samples] Silhouette Coefficient for each samples. References ---------- .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <http://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ distances = pairwise_distances(X, metric=metric, **kwds) n = labels.shape[0] A = np.array([_intra_cluster_distance(distances[i], labels, i) for i in range(n)]) B = np.array([_nearest_cluster_distance(distances[i], labels, i) for i in range(n)]) sil_samples = (B - A) / np.maximum(A, B) return sil_samples def _intra_cluster_distance(distances_row, labels, i): """Calculate the mean intra-cluster distance for sample i. Parameters ---------- distances_row : array, shape = [n_samples] Pairwise distance matrix between sample i and each sample. labels : array, shape = [n_samples] label values for each sample i : int Sample index being calculated. It is excluded from calculation and used to determine the current label Returns ------- a : float Mean intra-cluster distance for sample i """ mask = labels == labels[i] mask[i] = False if not np.any(mask): # cluster of size 1 return 0 a = np.mean(distances_row[mask]) return a def _nearest_cluster_distance(distances_row, labels, i): """Calculate the mean nearest-cluster distance for sample i. Parameters ---------- distances_row : array, shape = [n_samples] Pairwise distance matrix between sample i and each sample. labels : array, shape = [n_samples] label values for each sample i : int Sample index being calculated. It is used to determine the current label. Returns ------- b : float Mean nearest-cluster distance for sample i """ label = labels[i] b = np.min([np.mean(distances_row[labels == cur_label]) for cur_label in set(labels) if not cur_label == label]) return b
bsd-3-clause
frank-tancf/scikit-learn
sklearn/preprocessing/tests/test_imputation.py
46
12381
import numpy as np from scipy import sparse from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_true from sklearn.preprocessing.imputation import Imputer from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV from sklearn import tree from sklearn.random_projection import sparse_random_matrix def _check_statistics(X, X_true, strategy, statistics, missing_values): """Utility function for testing imputation for a given strategy. Test: - along the two axes - with dense and sparse arrays Check that: - the statistics (mean, median, mode) are correct - the missing values are imputed correctly""" err_msg = "Parameters: strategy = %s, missing_values = %s, " \ "axis = {0}, sparse = {1}" % (strategy, missing_values) # Normal matrix, axis = 0 imputer = Imputer(missing_values, strategy=strategy, axis=0) X_trans = imputer.fit(X).transform(X.copy()) assert_array_equal(imputer.statistics_, statistics, err_msg.format(0, False)) assert_array_equal(X_trans, X_true, err_msg.format(0, False)) # Normal matrix, axis = 1 imputer = Imputer(missing_values, strategy=strategy, axis=1) imputer.fit(X.transpose()) if np.isnan(statistics).any(): assert_raises(ValueError, imputer.transform, X.copy().transpose()) else: X_trans = imputer.transform(X.copy().transpose()) assert_array_equal(X_trans, X_true.transpose(), err_msg.format(1, False)) # Sparse matrix, axis = 0 imputer = Imputer(missing_values, strategy=strategy, axis=0) imputer.fit(sparse.csc_matrix(X)) X_trans = imputer.transform(sparse.csc_matrix(X.copy())) if sparse.issparse(X_trans): X_trans = X_trans.toarray() assert_array_equal(imputer.statistics_, statistics, err_msg.format(0, True)) assert_array_equal(X_trans, X_true, err_msg.format(0, True)) # Sparse matrix, axis = 1 imputer = Imputer(missing_values, strategy=strategy, axis=1) imputer.fit(sparse.csc_matrix(X.transpose())) if np.isnan(statistics).any(): assert_raises(ValueError, imputer.transform, sparse.csc_matrix(X.copy().transpose())) else: X_trans = imputer.transform(sparse.csc_matrix(X.copy().transpose())) if sparse.issparse(X_trans): X_trans = X_trans.toarray() assert_array_equal(X_trans, X_true.transpose(), err_msg.format(1, True)) def test_imputation_shape(): # Verify the shapes of the imputed matrix for different strategies. X = np.random.randn(10, 2) X[::2] = np.nan for strategy in ['mean', 'median', 'most_frequent']: imputer = Imputer(strategy=strategy) X_imputed = imputer.fit_transform(X) assert_equal(X_imputed.shape, (10, 2)) X_imputed = imputer.fit_transform(sparse.csr_matrix(X)) assert_equal(X_imputed.shape, (10, 2)) def test_imputation_mean_median_only_zero(): # Test imputation using the mean and median strategies, when # missing_values == 0. X = np.array([ [np.nan, 0, 0, 0, 5], [np.nan, 1, 0, np.nan, 3], [np.nan, 2, 0, 0, 0], [np.nan, 6, 0, 5, 13], ]) X_imputed_mean = np.array([ [3, 5], [1, 3], [2, 7], [6, 13], ]) statistics_mean = [np.nan, 3, np.nan, np.nan, 7] # Behaviour of median with NaN is undefined, e.g. different results in # np.median and np.ma.median X_for_median = X[:, [0, 1, 2, 4]] X_imputed_median = np.array([ [2, 5], [1, 3], [2, 5], [6, 13], ]) statistics_median = [np.nan, 2, np.nan, 5] _check_statistics(X, X_imputed_mean, "mean", statistics_mean, 0) _check_statistics(X_for_median, X_imputed_median, "median", statistics_median, 0) def safe_median(arr, *args, **kwargs): # np.median([]) raises a TypeError for numpy >= 1.10.1 length = arr.size if hasattr(arr, 'size') else len(arr) return np.nan if length == 0 else np.median(arr, *args, **kwargs) def safe_mean(arr, *args, **kwargs): # np.mean([]) raises a RuntimeWarning for numpy >= 1.10.1 length = arr.size if hasattr(arr, 'size') else len(arr) return np.nan if length == 0 else np.mean(arr, *args, **kwargs) def test_imputation_mean_median(): # Test imputation using the mean and median strategies, when # missing_values != 0. rng = np.random.RandomState(0) dim = 10 dec = 10 shape = (dim * dim, dim + dec) zeros = np.zeros(shape[0]) values = np.arange(1, shape[0]+1) values[4::2] = - values[4::2] tests = [("mean", "NaN", lambda z, v, p: safe_mean(np.hstack((z, v)))), ("mean", 0, lambda z, v, p: np.mean(v)), ("median", "NaN", lambda z, v, p: safe_median(np.hstack((z, v)))), ("median", 0, lambda z, v, p: np.median(v))] for strategy, test_missing_values, true_value_fun in tests: X = np.empty(shape) X_true = np.empty(shape) true_statistics = np.empty(shape[1]) # Create a matrix X with columns # - with only zeros, # - with only missing values # - with zeros, missing values and values # And a matrix X_true containing all true values for j in range(shape[1]): nb_zeros = (j - dec + 1 > 0) * (j - dec + 1) * (j - dec + 1) nb_missing_values = max(shape[0] + dec * dec - (j + dec) * (j + dec), 0) nb_values = shape[0] - nb_zeros - nb_missing_values z = zeros[:nb_zeros] p = np.repeat(test_missing_values, nb_missing_values) v = values[rng.permutation(len(values))[:nb_values]] true_statistics[j] = true_value_fun(z, v, p) # Create the columns X[:, j] = np.hstack((v, z, p)) if 0 == test_missing_values: X_true[:, j] = np.hstack((v, np.repeat( true_statistics[j], nb_missing_values + nb_zeros))) else: X_true[:, j] = np.hstack((v, z, np.repeat(true_statistics[j], nb_missing_values))) # Shuffle them the same way np.random.RandomState(j).shuffle(X[:, j]) np.random.RandomState(j).shuffle(X_true[:, j]) # Mean doesn't support columns containing NaNs, median does if strategy == "median": cols_to_keep = ~np.isnan(X_true).any(axis=0) else: cols_to_keep = ~np.isnan(X_true).all(axis=0) X_true = X_true[:, cols_to_keep] _check_statistics(X, X_true, strategy, true_statistics, test_missing_values) def test_imputation_median_special_cases(): # Test median imputation with sparse boundary cases X = np.array([ [0, np.nan, np.nan], # odd: implicit zero [5, np.nan, np.nan], # odd: explicit nonzero [0, 0, np.nan], # even: average two zeros [-5, 0, np.nan], # even: avg zero and neg [0, 5, np.nan], # even: avg zero and pos [4, 5, np.nan], # even: avg nonzeros [-4, -5, np.nan], # even: avg negatives [-1, 2, np.nan], # even: crossing neg and pos ]).transpose() X_imputed_median = np.array([ [0, 0, 0], [5, 5, 5], [0, 0, 0], [-5, 0, -2.5], [0, 5, 2.5], [4, 5, 4.5], [-4, -5, -4.5], [-1, 2, .5], ]).transpose() statistics_median = [0, 5, 0, -2.5, 2.5, 4.5, -4.5, .5] _check_statistics(X, X_imputed_median, "median", statistics_median, 'NaN') def test_imputation_most_frequent(): # Test imputation using the most-frequent strategy. X = np.array([ [-1, -1, 0, 5], [-1, 2, -1, 3], [-1, 1, 3, -1], [-1, 2, 3, 7], ]) X_true = np.array([ [2, 0, 5], [2, 3, 3], [1, 3, 3], [2, 3, 7], ]) # scipy.stats.mode, used in Imputer, doesn't return the first most # frequent as promised in the doc but the lowest most frequent. When this # test will fail after an update of scipy, Imputer will need to be updated # to be consistent with the new (correct) behaviour _check_statistics(X, X_true, "most_frequent", [np.nan, 2, 3, 3], -1) def test_imputation_pipeline_grid_search(): # Test imputation within a pipeline + gridsearch. pipeline = Pipeline([('imputer', Imputer(missing_values=0)), ('tree', tree.DecisionTreeRegressor(random_state=0))]) parameters = { 'imputer__strategy': ["mean", "median", "most_frequent"], 'imputer__axis': [0, 1] } l = 100 X = sparse_random_matrix(l, l, density=0.10) Y = sparse_random_matrix(l, 1, density=0.10).toarray() gs = GridSearchCV(pipeline, parameters) gs.fit(X, Y) def test_imputation_pickle(): # Test for pickling imputers. import pickle l = 100 X = sparse_random_matrix(l, l, density=0.10) for strategy in ["mean", "median", "most_frequent"]: imputer = Imputer(missing_values=0, strategy=strategy) imputer.fit(X) imputer_pickled = pickle.loads(pickle.dumps(imputer)) assert_array_equal(imputer.transform(X.copy()), imputer_pickled.transform(X.copy()), "Fail to transform the data after pickling " "(strategy = %s)" % (strategy)) def test_imputation_copy(): # Test imputation with copy X_orig = sparse_random_matrix(5, 5, density=0.75, random_state=0) # copy=True, dense => copy X = X_orig.copy().toarray() imputer = Imputer(missing_values=0, strategy="mean", copy=True) Xt = imputer.fit(X).transform(X) Xt[0, 0] = -1 assert_false(np.all(X == Xt)) # copy=True, sparse csr => copy X = X_orig.copy() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=True) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_false(np.all(X.data == Xt.data)) # copy=False, dense => no copy X = X_orig.copy().toarray() imputer = Imputer(missing_values=0, strategy="mean", copy=False) Xt = imputer.fit(X).transform(X) Xt[0, 0] = -1 assert_true(np.all(X == Xt)) # copy=False, sparse csr, axis=1 => no copy X = X_orig.copy() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=1) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_true(np.all(X.data == Xt.data)) # copy=False, sparse csc, axis=0 => no copy X = X_orig.copy().tocsc() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=0) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_true(np.all(X.data == Xt.data)) # copy=False, sparse csr, axis=0 => copy X = X_orig.copy() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=0) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_false(np.all(X.data == Xt.data)) # copy=False, sparse csc, axis=1 => copy X = X_orig.copy().tocsc() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=1) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_false(np.all(X.data == Xt.data)) # copy=False, sparse csr, axis=1, missing_values=0 => copy X = X_orig.copy() imputer = Imputer(missing_values=0, strategy="mean", copy=False, axis=1) Xt = imputer.fit(X).transform(X) assert_false(sparse.issparse(Xt)) # Note: If X is sparse and if missing_values=0, then a (dense) copy of X is # made, even if copy=False.
bsd-3-clause
IndraVikas/scikit-learn
examples/ensemble/plot_voting_decision_regions.py
228
2386
""" ================================================== Plot the decision boundaries of a VotingClassifier ================================================== Plot the decision boundaries of a `VotingClassifier` for two features of the Iris dataset. Plot the class probabilities of the first sample in a toy dataset predicted by three different classifiers and averaged by the `VotingClassifier`. First, three examplary classifiers are initialized (`DecisionTreeClassifier`, `KNeighborsClassifier`, and `SVC`) and used to initialize a soft-voting `VotingClassifier` with weights `[2, 1, 2]`, which means that the predicted probabilities of the `DecisionTreeClassifier` and `SVC` count 5 times as much as the weights of the `KNeighborsClassifier` classifier when the averaged probability is calculated. """ print(__doc__) from itertools import product import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.ensemble import VotingClassifier # Loading some example data iris = datasets.load_iris() X = iris.data[:, [0, 2]] y = iris.target # Training classifiers clf1 = DecisionTreeClassifier(max_depth=4) clf2 = KNeighborsClassifier(n_neighbors=7) clf3 = SVC(kernel='rbf', probability=True) eclf = VotingClassifier(estimators=[('dt', clf1), ('knn', clf2), ('svc', clf3)], voting='soft', weights=[2, 1, 2]) clf1.fit(X, y) clf2.fit(X, y) clf3.fit(X, y) eclf.fit(X, y) # Plotting decision regions x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8)) for idx, clf, tt in zip(product([0, 1], [0, 1]), [clf1, clf2, clf3, eclf], ['Decision Tree (depth=4)', 'KNN (k=7)', 'Kernel SVM', 'Soft Voting']): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4) axarr[idx[0], idx[1]].scatter(X[:, 0], X[:, 1], c=y, alpha=0.8) axarr[idx[0], idx[1]].set_title(tt) plt.show()
bsd-3-clause
christianurich/VIBe2UrbanSim
3rdparty/opus/src/psrc_parcel/models/water_demand_model.py
2
5875
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE import re from numpy import array, exp, arange, zeros from opus_core.resources import Resources from opus_core.regression_model import RegressionModel from opus_core.variables.variable_name import VariableName from opus_core.simulation_state import SimulationState class WaterDemandModel(RegressionModel): """ """ # filter_attribute = "include_in_housing_value_estimation" model_name = "Water Demand Model" model_short_name = "WDM" def __init__(self, regression_procedure="opus_core.linear_regression", outcome_attribute="month_combination_2", filter_attribute=None, submodel_string="land_use_type_id", run_config=None, estimate_config=None, debuglevel=0, dataset_pool=None): self.outcome_attribute = outcome_attribute if (self.outcome_attribute is not None) and not isinstance(self.outcome_attribute, VariableName): self.outcome_attribute = VariableName(self.outcome_attribute) self.filter_attribute = filter_attribute RegressionModel.__init__(self, regression_procedure=regression_procedure, submodel_string=submodel_string, run_config=run_config, estimate_config=estimate_config, debuglevel=debuglevel, dataset_pool=dataset_pool) def run(self, specification, coefficients, dataset, index=None, chunk_specification=None, data_objects=None, run_config=None, debuglevel=0): """ For info on the arguments see RegressionModel. """ outcome_attribute_short = self.outcome_attribute.get_alias() if data_objects is not None: self.dataset_pool.add_datasets_if_not_included(data_objects) if self.filter_attribute <> None: res = Resources({"debug":debuglevel}) index = dataset.get_filtered_index(self.filter_attribute, threshold=0, index=index, dataset_pool=self.dataset_pool, resources=res) current_year = SimulationState().get_current_time() current_month = int( re.search('\d+$', outcome_attribute_short).group() ) # date in YYYYMM format, matching to the id_name field of weather dataset date = int( "%d%02d" % (current_year, current_month) ) date = array([date] * dataset.size()) if "date" in dataset.get_known_attribute_names(): dataset.set_values_of_one_attribute("date", date) else: dataset.add_primary_attribute(date, "date") water_demand = RegressionModel.run(self, specification, coefficients, dataset, index, chunk_specification, run_config=run_config, debuglevel=debuglevel) if (water_demand == None) or (water_demand.size <=0): return water_demand if index == None: index = arange(dataset.size()) if re.search("^ln_", outcome_attribute_short): # if the outcome attr. name starts with 'ln_' the results will be exponentiated. outcome_attribute_name = outcome_attribute_short[3:len(outcome_attribute_short)] water_demand = exp(water_demand) else: outcome_attribute_name = outcome_attribute_short if outcome_attribute_name in dataset.get_known_attribute_names(): dataset.set_values_of_one_attribute(outcome_attribute_name, water_demand, index) else: results = zeros(dataset.size(), dtype=water_demand.dtype) results[index] = water_demand dataset.add_primary_attribute(results, outcome_attribute_name) return water_demand # def estimate(self, specification, dataset, outcome_attribute="housing_price", index = None, # procedure="opus_core.estimate_linear_regression", data_objects=None, # estimate_config=None, debuglevel=0): # if data_objects is not None: # self.dataset_pool.add_datasets_if_not_included(data_objects) # if self.filter_attribute <> None: # res = Resources({"debug":debuglevel}) # index = dataset.get_filtered_index(self.filter_attribute, threshold=0, index=index, # dataset_pool=self.dataset_pool, resources=res) # return RegressionModel.estimate(self, specification, dataset, outcome_attribute, index, procedure, # estimate_config=estimate_config, debuglevel=debuglevel) # # def prepare_for_estimate(self, specification_dict = None, specification_storage=None, # specification_table=None, dataset=None, # filter_variable="housing_price", # threshold=0): # from opus_core.model import get_specification_for_estimation # specification = get_specification_for_estimation(specification_dict, # specification_storage, # specification_table) # index = None # if dataset is not None: # dataset.compute_variables(filter_variable) # index = where(dataset.get_attribute(filter_variable) >= threshold)[0] # return (specification, index) # #
gpl-2.0
pkruskal/scikit-learn
sklearn/metrics/tests/test_pairwise.py
104
22788
import numpy as np from numpy import linalg from scipy.sparse import dok_matrix, csr_matrix, issparse from scipy.spatial.distance import cosine, cityblock, minkowski, wminkowski from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_true from sklearn.externals.six import iteritems from sklearn.metrics.pairwise import euclidean_distances from sklearn.metrics.pairwise import manhattan_distances from sklearn.metrics.pairwise import linear_kernel from sklearn.metrics.pairwise import chi2_kernel, additive_chi2_kernel from sklearn.metrics.pairwise import polynomial_kernel from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics.pairwise import sigmoid_kernel from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics.pairwise import cosine_distances from sklearn.metrics.pairwise import pairwise_distances from sklearn.metrics.pairwise import pairwise_distances_argmin_min from sklearn.metrics.pairwise import pairwise_distances_argmin from sklearn.metrics.pairwise import pairwise_kernels from sklearn.metrics.pairwise import PAIRWISE_KERNEL_FUNCTIONS from sklearn.metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS from sklearn.metrics.pairwise import PAIRED_DISTANCES from sklearn.metrics.pairwise import check_pairwise_arrays from sklearn.metrics.pairwise import check_paired_arrays from sklearn.metrics.pairwise import _parallel_pairwise from sklearn.metrics.pairwise import paired_distances from sklearn.metrics.pairwise import paired_euclidean_distances from sklearn.metrics.pairwise import paired_manhattan_distances from sklearn.preprocessing import normalize def test_pairwise_distances(): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)) S = pairwise_distances(X, metric="euclidean") S2 = euclidean_distances(X) assert_array_almost_equal(S, S2) # Euclidean distance, with Y != X. Y = rng.random_sample((2, 4)) S = pairwise_distances(X, Y, metric="euclidean") S2 = euclidean_distances(X, Y) assert_array_almost_equal(S, S2) # Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) S2 = pairwise_distances(X_tuples, Y_tuples, metric="euclidean") assert_array_almost_equal(S, S2) # "cityblock" uses sklearn metric, cityblock (function) is scipy.spatial. S = pairwise_distances(X, metric="cityblock") S2 = pairwise_distances(X, metric=cityblock) assert_equal(S.shape[0], S.shape[1]) assert_equal(S.shape[0], X.shape[0]) assert_array_almost_equal(S, S2) # The manhattan metric should be equivalent to cityblock. S = pairwise_distances(X, Y, metric="manhattan") S2 = pairwise_distances(X, Y, metric=cityblock) assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2) # Low-level function for manhattan can divide in blocks to avoid # using too much memory during the broadcasting S3 = manhattan_distances(X, Y, size_threshold=10) assert_array_almost_equal(S, S3) # Test cosine as a string metric versus cosine callable # "cosine" uses sklearn metric, cosine (function) is scipy.spatial S = pairwise_distances(X, Y, metric="cosine") S2 = pairwise_distances(X, Y, metric=cosine) assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2) # Tests that precomputed metric returns pointer to, and not copy of, X. S = np.dot(X, X.T) S2 = pairwise_distances(S, metric="precomputed") assert_true(S is S2) # Test with sparse X and Y, # currently only supported for Euclidean, L1 and cosine. X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) S = pairwise_distances(X_sparse, Y_sparse, metric="euclidean") S2 = euclidean_distances(X_sparse, Y_sparse) assert_array_almost_equal(S, S2) S = pairwise_distances(X_sparse, Y_sparse, metric="cosine") S2 = cosine_distances(X_sparse, Y_sparse) assert_array_almost_equal(S, S2) S = pairwise_distances(X_sparse, Y_sparse.tocsc(), metric="manhattan") S2 = manhattan_distances(X_sparse.tobsr(), Y_sparse.tocoo()) assert_array_almost_equal(S, S2) S2 = manhattan_distances(X, Y) assert_array_almost_equal(S, S2) # Test with scipy.spatial.distance metric, with a kwd kwds = {"p": 2.0} S = pairwise_distances(X, Y, metric="minkowski", **kwds) S2 = pairwise_distances(X, Y, metric=minkowski, **kwds) assert_array_almost_equal(S, S2) # same with Y = None kwds = {"p": 2.0} S = pairwise_distances(X, metric="minkowski", **kwds) S2 = pairwise_distances(X, metric=minkowski, **kwds) assert_array_almost_equal(S, S2) # Test that scipy distance metrics throw an error if sparse matrix given assert_raises(TypeError, pairwise_distances, X_sparse, metric="minkowski") assert_raises(TypeError, pairwise_distances, X, Y_sparse, metric="minkowski") # Test that a value error is raised if the metric is unkown assert_raises(ValueError, pairwise_distances, X, Y, metric="blah") def check_pairwise_parallel(func, metric, kwds): rng = np.random.RandomState(0) for make_data in (np.array, csr_matrix): X = make_data(rng.random_sample((5, 4))) Y = make_data(rng.random_sample((3, 4))) try: S = func(X, metric=metric, n_jobs=1, **kwds) except (TypeError, ValueError) as exc: # Not all metrics support sparse input # ValueError may be triggered by bad callable if make_data is csr_matrix: assert_raises(type(exc), func, X, metric=metric, n_jobs=2, **kwds) continue else: raise S2 = func(X, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) S = func(X, Y, metric=metric, n_jobs=1, **kwds) S2 = func(X, Y, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) def test_pairwise_parallel(): wminkowski_kwds = {'w': np.arange(1, 5).astype('double'), 'p': 1} metrics = [(pairwise_distances, 'euclidean', {}), (pairwise_distances, wminkowski, wminkowski_kwds), (pairwise_distances, 'wminkowski', wminkowski_kwds), (pairwise_kernels, 'polynomial', {'degree': 1}), (pairwise_kernels, callable_rbf_kernel, {'gamma': .1}), ] for func, metric, kwds in metrics: yield check_pairwise_parallel, func, metric, kwds def test_pairwise_callable_nonstrict_metric(): # paired_distances should allow callable metric where metric(x, x) != 0 # Knowing that the callable is a strict metric would allow the diagonal to # be left uncalculated and set to 0. assert_equal(pairwise_distances([[1]], metric=lambda x, y: 5)[0, 0], 5) def callable_rbf_kernel(x, y, **kwds): # Callable version of pairwise.rbf_kernel. K = rbf_kernel(np.atleast_2d(x), np.atleast_2d(y), **kwds) return K def test_pairwise_kernels(): # Test the pairwise_kernels helper function. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) # Test with all metrics that should be in PAIRWISE_KERNEL_FUNCTIONS. test_metrics = ["rbf", "sigmoid", "polynomial", "linear", "chi2", "additive_chi2"] for metric in test_metrics: function = PAIRWISE_KERNEL_FUNCTIONS[metric] # Test with Y=None K1 = pairwise_kernels(X, metric=metric) K2 = function(X) assert_array_almost_equal(K1, K2) # Test with Y=Y K1 = pairwise_kernels(X, Y=Y, metric=metric) K2 = function(X, Y=Y) assert_array_almost_equal(K1, K2) # Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) K2 = pairwise_kernels(X_tuples, Y_tuples, metric=metric) assert_array_almost_equal(K1, K2) # Test with sparse X and Y X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) if metric in ["chi2", "additive_chi2"]: # these don't support sparse matrices yet assert_raises(ValueError, pairwise_kernels, X_sparse, Y=Y_sparse, metric=metric) continue K1 = pairwise_kernels(X_sparse, Y=Y_sparse, metric=metric) assert_array_almost_equal(K1, K2) # Test with a callable function, with given keywords. metric = callable_rbf_kernel kwds = {} kwds['gamma'] = 0.1 K1 = pairwise_kernels(X, Y=Y, metric=metric, **kwds) K2 = rbf_kernel(X, Y=Y, **kwds) assert_array_almost_equal(K1, K2) # callable function, X=Y K1 = pairwise_kernels(X, Y=X, metric=metric, **kwds) K2 = rbf_kernel(X, Y=X, **kwds) assert_array_almost_equal(K1, K2) def test_pairwise_kernels_filter_param(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) K = rbf_kernel(X, Y, gamma=0.1) params = {"gamma": 0.1, "blabla": ":)"} K2 = pairwise_kernels(X, Y, metric="rbf", filter_params=True, **params) assert_array_almost_equal(K, K2) assert_raises(TypeError, pairwise_kernels, X, Y, "rbf", **params) def test_paired_distances(): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)) # Euclidean distance, with Y != X. Y = rng.random_sample((5, 4)) for metric, func in iteritems(PAIRED_DISTANCES): S = paired_distances(X, Y, metric=metric) S2 = func(X, Y) assert_array_almost_equal(S, S2) S3 = func(csr_matrix(X), csr_matrix(Y)) assert_array_almost_equal(S, S3) if metric in PAIRWISE_DISTANCE_FUNCTIONS: # Check the the pairwise_distances implementation # gives the same value distances = PAIRWISE_DISTANCE_FUNCTIONS[metric](X, Y) distances = np.diag(distances) assert_array_almost_equal(distances, S) # Check the callable implementation S = paired_distances(X, Y, metric='manhattan') S2 = paired_distances(X, Y, metric=lambda x, y: np.abs(x - y).sum(axis=0)) assert_array_almost_equal(S, S2) # Test that a value error is raised when the lengths of X and Y should not # differ Y = rng.random_sample((3, 4)) assert_raises(ValueError, paired_distances, X, Y) def test_pairwise_distances_argmin_min(): # Check pairwise minimum distances computation for any metric X = [[0], [1]] Y = [[-1], [2]] Xsp = dok_matrix(X) Ysp = csr_matrix(Y, dtype=np.float32) # euclidean metric D, E = pairwise_distances_argmin_min(X, Y, metric="euclidean") D2 = pairwise_distances_argmin(X, Y, metric="euclidean") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(D2, [0, 1]) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # sparse matrix case Dsp, Esp = pairwise_distances_argmin_min(Xsp, Ysp, metric="euclidean") assert_array_equal(Dsp, D) assert_array_equal(Esp, E) # We don't want np.matrix here assert_equal(type(Dsp), np.ndarray) assert_equal(type(Esp), np.ndarray) # Non-euclidean sklearn metric D, E = pairwise_distances_argmin_min(X, Y, metric="manhattan") D2 = pairwise_distances_argmin(X, Y, metric="manhattan") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(D2, [0, 1]) assert_array_almost_equal(E, [1., 1.]) D, E = pairwise_distances_argmin_min(Xsp, Ysp, metric="manhattan") D2 = pairwise_distances_argmin(Xsp, Ysp, metric="manhattan") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Non-euclidean Scipy distance (callable) D, E = pairwise_distances_argmin_min(X, Y, metric=minkowski, metric_kwargs={"p": 2}) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Non-euclidean Scipy distance (string) D, E = pairwise_distances_argmin_min(X, Y, metric="minkowski", metric_kwargs={"p": 2}) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Compare with naive implementation rng = np.random.RandomState(0) X = rng.randn(97, 149) Y = rng.randn(111, 149) dist = pairwise_distances(X, Y, metric="manhattan") dist_orig_ind = dist.argmin(axis=0) dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))] dist_chunked_ind, dist_chunked_val = pairwise_distances_argmin_min( X, Y, axis=0, metric="manhattan", batch_size=50) np.testing.assert_almost_equal(dist_orig_ind, dist_chunked_ind, decimal=7) np.testing.assert_almost_equal(dist_orig_val, dist_chunked_val, decimal=7) def test_euclidean_distances(): # Check the pairwise Euclidean distances computation X = [[0]] Y = [[1], [2]] D = euclidean_distances(X, Y) assert_array_almost_equal(D, [[1., 2.]]) X = csr_matrix(X) Y = csr_matrix(Y) D = euclidean_distances(X, Y) assert_array_almost_equal(D, [[1., 2.]]) # Paired distances def test_paired_euclidean_distances(): # Check the paired Euclidean distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_euclidean_distances(X, Y) assert_array_almost_equal(D, [1., 2.]) def test_paired_manhattan_distances(): # Check the paired manhattan distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_manhattan_distances(X, Y) assert_array_almost_equal(D, [1., 2.]) def test_chi_square_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((10, 4)) K_add = additive_chi2_kernel(X, Y) gamma = 0.1 K = chi2_kernel(X, Y, gamma=gamma) assert_equal(K.dtype, np.float) for i, x in enumerate(X): for j, y in enumerate(Y): chi2 = -np.sum((x - y) ** 2 / (x + y)) chi2_exp = np.exp(gamma * chi2) assert_almost_equal(K_add[i, j], chi2) assert_almost_equal(K[i, j], chi2_exp) # check diagonal is ones for data with itself K = chi2_kernel(Y) assert_array_equal(np.diag(K), 1) # check off-diagonal is < 1 but > 0: assert_true(np.all(K > 0)) assert_true(np.all(K - np.diag(np.diag(K)) < 1)) # check that float32 is preserved X = rng.random_sample((5, 4)).astype(np.float32) Y = rng.random_sample((10, 4)).astype(np.float32) K = chi2_kernel(X, Y) assert_equal(K.dtype, np.float32) # check integer type gets converted, # check that zeros are handled X = rng.random_sample((10, 4)).astype(np.int32) K = chi2_kernel(X, X) assert_true(np.isfinite(K).all()) assert_equal(K.dtype, np.float) # check that kernel of similar things is greater than dissimilar ones X = [[.3, .7], [1., 0]] Y = [[0, 1], [.9, .1]] K = chi2_kernel(X, Y) assert_greater(K[0, 0], K[0, 1]) assert_greater(K[1, 1], K[1, 0]) # test negative input assert_raises(ValueError, chi2_kernel, [[0, -1]]) assert_raises(ValueError, chi2_kernel, [[0, -1]], [[-1, -1]]) assert_raises(ValueError, chi2_kernel, [[0, 1]], [[-1, -1]]) # different n_features in X and Y assert_raises(ValueError, chi2_kernel, [[0, 1]], [[.2, .2, .6]]) # sparse matrices assert_raises(ValueError, chi2_kernel, csr_matrix(X), csr_matrix(Y)) assert_raises(ValueError, additive_chi2_kernel, csr_matrix(X), csr_matrix(Y)) def test_kernel_symmetry(): # Valid kernels should be symmetric rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, sigmoid_kernel, cosine_similarity): K = kernel(X, X) assert_array_almost_equal(K, K.T, 15) def test_kernel_sparse(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) X_sparse = csr_matrix(X) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, sigmoid_kernel, cosine_similarity): K = kernel(X, X) K2 = kernel(X_sparse, X_sparse) assert_array_almost_equal(K, K2) def test_linear_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = linear_kernel(X, X) # the diagonal elements of a linear kernel are their squared norm assert_array_almost_equal(K.flat[::6], [linalg.norm(x) ** 2 for x in X]) def test_rbf_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = rbf_kernel(X, X) # the diagonal elements of a rbf kernel are 1 assert_array_almost_equal(K.flat[::6], np.ones(5)) def test_cosine_similarity_sparse_output(): # Test if cosine_similarity correctly produces sparse output. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y) K1 = cosine_similarity(Xcsr, Ycsr, dense_output=False) assert_true(issparse(K1)) K2 = pairwise_kernels(Xcsr, Y=Ycsr, metric="cosine") assert_array_almost_equal(K1.todense(), K2) def test_cosine_similarity(): # Test the cosine_similarity. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y) for X_, Y_ in ((X, None), (X, Y), (Xcsr, None), (Xcsr, Ycsr)): # Test that the cosine is kernel is equal to a linear kernel when data # has been previously normalized by L2-norm. K1 = pairwise_kernels(X_, Y=Y_, metric="cosine") X_ = normalize(X_) if Y_ is not None: Y_ = normalize(Y_) K2 = pairwise_kernels(X_, Y=Y_, metric="linear") assert_array_almost_equal(K1, K2) def test_check_dense_matrices(): # Ensure that pairwise array check works for dense matrices. # Check that if XB is None, XB is returned as reference to XA XA = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert_true(XA_checked is XB_checked) assert_array_equal(XA, XA_checked) def test_check_XB_returned(): # Ensure that if XA and XB are given correctly, they return as equal. # Check that if XB is not None, it is returned equal. # Note that the second dimension of XB is the same as XA. XA = np.resize(np.arange(40), (5, 8)) XB = np.resize(np.arange(32), (4, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked) XB = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_paired_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked) def test_check_different_dimensions(): # Ensure an error is raised if the dimensions are different. XA = np.resize(np.arange(45), (5, 9)) XB = np.resize(np.arange(32), (4, 8)) assert_raises(ValueError, check_pairwise_arrays, XA, XB) XB = np.resize(np.arange(4 * 9), (4, 9)) assert_raises(ValueError, check_paired_arrays, XA, XB) def test_check_invalid_dimensions(): # Ensure an error is raised on 1D input arrays. XA = np.arange(45) XB = np.resize(np.arange(32), (4, 8)) assert_raises(ValueError, check_pairwise_arrays, XA, XB) XA = np.resize(np.arange(45), (5, 9)) XB = np.arange(32) assert_raises(ValueError, check_pairwise_arrays, XA, XB) def test_check_sparse_arrays(): # Ensures that checks return valid sparse matrices. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_sparse = csr_matrix(XA) XB = rng.random_sample((5, 4)) XB_sparse = csr_matrix(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_sparse, XB_sparse) # compare their difference because testing csr matrices for # equality with '==' does not work as expected. assert_true(issparse(XA_checked)) assert_equal(abs(XA_sparse - XA_checked).sum(), 0) assert_true(issparse(XB_checked)) assert_equal(abs(XB_sparse - XB_checked).sum(), 0) XA_checked, XA_2_checked = check_pairwise_arrays(XA_sparse, XA_sparse) assert_true(issparse(XA_checked)) assert_equal(abs(XA_sparse - XA_checked).sum(), 0) assert_true(issparse(XA_2_checked)) assert_equal(abs(XA_2_checked - XA_checked).sum(), 0) def tuplify(X): # Turns a numpy matrix (any n-dimensional array) into tuples. s = X.shape if len(s) > 1: # Tuplify each sub-array in the input. return tuple(tuplify(row) for row in X) else: # Single dimension input, just return tuple of contents. return tuple(r for r in X) def test_check_tuple_input(): # Ensures that checks return valid tuples. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_tuples = tuplify(XA) XB = rng.random_sample((5, 4)) XB_tuples = tuplify(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_tuples, XB_tuples) assert_array_equal(XA_tuples, XA_checked) assert_array_equal(XB_tuples, XB_checked) def test_check_preserve_type(): # Ensures that type float32 is preserved. XA = np.resize(np.arange(40), (5, 8)).astype(np.float32) XB = np.resize(np.arange(40), (5, 8)).astype(np.float32) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert_equal(XA_checked.dtype, np.float32) # both float32 XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert_equal(XA_checked.dtype, np.float32) assert_equal(XB_checked.dtype, np.float32) # mismatched A XA_checked, XB_checked = check_pairwise_arrays(XA.astype(np.float), XB) assert_equal(XA_checked.dtype, np.float) assert_equal(XB_checked.dtype, np.float) # mismatched B XA_checked, XB_checked = check_pairwise_arrays(XA, XB.astype(np.float)) assert_equal(XA_checked.dtype, np.float) assert_equal(XB_checked.dtype, np.float)
bsd-3-clause
nightjean/Deep-Learning
tensorflow/contrib/keras/python/keras/datasets/__init__.py
57
1290
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keras datasets: utilities for downloading and pre-processing common datasets. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.python.keras.datasets import boston_housing from tensorflow.contrib.keras.python.keras.datasets import cifar10 from tensorflow.contrib.keras.python.keras.datasets import cifar100 from tensorflow.contrib.keras.python.keras.datasets import imdb from tensorflow.contrib.keras.python.keras.datasets import mnist from tensorflow.contrib.keras.python.keras.datasets import reuters
apache-2.0
ammarkhann/FinalSeniorCode
lib/python2.7/site-packages/numpy/lib/function_base.py
19
164441
from __future__ import division, absolute_import, print_function import collections import operator import re import sys import warnings import numpy as np import numpy.core.numeric as _nx from numpy.core import linspace, atleast_1d, atleast_2d, transpose from numpy.core.numeric import ( ones, zeros, arange, concatenate, array, asarray, asanyarray, empty, empty_like, ndarray, around, floor, ceil, take, dot, where, intp, integer, isscalar, absolute ) from numpy.core.umath import ( pi, multiply, add, arctan2, frompyfunc, cos, less_equal, sqrt, sin, mod, exp, log10 ) from numpy.core.fromnumeric import ( ravel, nonzero, sort, partition, mean, any, sum ) from numpy.core.numerictypes import typecodes, number from numpy.lib.twodim_base import diag from .utils import deprecate from numpy.core.multiarray import ( _insert, add_docstring, digitize, bincount, interp as compiled_interp, interp_complex as compiled_interp_complex ) from numpy.core.umath import _add_newdoc_ufunc as add_newdoc_ufunc from numpy.compat import long from numpy.compat.py3k import basestring if sys.version_info[0] < 3: # Force range to be a generator, for np.delete's usage. range = xrange import __builtin__ as builtins else: import builtins __all__ = [ 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', 'flip', 'rot90', 'extract', 'place', 'vectorize', 'asarray_chkfinite', 'average', 'histogram', 'histogramdd', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', 'delete', 'insert', 'append', 'interp', 'add_newdoc_ufunc' ] def rot90(m, k=1, axes=(0,1)): """ Rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. .. versionadded:: 1.12.0 Parameters ---------- m : array_like Array of two or more dimensions. k : integer Number of times the array is rotated by 90 degrees. axes: (2,) array_like The array is rotated in the plane defined by the axes. Axes must be different. Returns ------- y : ndarray A rotated view of `m`. See Also -------- flip : Reverse the order of elements in an array along the given axis. fliplr : Flip an array horizontally. flipud : Flip an array vertically. Notes ----- rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1)) rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1)) Examples -------- >>> m = np.array([[1,2],[3,4]], int) >>> m array([[1, 2], [3, 4]]) >>> np.rot90(m) array([[2, 4], [1, 3]]) >>> np.rot90(m, 2) array([[4, 3], [2, 1]]) >>> m = np.arange(8).reshape((2,2,2)) >>> np.rot90(m, 1, (1,2)) array([[[1, 3], [0, 2]], [[5, 7], [4, 6]]]) """ axes = tuple(axes) if len(axes) != 2: raise ValueError("len(axes) must be 2.") m = asanyarray(m) if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim: raise ValueError("Axes must be different.") if (axes[0] >= m.ndim or axes[0] < -m.ndim or axes[1] >= m.ndim or axes[1] < -m.ndim): raise ValueError("Axes={} out of range for array of ndim={}." .format(axes, m.ndim)) k %= 4 if k == 0: return m[:] if k == 2: return flip(flip(m, axes[0]), axes[1]) axes_list = arange(0, m.ndim) axes_list[axes[0]], axes_list[axes[1]] = axes_list[axes[1]], axes_list[axes[0]] if k == 1: return transpose(flip(m,axes[1]), axes_list) else: # k == 3 return flip(transpose(m, axes_list), axes[1]) def flip(m, axis): """ Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered. .. versionadded:: 1.12.0 Parameters ---------- m : array_like Input array. axis : integer Axis in array, which entries are reversed. Returns ------- out : array_like A view of `m` with the entries of axis reversed. Since a view is returned, this operation is done in constant time. See Also -------- flipud : Flip an array vertically (axis=0). fliplr : Flip an array horizontally (axis=1). Notes ----- flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m). flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n. Examples -------- >>> A = np.arange(8).reshape((2,2,2)) >>> A array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> flip(A, 0) array([[[4, 5], [6, 7]], [[0, 1], [2, 3]]]) >>> flip(A, 1) array([[[2, 3], [0, 1]], [[6, 7], [4, 5]]]) >>> A = np.random.randn(3,4,5) >>> np.all(flip(A,2) == A[:,:,::-1,...]) True """ if not hasattr(m, 'ndim'): m = asarray(m) indexer = [slice(None)] * m.ndim try: indexer[axis] = slice(None, None, -1) except IndexError: raise ValueError("axis=%i is invalid for the %i-dimensional input array" % (axis, m.ndim)) return m[tuple(indexer)] def iterable(y): """ Check whether or not an object can be iterated over. Parameters ---------- y : object Input object. Returns ------- b : bool Return ``True`` if the object has an iterator method or is a sequence and ``False`` otherwise. Examples -------- >>> np.iterable([1, 2, 3]) True >>> np.iterable(2) False """ try: iter(y) except TypeError: return False return True def _hist_bin_sqrt(x): """ Square root histogram bin estimator. Bin width is inversely proportional to the data size. Used by many programs for its simplicity. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return x.ptp() / np.sqrt(x.size) def _hist_bin_sturges(x): """ Sturges histogram bin estimator. A very simplistic estimator based on the assumption of normality of the data. This estimator has poor performance for non-normal data, which becomes especially obvious for large data sets. The estimate depends only on size of the data. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return x.ptp() / (np.log2(x.size) + 1.0) def _hist_bin_rice(x): """ Rice histogram bin estimator. Another simple estimator with no normality assumption. It has better performance for large data than Sturges, but tends to overestimate the number of bins. The number of bins is proportional to the cube root of data size (asymptotically optimal). The estimate depends only on size of the data. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return x.ptp() / (2.0 * x.size ** (1.0 / 3)) def _hist_bin_scott(x): """ Scott histogram bin estimator. The binwidth is proportional to the standard deviation of the data and inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x) def _hist_bin_doane(x): """ Doane's histogram bin estimator. Improved version of Sturges' formula which works better for non-normal data. See http://stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ if x.size > 2: sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3))) sigma = np.std(x) if sigma > 0.0: # These three operations add up to # g1 = np.mean(((x - np.mean(x)) / sigma)**3) # but use only one temp array instead of three temp = x - np.mean(x) np.true_divide(temp, sigma, temp) np.power(temp, 3, temp) g1 = np.mean(temp) return x.ptp() / (1.0 + np.log2(x.size) + np.log2(1.0 + np.absolute(g1) / sg1)) return 0.0 def _hist_bin_fd(x): """ The Freedman-Diaconis histogram bin estimator. The Freedman-Diaconis rule uses interquartile range (IQR) to estimate binwidth. It is considered a variation of the Scott rule with more robustness as the IQR is less affected by outliers than the standard deviation. However, the IQR depends on fewer points than the standard deviation, so it is less accurate, especially for long tailed distributions. If the IQR is 0, this function returns 1 for the number of bins. Binwidth is inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ iqr = np.subtract(*np.percentile(x, [75, 25])) return 2.0 * iqr * x.size ** (-1.0 / 3.0) def _hist_bin_auto(x): """ Histogram bin estimator that uses the minimum width of the Freedman-Diaconis and Sturges estimators. The FD estimator is usually the most robust method, but its width estimate tends to be too large for small `x`. The Sturges estimator is quite good for small (<1000) datasets and is the default in the R language. This method gives good off the shelf behaviour. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. See Also -------- _hist_bin_fd, _hist_bin_sturges """ # There is no need to check for zero here. If ptp is, so is IQR and # vice versa. Either both are zero or neither one is. return min(_hist_bin_fd(x), _hist_bin_sturges(x)) # Private dict initialized at module load time _hist_bin_selectors = {'auto': _hist_bin_auto, 'doane': _hist_bin_doane, 'fd': _hist_bin_fd, 'rice': _hist_bin_rice, 'scott': _hist_bin_scott, 'sqrt': _hist_bin_sqrt, 'sturges': _hist_bin_sturges} def histogram(a, bins=10, range=None, normed=False, weights=None, density=None): r""" Compute the histogram of a set of data. Parameters ---------- a : array_like Input data. The histogram is computed over the flattened array. bins : int or sequence of scalars or str, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If `bins` is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. .. versionadded:: 1.11.0 If `bins` is a string from the list below, `histogram` will use the method chosen to calculate the optimal bin width and consequently the number of bins (see `Notes` for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the 'auto' option is suggested. Weighted data is not supported for automated bin size selection. 'auto' Maximum of the 'sturges' and 'fd' estimators. Provides good all around performance. 'fd' (Freedman Diaconis Estimator) Robust (resilient to outliers) estimator that takes into account data variability and data size. 'doane' An improved version of Sturges' estimator that works better with non-normal datasets. 'scott' Less robust estimator that that takes into account data variability and data size. 'rice' Estimator does not take variability into account, only data size. Commonly overestimates number of bins required. 'sturges' R's default method, only accounts for data size. Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets. 'sqrt' Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity. range : (float, float), optional The lower and upper range of the bins. If not provided, range is simply ``(a.min(), a.max())``. Values outside the range are ignored. The first element of the range must be less than or equal to the second. `range` affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within `range`, the bin count will fill the entire range including portions containing no data. normed : bool, optional This keyword is deprecated in NumPy 1.6.0 due to confusing/buggy behavior. It will be removed in NumPy 2.0.0. Use the ``density`` keyword instead. If ``False``, the result will contain the number of samples in each bin. If ``True``, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that this latter behavior is known to be buggy with unequal bin widths; use ``density`` instead. weights : array_like, optional An array of weights, of the same shape as `a`. Each value in `a` only contributes its associated weight towards the bin count (instead of 1). If `density` is True, the weights are normalized, so that the integral of the density over the range remains 1. density : bool, optional If ``False``, the result will contain the number of samples in each bin. If ``True``, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability *mass* function. Overrides the ``normed`` keyword if given. Returns ------- hist : array The values of the histogram. See `density` and `weights` for a description of the possible semantics. bin_edges : array of dtype float Return the bin edges ``(length(hist)+1)``. See Also -------- histogramdd, bincount, searchsorted, digitize Notes ----- All but the last (righthand-most) bin is half-open. In other words, if `bins` is:: [1, 2, 3, 4] then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. .. versionadded:: 1.11.0 The methods to estimate the optimal number of bins are well founded in literature, and are inspired by the choices R provides for histogram visualisation. Note that having the number of bins proportional to :math:`n^{1/3}` is asymptotically optimal, which is why it appears in most estimators. These are simply plug-in methods that give good starting points for number of bins. In the equations below, :math:`h` is the binwidth and :math:`n_h` is the number of bins. All estimators that compute bin counts are recast to bin width using the `ptp` of the data. The final bin count is obtained from ``np.round(np.ceil(range / h))`. 'Auto' (maximum of the 'Sturges' and 'FD' estimators) A compromise to get a good value. For small datasets the Sturges value will usually be chosen, while larger datasets will usually default to FD. Avoids the overly conservative behaviour of FD and Sturges for small and large datasets respectively. Switchover point is usually :math:`a.size \approx 1000`. 'FD' (Freedman Diaconis Estimator) .. math:: h = 2 \frac{IQR}{n^{1/3}} The binwidth is proportional to the interquartile range (IQR) and inversely proportional to cube root of a.size. Can be too conservative for small datasets, but is quite good for large datasets. The IQR is very robust to outliers. 'Scott' .. math:: h = \sigma \sqrt[3]{\frac{24 * \sqrt{\pi}}{n}} The binwidth is proportional to the standard deviation of the data and inversely proportional to cube root of ``x.size``. Can be too conservative for small datasets, but is quite good for large datasets. The standard deviation is not very robust to outliers. Values are very similar to the Freedman-Diaconis estimator in the absence of outliers. 'Rice' .. math:: n_h = 2n^{1/3} The number of bins is only proportional to cube root of ``a.size``. It tends to overestimate the number of bins and it does not take into account data variability. 'Sturges' .. math:: n_h = \log _{2}n+1 The number of bins is the base 2 log of ``a.size``. This estimator assumes normality of data and is too conservative for larger, non-normal datasets. This is the default method in R's ``hist`` method. 'Doane' .. math:: n_h = 1 + \log_{2}(n) + \log_{2}(1 + \frac{|g_1|}{\sigma_{g_1}}) g_1 = mean[(\frac{x - \mu}{\sigma})^3] \sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}} An improved version of Sturges' formula that produces better estimates for non-normal datasets. This estimator attempts to account for the skew of the data. 'Sqrt' .. math:: n_h = \sqrt n The simplest and fastest estimator. Only takes into account the data size. Examples -------- >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) (array([0, 2, 1]), array([0, 1, 2, 3])) >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) (array([ 0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3])) >>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, density=True) >>> hist array([ 0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) >>> hist.sum() 2.4999999999999996 >>> np.sum(hist*np.diff(bin_edges)) 1.0 .. versionadded:: 1.11.0 Automated Bin Selection Methods example, using 2 peak random data with 2000 points: >>> import matplotlib.pyplot as plt >>> rng = np.random.RandomState(10) # deterministic random data >>> a = np.hstack((rng.normal(size=1000), ... rng.normal(loc=5, scale=2, size=1000))) >>> plt.hist(a, bins='auto') # plt.hist passes it's arguments to np.histogram >>> plt.title("Histogram with 'auto' bins") >>> plt.show() """ a = asarray(a) if weights is not None: weights = asarray(weights) if np.any(weights.shape != a.shape): raise ValueError( 'weights should have the same shape as a.') weights = weights.ravel() a = a.ravel() # Do not modify the original value of range so we can check for `None` if range is None: if a.size == 0: # handle empty arrays. Can't determine range, so use 0-1. mn, mx = 0.0, 1.0 else: mn, mx = a.min() + 0.0, a.max() + 0.0 else: mn, mx = [mi + 0.0 for mi in range] if mn > mx: raise ValueError( 'max must be larger than min in range parameter.') if not np.all(np.isfinite([mn, mx])): raise ValueError( 'range parameter must be finite.') if mn == mx: mn -= 0.5 mx += 0.5 if isinstance(bins, basestring): # if `bins` is a string for an automatic method, # this will replace it with the number of bins calculated if bins not in _hist_bin_selectors: raise ValueError("{0} not a valid estimator for bins".format(bins)) if weights is not None: raise TypeError("Automated estimation of the number of " "bins is not supported for weighted data") # Make a reference to `a` b = a # Update the reference if the range needs truncation if range is not None: keep = (a >= mn) keep &= (a <= mx) if not np.logical_and.reduce(keep): b = a[keep] if b.size == 0: bins = 1 else: # Do not call selectors on empty arrays width = _hist_bin_selectors[bins](b) if width: bins = int(np.ceil((mx - mn) / width)) else: # Width can be zero for some estimators, e.g. FD when # the IQR of the data is zero. bins = 1 # Histogram is an integer or a float array depending on the weights. if weights is None: ntype = np.dtype(np.intp) else: ntype = weights.dtype # We set a block size, as this allows us to iterate over chunks when # computing histograms, to minimize memory usage. BLOCK = 65536 if not iterable(bins): if np.isscalar(bins) and bins < 1: raise ValueError( '`bins` should be a positive integer.') # At this point, if the weights are not integer, floating point, or # complex, we have to use the slow algorithm. if weights is not None and not (np.can_cast(weights.dtype, np.double) or np.can_cast(weights.dtype, np.complex)): bins = linspace(mn, mx, bins + 1, endpoint=True) if not iterable(bins): # We now convert values of a to bin indices, under the assumption of # equal bin widths (which is valid here). # Initialize empty histogram n = np.zeros(bins, ntype) # Pre-compute histogram scaling factor norm = bins / (mx - mn) # Compute the bin edges for potential correction. bin_edges = linspace(mn, mx, bins + 1, endpoint=True) # We iterate over blocks here for two reasons: the first is that for # large arrays, it is actually faster (for example for a 10^8 array it # is 2x as fast) and it results in a memory footprint 3x lower in the # limit of large arrays. for i in arange(0, len(a), BLOCK): tmp_a = a[i:i+BLOCK] if weights is None: tmp_w = None else: tmp_w = weights[i:i + BLOCK] # Only include values in the right range keep = (tmp_a >= mn) keep &= (tmp_a <= mx) if not np.logical_and.reduce(keep): tmp_a = tmp_a[keep] if tmp_w is not None: tmp_w = tmp_w[keep] tmp_a_data = tmp_a.astype(float) tmp_a = tmp_a_data - mn tmp_a *= norm # Compute the bin indices, and for values that lie exactly on mx we # need to subtract one indices = tmp_a.astype(np.intp) indices[indices == bins] -= 1 # The index computation is not guaranteed to give exactly # consistent results within ~1 ULP of the bin edges. decrement = tmp_a_data < bin_edges[indices] indices[decrement] -= 1 # The last bin includes the right edge. The other bins do not. increment = (tmp_a_data >= bin_edges[indices + 1]) & (indices != bins - 1) indices[increment] += 1 # We now compute the histogram using bincount if ntype.kind == 'c': n.real += np.bincount(indices, weights=tmp_w.real, minlength=bins) n.imag += np.bincount(indices, weights=tmp_w.imag, minlength=bins) else: n += np.bincount(indices, weights=tmp_w, minlength=bins).astype(ntype) # Rename the bin edges for return. bins = bin_edges else: bins = asarray(bins) if (np.diff(bins) < 0).any(): raise ValueError( 'bins must increase monotonically.') # Initialize empty histogram n = np.zeros(bins.shape, ntype) if weights is None: for i in arange(0, len(a), BLOCK): sa = sort(a[i:i+BLOCK]) n += np.r_[sa.searchsorted(bins[:-1], 'left'), sa.searchsorted(bins[-1], 'right')] else: zero = array(0, dtype=ntype) for i in arange(0, len(a), BLOCK): tmp_a = a[i:i+BLOCK] tmp_w = weights[i:i+BLOCK] sorting_index = np.argsort(tmp_a) sa = tmp_a[sorting_index] sw = tmp_w[sorting_index] cw = np.concatenate(([zero, ], sw.cumsum())) bin_index = np.r_[sa.searchsorted(bins[:-1], 'left'), sa.searchsorted(bins[-1], 'right')] n += cw[bin_index] n = np.diff(n) if density is not None: if density: db = array(np.diff(bins), float) return n/db/n.sum(), bins else: return n, bins else: # deprecated, buggy behavior. Remove for NumPy 2.0.0 if normed: db = array(np.diff(bins), float) return n/(n*db).sum(), bins else: return n, bins def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """ Compute the multidimensional histogram of some data. Parameters ---------- sample : array_like The data to be histogrammed. It must be an (N,D) array or data that can be converted to such. The rows of the resulting array are the coordinates of points in a D dimensional polytope. bins : sequence or int, optional The bin specification: * A sequence of arrays describing the bin edges along each dimension. * The number of bins for each dimension (nx, ny, ... =bins) * The number of bins for all dimensions (nx=ny=...=bins). range : sequence, optional A sequence of lower and upper bin edges to be used if the edges are not given explicitly in `bins`. Defaults to the minimum and maximum values along each dimension. normed : bool, optional If False, returns the number of samples in each bin. If True, returns the bin density ``bin_count / sample_count / bin_volume``. weights : (N,) array_like, optional An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin. Returns ------- H : ndarray The multidimensional histogram of sample x. See normed and weights for the different possible semantics. edges : list A list of D arrays describing the bin edges for each dimension. See Also -------- histogram: 1-D histogram histogram2d: 2-D histogram Examples -------- >>> r = np.random.randn(100,3) >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) >>> H.shape, edges[0].size, edges[1].size, edges[2].size ((5, 8, 4), 6, 9, 5) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D*[None] dedges = D*[None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise ValueError( 'The dimension of bins must be equal to the dimension of the ' ' sample x.') except TypeError: # bins is an integer bins = D*[bins] # Select range for each dimension # Used only if number of bins is given. if range is None: # Handle empty input. Range can't be determined in that case, use 0-1. if N == 0: smin = zeros(D) smax = ones(D) else: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: if not np.all(np.isfinite(range)): raise ValueError( 'range parameter must be finite.') smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # avoid rounding issues for comparisons when dealing with inexact types if np.issubdtype(sample.dtype, np.inexact): edge_dt = sample.dtype else: edge_dt = float # Create edge arrays for i in arange(D): if isscalar(bins[i]): if bins[i] < 1: raise ValueError( "Element at index %s in `bins` should be a positive " "integer." % i) nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = linspace(smin[i], smax[i], nbin[i]-1, dtype=edge_dt) else: edges[i] = asarray(bins[i], edge_dt) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = diff(edges[i]) if np.any(np.asarray(dedges[i]) <= 0): raise ValueError( "Found bin edge of size <= 0. Did you specify `bins` with" "non-monotonic sequence?") nbin = asarray(nbin) # Handle empty input. if N == 0: return np.zeros(nbin-2), edges # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:, i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right edge to be # counted in the last bin, and not as an outlier. for i in arange(D): # Rounding precision mindiff = dedges[i].min() if not np.isinf(mindiff): decimal = int(-log10(mindiff)) + 6 # Find which points are on the rightmost edge. not_smaller_than_edge = (sample[:, i] >= edges[i][-1]) on_edge = (around(sample[:, i], decimal) == around(edges[i][-1], decimal)) # Shift these points one bin to the left. Ncount[i][where(on_edge & not_smaller_than_edge)[0]] -= 1 # Flattened histogram matrix (1D) # Reshape is used so that overlarge arrays # will raise an error. hist = zeros(nbin, float).reshape(-1) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() xy = zeros(N, int) for i in arange(0, D-1): xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the # flattened histmat. if len(xy) == 0: return zeros(nbin-2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni.argsort()[i] hist = hist.swapaxes(i, j) ni[i], ni[j] = ni[j], ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D*[slice(1, -1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i] - 2 hist = hist / dedges[i].reshape(shape) hist /= s if (hist.shape != nbin - 2).any(): raise RuntimeError( "Internal Shape Error") return hist, edges def average(a, axis=None, weights=None, returned=False): """ Compute the weighted average along the specified axis. Parameters ---------- a : array_like Array containing data to be averaged. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which to average `a`. If `None`, averaging is done over the flattened array. weights : array_like, optional An array of weights associated with the values in `a`. Each value in `a` contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of `a` along the given axis) or of the same shape as `a`. If `weights=None`, then all data in `a` are assumed to have a weight equal to one. returned : bool, optional Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) is returned, otherwise only the average is returned. If `weights=None`, `sum_of_weights` is equivalent to the number of elements over which the average is taken. Returns ------- average, [sum_of_weights] : array_type or double Return the average along the specified axis. When returned is `True`, return a tuple with the average as the first element and the sum of the weights as the second element. The return type is `Float` if `a` is of integer type, otherwise it is of the same type as `a`. `sum_of_weights` is of the same type as `average`. Raises ------ ZeroDivisionError When all weights along axis are zero. See `numpy.ma.average` for a version robust to this type of error. TypeError When the length of 1D `weights` is not the same as the shape of `a` along axis. See Also -------- mean ma.average : average for masked arrays -- useful if your data contains "missing" values Examples -------- >>> data = range(1,5) >>> data [1, 2, 3, 4] >>> np.average(data) 2.5 >>> np.average(range(1,11), weights=range(10,0,-1)) 4.0 >>> data = np.arange(6).reshape((3,2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([ 0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): ... TypeError: Axis must be specified when shapes of a and weights differ. """ # 3/19/2016 1.12.0: # replace the next few lines with "a = np.asanyarray(a)" if (type(a) not in (np.ndarray, np.matrix) and issubclass(type(a), np.ndarray)): warnings.warn("np.average currently does not preserve subclasses, but " "will do so in the future to match the behavior of most " "other numpy functions such as np.mean. In particular, " "this means calls which returned a scalar may return a " "0-d subclass object instead.", FutureWarning, stacklevel=2) if not isinstance(a, np.matrix): a = np.asarray(a) if weights is None: avg = a.mean(axis) scl = avg.dtype.type(a.size/avg.size) else: wgt = np.asanyarray(weights) if issubclass(a.dtype.type, (np.integer, np.bool_)): result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8') else: result_dtype = np.result_type(a.dtype, wgt.dtype) # Sanity checks if a.shape != wgt.shape: if axis is None: raise TypeError( "Axis must be specified when shapes of a and weights " "differ.") if wgt.ndim != 1: raise TypeError( "1D weights expected when shapes of a and weights differ.") if wgt.shape[0] != a.shape[axis]: raise ValueError( "Length of weights not compatible with specified axis.") # setup wgt to broadcast along axis wgt = np.broadcast_to(wgt, (a.ndim-1)*(1,) + wgt.shape) wgt = wgt.swapaxes(-1, axis) scl = wgt.sum(axis=axis, dtype=result_dtype) if (scl == 0.0).any(): raise ZeroDivisionError( "Weights sum to zero, can't be normalized") avg = np.multiply(a, wgt, dtype=result_dtype).sum(axis)/scl if returned: if scl.shape != avg.shape: scl = np.broadcast_to(scl, avg.shape).copy() return avg, scl else: return avg def asarray_chkfinite(a, dtype=None, order=None): """Convert the input to an array, checking for NaNs or Infs. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to 'C'. Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray. If `a` is a subclass of ndarray, a base class ndarray is returned. Raises ------ ValueError Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity). See Also -------- asarray : Create and array. asanyarray : Similar function which passes through subclasses. ascontiguousarray : Convert input to a contiguous array. asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major memory order. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions. Examples -------- Convert a list into an array. If all elements are finite ``asarray_chkfinite`` is identical to ``asarray``. >>> a = [1, 2] >>> np.asarray_chkfinite(a, dtype=float) array([1., 2.]) Raises ValueError if array_like contains Nans or Infs. >>> a = [1, 2, np.inf] >>> try: ... np.asarray_chkfinite(a) ... except ValueError: ... print('ValueError') ... ValueError """ a = asarray(a, dtype=dtype, order=order) if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all(): raise ValueError( "array must not contain infs or NaNs") return a def piecewise(x, condlist, funclist, *args, **kw): """ Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true. Parameters ---------- x : ndarray or scalar The input domain. condlist : list of bool arrays or bool scalars Each boolean array corresponds to a function in `funclist`. Wherever `condlist[i]` is True, `funclist[i](x)` is used as the output value. Each boolean array in `condlist` selects a piece of `x`, and should therefore be of the same shape as `x`. The length of `condlist` must correspond to that of `funclist`. If one extra function is given, i.e. if ``len(funclist) - len(condlist) == 1``, then that extra function is the default value, used wherever all conditions are false. funclist : list of callables, f(x,*args,**kw), or scalars Each function is evaluated over `x` wherever its corresponding condition is True. It should take an array as input and give an array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (``lambda x: scalar``) is assumed. args : tuple, optional Any further arguments given to `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then each function is called as ``f(x, 1, 'a')``. kw : dict, optional Keyword arguments used in calling `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., alpha=1)``, then each function is called as ``f(x, alpha=1)``. Returns ------- out : ndarray The output is the same shape and type as x and is found by calling the functions in `funclist` on the appropriate portions of `x`, as defined by the boolean arrays in `condlist`. Portions not covered by any condition have a default value of 0. See Also -------- choose, select, where Notes ----- This is similar to choose or select, except that functions are evaluated on elements of `x` that satisfy the corresponding condition from `condlist`. The result is:: |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- Examples -------- Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.]) Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for ``x >= 0``. >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x]) array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5]) Apply the same function to a scalar value. >>> y = -2 >>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x]) array(2) """ x = asanyarray(x) n2 = len(funclist) if (isscalar(condlist) or not (isinstance(condlist[0], list) or isinstance(condlist[0], ndarray))): if not isscalar(condlist) and x.size == 1 and x.ndim == 0: condlist = [[c] for c in condlist] else: condlist = [condlist] condlist = array(condlist, dtype=bool) n = len(condlist) # This is a hack to work around problems with NumPy's # handling of 0-d arrays and boolean indexing with # numpy.bool_ scalars zerod = False if x.ndim == 0: x = x[None] zerod = True if n == n2 - 1: # compute the "otherwise" condition. totlist = np.logical_or.reduce(condlist, axis=0) # Only able to stack vertically if the array is 1d or less if x.ndim <= 1: condlist = np.vstack([condlist, ~totlist]) else: condlist = [asarray(c, dtype=bool) for c in condlist] totlist = condlist[0] for k in range(1, n): totlist |= condlist[k] condlist.append(~totlist) n += 1 y = zeros(x.shape, x.dtype) for k in range(n): item = funclist[k] if not isinstance(item, collections.Callable): y[condlist[k]] = item else: vals = x[condlist[k]] if vals.size > 0: y[condlist[k]] = item(vals, *args, **kw) if zerod: y = y.squeeze() return y def select(condlist, choicelist, default=0): """ Return an array drawn from elements in choicelist, depending on conditions. Parameters ---------- condlist : list of bool ndarrays The list of conditions which determine from which array in `choicelist` the output elements are taken. When multiple conditions are satisfied, the first one encountered in `condlist` is used. choicelist : list of ndarrays The list of arrays from which the output elements are taken. It has to be of the same length as `condlist`. default : scalar, optional The element inserted in `output` when all conditions evaluate to False. Returns ------- output : ndarray The output at position m is the m-th element of the array in `choicelist` where the m-th element of the corresponding array in `condlist` is True. See Also -------- where : Return elements from one of two arrays depending on condition. take, choose, compress, diag, diagonal Examples -------- >>> x = np.arange(10) >>> condlist = [x<3, x>5] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist) array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81]) """ # Check the size of condlist and choicelist are the same, or abort. if len(condlist) != len(choicelist): raise ValueError( 'list of cases must be same length as list of conditions') # Now that the dtype is known, handle the deprecated select([], []) case if len(condlist) == 0: # 2014-02-24, 1.9 warnings.warn("select with an empty condition list is not possible" "and will be deprecated", DeprecationWarning, stacklevel=2) return np.asarray(default)[()] choicelist = [np.asarray(choice) for choice in choicelist] choicelist.append(np.asarray(default)) # need to get the result type before broadcasting for correct scalar # behaviour dtype = np.result_type(*choicelist) # Convert conditions to arrays and broadcast conditions and choices # as the shape is needed for the result. Doing it separately optimizes # for example when all choices are scalars. condlist = np.broadcast_arrays(*condlist) choicelist = np.broadcast_arrays(*choicelist) # If cond array is not an ndarray in boolean format or scalar bool, abort. deprecated_ints = False for i in range(len(condlist)): cond = condlist[i] if cond.dtype.type is not np.bool_: if np.issubdtype(cond.dtype, np.integer): # A previous implementation accepted int ndarrays accidentally. # Supported here deliberately, but deprecated. condlist[i] = condlist[i].astype(bool) deprecated_ints = True else: raise ValueError( 'invalid entry in choicelist: should be boolean ndarray') if deprecated_ints: # 2014-02-24, 1.9 msg = "select condlists containing integer ndarrays is deprecated " \ "and will be removed in the future. Use `.astype(bool)` to " \ "convert to bools." warnings.warn(msg, DeprecationWarning, stacklevel=2) if choicelist[0].ndim == 0: # This may be common, so avoid the call. result_shape = condlist[0].shape else: result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape result = np.full(result_shape, choicelist[-1], dtype) # Use np.copyto to burn each choicelist array onto result, using the # corresponding condlist as a boolean mask. This is done in reverse # order since the first choice should take precedence. choicelist = choicelist[-2::-1] condlist = condlist[::-1] for choice, cond in zip(choicelist, condlist): np.copyto(result, choice, where=cond) return result def copy(a, order='K'): """ Return an array copy of the given object. Parameters ---------- a : array_like Input data. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :meth:ndarray.copy are very similar, but have different default values for their order= arguments.) Returns ------- arr : ndarray Array interpretation of `a`. Notes ----- This is equivalent to >>> np.array(a, copy=True) #doctest: +SKIP Examples -------- Create an array x, with a reference y and a copy z: >>> x = np.array([1, 2, 3]) >>> y = x >>> z = np.copy(x) Note that, when we modify x, y changes, but not z: >>> x[0] = 10 >>> x[0] == y[0] True >>> x[0] == z[0] False """ return array(a, order=order, copy=True) # Basic operations def gradient(f, *varargs, **kwargs): """ Return the gradient of an N-dimensional array. The gradient is computed using second order accurate central differences in the interior and either first differences or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array. Parameters ---------- f : array_like An N-dimensional array containing samples of a scalar function. varargs : scalar or list of scalar, optional N scalars specifying the sample distances for each dimension, i.e. `dx`, `dy`, `dz`, ... Default distance: 1. single scalar specifies sample distance for all dimensions. if `axis` is given, the number of varargs must equal the number of axes. edge_order : {1, 2}, optional Gradient is calculated using N-th order accurate differences at the boundaries. Default: 1. .. versionadded:: 1.9.1 axis : None or int or tuple of ints, optional Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array. axis may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.11.0 Returns ------- gradient : ndarray or list of ndarray A set of ndarrays (or a single ndarray if there is only one dimension) correposnding to the derivatives of f with respect to each dimension. Each derivative has the same shape as f. Examples -------- >>> x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float) >>> np.gradient(x) array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ]) >>> np.gradient(x, 2) array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ]) For two dimensional arrays, the return will be two arrays ordered by axis. In this example the first array stands for the gradient in rows and the second one in columns direction: >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float)) [array([[ 2., 2., -1.], [ 2., 2., -1.]]), array([[ 1. , 2.5, 4. ], [ 1. , 1. , 1. ]])] >>> x = np.array([0, 1, 2, 3, 4]) >>> y = x**2 >>> np.gradient(y, edge_order=2) array([-0., 2., 4., 6., 8.]) The axis keyword can be used to specify a subset of axes of which the gradient is calculated >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float), axis=0) array([[ 2., 2., -1.], [ 2., 2., -1.]]) """ f = np.asanyarray(f) N = len(f.shape) # number of dimensions axes = kwargs.pop('axis', None) if axes is None: axes = tuple(range(N)) # check axes to have correct type and no duplicate entries if isinstance(axes, int): axes = (axes,) if not isinstance(axes, tuple): raise TypeError("A tuple of integers or a single integer is required") # normalize axis values: axes = tuple(x + N if x < 0 else x for x in axes) if max(axes) >= N or min(axes) < 0: raise ValueError("'axis' entry is out of bounds") if len(set(axes)) != len(axes): raise ValueError("duplicate value in 'axis'") n = len(varargs) if n == 0: dx = [1.0]*N elif n == 1: dx = [varargs[0]]*N elif n == len(axes): dx = list(varargs) else: raise SyntaxError( "invalid number of arguments") if any([not np.isscalar(dxi) for dxi in dx]): raise ValueError("distances must be scalars") edge_order = kwargs.pop('edge_order', 1) if kwargs: raise TypeError('"{}" are not valid keyword arguments.'.format( '", "'.join(kwargs.keys()))) if edge_order > 2: raise ValueError("'edge_order' greater than 2 not supported") # use central differences on interior and one-sided differences on the # endpoints. This preserves second order-accuracy over the full domain. outvals = [] # create slice objects --- initially all are [:, :, ..., :] slice1 = [slice(None)]*N slice2 = [slice(None)]*N slice3 = [slice(None)]*N slice4 = [slice(None)]*N otype = f.dtype.char if otype not in ['f', 'd', 'F', 'D', 'm', 'M']: otype = 'd' # Difference of datetime64 elements results in timedelta64 if otype == 'M': # Need to use the full dtype name because it contains unit information otype = f.dtype.name.replace('datetime', 'timedelta') elif otype == 'm': # Needs to keep the specific units, can't be a general unit otype = f.dtype # Convert datetime64 data into ints. Make dummy variable `y` # that is a view of ints if the data is datetime64, otherwise # just set y equal to the array `f`. if f.dtype.char in ["M", "m"]: y = f.view('int64') else: y = f for i, axis in enumerate(axes): if y.shape[axis] < 2: raise ValueError( "Shape of array too small to calculate a numerical gradient, " "at least two elements are required.") # Numerical differentiation: 1st order edges, 2nd order interior if y.shape[axis] == 2 or edge_order == 1: # Use first order differences for time data out = np.empty_like(y, dtype=otype) slice1[axis] = slice(1, -1) slice2[axis] = slice(2, None) slice3[axis] = slice(None, -2) # 1D equivalent -- out[1:-1] = (y[2:] - y[:-2])/2.0 out[slice1] = (y[slice2] - y[slice3])/2.0 slice1[axis] = 0 slice2[axis] = 1 slice3[axis] = 0 # 1D equivalent -- out[0] = (y[1] - y[0]) out[slice1] = (y[slice2] - y[slice3]) slice1[axis] = -1 slice2[axis] = -1 slice3[axis] = -2 # 1D equivalent -- out[-1] = (y[-1] - y[-2]) out[slice1] = (y[slice2] - y[slice3]) # Numerical differentiation: 2st order edges, 2nd order interior else: # Use second order differences where possible out = np.empty_like(y, dtype=otype) slice1[axis] = slice(1, -1) slice2[axis] = slice(2, None) slice3[axis] = slice(None, -2) # 1D equivalent -- out[1:-1] = (y[2:] - y[:-2])/2.0 out[slice1] = (y[slice2] - y[slice3])/2.0 slice1[axis] = 0 slice2[axis] = 0 slice3[axis] = 1 slice4[axis] = 2 # 1D equivalent -- out[0] = -(3*y[0] - 4*y[1] + y[2]) / 2.0 out[slice1] = -(3.0*y[slice2] - 4.0*y[slice3] + y[slice4])/2.0 slice1[axis] = -1 slice2[axis] = -1 slice3[axis] = -2 slice4[axis] = -3 # 1D equivalent -- out[-1] = (3*y[-1] - 4*y[-2] + y[-3]) out[slice1] = (3.0*y[slice2] - 4.0*y[slice3] + y[slice4])/2.0 # divide by step size out /= dx[i] outvals.append(out) # reset the slice object in this dimension to ":" slice1[axis] = slice(None) slice2[axis] = slice(None) slice3[axis] = slice(None) slice4[axis] = slice(None) if len(axes) == 1: return outvals[0] else: return outvals def diff(a, n=1, axis=-1): """ Calculate the n-th discrete difference along given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher differences are calculated by using `diff` recursively. Parameters ---------- a : array_like Input array n : int, optional The number of times values are differenced. axis : int, optional The axis along which the difference is taken, default is the last axis. Returns ------- diff : ndarray The n-th differences. The shape of the output is the same as `a` except along `axis` where the dimension is smaller by `n`. See Also -------- gradient, ediff1d, cumsum Examples -------- >>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) array([ 1, 2, 3, -7]) >>> np.diff(x, n=2) array([ 1, 1, -10]) >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]]) """ if n == 0: return a if n < 0: raise ValueError( "order must be non-negative but got " + repr(n)) a = asanyarray(a) nd = len(a.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) slice1 = tuple(slice1) slice2 = tuple(slice2) if n > 1: return diff(a[slice1]-a[slice2], n-1, axis=axis) else: return a[slice1]-a[slice2] def interp(x, xp, fp, left=None, right=None, period=None): """ One-dimensional linear interpolation. Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points. Parameters ---------- x : array_like The x-coordinates of the interpolated values. xp : 1-D sequence of floats The x-coordinates of the data points, must be increasing if argument `period` is not specified. Otherwise, `xp` is internally sorted after normalizing the periodic boundaries with ``xp = xp % period``. fp : 1-D sequence of float or complex The y-coordinates of the data points, same length as `xp`. left : optional float or complex corresponding to fp Value to return for `x < xp[0]`, default is `fp[0]`. right : optional float or complex corresponding to fp Value to return for `x > xp[-1]`, default is `fp[-1]`. period : None or float, optional A period for the x-coordinates. This parameter allows the proper interpolation of angular x-coordinates. Parameters `left` and `right` are ignored if `period` is specified. .. versionadded:: 1.10.0 Returns ------- y : float or complex (corresponding to fp) or ndarray The interpolated values, same shape as `x`. Raises ------ ValueError If `xp` and `fp` have different length If `xp` or `fp` are not 1-D sequences If `period == 0` Notes ----- Does not check that the x-coordinate sequence `xp` is increasing. If `xp` is not increasing, the results are nonsense. A simple check for increasing is:: np.all(np.diff(xp) > 0) Examples -------- >>> xp = [1, 2, 3] >>> fp = [3, 2, 0] >>> np.interp(2.5, xp, fp) 1.0 >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp) array([ 3. , 3. , 2.5 , 0.56, 0. ]) >>> UNDEF = -99.0 >>> np.interp(3.14, xp, fp, right=UNDEF) -99.0 Plot an interpolant to the sine function: >>> x = np.linspace(0, 2*np.pi, 10) >>> y = np.sin(x) >>> xvals = np.linspace(0, 2*np.pi, 50) >>> yinterp = np.interp(xvals, x, y) >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(xvals, yinterp, '-x') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.show() Interpolation with periodic x-coordinates: >>> x = [-180, -170, -185, 185, -10, -5, 0, 365] >>> xp = [190, -190, 350, -350] >>> fp = [5, 10, 3, 4] >>> np.interp(x, xp, fp, period=360) array([7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75]) Complex interpolation >>> x = [1.5, 4.0] >>> xp = [2,3,5] >>> fp = [1.0j, 0, 2+3j] >>> np.interp(x, xp, fp) array([ 0.+1.j , 1.+1.5j]) """ fp = np.asarray(fp) if np.iscomplexobj(fp): interp_func = compiled_interp_complex input_dtype = np.complex128 else: interp_func = compiled_interp input_dtype = np.float64 if period is None: if isinstance(x, (float, int, number)): return interp_func([x], xp, fp, left, right).item() elif isinstance(x, np.ndarray) and x.ndim == 0: return interp_func([x], xp, fp, left, right).item() else: return interp_func(x, xp, fp, left, right) else: if period == 0: raise ValueError("period must be a non-zero value") period = abs(period) left = None right = None return_array = True if isinstance(x, (float, int, number)): return_array = False x = [x] x = np.asarray(x, dtype=np.float64) xp = np.asarray(xp, dtype=np.float64) fp = np.asarray(fp, dtype=input_dtype) if xp.ndim != 1 or fp.ndim != 1: raise ValueError("Data points must be 1-D sequences") if xp.shape[0] != fp.shape[0]: raise ValueError("fp and xp are not of the same length") # normalizing periodic boundaries x = x % period xp = xp % period asort_xp = np.argsort(xp) xp = xp[asort_xp] fp = fp[asort_xp] xp = np.concatenate((xp[-1:]-period, xp, xp[0:1]+period)) fp = np.concatenate((fp[-1:], fp, fp[0:1])) if return_array: return interp_func(x, xp, fp, left, right) else: return interp_func(x, xp, fp, left, right).item() def angle(z, deg=0): """ Return the angle of the complex argument. Parameters ---------- z : array_like A complex number or sequence of complex numbers. deg : bool, optional Return angle in degrees if True, radians if False (default). Returns ------- angle : ndarray or scalar The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. See Also -------- arctan2 absolute Examples -------- >>> np.angle([1.0, 1.0j, 1+1j]) # in radians array([ 0. , 1.57079633, 0.78539816]) >>> np.angle(1+1j, deg=True) # in degrees 45.0 """ if deg: fact = 180/pi else: fact = 1.0 z = asarray(z) if (issubclass(z.dtype.type, _nx.complexfloating)): zimag = z.imag zreal = z.real else: zimag = 0 zreal = z return arctan2(zimag, zreal) * fact def unwrap(p, discont=pi, axis=-1): """ Unwrap by changing deltas between values to 2*pi complement. Unwrap radian phase `p` by changing absolute jumps greater than `discont` to their 2*pi complement along the given axis. Parameters ---------- p : array_like Input array. discont : float, optional Maximum discontinuity between values, default is ``pi``. axis : int, optional Axis along which unwrap will operate, default is the last axis. Returns ------- out : ndarray Output array. See Also -------- rad2deg, deg2rad Notes ----- If the discontinuity in `p` is smaller than ``pi``, but larger than `discont`, no unwrapping is done because taking the 2*pi complement would only make the discontinuity larger. Examples -------- >>> phase = np.linspace(0, np.pi, num=5) >>> phase[3:] += np.pi >>> phase array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) >>> np.unwrap(phase) array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) """ p = asarray(p) nd = len(p.shape) dd = diff(p, axis=axis) slice1 = [slice(None, None)]*nd # full slices slice1[axis] = slice(1, None) ddmod = mod(dd + pi, 2*pi) - pi _nx.copyto(ddmod, pi, where=(ddmod == -pi) & (dd > 0)) ph_correct = ddmod - dd _nx.copyto(ph_correct, 0, where=abs(dd) < discont) up = array(p, copy=True, dtype='d') up[slice1] = p[slice1] + ph_correct.cumsum(axis) return up def sort_complex(a): """ Sort a complex array using the real part first, then the imaginary part. Parameters ---------- a : array_like Input array Returns ------- out : complex ndarray Always returns a sorted complex array. Examples -------- >>> np.sort_complex([5, 3, 6, 2, 1]) array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j]) >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j]) """ b = array(a, copy=True) b.sort() if not issubclass(b.dtype.type, _nx.complexfloating): if b.dtype.char in 'bhBH': return b.astype('F') elif b.dtype.char == 'g': return b.astype('G') else: return b.astype('D') else: return b def trim_zeros(filt, trim='fb'): """ Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front and back of the array. Returns ------- trimmed : 1-D array or sequence The result of trimming the input. The input data type is preserved. Examples -------- >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, 1, 2, 3, 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2] """ first = 0 trim = trim.upper() if 'F' in trim: for i in filt: if i != 0.: break else: first = first + 1 last = len(filt) if 'B' in trim: for i in filt[::-1]: if i != 0.: break else: last = last - 1 return filt[first:last] @deprecate def unique(x): """ This function is deprecated. Use numpy.lib.arraysetops.unique() instead. """ try: tmp = x.flatten() if tmp.size == 0: return tmp tmp.sort() idx = concatenate(([True], tmp[1:] != tmp[:-1])) return tmp[idx] except AttributeError: items = sorted(set(x)) return asarray(items) def extract(condition, arr): """ Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. Note that `place` does the exact opposite of `extract`. Parameters ---------- condition : array_like An array whose nonzero or True entries indicate the elements of `arr` to extract. arr : array_like Input array of the same size as `condition`. Returns ------- extract : ndarray Rank 1 array of values from `arr` where `condition` is True. See Also -------- take, put, copyto, compress, place Examples -------- >>> arr = np.arange(12).reshape((3, 4)) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition array([[ True, False, False, True], [False, False, True, False], [False, True, False, False]], dtype=bool) >>> np.extract(condition, arr) array([0, 3, 6, 9]) If `condition` is boolean: >>> arr[condition] array([0, 3, 6, 9]) """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : ndarray Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N, it will be repeated, and if elements of `a` are to be masked, this sequence must be non-empty. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ if not isinstance(arr, np.ndarray): raise TypeError("argument 1 must be numpy.ndarray, " "not {name}".format(name=type(arr).__name__)) return _insert(arr, mask, vals) def disp(mesg, device=None, linefeed=True): """ Display a message on a device. Parameters ---------- mesg : str Message to display. device : object Device to write message. If None, defaults to ``sys.stdout`` which is very similar to ``print``. `device` needs to have ``write()`` and ``flush()`` methods. linefeed : bool, optional Option whether to print a line feed or not. Defaults to True. Raises ------ AttributeError If `device` does not have a ``write()`` or ``flush()`` method. Examples -------- Besides ``sys.stdout``, a file-like object can also be used as it has both required methods: >>> from StringIO import StringIO >>> buf = StringIO() >>> np.disp('"Display" in a file', device=buf) >>> buf.getvalue() '"Display" in a file\\n' """ if device is None: device = sys.stdout if linefeed: device.write('%s\n' % mesg) else: device.write('%s' % mesg) device.flush() return # See http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html _DIMENSION_NAME = r'\w+' _CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME) _ARGUMENT = r'\({}\)'.format(_CORE_DIMENSION_LIST) _ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT) _SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST) def _parse_gufunc_signature(signature): """ Parse string signatures for a generalized universal function. Arguments --------- signature : string Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)`` for ``np.matmul``. Returns ------- Tuple of input and output core dimensions parsed from the signature, each of the form List[Tuple[str, ...]]. """ if not re.match(_SIGNATURE, signature): raise ValueError( 'not a valid gufunc signature: {}'.format(signature)) return tuple([tuple(re.findall(_DIMENSION_NAME, arg)) for arg in re.findall(_ARGUMENT, arg_list)] for arg_list in signature.split('->')) def _update_dim_sizes(dim_sizes, arg, core_dims): """ Incrementally check and update core dimension sizes for a single argument. Arguments --------- dim_sizes : Dict[str, int] Sizes of existing core dimensions. Will be updated in-place. arg : ndarray Argument to examine. core_dims : Tuple[str, ...] Core dimensions for this argument. """ if not core_dims: return num_core_dims = len(core_dims) if arg.ndim < num_core_dims: raise ValueError( '%d-dimensional argument does not have enough ' 'dimensions for all core dimensions %r' % (arg.ndim, core_dims)) core_shape = arg.shape[-num_core_dims:] for dim, size in zip(core_dims, core_shape): if dim in dim_sizes: if size != dim_sizes[dim]: raise ValueError( 'inconsistent size for core dimension %r: %r vs %r' % (dim, size, dim_sizes[dim])) else: dim_sizes[dim] = size def _parse_input_dimensions(args, input_core_dims): """ Parse broadcast and core dimensions for vectorize with a signature. Arguments --------- args : Tuple[ndarray, ...] Tuple of input arguments to examine. input_core_dims : List[Tuple[str, ...]] List of core dimensions corresponding to each input. Returns ------- broadcast_shape : Tuple[int, ...] Common shape to broadcast all non-core dimensions to. dim_sizes : Dict[str, int] Common sizes for named core dimensions. """ broadcast_args = [] dim_sizes = {} for arg, core_dims in zip(args, input_core_dims): _update_dim_sizes(dim_sizes, arg, core_dims) ndim = arg.ndim - len(core_dims) dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim]) broadcast_args.append(dummy_array) broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args) return broadcast_shape, dim_sizes def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims): """Helper for calculating broadcast shapes with core dimensions.""" return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims) for core_dims in list_of_core_dims] def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes): """Helper for creating output arrays in vectorize.""" shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims) arrays = tuple(np.empty(shape, dtype=dtype) for shape, dtype in zip(shapes, dtypes)) return arrays class vectorize(object): """ vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None) Generalized function class. Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns an single or tuple of numpy array as output. The vectorized function evaluates `pyfunc` over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy. The data type of the output of `vectorized` is determined by calling the function with the first element of the input. This can be avoided by specifying the `otypes` argument. Parameters ---------- pyfunc : callable A python function or method. otypes : str or list of dtypes, optional The output data type. It must be specified as either a string of typecode characters or a list of data type specifiers. There should be one data type specifier for each output. doc : str, optional The docstring for the function. If `None`, the docstring will be the ``pyfunc.__doc__``. excluded : set, optional Set of strings or integers representing the positional or keyword arguments for which the function will not be vectorized. These will be passed directly to `pyfunc` unmodified. .. versionadded:: 1.7.0 cache : bool, optional If `True`, then cache the first function call that determines the number of outputs if `otypes` is not provided. .. versionadded:: 1.7.0 signature : string, optional Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for vectorized matrix-vector multiplication. If provided, ``pyfunc`` will be called with (and expected to return) arrays with shapes given by the size of corresponding core dimensions. By default, ``pyfunc`` is assumed to take scalars as input and output. .. versionadded:: 1.12.0 Returns ------- vectorized : callable Vectorized function. Examples -------- >>> def myfunc(a, b): ... "Return a-b if a>b, otherwise return a+b" ... if a > b: ... return a - b ... else: ... return a + b >>> vfunc = np.vectorize(myfunc) >>> vfunc([1, 2, 3, 4], 2) array([3, 4, 1, 2]) The docstring is taken from the input function to `vectorize` unless it is specified: >>> vfunc.__doc__ 'Return a-b if a>b, otherwise return a+b' >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`') >>> vfunc.__doc__ 'Vectorized `myfunc`' The output type is determined by evaluating the first element of the input, unless it is specified: >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <type 'numpy.int32'> >>> vfunc = np.vectorize(myfunc, otypes=[np.float]) >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <type 'numpy.float64'> The `excluded` argument can be used to prevent vectorizing over certain arguments. This can be useful for array-like arguments of a fixed length such as the coefficients for a polynomial as in `polyval`: >>> def mypolyval(p, x): ... _p = list(p) ... res = _p.pop(0) ... while _p: ... res = res*x + _p.pop(0) ... return res >>> vpolyval = np.vectorize(mypolyval, excluded=['p']) >>> vpolyval(p=[1, 2, 3], x=[0, 1]) array([3, 6]) Positional arguments may also be excluded by specifying their position: >>> vpolyval.excluded.add(0) >>> vpolyval([1, 2, 3], x=[0, 1]) array([3, 6]) The `signature` argument allows for vectorizing functions that act on non-scalar arrays of fixed length. For example, you can use it for a vectorized calculation of Pearson correlation coefficient and its p-value: >>> import scipy.stats >>> pearsonr = np.vectorize(scipy.stats.pearsonr, ... signature='(n),(n)->(),()') >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) (array([ 1., -1.]), array([ 0., 0.])) Or for a vectorized convolution: >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') >>> convolve(np.eye(4), [1, 2, 1]) array([[ 1., 2., 1., 0., 0., 0.], [ 0., 1., 2., 1., 0., 0.], [ 0., 0., 1., 2., 1., 0.], [ 0., 0., 0., 1., 2., 1.]]) See Also -------- frompyfunc : Takes an arbitrary Python function and returns a ufunc Notes ----- The `vectorize` function is provided primarily for convenience, not for performance. The implementation is essentially a for loop. If `otypes` is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if `cache` is `True` to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive. The new keyword argument interface and `excluded` argument support further degrades performance. References ---------- .. [1] NumPy Reference, section `Generalized Universal Function API <http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html>`_. """ def __init__(self, pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None): self.pyfunc = pyfunc self.cache = cache self.signature = signature self._ufunc = None # Caching to improve default performance if doc is None: self.__doc__ = pyfunc.__doc__ else: self.__doc__ = doc if isinstance(otypes, str): for char in otypes: if char not in typecodes['All']: raise ValueError("Invalid otype specified: %s" % (char,)) elif iterable(otypes): otypes = ''.join([_nx.dtype(x).char for x in otypes]) elif otypes is not None: raise ValueError("Invalid otype specification") self.otypes = otypes # Excluded variable support if excluded is None: excluded = set() self.excluded = set(excluded) if signature is not None: self._in_and_out_core_dims = _parse_gufunc_signature(signature) else: self._in_and_out_core_dims = None def __call__(self, *args, **kwargs): """ Return arrays with the results of `pyfunc` broadcast (vectorized) over `args` and `kwargs` not in `excluded`. """ excluded = self.excluded if not kwargs and not excluded: func = self.pyfunc vargs = args else: # The wrapper accepts only positional arguments: we use `names` and # `inds` to mutate `the_args` and `kwargs` to pass to the original # function. nargs = len(args) names = [_n for _n in kwargs if _n not in excluded] inds = [_i for _i in range(nargs) if _i not in excluded] the_args = list(args) def func(*vargs): for _n, _i in enumerate(inds): the_args[_i] = vargs[_n] kwargs.update(zip(names, vargs[len(inds):])) return self.pyfunc(*the_args, **kwargs) vargs = [args[_i] for _i in inds] vargs.extend([kwargs[_n] for _n in names]) return self._vectorize_call(func=func, args=vargs) def _get_ufunc_and_otypes(self, func, args): """Return (ufunc, otypes).""" # frompyfunc will fail if args is empty if not args: raise ValueError('args can not be empty') if self.otypes is not None: otypes = self.otypes nout = len(otypes) # Note logic here: We only *use* self._ufunc if func is self.pyfunc # even though we set self._ufunc regardless. if func is self.pyfunc and self._ufunc is not None: ufunc = self._ufunc else: ufunc = self._ufunc = frompyfunc(func, len(args), nout) else: # Get number of outputs and output types by calling the function on # the first entries of args. We also cache the result to prevent # the subsequent call when the ufunc is evaluated. # Assumes that ufunc first evaluates the 0th elements in the input # arrays (the input values are not checked to ensure this) args = [asarray(arg) for arg in args] if builtins.any(arg.size == 0 for arg in args): raise ValueError('cannot call `vectorize` on size 0 inputs ' 'unless `otypes` is set') inputs = [arg.flat[0] for arg in args] outputs = func(*inputs) # Performance note: profiling indicates that -- for simple # functions at least -- this wrapping can almost double the # execution time. # Hence we make it optional. if self.cache: _cache = [outputs] def _func(*vargs): if _cache: return _cache.pop() else: return func(*vargs) else: _func = func if isinstance(outputs, tuple): nout = len(outputs) else: nout = 1 outputs = (outputs,) otypes = ''.join([asarray(outputs[_k]).dtype.char for _k in range(nout)]) # Performance note: profiling indicates that creating the ufunc is # not a significant cost compared with wrapping so it seems not # worth trying to cache this. ufunc = frompyfunc(_func, len(args), nout) return ufunc, otypes def _vectorize_call(self, func, args): """Vectorized call to `func` over positional `args`.""" if self.signature is not None: res = self._vectorize_call_with_signature(func, args) elif not args: res = func() else: ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) # Convert args to object arrays first inputs = [array(a, copy=False, subok=True, dtype=object) for a in args] outputs = ufunc(*inputs) if ufunc.nout == 1: res = array(outputs, copy=False, subok=True, dtype=otypes[0]) else: res = tuple([array(x, copy=False, subok=True, dtype=t) for x, t in zip(outputs, otypes)]) return res def _vectorize_call_with_signature(self, func, args): """Vectorized call over positional arguments with a signature.""" input_core_dims, output_core_dims = self._in_and_out_core_dims if len(args) != len(input_core_dims): raise TypeError('wrong number of positional arguments: ' 'expected %r, got %r' % (len(input_core_dims), len(args))) args = tuple(asanyarray(arg) for arg in args) broadcast_shape, dim_sizes = _parse_input_dimensions( args, input_core_dims) input_shapes = _calculate_shapes(broadcast_shape, dim_sizes, input_core_dims) args = [np.broadcast_to(arg, shape, subok=True) for arg, shape in zip(args, input_shapes)] outputs = None otypes = self.otypes nout = len(output_core_dims) for index in np.ndindex(*broadcast_shape): results = func(*(arg[index] for arg in args)) n_results = len(results) if isinstance(results, tuple) else 1 if nout != n_results: raise ValueError( 'wrong number of outputs from pyfunc: expected %r, got %r' % (nout, n_results)) if nout == 1: results = (results,) if outputs is None: for result, core_dims in zip(results, output_core_dims): _update_dim_sizes(dim_sizes, result, core_dims) if otypes is None: otypes = [asarray(result).dtype for result in results] outputs = _create_arrays(broadcast_shape, dim_sizes, output_core_dims, otypes) for output, result in zip(outputs, results): output[index] = result if outputs is None: # did not call the function even once if otypes is None: raise ValueError('cannot call `vectorize` on size 0 inputs ' 'unless `otypes` is set') if builtins.any(dim not in dim_sizes for dims in output_core_dims for dim in dims): raise ValueError('cannot call `vectorize` with a signature ' 'including new output dimensions on size 0 ' 'inputs') outputs = _create_arrays(broadcast_shape, dim_sizes, output_core_dims, otypes) return outputs[0] if nout == 1 else outputs def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None): """ Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance of :math:`x_i`. See the notes for an outline of the algorithm. Parameters ---------- m : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same form as that of `m`. rowvar : bool, optional If `rowvar` is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : bool, optional Default normalization (False) is by ``(N - 1)``, where ``N`` is the number of observations given (unbiased estimate). If `bias` is True, then normalization is by ``N``. These values can be overridden by using the keyword ``ddof`` in numpy versions >= 1.5. ddof : int, optional If not ``None`` the default value implied by `bias` is overridden. Note that ``ddof=1`` will return the unbiased estimate, even if both `fweights` and `aweights` are specified, and ``ddof=0`` will return the simple average. See the notes for the details. The default value is ``None``. .. versionadded:: 1.5 fweights : array_like, int, optional 1-D array of integer freguency weights; the number of times each observation vector should be repeated. .. versionadded:: 1.10 aweights : array_like, optional 1-D array of observation vector weights. These relative weights are typically large for observations considered "important" and smaller for observations considered less "important". If ``ddof=0`` the array of weights can be used to assign probabilities to observation vectors. .. versionadded:: 1.10 Returns ------- out : ndarray The covariance matrix of the variables. See Also -------- corrcoef : Normalized covariance matrix Notes ----- Assume that the observations are in the columns of the observation array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The steps to compute the weighted covariance are as follows:: >>> w = f * a >>> v1 = np.sum(w) >>> v2 = np.sum(w * a) >>> m -= np.sum(m * w, axis=1, keepdims=True) / v1 >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2) Note that when ``a == 1``, the normalization factor ``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)`` as it should. Examples -------- Consider two variables, :math:`x_0` and :math:`x_1`, which correlate perfectly, but in opposite directions: >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T >>> x array([[0, 1, 2], [2, 1, 0]]) Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance matrix shows this clearly: >>> np.cov(x) array([[ 1., -1.], [-1., 1.]]) Note that element :math:`C_{0,1}`, which shows the correlation between :math:`x_0` and :math:`x_1`, is negative. Further, note how `x` and `y` are combined: >>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.vstack((x,y)) >>> print(np.cov(X)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print(np.cov(x, y)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print(np.cov(x)) 11.71 """ # Check inputs if ddof is not None and ddof != int(ddof): raise ValueError( "ddof must be integer") # Handles complex arrays too m = np.asarray(m) if m.ndim > 2: raise ValueError("m has more than 2 dimensions") if y is None: dtype = np.result_type(m, np.float64) else: y = np.asarray(y) if y.ndim > 2: raise ValueError("y has more than 2 dimensions") dtype = np.result_type(m, y, np.float64) X = array(m, ndmin=2, dtype=dtype) if rowvar == 0 and X.shape[0] != 1: X = X.T if X.shape[0] == 0: return np.array([]).reshape(0, 0) if y is not None: y = array(y, copy=False, ndmin=2, dtype=dtype) if rowvar == 0 and y.shape[0] != 1: y = y.T X = np.vstack((X, y)) if ddof is None: if bias == 0: ddof = 1 else: ddof = 0 # Get the product of frequencies and weights w = None if fweights is not None: fweights = np.asarray(fweights, dtype=np.float) if not np.all(fweights == np.around(fweights)): raise TypeError( "fweights must be integer") if fweights.ndim > 1: raise RuntimeError( "cannot handle multidimensional fweights") if fweights.shape[0] != X.shape[1]: raise RuntimeError( "incompatible numbers of samples and fweights") if any(fweights < 0): raise ValueError( "fweights cannot be negative") w = fweights if aweights is not None: aweights = np.asarray(aweights, dtype=np.float) if aweights.ndim > 1: raise RuntimeError( "cannot handle multidimensional aweights") if aweights.shape[0] != X.shape[1]: raise RuntimeError( "incompatible numbers of samples and aweights") if any(aweights < 0): raise ValueError( "aweights cannot be negative") if w is None: w = aweights else: w *= aweights avg, w_sum = average(X, axis=1, weights=w, returned=True) w_sum = w_sum[0] # Determine the normalization if w is None: fact = X.shape[1] - ddof elif ddof == 0: fact = w_sum elif aweights is None: fact = w_sum - ddof else: fact = w_sum - ddof*sum(w*aweights)/w_sum if fact <= 0: warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2) fact = 0.0 X -= avg[:, None] if w is None: X_T = X.T else: X_T = (X*w).T c = dot(X, X_T.conj()) c *= 1. / np.float64(fact) return c.squeeze() def corrcoef(x, y=None, rowvar=1, bias=np._NoValue, ddof=np._NoValue): """ Return Pearson product-moment correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, `R`, and the covariance matrix, `C`, is .. math:: R_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } } The values of `R` are between -1 and 1, inclusive. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `x` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same shape as `x`. rowvar : int, optional If `rowvar` is non-zero (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.10.0 ddof : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.10.0 Returns ------- R : ndarray The correlation coefficient matrix of the variables. See Also -------- cov : Covariance matrix Notes ----- Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case. This function accepts but discards arguments `bias` and `ddof`. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy. """ if bias is not np._NoValue or ddof is not np._NoValue: # 2015-03-15, 1.10 warnings.warn('bias and ddof have no effect and are deprecated', DeprecationWarning, stacklevel=2) c = cov(x, y, rowvar) try: d = diag(c) except ValueError: # scalar covariance # nan if incorrect value (nan, inf, 0), 1 otherwise return c / c stddev = sqrt(d.real) c /= stddev[:, None] c /= stddev[None, :] # Clip real and imaginary parts to [-1, 1]. This does not guarantee # abs(a[i,j]) <= 1 for complex arrays, but is the best we can do without # excessive work. np.clip(c.real, -1, 1, out=c.real) if np.iscomplexobj(c): np.clip(c.imag, -1, 1, out=c.imag) return c def blackman(M): """ Return the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, hamming, hanning, kaiser Notes ----- The Blackman window is defined as .. math:: w(n) = 0.42 - 0.5 \\cos(2\\pi n/M) + 0.08 \\cos(4\\pi n/M) Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a "near optimal" tapering function, almost as good (by some measures) as the kaiser window. References ---------- Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. Examples -------- >>> np.blackman(12) array([ -1.38777878e-17, 3.26064346e-02, 1.59903635e-01, 4.14397981e-01, 7.36045180e-01, 9.67046769e-01, 9.67046769e-01, 7.36045180e-01, 4.14397981e-01, 1.59903635e-01, 3.26064346e-02, -1.38777878e-17]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.blackman(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Blackman window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Blackman window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.42 - 0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) def bartlett(M): """ Return the Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : array The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero. See Also -------- blackman, hamming, hanning, kaiser Notes ----- The Bartlett window is defined as .. math:: w(n) = \\frac{2}{M-1} \\left( \\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right| \\right) Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means"removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich. References ---------- .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", Biometrika 37, 1-16, 1950. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal Processing", Prentice-Hall, 1999, pp. 468-471. .. [4] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 429. Examples -------- >>> np.bartlett(12) array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, 0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636, 0.18181818, 0. ]) Plot the window and its frequency response (requires SciPy and matplotlib): >>> from numpy.fft import fft, fftshift >>> window = np.bartlett(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Bartlett window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Bartlett window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return where(less_equal(n, (M-1)/2.0), 2.0*n/(M-1), 2.0 - 2.0*n/(M-1)) def hanning(M): """ Return the Hanning window. The Hanning window is a taper formed by using a weighted cosine. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray, shape(M,) The window, with the maximum value normalized to one (the value one appears only if `M` is odd). See Also -------- bartlett, blackman, hamming, kaiser Notes ----- The Hanning window is defined as .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right) \\qquad 0 \\leq n \\leq M-1 The Hanning was named for Julius von Hann, an Austrian meteorologist. It is also known as the Cosine Bell. Some authors prefer that it be called a Hann window, to help avoid confusion with the very similar Hamming window. Most references to the Hanning window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 106-108. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- >>> np.hanning(12) array([ 0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037, 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249, 0.07937323, 0. ]) Plot the window and its frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.hanning(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hann window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of the Hann window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.5 - 0.5*cos(2.0*pi*n/(M-1)) def hamming(M): """ Return the Hamming window. The Hamming window is a taper formed by using a weighted cosine. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, blackman, hanning, kaiser Notes ----- The Hamming window is defined as .. math:: w(n) = 0.54 - 0.46cos\\left(\\frac{2\\pi{n}}{M-1}\\right) \\qquad 0 \\leq n \\leq M-1 The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman and Tukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Most references to the Hamming window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- >>> np.hamming(12) array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, 0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909, 0.15302337, 0.08 ]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.hamming(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hamming window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Hamming window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.54 - 0.46*cos(2.0*pi*n/(M-1)) ## Code from cephes for i0 _i0A = [ -4.41534164647933937950E-18, 3.33079451882223809783E-17, -2.43127984654795469359E-16, 1.71539128555513303061E-15, -1.16853328779934516808E-14, 7.67618549860493561688E-14, -4.85644678311192946090E-13, 2.95505266312963983461E-12, -1.72682629144155570723E-11, 9.67580903537323691224E-11, -5.18979560163526290666E-10, 2.65982372468238665035E-9, -1.30002500998624804212E-8, 6.04699502254191894932E-8, -2.67079385394061173391E-7, 1.11738753912010371815E-6, -4.41673835845875056359E-6, 1.64484480707288970893E-5, -5.75419501008210370398E-5, 1.88502885095841655729E-4, -5.76375574538582365885E-4, 1.63947561694133579842E-3, -4.32430999505057594430E-3, 1.05464603945949983183E-2, -2.37374148058994688156E-2, 4.93052842396707084878E-2, -9.49010970480476444210E-2, 1.71620901522208775349E-1, -3.04682672343198398683E-1, 6.76795274409476084995E-1 ] _i0B = [ -7.23318048787475395456E-18, -4.83050448594418207126E-18, 4.46562142029675999901E-17, 3.46122286769746109310E-17, -2.82762398051658348494E-16, -3.42548561967721913462E-16, 1.77256013305652638360E-15, 3.81168066935262242075E-15, -9.55484669882830764870E-15, -4.15056934728722208663E-14, 1.54008621752140982691E-14, 3.85277838274214270114E-13, 7.18012445138366623367E-13, -1.79417853150680611778E-12, -1.32158118404477131188E-11, -3.14991652796324136454E-11, 1.18891471078464383424E-11, 4.94060238822496958910E-10, 3.39623202570838634515E-9, 2.26666899049817806459E-8, 2.04891858946906374183E-7, 2.89137052083475648297E-6, 6.88975834691682398426E-5, 3.36911647825569408990E-3, 8.04490411014108831608E-1 ] def _chbevl(x, vals): b0 = vals[0] b1 = 0.0 for i in range(1, len(vals)): b2 = b1 b1 = b0 b0 = x*b1 - b2 + vals[i] return 0.5*(b0 - b2) def _i0_1(x): return exp(x) * _chbevl(x/2.0-2, _i0A) def _i0_2(x): return exp(x) * _chbevl(32.0/x - 2.0, _i0B) / sqrt(x) def i0(x): """ Modified Bessel function of the first kind, order 0. Usually denoted :math:`I_0`. This function does broadcast, but will *not* "up-cast" int dtype arguments unless accompanied by at least one float or complex dtype argument (see Raises below). Parameters ---------- x : array_like, dtype float or complex Argument of the Bessel function. Returns ------- out : ndarray, shape = x.shape, dtype = x.dtype The modified Bessel function evaluated at each of the elements of `x`. Raises ------ TypeError: array cannot be safely cast to required type If argument consists exclusively of int dtypes. See Also -------- scipy.special.iv, scipy.special.ive Notes ----- We use the algorithm published by Clenshaw [1]_ and referenced by Abramowitz and Stegun [2]_, for which the function domain is partitioned into the two intervals [0,8] and (8,inf), and Chebyshev polynomial expansions are employed in each interval. Relative error on the domain [0,30] using IEEE arithmetic is documented [3]_ as having a peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000). References ---------- .. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in *National Physical Laboratory Mathematical Tables*, vol. 5, London: Her Majesty's Stationery Office, 1962. .. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 379. http://www.math.sfu.ca/~cbm/aands/page_379.htm .. [3] http://kobesearch.cpan.org/htdocs/Math-Cephes/Math/Cephes.html Examples -------- >>> np.i0([0.]) array(1.0) >>> np.i0([0., 1. + 2j]) array([ 1.00000000+0.j , 0.18785373+0.64616944j]) """ x = atleast_1d(x).copy() y = empty_like(x) ind = (x < 0) x[ind] = -x[ind] ind = (x <= 8.0) y[ind] = _i0_1(x[ind]) ind2 = ~ind y[ind2] = _i0_2(x[ind2]) return y.squeeze() ## End of cephes code for i0 def kaiser(M, beta): """ Return the Kaiser window. The Kaiser window is a taper formed by using a Bessel function. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. beta : float Shape parameter for window. Returns ------- out : array The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, blackman, hamming, hanning Notes ----- The Kaiser window is defined as .. math:: w(n) = I_0\\left( \\beta \\sqrt{1-\\frac{4n^2}{(M-1)^2}} \\right)/I_0(\\beta) with .. math:: \\quad -\\frac{M-1}{2} \\leq n \\leq \\frac{M-1}{2}, where :math:`I_0` is the modified zeroth-order Bessel function. The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based on Bessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence, or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative to total energy. The Kaiser can approximate many other windows by varying the beta parameter. ==== ======================= beta Window shape ==== ======================= 0 Rectangular 5 Similar to a Hamming 6 Similar to a Hanning 8.6 Similar to a Blackman ==== ======================= A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned. Most references to the Kaiser window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966). .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 177-178. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function Examples -------- >>> np.kaiser(12, 14) array([ 7.72686684e-06, 3.46009194e-03, 4.65200189e-02, 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, 4.65200189e-02, 3.46009194e-03, 7.72686684e-06]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.kaiser(51, 14) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Kaiser window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Kaiser window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ from numpy.dual import i0 if M == 1: return np.array([1.]) n = arange(0, M) alpha = (M-1)/2.0 return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(float(beta)) def sinc(x): """ Return the sinc function. The sinc function is :math:`\\sin(\\pi x)/(\\pi x)`. Parameters ---------- x : ndarray Array (possibly multi-dimensional) of values for which to to calculate ``sinc(x)``. Returns ------- out : ndarray ``sinc(x)``, which has the same shape as the input. Notes ----- ``sinc(0)`` is the limit value 1. The name sinc is short for "sine cardinal" or "sinus cardinalis". The sinc function is used in various signal processing applications, including in anti-aliasing, in the construction of a Lanczos resampling filter, and in interpolation. For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function. References ---------- .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/SincFunction.html .. [2] Wikipedia, "Sinc function", http://en.wikipedia.org/wiki/Sinc_function Examples -------- >>> x = np.linspace(-4, 4, 41) >>> np.sinc(x) array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02, -8.90384387e-02, -5.84680802e-02, 3.89804309e-17, 6.68206631e-02, 1.16434881e-01, 1.26137788e-01, 8.50444803e-02, -3.89804309e-17, -1.03943254e-01, -1.89206682e-01, -2.16236208e-01, -1.55914881e-01, 3.89804309e-17, 2.33872321e-01, 5.04551152e-01, 7.56826729e-01, 9.35489284e-01, 1.00000000e+00, 9.35489284e-01, 7.56826729e-01, 5.04551152e-01, 2.33872321e-01, 3.89804309e-17, -1.55914881e-01, -2.16236208e-01, -1.89206682e-01, -1.03943254e-01, -3.89804309e-17, 8.50444803e-02, 1.26137788e-01, 1.16434881e-01, 6.68206631e-02, 3.89804309e-17, -5.84680802e-02, -8.90384387e-02, -8.40918587e-02, -4.92362781e-02, -3.89804309e-17]) >>> plt.plot(x, np.sinc(x)) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Sinc Function") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("X") <matplotlib.text.Text object at 0x...> >>> plt.show() It works in 2-D as well: >>> x = np.linspace(-4, 4, 401) >>> xx = np.outer(x, x) >>> plt.imshow(np.sinc(xx)) <matplotlib.image.AxesImage object at 0x...> """ x = np.asanyarray(x) y = pi * where(x == 0, 1.0e-20, x) return sin(y)/y def msort(a): """ Return a copy of an array sorted along the first axis. Parameters ---------- a : array_like Array to be sorted. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- sort Notes ----- ``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``. """ b = array(a, subok=True, copy=True) b.sort(0) return b def _ureduce(a, func, **kwargs): """ Internal Function. Call `func` with `a` as first argument swapping the axes to use extended axis on functions that don't support it natively. Returns result and a.shape with axis dims set to 1. Parameters ---------- a : array_like Input array or object that can be converted to an array. func : callable Reduction function capable of receiving a single axis argument. It is is called with `a` as first argument followed by `kwargs`. kwargs : keyword arguments additional keyword arguments to pass to `func`. Returns ------- result : tuple Result of func(a, **kwargs) and a.shape with axis dims set to 1 which can be used to reshape the result to the same shape a ufunc with keepdims=True would produce. """ a = np.asanyarray(a) axis = kwargs.get('axis', None) if axis is not None: keepdim = list(a.shape) nd = a.ndim try: axis = operator.index(axis) if axis >= nd or axis < -nd: raise IndexError("axis %d out of bounds (%d)" % (axis, a.ndim)) keepdim[axis] = 1 except TypeError: sax = set() for x in axis: if x >= nd or x < -nd: raise IndexError("axis %d out of bounds (%d)" % (x, nd)) if x in sax: raise ValueError("duplicate value in axis") sax.add(x % nd) keepdim[x] = 1 keep = sax.symmetric_difference(frozenset(range(nd))) nkeep = len(keep) # swap axis that should not be reduced to front for i, s in enumerate(sorted(keep)): a = a.swapaxes(i, s) # merge reduced axis a = a.reshape(a.shape[:nkeep] + (-1,)) kwargs['axis'] = -1 else: keepdim = [1] * a.ndim r = func(a, **kwargs) return r, keepdim def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): """ Compute the median along the specified axis. Returns the median of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : {int, sequence of int, None}, optional Axis or axes along which the medians are computed. The default is to compute the median along a flattened version of the array. A sequence of axes is supported since version 1.9.0. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array `a` for calculations. The input array will be modified by the call to `median`. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, but it will probably be fully or partially sorted. Default is False. If `overwrite_input` is ``True`` and `a` is not already an `ndarray`, an error will be raised. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. .. versionadded:: 1.9.0 Returns ------- median : ndarray A new array holding the result. If the input contains integers or floats smaller than ``float64``, then the output data-type is ``np.float64``. Otherwise, the data-type of the output is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- mean, percentile Notes ----- Given a vector ``V`` of length ``N``, the median of ``V`` is the middle value of a sorted copy of ``V``, ``V_sorted`` - i e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the two middle values of ``V_sorted`` when ``N`` is even. Examples -------- >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.median(a) 3.5 >>> np.median(a, axis=0) array([ 6.5, 4.5, 2.5]) >>> np.median(a, axis=1) array([ 7., 2.]) >>> m = np.median(a, axis=0) >>> out = np.zeros_like(m) >>> np.median(a, axis=0, out=m) array([ 6.5, 4.5, 2.5]) >>> m array([ 6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.median(b, axis=1, overwrite_input=True) array([ 7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.median(b, axis=None, overwrite_input=True) 3.5 >>> assert not np.all(a==b) """ r, k = _ureduce(a, func=_median, axis=axis, out=out, overwrite_input=overwrite_input) if keepdims: return r.reshape(k) else: return r def _median(a, axis=None, out=None, overwrite_input=False): # can't be reasonably be implemented in terms of percentile as we have to # call mean to not break astropy a = np.asanyarray(a) # Set the partition indexes if axis is None: sz = a.size else: sz = a.shape[axis] if sz % 2 == 0: szh = sz // 2 kth = [szh - 1, szh] else: kth = [(sz - 1) // 2] # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): kth.append(-1) if overwrite_input: if axis is None: part = a.ravel() part.partition(kth) else: a.partition(kth, axis=axis) part = a else: part = partition(a, kth, axis=axis) if part.shape == (): # make 0-D arrays work return part.item() if axis is None: axis = 0 indexer = [slice(None)] * part.ndim index = part.shape[axis] // 2 if part.shape[axis] % 2 == 1: # index with slice to allow mean (below) to work indexer[axis] = slice(index, index+1) else: indexer[axis] = slice(index-1, index+1) # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact) and sz > 0: # warn and return nans like mean would rout = mean(part[indexer], axis=axis, out=out) return np.lib.utils._median_nancheck(part, rout, axis, out) else: # if there are no nans # Use mean in odd and even case to coerce data type # and check, use out array. return mean(part[indexer], axis=axis, out=out) def percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False): """ Compute the qth percentile of the data along the specified axis. Returns the qth percentile(s) of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. q : float in range of [0,100] (or sequence of floats) Percentile to compute, which must be between 0 and 100 inclusive. axis : {int, sequence of int, None}, optional Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array. A sequence of axes is supported since version 1.9.0. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array `a` calculations. The input array will be modified by the call to `percentile`. This will save memory when you do not need to preserve the contents of the input array. In this case you should not make any assumptions about the contents of the input `a` after this function completes -- treat it as undefined. Default is False. If `a` is not already an array, this parameter will have no effect as `a` will be converted to an array internally regardless of the value of this parameter. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points ``i < j``: * linear: ``i + (j - i) * fraction``, where ``fraction`` is the fractional part of the index surrounded by ``i`` and ``j``. * lower: ``i``. * higher: ``j``. * nearest: ``i`` or ``j``, whichever is nearest. * midpoint: ``(i + j) / 2``. .. versionadded:: 1.9.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array `a`. .. versionadded:: 1.9.0 Returns ------- percentile : scalar or ndarray If `q` is a single percentile and `axis=None`, then the result is a scalar. If multiple percentiles are given, first axis of the result corresponds to the percentiles. The other axes are the axes that remain after the reduction of `a`. If the input contains integers or floats smaller than ``float64``, the output data-type is ``float64``. Otherwise, the output data-type is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- mean, median, nanpercentile Notes ----- Given a vector ``V`` of length ``N``, the ``q``-th percentile of ``V`` is the value ``q/100`` of the way from the mimumum to the maximum in in a sorted copy of ``V``. The values and distances of the two nearest neighbors as well as the `interpolation` parameter will determine the percentile if the normalized ranking does not match the location of ``q`` exactly. This function is the same as the median if ``q=50``, the same as the minimum if ``q=0`` and the same as the maximum if ``q=100``. Examples -------- >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.percentile(a, 50) 3.5 >>> np.percentile(a, 50, axis=0) array([[ 6.5, 4.5, 2.5]]) >>> np.percentile(a, 50, axis=1) array([ 7., 2.]) >>> np.percentile(a, 50, axis=1, keepdims=True) array([[ 7.], [ 2.]]) >>> m = np.percentile(a, 50, axis=0) >>> out = np.zeros_like(m) >>> np.percentile(a, 50, axis=0, out=out) array([[ 6.5, 4.5, 2.5]]) >>> m array([[ 6.5, 4.5, 2.5]]) >>> b = a.copy() >>> np.percentile(b, 50, axis=1, overwrite_input=True) array([ 7., 2.]) >>> assert not np.all(a == b) """ q = array(q, dtype=np.float64, copy=True) r, k = _ureduce(a, func=_percentile, q=q, axis=axis, out=out, overwrite_input=overwrite_input, interpolation=interpolation) if keepdims: if q.ndim == 0: return r.reshape(k) else: return r.reshape([len(q)] + k) else: return r def _percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False): a = asarray(a) if q.ndim == 0: # Do not allow 0-d arrays because following code fails for scalar zerod = True q = q[None] else: zerod = False # avoid expensive reductions, relevant for arrays with < O(1000) elements if q.size < 10: for i in range(q.size): if q[i] < 0. or q[i] > 100.: raise ValueError("Percentiles must be in the range [0,100]") q[i] /= 100. else: # faster than any() if np.count_nonzero(q < 0.) or np.count_nonzero(q > 100.): raise ValueError("Percentiles must be in the range [0,100]") q /= 100. # prepare a for partioning if overwrite_input: if axis is None: ap = a.ravel() else: ap = a else: if axis is None: ap = a.flatten() else: ap = a.copy() if axis is None: axis = 0 Nx = ap.shape[axis] indices = q * (Nx - 1) # round fractional indices according to interpolation method if interpolation == 'lower': indices = floor(indices).astype(intp) elif interpolation == 'higher': indices = ceil(indices).astype(intp) elif interpolation == 'midpoint': indices = 0.5 * (floor(indices) + ceil(indices)) elif interpolation == 'nearest': indices = around(indices).astype(intp) elif interpolation == 'linear': pass # keep index as fraction and interpolate else: raise ValueError( "interpolation can only be 'linear', 'lower' 'higher', " "'midpoint', or 'nearest'") n = np.array(False, dtype=bool) # check for nan's flag if indices.dtype == intp: # take the points along axis # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices = concatenate((indices, [-1])) ap.partition(indices, axis=axis) # ensure axis with qth is first ap = np.rollaxis(ap, axis, 0) axis = 0 # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices = indices[:-1] n = np.isnan(ap[-1:, ...]) if zerod: indices = indices[0] r = take(ap, indices, axis=axis, out=out) else: # weight the points above and below the indices indices_below = floor(indices).astype(intp) indices_above = indices_below + 1 indices_above[indices_above > Nx - 1] = Nx - 1 # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices_above = concatenate((indices_above, [-1])) weights_above = indices - indices_below weights_below = 1.0 - weights_above weights_shape = [1, ] * ap.ndim weights_shape[axis] = len(indices) weights_below.shape = weights_shape weights_above.shape = weights_shape ap.partition(concatenate((indices_below, indices_above)), axis=axis) # ensure axis with qth is first ap = np.rollaxis(ap, axis, 0) weights_below = np.rollaxis(weights_below, axis, 0) weights_above = np.rollaxis(weights_above, axis, 0) axis = 0 # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices_above = indices_above[:-1] n = np.isnan(ap[-1:, ...]) x1 = take(ap, indices_below, axis=axis) * weights_below x2 = take(ap, indices_above, axis=axis) * weights_above # ensure axis with qth is first x1 = np.rollaxis(x1, axis, 0) x2 = np.rollaxis(x2, axis, 0) if zerod: x1 = x1.squeeze(0) x2 = x2.squeeze(0) if out is not None: r = add(x1, x2, out=out) else: r = add(x1, x2) if np.any(n): warnings.warn("Invalid value encountered in percentile", RuntimeWarning, stacklevel=3) if zerod: if ap.ndim == 1: if out is not None: out[...] = a.dtype.type(np.nan) r = out else: r = a.dtype.type(np.nan) else: r[..., n.squeeze(0)] = a.dtype.type(np.nan) else: if r.ndim == 1: r[:] = a.dtype.type(np.nan) else: r[..., n.repeat(q.size, 0)] = a.dtype.type(np.nan) return r def trapz(y, x=None, dx=1.0, axis=-1): """ Integrate along the given axis using the composite trapezoidal rule. Integrate `y` (`x`) along given axis. Parameters ---------- y : array_like Input array to integrate. x : array_like, optional The sample points corresponding to the `y` values. If `x` is None, the sample points are assumed to be evenly spaced `dx` apart. The default is None. dx : scalar, optional The spacing between sample points when `x` is None. The default is 1. axis : int, optional The axis along which to integrate. Returns ------- trapz : float Definite integral as approximated by trapezoidal rule. See Also -------- sum, cumsum Notes ----- Image [2]_ illustrates trapezoidal rule -- y-axis locations of points will be taken from `y` array, by default x-axis distances between points will be 1.0, alternatively they can be provided with `x` array or with `dx` scalar. Return value will be equal to combined area under the red lines. References ---------- .. [1] Wikipedia page: http://en.wikipedia.org/wiki/Trapezoidal_rule .. [2] Illustration image: http://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png Examples -------- >>> np.trapz([1,2,3]) 4.0 >>> np.trapz([1,2,3], x=[4,6,8]) 8.0 >>> np.trapz([1,2,3], dx=2) 8.0 >>> a = np.arange(6).reshape(2, 3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.trapz(a, axis=0) array([ 1.5, 2.5, 3.5]) >>> np.trapz(a, axis=1) array([ 2., 8.]) """ y = asanyarray(y) if x is None: d = dx else: x = asanyarray(x) if x.ndim == 1: d = diff(x) # reshape to correct shape shape = [1]*y.ndim shape[axis] = d.shape[0] d = d.reshape(shape) else: d = diff(x, axis=axis) nd = len(y.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) try: ret = (d * (y[slice1] + y[slice2]) / 2.0).sum(axis) except ValueError: # Operations didn't work, cast to ndarray d = np.asarray(d) y = np.asarray(y) ret = add.reduce(d * (y[slice1]+y[slice2])/2.0, axis) return ret #always succeed def add_newdoc(place, obj, doc): """ Adds documentation to obj which is in module place. If doc is a string add it to obj as a docstring If doc is a tuple, then the first element is interpreted as an attribute of obj and the second as the docstring (method, docstring) If doc is a list, then each element of the list should be a sequence of length two --> [(method1, docstring1), (method2, docstring2), ...] This routine never raises an error. This routine cannot modify read-only docstrings, as appear in new-style classes or built-in functions. Because this routine never raises an error the caller must check manually that the docstrings were changed. """ try: new = getattr(__import__(place, globals(), {}, [obj]), obj) if isinstance(doc, str): add_docstring(new, doc.strip()) elif isinstance(doc, tuple): add_docstring(getattr(new, doc[0]), doc[1].strip()) elif isinstance(doc, list): for val in doc: add_docstring(getattr(new, val[0]), val[1].strip()) except: pass # Based on scitools meshgrid def meshgrid(*xi, **kwargs): """ Return coordinate matrices from coordinate vectors. Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn. .. versionchanged:: 1.9 1-D and 0-D cases are allowed. Parameters ---------- x1, x2,..., xn : array_like 1-D arrays representing the coordinates of a grid. indexing : {'xy', 'ij'}, optional Cartesian ('xy', default) or matrix ('ij') indexing of output. See Notes for more details. .. versionadded:: 1.7.0 sparse : bool, optional If True a sparse grid is returned in order to conserve memory. Default is False. .. versionadded:: 1.7.0 copy : bool, optional If False, a view into the original arrays are returned in order to conserve memory. Default is True. Please note that ``sparse=False, copy=False`` will likely return non-contiguous arrays. Furthermore, more than one element of a broadcast array may refer to a single memory location. If you need to write to the arrays, make copies first. .. versionadded:: 1.7.0 Returns ------- X1, X2,..., XN : ndarray For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` , return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij' or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy' with the elements of `xi` repeated to fill the matrix along the first dimension for `x1`, the second for `x2` and so on. Notes ----- This function supports both indexing conventions through the indexing keyword argument. Giving the string 'ij' returns a meshgrid with matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. In the 2-D case with inputs of length M and N, the outputs are of shape (N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case with inputs of length M, N and P, outputs are of shape (N, M, P) for 'xy' indexing and (M, N, P) for 'ij' indexing. The difference is illustrated by the following code snippet:: xv, yv = meshgrid(x, y, sparse=False, indexing='ij') for i in range(nx): for j in range(ny): # treat xv[i,j], yv[i,j] xv, yv = meshgrid(x, y, sparse=False, indexing='xy') for i in range(nx): for j in range(ny): # treat xv[j,i], yv[j,i] In the 1-D and 0-D case, the indexing and sparse keywords have no effect. See Also -------- index_tricks.mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. index_tricks.ogrid : Construct an open multi-dimensional "meshgrid" using indexing notation. Examples -------- >>> nx, ny = (3, 2) >>> x = np.linspace(0, 1, nx) >>> y = np.linspace(0, 1, ny) >>> xv, yv = meshgrid(x, y) >>> xv array([[ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ]]) >>> yv array([[ 0., 0., 0.], [ 1., 1., 1.]]) >>> xv, yv = meshgrid(x, y, sparse=True) # make sparse output arrays >>> xv array([[ 0. , 0.5, 1. ]]) >>> yv array([[ 0.], [ 1.]]) `meshgrid` is very useful to evaluate functions on a grid. >>> x = np.arange(-5, 5, 0.1) >>> y = np.arange(-5, 5, 0.1) >>> xx, yy = meshgrid(x, y, sparse=True) >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) >>> h = plt.contourf(x,y,z) """ ndim = len(xi) copy_ = kwargs.pop('copy', True) sparse = kwargs.pop('sparse', False) indexing = kwargs.pop('indexing', 'xy') if kwargs: raise TypeError("meshgrid() got an unexpected keyword argument '%s'" % (list(kwargs)[0],)) if indexing not in ['xy', 'ij']: raise ValueError( "Valid values for `indexing` are 'xy' and 'ij'.") s0 = (1,) * ndim output = [np.asanyarray(x).reshape(s0[:i] + (-1,) + s0[i + 1::]) for i, x in enumerate(xi)] shape = [x.size for x in output] if indexing == 'xy' and ndim > 1: # switch first and second axis output[0].shape = (1, -1) + (1,)*(ndim - 2) output[1].shape = (-1, 1) + (1,)*(ndim - 2) shape[0], shape[1] = shape[1], shape[0] if sparse: if copy_: return [x.copy() for x in output] else: return output else: # Return the full N-D matrix (not only the 1-D vector) if copy_: mult_fact = np.ones(shape, dtype=int) return [x * mult_fact for x in output] else: return np.broadcast_arrays(*output) def delete(arr, obj, axis=None): """ Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by `arr[obj]`. Parameters ---------- arr : array_like Input array. obj : slice, int or array of ints Indicate which sub-arrays to remove. axis : int, optional The axis along which to delete the subarray defined by `obj`. If `axis` is None, `obj` is applied to the flattened array. Returns ------- out : ndarray A copy of `arr` with the elements specified by `obj` removed. Note that `delete` does not occur in-place. If `axis` is None, `out` is a flattened array. See Also -------- insert : Insert elements into an array. append : Append elements at the end of an array. Notes ----- Often it is preferable to use a boolean mask. For example: >>> mask = np.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...] Is equivalent to `np.delete(arr, [0,2,4], axis=0)`, but allows further use of `mask`. Examples -------- >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) >>> np.delete(arr, 1, 0) array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]]) >>> np.delete(arr, np.s_[::2], 1) array([[ 2, 4], [ 6, 8], [10, 12]]) >>> np.delete(arr, [1,3,5], None) array([ 1, 3, 5, 7, 8, 9, 10, 11, 12]) """ wrap = None if type(arr) is not ndarray: try: wrap = arr.__array_wrap__ except AttributeError: pass arr = asarray(arr) ndim = arr.ndim arrorder = 'F' if arr.flags.fnc else 'C' if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim - 1 if ndim == 0: # 2013-09-24, 1.9 warnings.warn( "in the future the special handling of scalars will be removed " "from delete and raise an error", DeprecationWarning, stacklevel=2) if wrap: return wrap(arr) else: return arr.copy(order=arrorder) slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): start, stop, step = obj.indices(N) xr = range(start, stop, step) numtodel = len(xr) if numtodel <= 0: if wrap: return wrap(arr.copy(order=arrorder)) else: return arr.copy(order=arrorder) # Invert if step is negative: if step < 0: step = -step start = xr[-1] stop = xr[0] + 1 newshape[axis] -= numtodel new = empty(newshape, arr.dtype, arrorder) # copy initial chunk if start == 0: pass else: slobj[axis] = slice(None, start) new[slobj] = arr[slobj] # copy end chunck if stop == N: pass else: slobj[axis] = slice(stop-numtodel, None) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(stop, None) new[slobj] = arr[slobj2] # copy middle pieces if step == 1: pass else: # use array indexing. keep = ones(stop-start, dtype=bool) keep[:stop-start:step] = False slobj[axis] = slice(start, stop-numtodel) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(start, stop) arr = arr[slobj2] slobj2[axis] = keep new[slobj] = arr[slobj2] if wrap: return wrap(new) else: return new _obj = obj obj = np.asarray(obj) # After removing the special handling of booleans and out of # bounds values, the conversion to the array can be removed. if obj.dtype == bool: warnings.warn( "in the future insert will treat boolean arrays and array-likes " "as boolean index instead of casting it to integer", FutureWarning, stacklevel=2) obj = obj.astype(intp) if isinstance(_obj, (int, long, integer)): # optimization for a single value obj = obj.item() if (obj < -N or obj >= N): raise IndexError( "index %i is out of bounds for axis %i with " "size %i" % (obj, axis, N)) if (obj < 0): obj += N newshape[axis] -= 1 new = empty(newshape, arr.dtype, arrorder) slobj[axis] = slice(None, obj) new[slobj] = arr[slobj] slobj[axis] = slice(obj, None) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(obj+1, None) new[slobj] = arr[slobj2] else: if obj.size == 0 and not isinstance(_obj, np.ndarray): obj = obj.astype(intp) if not np.can_cast(obj, intp, 'same_kind'): # obj.size = 1 special case always failed and would just # give superfluous warnings. # 2013-09-24, 1.9 warnings.warn( "using a non-integer array as obj in delete will result in an " "error in the future", DeprecationWarning, stacklevel=2) obj = obj.astype(intp) keep = ones(N, dtype=bool) # Test if there are out of bound indices, this is deprecated inside_bounds = (obj < N) & (obj >= -N) if not inside_bounds.all(): # 2013-09-24, 1.9 warnings.warn( "in the future out of bounds indices will raise an error " "instead of being ignored by `numpy.delete`.", DeprecationWarning, stacklevel=2) obj = obj[inside_bounds] positive_indices = obj >= 0 if not positive_indices.all(): warnings.warn( "in the future negative indices will not be ignored by " "`numpy.delete`.", FutureWarning, stacklevel=2) obj = obj[positive_indices] keep[obj, ] = False slobj[axis] = keep new = arr[slobj] if wrap: return wrap(new) else: return new def insert(arr, obj, values, axis=None): """ Insert values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : int, slice or sequence of ints Object that defines the index or indices before which `values` is inserted. .. versionadded:: 1.8.0 Support for multiple insertions when `obj` is a single scalar or a sequence with one element (similar to calling insert multiple times). values : array_like Values to insert into `arr`. If the type of `values` is different from that of `arr`, `values` is converted to the type of `arr`. `values` should be shaped so that ``arr[...,obj,...] = values`` is legal. axis : int, optional Axis along which to insert `values`. If `axis` is None then `arr` is flattened first. Returns ------- out : ndarray A copy of `arr` with `values` inserted. Note that `insert` does not occur in-place: a new array is returned. If `axis` is None, `out` is a flattened array. See Also -------- append : Append elements at the end of an array. concatenate : Join a sequence of arrays along an existing axis. delete : Delete elements from an array. Notes ----- Note that for higher dimensional inserts `obj=0` behaves very different from `obj=[0]` just like `arr[:,0,:] = values` is different from `arr[:,[0],:] = values`. Examples -------- >>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, 2, 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) Difference between sequence and scalars: >>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), ... np.insert(a, [1], [[1],[2],[3]], axis=1)) True >>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, 6, 2, 2, 3, 3]) >>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, 2, 6, 2, 3, 3]) >>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, 0, 2, 2, 3, 3]) >>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]]) """ wrap = None if type(arr) is not ndarray: try: wrap = arr.__array_wrap__ except AttributeError: pass arr = asarray(arr) ndim = arr.ndim arrorder = 'F' if arr.flags.fnc else 'C' if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim - 1 else: if ndim > 0 and (axis < -ndim or axis >= ndim): raise IndexError( "axis %i is out of bounds for an array of " "dimension %i" % (axis, ndim)) if (axis < 0): axis += ndim if (ndim == 0): # 2013-09-24, 1.9 warnings.warn( "in the future the special handling of scalars will be removed " "from insert and raise an error", DeprecationWarning, stacklevel=2) arr = arr.copy(order=arrorder) arr[...] = values if wrap: return wrap(arr) else: return arr slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): # turn it into a range object indices = arange(*obj.indices(N), **{'dtype': intp}) else: # need to copy obj, because indices will be changed in-place indices = np.array(obj) if indices.dtype == bool: # See also delete warnings.warn( "in the future insert will treat boolean arrays and " "array-likes as a boolean index instead of casting it to " "integer", FutureWarning, stacklevel=2) indices = indices.astype(intp) # Code after warning period: #if obj.ndim != 1: # raise ValueError('boolean array argument obj to insert ' # 'must be one dimensional') #indices = np.flatnonzero(obj) elif indices.ndim > 1: raise ValueError( "index array argument obj to insert must be one dimensional " "or scalar") if indices.size == 1: index = indices.item() if index < -N or index > N: raise IndexError( "index %i is out of bounds for axis %i with " "size %i" % (obj, axis, N)) if (index < 0): index += N # There are some object array corner cases here, but we cannot avoid # that: values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype) if indices.ndim == 0: # broadcasting is very different here, since a[:,0,:] = ... behaves # very different from a[:,[0],:] = ...! This changes values so that # it works likes the second case. (here a[:,0:1,:]) values = np.rollaxis(values, 0, (axis % values.ndim) + 1) numnew = values.shape[axis] newshape[axis] += numnew new = empty(newshape, arr.dtype, arrorder) slobj[axis] = slice(None, index) new[slobj] = arr[slobj] slobj[axis] = slice(index, index+numnew) new[slobj] = values slobj[axis] = slice(index+numnew, None) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(index, None) new[slobj] = arr[slobj2] if wrap: return wrap(new) return new elif indices.size == 0 and not isinstance(obj, np.ndarray): # Can safely cast the empty list to intp indices = indices.astype(intp) if not np.can_cast(indices, intp, 'same_kind'): # 2013-09-24, 1.9 warnings.warn( "using a non-integer array as obj in insert will result in an " "error in the future", DeprecationWarning, stacklevel=2) indices = indices.astype(intp) indices[indices < 0] += N numnew = len(indices) order = indices.argsort(kind='mergesort') # stable sort indices[order] += np.arange(numnew) newshape[axis] += numnew old_mask = ones(newshape[axis], dtype=bool) old_mask[indices] = False new = empty(newshape, arr.dtype, arrorder) slobj2 = [slice(None)]*ndim slobj[axis] = indices slobj2[axis] = old_mask new[slobj] = values new[slobj2] = arr if wrap: return wrap(new) return new def append(arr, values, axis=None): """ Append values to the end of an array. Parameters ---------- arr : array_like Values are appended to a copy of this array. values : array_like These values are appended to a copy of `arr`. It must be of the correct shape (the same shape as `arr`, excluding `axis`). If `axis` is not specified, `values` can be any shape and will be flattened before use. axis : int, optional The axis along which `values` are appended. If `axis` is not given, both `arr` and `values` are flattened before use. Returns ------- append : ndarray A copy of `arr` with `values` appended to `axis`. Note that `append` does not occur in-place: a new array is allocated and filled. If `axis` is None, `out` is a flattened array. See Also -------- insert : Insert elements into an array. delete : Delete elements from an array. Examples -------- >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) When `axis` is specified, `values` must have the correct shape. >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): ... ValueError: arrays must have same number of dimensions """ arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axis)
mit
ageron/tensorflow
tensorflow/contrib/learn/python/learn/estimators/logistic_regressor_test.py
44
4901
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for LogisticRegressor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib import layers from tensorflow.python.training import training_util from tensorflow.contrib.layers.python.layers import optimizers from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.contrib.learn.python.learn.estimators import logistic_regressor from tensorflow.contrib.learn.python.learn.estimators import metric_key from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops.losses import losses from tensorflow.python.platform import test def _iris_data_input_fn(): # Converts iris data to a logistic regression problem. iris = base.load_iris() ids = np.where((iris.target == 0) | (iris.target == 1)) features = constant_op.constant(iris.data[ids], dtype=dtypes.float32) labels = constant_op.constant(iris.target[ids], dtype=dtypes.float32) labels = array_ops.reshape(labels, labels.get_shape().concatenate(1)) return features, labels def _logistic_regression_model_fn(features, labels, mode): _ = mode logits = layers.linear( features, 1, weights_initializer=init_ops.zeros_initializer(), # Intentionally uses really awful initial values so that # AUC/precision/recall/etc will change meaningfully even on a toy dataset. biases_initializer=init_ops.constant_initializer(-10.0)) predictions = math_ops.sigmoid(logits) loss = losses.sigmoid_cross_entropy(labels, logits) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return predictions, loss, train_op class LogisticRegressorTest(test.TestCase): def test_fit_and_evaluate_metrics(self): """Tests basic fit and evaluate, and checks the evaluation metrics.""" regressor = logistic_regressor.LogisticRegressor( model_fn=_logistic_regression_model_fn) # Get some (intentionally horrible) baseline metrics. regressor.fit(input_fn=_iris_data_input_fn, steps=1) eval_metrics = regressor.evaluate(input_fn=_iris_data_input_fn, steps=1) self.assertNear( 0.0, eval_metrics[metric_key.MetricKey.PREDICTION_MEAN], err=1e-3) self.assertNear( 0.5, eval_metrics[metric_key.MetricKey.LABEL_MEAN], err=1e-6) self.assertNear( 0.5, eval_metrics[metric_key.MetricKey.ACCURACY_BASELINE], err=1e-6) self.assertNear(0.5, eval_metrics[metric_key.MetricKey.AUC], err=1e-6) self.assertNear( 0.5, eval_metrics[metric_key.MetricKey.ACCURACY_MEAN % 0.5], err=1e-6) self.assertNear( 0.0, eval_metrics[metric_key.MetricKey.PRECISION_MEAN % 0.5], err=1e-6) self.assertNear( 0.0, eval_metrics[metric_key.MetricKey.RECALL_MEAN % 0.5], err=1e-6) # Train for more steps and check the metrics again. regressor.fit(input_fn=_iris_data_input_fn, steps=100) eval_metrics = regressor.evaluate(input_fn=_iris_data_input_fn, steps=1) # Mean prediction moves from ~0.0 to ~0.5 as we stop predicting all 0's. self.assertNear( 0.5, eval_metrics[metric_key.MetricKey.PREDICTION_MEAN], err=1e-2) # Label mean and baseline both remain the same at 0.5. self.assertNear( 0.5, eval_metrics[metric_key.MetricKey.LABEL_MEAN], err=1e-6) self.assertNear( 0.5, eval_metrics[metric_key.MetricKey.ACCURACY_BASELINE], err=1e-6) # AUC improves from 0.5 to 1.0. self.assertNear(1.0, eval_metrics[metric_key.MetricKey.AUC], err=1e-6) # Accuracy improves from 0.5 to >0.9. self.assertTrue( eval_metrics[metric_key.MetricKey.ACCURACY_MEAN % 0.5] > 0.9) # Precision improves from 0.0 to 1.0. self.assertNear( 1.0, eval_metrics[metric_key.MetricKey.PRECISION_MEAN % 0.5], err=1e-6) # Recall improves from 0.0 to >0.9. self.assertTrue(eval_metrics[metric_key.MetricKey.RECALL_MEAN % 0.5] > 0.9) if __name__ == '__main__': test.main()
apache-2.0